answer stringlengths 17 10.2M |
|---|
package com.RyanHodin.RPG;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Cgame implements Serializable, Parcelable
{
public static final long serialVersionUID=1;
public int stage; // Where are we?
public int line; // Persistent input
public int inputted; // Overwritten per input
public boolean doCommitSuicide; // Does exiting the input menu execute user.commitSuicide() or return to runStage()?
public static MainActivity t;
public Cgame()
{
stage=0;
line=0;
inputted=-1;
}
private Cgame (Parcel in)
{
stage=in.readInt();
line=in.readInt();
inputted=in.readInt();
}
public void saveTo(SharedPreferences.Editor edit)
{
edit.putInt("gameStage", stage-1);
edit.putInt("gameLine", line);
edit.putInt("gameInputted", inputted);
if (Build.VERSION.SDK_INT>=9)
edit.apply();
else
edit.commit();
}
public void loadFrom(SharedPreferences sp)
{
stage=sp.getInt("gameStage", stage);
line=sp.getInt("gameLine", line);
inputted=sp.getInt("gameInputted", inputted);
}
public void runStage()
{
t.displayHandler.removeMessages(1);
if (Thread.interrupted())
return;
t.config.computerPaused=true;
doCommitSuicide=false;
t.user.dead=false;
if (t.config.autosave)
{
(new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occurring at once. Consider naming the save thread.
{
@Override
public void run()
{
t.saveGame();
}
})).start();
}
switch (stage)
{
case -1:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
t.setContentView(R.layout.dead);
t.currentView=R.id.deadLayout;
t.setUi();
}
});
break;
case 0:
if (t.config.easterEggs && ("King Arthur".equalsIgnoreCase(t.user.name) || "King Arthur of Camelot".equalsIgnoreCase(t.user.name) || "Arthur, King of the Britons".equalsIgnoreCase(t.user.name) || "It is Arthur, King of the Britons".equalsIgnoreCase(t.user.name)))
{
runArthur((byte)0, null);
return;
}
if (t.config.gender)
{
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
t.say("Good.\n\n\tNow, "+t.user.name+", since it\'s too dark to see, and for my accounting purposes...");
}
});
t.th.start();
prepContinueButton();
}
else
{
stage=2;
runStage();
return;
}
break;
case 1:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void run()
{
LinearLayout l=prepInput("What gender are you?");
List<String> genders=new ArrayList<String>(100);
genders.add("Male");
genders.add("Female");
if (!t.config.twoGender)
{
if (t.config.specialGender)
{
genders.add("Transsexual male");
genders.add("Transsexual female");
genders.add("Metrosexual male");
genders.add("Metrosexual female");
genders.add("Male to Female");
genders.add("Female to Male");
genders.add("Uncertain");
genders.add("Unwilling to say");
genders.add("It\'s complicated");
genders.add("Genderqueer");
genders.add("Dual");
genders.add("Male, but curious as to what being a female is like");
genders.add("Female, but curious as to what being a male is like");
genders.add("Male, but overweight, so have moobs");
genders.add("Female, but have Adam\'s apple");
genders.add("Hermaphrodite with strong male leanings");
genders.add("Hermaphrodite with strong female leanings");
genders.add("Hermaphrodite with no strong gender leanings");
genders.add("Conjoined twin - Male");
genders.add("Conjoined twin - Female");
genders.add("Conjoined twin - Other");
genders.add("Born without genitals - Identify as male");
genders.add("Born without genitals - Identify as female");
genders.add("Born without genitals - Identify otherwise");
genders.add("Born without genitals - and proud of it");
genders.add("Born male, had bad circumcision, raised female");
genders.add("WOMYN, thank you very much!");
genders.add("Angel");
genders.add("Mortal Angel");
genders.add("Sentient Artificial Intelligence - Identify as ungendered");
genders.add("Sentient Artificial Intelligence - Identify as male");
genders.add("Sentient Artificial Intelligence - Identify as female");
genders.add("Sentient Artificial Intelligence - Identify as other");
genders.add("Household pet that walked across the device - Male");
genders.add("Household pet that walked across the device - Female");
genders.add("Household pet that walked across the device - Other");
genders.add("Cross Dresser");
genders.add("In between");
genders.add("Intersex");
genders.add("Pangender");
genders.add("Two spirit");
genders.add("Other");
genders.add("Neutrois");
genders.add("Prefer not to say");
genders.add("None of your business");
if (t.config.easterEggs)
{
genders.add("Kanye West");
genders.add("Cheese");
genders.add("Raygun");
if (t.config.GoTEggs)
{
genders.add("The Dothraki do not follow your Genders");
genders.add("Khaleesi");
genders.add("Dragon - Male");
genders.add("Dragon - Female");
genders.add("Dragon - Other");
genders.add("Direwolf");
genders.add("White Walker");
genders.add("Child of the Forest");
}
if (t.config.ESEggs)
{
genders.add("Khajiit");
genders.add("Dovahkiin");
genders.add("Dovah");
genders.add("Draugr");
}
if (t.config.schoolEggs)
{
genders.add("Student");
genders.add("IB Student");
genders.add("Teacher");
genders.add("IB Teacher");
}
}
}
else
{
genders.add("Multiple");
genders.add("In between");
genders.add("Unsure");
genders.add("None");
genders.add("Prefer not to say");
genders.add("Other");
}
}
for (int i=0; i<genders.size(); ++i)
{
Button b=new Button(t);
b.setText(genders.get(i));
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.user.gender=((TextView)v).getText().toString();
t.th=new Thread (new Runnable ()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
genders.clear();
if (t.config.customGender)
{
Button b=new Button (t);
b.setText("Custom");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.config.computerPaused=true;
ScrollView sv=new ScrollView (t);
int id=Build.VERSION.SDK_INT>=17 ? View.generateViewId() : 5;
sv.setId(id);
t.currentView=id;
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
t.setContentView(sv);
LinearLayout l=new LinearLayout(t);
l.setOrientation(LinearLayout.VERTICAL);
sv.addView(l);
t.setUi();
lp.topMargin=10;
OnFocusChangeListener ofcl=new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus && t.config.fullscreen)
{
t.setUi();
EditText ev=((EditText)t.findViewById(t.user.parsedGender));
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)ev.getLayoutParams();
int result=0;
int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = t.getResources().getDimensionPixelSize(resourceId);
}
lp.topMargin=result+5;
}
}
};
EditText ev=new EditText(t);
t.user.parsedGender=999999999;
ev.setId(t.user.parsedGender);
ev.setOnFocusChangeListener(ofcl);
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("What gender are you?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setSingleLine(false);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_AUTO_CORRECT|InputType.TYPE_TEXT_FLAG_MULTI_LINE|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
ev.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
l.addView(ev, lp);
if (t.config.addressGender)
{
ev=new EditText(t);
lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.topMargin=20;
t.user.weapon.type=7; // Bad form, but we won't have a real parsed weapon for a while... It can be temporary storage until then.
ev.setId(t.user.weapon.type);
ev.setOnFocusChangeListener(ofcl);
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("What should I address one of your gender as?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setSingleLine(false);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_AUTO_CORRECT|InputType.TYPE_TEXT_FLAG_MULTI_LINE|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
ev.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
l.addView(ev, lp);
}
Button b=new Button(t);
b.setText("Submit");
lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.topMargin=250;
lp.gravity=Gravity.RIGHT;
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
// Close the soft keyboard, now that there's nothing for it to write to.
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(t.findViewById(t.user.parsedGender).getWindowToken(), 0);
t.user.gender=((TextView)t.findViewById(t.user.parsedGender)).getText().toString().trim();
if (t.config.addressGender)
{
String str=((TextView)t.findViewById(t.user.weapon.type)).getText().toString().trim();
if (str.startsWith("the ") || str.startsWith("The "))
str=str.substring(4); // Trim off the 'the' to avoid the 'The The' quirk.
t.user.genderAddress="The "+str;
}
runStage();
}
});
t.th.start();
}
});
l.addView(b, lp);
}
});
l.addView(b);
}
}
});
break;
case 2:
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
if (t.config.gender && t.config.addressGender && t.user.parsedGender!=999999999)
t.user.parseGenderAddress();
t.say("I see.\n\n\tWell, "+t.user+", it is time to make a decision.\n\n\tAre you going to try to escape?");
}
});
t.th.start();
prepContinueButton();
if (t.config.gender)
t.user.parseGender();
break;
case 3:
t.fadeout();
t.runOnUiThread (new Runnable ()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button (t);
b.setText("Escape");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button (t);
b.setText("Stay");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 4:
if (inputted==0)
{
if (onMove(99))
return;
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
String creature;
boolean plural=false;
if (t.gen.nextBoolean())
{
if (t.gen.nextBoolean())
creature="troll";
else
creature="dinosaur";
}
else
{
if (t.gen.nextBoolean())
{
creature="alligator";
plural=true;
}
else
creature="goblin";
}
t.say("You start to escape...","But you see a shape.\n\tIt\'s "+(plural ? "an" : "a")+" "+creature+"!\n\n\tYou search for a weapon, but only find a stick.");
}
});
t.th.start();
prepContinueButton();
}
else
{
if (onMove(50))
return;
line=1;
if (t.config.triggerEgg(.1))
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("You remain in the cave.","Despite the lack of any way to survive, you stubbornly stay in the cave, starving...\n\tSuddenly, Gandalf the Grey appears.\n\t\t\"Fly, you fool! You will die!!\"\nSince you make no move to escape, Gandalf sighs, and takes you with him.");
}
});
t.th.start();
prepContinueButton();
}
else
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("You stay in the cave...","...And starve to death because there\'s no food in the cave.");
}
});
t.th.start();
t.user.dead=true;
prepContinueButton();
}
}
break;
case 5:
if (line==0)
{
t.fadeout();
t.runOnUiThread(new Runnable ()
{
@Override
public void run ()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Fight it with a stick");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th=new Thread (new Runnable ()
{
@Override
public void run()
{
t.user.weapon.name="stick";
t.user.weapon.type=Cweapon.TYPE_BLUNT;
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Fight it with your fists");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th=new Thread (new Runnable ()
{
@Override
public void run()
{
t.user.weapon.type=Cweapon.TYPE_HAND_TO_HAND;
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Run away!!");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th=new Thread (new Runnable ()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
}
else
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("You win!","You have won the game of life.");
}
});
t.th.start();
doCommitSuicide=true;
prepContinueButton(onWin);
}
break;
case 6:
if (inputted==1)
{
if (onMove(78))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Run away!!!", "You try to run away from the creature, but it\'s too fast.");
}
});
t.th.start();
t.user.dead=true;
prepContinueButton();
}
else
{
if (t.user.weapon.type==Cweapon.TYPE_HAND_TO_HAND)
{
if (t.determineUserDeath(.5))
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Fight with fists!","You punch it, but it eats you anyway.");
}
});
t.th.start();
prepContinueButton();
}
else
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Fight with fists", "You punch the monster, and barely manage to scare it.\n\tYou take a deep breath, and continue.");
}
});
t.th.start();
prepContinueButton();
}
}
else
{
t.th=new Thread(new Runnable ()
{
@Override
public void run ()
{
t.say("You grab the stick, and beat the creature until it leaves.");
}
});
t.th.start();
prepContinueButton();
}
}
break;
case 7:
if (onMove(105))
return;
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
t.say ("You Escape!", "You escape from the cave.\n\n\tIt is a bright and sunny day outside.\n\n\tHowever, there is nothing around you besides sand and dust.\nIt would appear that you are in a desert.\n\n\n\tHowever, a while away, there is a lush valley, full of greenery. You decide to head for it.\n\n\tAlong the way, you find a foreboding cave. A sharp iron sword is sitting by the mouth of the cave, glimmering in the sunlight.");
}
});
t.th.start();
prepContinueButton();
break;
case 8:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button (t);
b.setText("Grab the sword and enter the cave");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.isArthur) {
t.user.weapon.name="Excalibur"; // King Arthur gets the greatest of swords
t.user.weapon.setCharacteristics(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD);
t.user.weapon.strengthModifier=1+t.gen.nextDouble(); // Excalibur is in epic condition.
}
else {
t.user.weapon.name = "sword";
t.user.weapon.setCharacteristics(Cweapon.ACCURATE | Cweapon.CLOSE_RANGE | Cweapon.CLOSE_RANGE_ONLY | Cweapon.HIGH_CALIBER | Cweapon.ONE_ROUND_MAGAZINE | Cweapon.QUICK_RELOAD);
t.user.weapon.strengthModifier=-0.05*t.gen.nextDouble(); // The sword should be in poor condition
// This exaggerates the difference between the sword and Excalibur
}
t.user.weapon.type = Cweapon.TYPE_SHARP;
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button (t);
b.setText("Ignore the sword and enter the cave");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button (t);
b.setText("Ignore the sword and continue away from the cave");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button (t);
b.setText("Grab the sword and continue away from the cave");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run() {
if (t.user.isArthur) {
t.user.weapon.name="Excalibur"; // King Arthur gets the greatest of swords
t.user.weapon.setCharacteristics(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD);
t.user.weapon.strengthModifier=1+t.gen.nextDouble(); // Excalibur is in epic condition.
}
else {
t.user.weapon.name = "sword";
t.user.weapon.setCharacteristics(Cweapon.ACCURATE | Cweapon.CLOSE_RANGE | Cweapon.CLOSE_RANGE_ONLY | Cweapon.HIGH_CALIBER | Cweapon.ONE_ROUND_MAGAZINE | Cweapon.QUICK_RELOAD);
t.user.weapon.strengthModifier=-0.05*t.gen.nextDouble(); // The sword should be in poor condition
// This exaggerates the difference between the sword and Excalibur
}
t.user.weapon.type = Cweapon.TYPE_SHARP;
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 9:
if (inputted==0)
{
if (onMove(67))
return;
t.user.dead=(t.user.weapon.type<Cweapon.TYPE_SHARP);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String title="You enter the cave";
if (t.user.dead)
t.say(title,"Ignoring the sword, you enter.\n\tImmediately, the creature from the last cave attacks you. It is incredibly angry, and no "+t.user.weapon+" will scare it off.");
else {
if (t.user.isArthur)
t.say(title,"You take the sword, and examine it.\n\n\tIt seemed to call to you like an old friend, and suddenly you recognize it: It is "+t.user.weapon+"!\n\n\n\tYou take a moment with the blade, twirling it about to remember.\n\n\tAll of a sudden, a shape approaches: You recognize it as the creature from the last cave.\n\tYou bring "+t.user.weapon+" to bear.");
else
t.say(title, "With the sword in hand, you enter.\n\tImmediately, the creature that fled the last cave attacks you. It is incredibly angry, and a stick will not be enough to make it flee.\n\n\tLuckily, you had the prudence to grab the " + t.user.weapon + ".\n\tYou ready it.");
}
}
});
t.th.start();
prepContinueButton();
}
else
{
stage=25;
runStage();
return;
}
break;
case 10:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Fight the monster");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Run away!!");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 11:
if (onMove(45))
return;
t.user.dead=(inputted!=0);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("Run away!!!", "You turn to run, but the monster is far too fast.");
else
t.say("You fight the monster", "The monster lunges at you, but you swiftly dodge it, turn, and behead it.\n\n\n\tCovered in blood, you contemplate whether you should continue.");
}
});
t.th.start();
prepContinueButton();
break;
case 12:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button (t);
b.setText("Continue into the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Escape from the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 13:
if (onMove(15+t.gen.nextInt(20)))
return;
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("Forward into Dusk","You continue into the cave.\n\tYou encounter a rather horrifying monster, one that chills you to the bone.\n\n\tIt seems to be extremely afraid of the light.\n\n\n\tUnfortunately, there is no way around it.");
}
});
t.th.start();
prepContinueButton();
break;
case 14:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Fight the grue");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Flee from the grue");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 15:
if (t.user.weapon.characteristicSet(Cweapon.LEGENDARY)) // Check for Excalibur
t.determineUserDeath(1,5); // Slightly reduced odds of death
else
t.determineUserDeath(1, 3); // Standard, "Traditional" weighting
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
if (t.config.specMon)
{
t.user.dead=false;
line=1;
}
t.say("You lunge at the grue", "But the grue is too strong, and you get eaten.");
}
else
t.say("You swing your sword...", "...and get in a lucky shot. The grue\'s head falls to the floor.\n\n\tYou again consider whether you should continue.");
}
});
t.th.start();
prepContinueButton();
break;
case 16:
if (line==1)
{
eatenByGrue();
prepContinueButton();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.gameContinueButton)).setTextColor(Color.GREEN);
}
});
}
else
{
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Continue into the depths of the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Escape from the monsters yet to be found within the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
}
break;
case 17:
if (onMove(5+t.gen.nextInt(10)))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Into the Darkness of Death", "You continue into the foreboding darkness of the cave, trembling in fear, wondering what the next monster to come far too close to ending your life will be.\n\n\n\n\tYour fears are answered in a horrifying way when you see an enormous, hulking, towering shape in front of you.\n\n\tIt lumbers toward you, the ground quaking as it stomps.\n\n\tYou quickly contemplate taking flight.");
}
});
t.th.start();
prepContinueButton();
break;
case 18:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Run away before you get killed");
b.setTextColor(Color.rgb(250, 255, 250));
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Challenge the utter despotic power of the creature before you");
b.setTextColor(Color.rgb(255, 250, 250));
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 19:
if (t.user.weapon.characteristicSet(Cweapon.LEGENDARY)) // Check for Excalibur
t.determineUserDeath(3, 10); // Slightly less than one third
else
t.determineUserDeath(2, 3); // Two thirds "Traditional" weighting
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("You fight the monster...", "... But it flattens you.");
else
t.say("David vs. Goliath", "David killed Goliath, and you killed.... Whatever that was.\n\n\tCollecting yourself as a massive thud rolls through the cave and the monster lies vanquished before you, you again consider whether you should continue further into the depths of the frightening cave.");
}
});
t.th.start();
prepContinueButton();
break;
case 20:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=t.config.easterEggs;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Get out of the cave now, before it is too late!");
b.setPadding(5, 5, 5, 5);
b.setTextColor(Color.rgb(245, 255, 245));
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Bravely, yet perhaps foolishly, continue onwards towards the horrors you know not of");
b.setTextColor(Color.rgb(245, 235, 235));
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 21:
if (line==1)
{
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Ignore the weapon and exit the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Grab the superweapon and exit the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_FUTURE, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, "raygun", null));
t.user.weapon.strengthModifier=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
}
else
{
if (onMove(50))
return;
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("You come to a dead end in the cave, sighing with relief.\n\n\tOn the ground before you, there is a semi-automatic pistol.");
}
});
t.th.start();
prepContinueButton();
}
break;
case 22:
if (line==1)
{
line=0;
if (t.user.weapon.type==Cweapon.TYPE_FUTURE)
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("The "+t.capitalize(t.user.weapon.name), "You take the "+t.user.weapon+", considering it.\n\n\tSuddenly, a grue appears!\n\n\n\n\n\tWithout thinking, you aim the "+t.user.weapon+" at the grue, and pull the trigger.\n\n\tA bright green bolt shoots out of the superweapon, and where the grue was, there is only ash.\n\n\n\tYou consider the "+t.user.weapon+", thinking you\'ll never need to worry about any monster ever again.\n\n\tGrinning, you set off to leave the cave.");
}
});
}
else
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.dead=true;
if (t.config.specMon)
{
t.user.dead=false;
line=1;
}
t.say("You ignore the superweapon, turning to head out of the cave.\n\n\tSuddenly, a grue appears!\n\n\tYou try to bring your sword to bear, but it\'s too slow.");
}
});
}
t.th.start();
prepContinueButton();
}
else
{
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Grab the pistol and escape the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, "pistol", null));
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Foolishly ignore the pistol and leave the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
}
break;
case 23:
if (line==1)
{
eatenByGrue();
t.frameTick();
prepContinueButton();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.gameContinueButton)).setTextColor(Color.GREEN);
}
});
break;
}
++stage;
// Fall through
case 24:
if (onMove(70))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("You escape!", "You leave the cave, and gaze towards the lush valley in the distance.");
}
});
t.th.start();
prepContinueButton();
break;
case 25:
if (onMove(90))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String address;
String pronoun;
if (t.gen.nextBoolean())
{
address="him";
pronoun="he";
}
else
{
address="her";
pronoun="she";
}
t.say("Continuation", "You continue, towards the lush valley.\n\n\tAlong the way, you encounter an archer.\n\tBefore you\'re able to greet "+address+", "+pronoun+" readies "+address+"self to shoot you.");
}
});
t.th.start();
prepContinueButton();
break;
case 26:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
String action;
switch(t.user.weapon.type)
{
case Cweapon.TYPE_HAND_TO_HAND:
case Cweapon.TYPE_BLUNT:
action="Fight";
break;
case Cweapon.TYPE_SHARP:
action="Stab";
break;
case Cweapon.TYPE_MODERN:
case Cweapon.TYPE_FUTURE:
action="Shoot";
break;
default:
action="Kill";
}
b.setText(action+" the archer");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l);
b=new Button(t);
b.setText("Run away");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 27:
if (inputted==0)
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
switch (t.user.weapon.type)
{
case Cweapon.TYPE_HAND_TO_HAND:
t.user.dead=true;
t.say("Fistfight!", "You try to get in punching range of the archer, but an arrow appears in your chest before you get close.");
break;
case Cweapon.TYPE_BLUNT:
t.user.dead=true;
t.say(t.capitalize(t.user.weapon.name)+"fight", "You run up to the archer, barely managing to get in a swing, when the archer shoots you.");
break;
case Cweapon.TYPE_SHARP:
if (t.user.weapon.characteristicSet(Cweapon.LEGENDARY)) { // Excalibur check
t.determineUserDeath(.2); // Excalibur weighting
if (t.user.dead)
t.say("The Might of "+t.user.weapon, "With "+t.user.weapon+" in hand, you charge the archer.\n\n\tA few arrows fly towards you, and one strikes you in the stomach, stopping you in your tracks.\n\n\t"+t.user.weapon+" falls beside you as your eyes fixate upon it, barely seeing the archer walk up beside you to draw a killing arrow from his quiver.\n\n\n\tAs you watch, "+t.user.weapon+" is surrounded by a pool of growing, shimmering water, forming a mirror.\n\n\tAs the blade is enveloped, it begins to dissolve, becoming one with the water, until it is but a part of the pool.\n\n\tAs the archer shoots an arrow into your head, you watch the pool that was "+t.user.weapon+" dissolve into the soil, lost once more in the oceans of time.");
else
t.say("The Might of "+t.user.weapon, "With "+t.user.weapon+" in hand, you charge the archer.\n\n\tA few arrows fly towards you, but you dodge one half, and "+(t.gen.nextBoolean() ? "swiftly" : "deftly")+" deflect the other.\n\n\tHaving closed the distance between yourself and the archer, you swing your legendary blade at your enemy.\n\n\n\tThe archer deftly rolls away, but "+t.user.weapon+" knows what to do, adjusting its swing, pulling you along, until you cleave the archer in two.");
}
else {
t.determineUserDeath(.5); // Traditional weighting
t.say(t.capitalize(t.user.weapon.name) + " battle!", "You run up to the archer, and lunge!\n\n\t" + (t.user.dead ? "Unfortunately, you miss, and get shot in the " + (t.config.ESEggs && t.config.triggerEgg(.9) ? "knee." : "back.") : "You connect!\n\n\tThe archer falls, dead.\n\n\tThe bow drops to the ground.\n\tYou eye it."));
}
break;
case Cweapon.TYPE_MODERN:
t.determineUserDeath(1, 6);
t.say(t.capitalize(t.user.weapon.name)+" vs. bow", "You carefully take aim at the archer, and pull the trigger.\n\n\t"+(t.user.dead ? "Unfortunately, you miss, and get shot before you can aim again." : (t.gen.nextBoolean() ? "A neat hole appears in the archer\'s chest." : "You wing the archer, the bow swinging off it\'s aim, and then you shoot again, scoring a fatal hit.")+"\n\n\tThe bow falls to the ground.\n\tYou eye it, but decide that you prefer your "+t.user.weapon+"."));
break;
case Cweapon.TYPE_FUTURE:
t.say(t.capitalize(t.user.weapon.name)+" Kill", "You calmly aim at the archer, and pull the trigger.\n\n\tWhere the archer was standing, there is only ash.");
break;
default:
t.user.dead=true;
t.logError("Unknown weapon code: "+t.user.weapon.type+". Weapon: "+t.user.weapon+".");
t.say("Your weapon is unknowable to the mere humans, so...");
}
}
});
t.th.start();
if (t.user.weapon.type<Cweapon.TYPE_HAND_TO_HAND || t.user.weapon.type==Cweapon.TYPE_ARCHERY || t.user.weapon.type>Cweapon.TYPE_FUTURE)
prepContinueButton(new OnClickListener ()
{
@Override
public void onClick (View v)
{
t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE;
t.user.commitSuicide();
}
});
else
prepContinueButton();
}
else
{
if (onMove(65))
return;
t.user.dead=true;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Run away!!!", "You try to run away, but you "+(t.config.easterEggs && t.config.ESEggs ? "take an arrow in the knee." : "get shot before you can get away."));
}
});
t.th.start();
prepContinueButton();
}
break;
case 28:
if (t.user.weapon.type==Cweapon.TYPE_MODERN || t.user.weapon.type==Cweapon.TYPE_FUTURE)
{
++stage;
runStage();
return;
}
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput("Do you take the bow?");
Button b=new Button(t);
b.setText("Yes");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run () {
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_ARCHERY, Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.LOW_POWER|Cweapon.ONE_ROUND_MAGAZINE, 0, "bow", null));
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("No");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 29:
if (onMove(80))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Weaponry is King", "Moving away from the cave yet again, you encounter an abandoned gunstore.\n\n\tInside, there are two shapes.");
}
});
t.th.start();
prepContinueButton();
break;
case 30:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Enter the store");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Continue away from the gunstore");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=37;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 31:
if (onMove(75+t.gen.nextInt(75)))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String monster;
if (t.gen.nextBoolean())
{
if (t.gen.nextBoolean())
monster="alligators";
else
monster="trolls";
}
else
{
if (t.gen.nextBoolean())
monster="goblins";
else
monster="dinosaurs";
}
t.say("The Gunstore", "Inside the gunstore, you\'re finally able to identify the shapes...\n\tThey\'re "+monster+"!\n\n\tYou eye the shelves, rife with weaponry you could have, if not for the "+monster+"...");
}
});
t.th.start();
prepContinueButton();
break;
case 32:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Fight the deadly creatures");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l);
b=new Button(t);
b.setText("Run away!!");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run ()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 33:
t.user.dead=(inputted==1);
if (!t.user.dead && onMove(60))
return;
if (!t.user.dead && t.user.weapon.type==Cweapon.TYPE_ARCHERY)
{
archeryMinigame((int)Math.round(25*(.5+(.5*t.config.difficultyMult))), 5+t.gen.nextGaussian());
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Archery", "You shoot one creature, felling it. The other lunges towards you...\n\tYou shoot an arrow at it, "+(t.user.dead ? "but miss." : "and hit it, square in between the eyes.\n\n\tIt falls to the ground, dead."));
}
});
t.th.start();
if (!t.user.dead)
t.user.gold.amount=(int)((99*Math.abs(t.gen.nextGaussian()))+1);
prepContinueButton();
break;
}
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("Run away!!", "You try to run, but the closer creature catches you in the doorway, and drags you back.\n\n\tThey make a delicious meal of you.");
else
{
switch (t.user.weapon.type)
{
case Cweapon.TYPE_SHARP:
if (t.user.weapon.characteristicSet(Cweapon.LEGENDARY)) // Excalibur check
t.determineUserDeath(.4); // Easier weighting for Excalibur
else
t.determineUserDeath(.75); // Traditional weighting
if (t.user.dead)
t.say ("Swordfight!", "You slash at one creature, then the other, trying to keep the creatures away from you, but they overwhelm you.");
else
t.say ("Slash and Stab", "You slash at one creature, barely slicing some flesh off.\n\tIt jumps back, stunned by the injury.\n\tYou take the opportunity to focus on the other one, barely managing to defeat it in time to swing around and duel the other.\n\n\tAfter killing it too, you stand in the center of the store, blood dripping off you, examining the shelves.");
break;
case Cweapon.TYPE_ARCHERY:
break;
case Cweapon.TYPE_MODERN:
if (t.determineUserDeath(.25))
t.say("A hit and a miss", "You place one shot cleanly between the eyes of the nearest creature.\n\tIt falls, dead.\n\n\tThe second creature lunges toward you, and you fire, hitting it in the shoulder, failing to kill it.");
else
t.say("Sharpshooter", "You cleanly shoot the near creature between the eyes, killing it instantly.\n\n\tYou spin around, and quickly shoot the far creature.\n\tIt stumbles, and you fire another round into it\'s skull.");
break;
case Cweapon.TYPE_FUTURE:
t.say(t.capitalize(t.user.weapon.name)+" kill", "You level your "+t.user.weapon.name+" at the near creature, calmly turning it to ash.\n\n\tThe second creature seems frightened.\n\n\n\tNo matter. You burn it too.");
break;
default:
t.say("Your weapon is unknown to this universe as of the time being, so...");
t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE;
t.user.commitSuicide();
}
}
}
});
t.th.start();
Thread.yield();
if (!t.user.dead)
{
Random gen=new Random();
t.user.gold.amount=(int)((99*Math.abs(gen.nextGaussian()))+1); // If the user is still alive,then they're going to the gunstore. It will be more persistent here.
t.user.clearedGunstore=true;
}
prepContinueButton();
break;
case 34:
if (inputted!=-1 && onMove(90))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (inputted==-1)
t.say("With the monsters defeated, you clean their remnants off of you, then survey your prize, walls and walls full of weapons"+(t.user.gold.amount==0 ? "" : ", and the contents of the cash register"+(t.user.gold.amount==1 ? ": " : ", which is oddly full of ")+t.user.gold)+".\n\n\tYou decide to grab a weapon, then depart.");
else if (t.user.clearedGunstore)
t.say("Return", "You return to the gunstore.\n\n\tLuckily, it\'s still lacking as far as things that want to kill and eat you are concerned.\n\n\tYou look to the walls, filled with more weapons than you can count, again resolving to grab one, then go back to the valley.");
else {
stage=29; // Return to the gunstore fight
runStage();
}
}
});
t.th.start();
prepContinueButton();
break;
case 35:
t.fadeout();
t.user.clearedGunstore=true; // Sanity setting.
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput("Choose your weapon");
Button b=new Button(t);
b.setText("Combat knife");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_SHARP, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.QUICK_RELOAD|Cweapon.WEAK_ROUNDS, .05, "combat knife", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Crossbow");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_ARCHERY, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .1, "crossbow", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Composite bow");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_ARCHERY, Cweapon.BOLT_FIRE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.LONG_RANGE|Cweapon.LOW_POWER|Cweapon.ONE_ROUND_MAGAZINE, .025, "composite bow", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
if (t.user.weapon.type!=Cweapon.TYPE_MODERN)
{
b.setText("Pistol");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, "pistol", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
b.setText(t.gen.nextBoolean() ? "Revolver" : "Colt .45");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ANCIENT|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .04, t.gen.nextBoolean() ? "Colt .45" : (t.gen.nextBoolean() ? "revolver" : "six-shot"), null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M16 Assault Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .1, "M16", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M4A1 Assault Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, .05, "M4", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("AK47 Assault Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .1, t.gen.nextBoolean() ? "AK47" : (t.gen.nextBoolean() ? "AK" : "Kalashnikov"), null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("AK74 Assault Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.QUICK_RELOAD, -.1, "AK74", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M14 Designated Marksman\'s Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, .075, "M14", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("FN FAL Designated Marksman\'s Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, -.025, "FN FAL", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Dragunov SVU Designated Marksman\'s Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .01, "SVU", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Zastava M76 Designated Marksman\'s Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, "Zastava", null));
t.user.weapon.strengthModifier=.25; // Here to circumvent the block on construction of weapons this strong
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Barrett M95 Sniper Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .05, "Barrett .50", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Barrett XM109 Sniper Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .1, "Barrett grenade-firing sniper rifle", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("L115A3 AWM Sniper Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .2, "L115", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Anzio 20mm Anti-Material rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .25, "extra heavy rifle", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("P90 submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_CALIBER|Cweapon.QUICK_RELOAD, .5, "P90", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("MP5K submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .1, "MP5K", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("UMP45 Submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .02, "UMP45", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Thompson Submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String weapon;
if (t.gen.nextBoolean())
{
if (t.gen.nextBoolean())
weapon="Annihilator";
else
weapon="Tommy gun";
}
else
{
if (t.gen.nextBoolean())
weapon="M1928";
else
weapon="Thompson";
}
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ANCIENT|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .1, weapon, null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Uzi submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, .075, "Uzi", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("AA-12 Shotgun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, -.01, "AA-12", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("SPAS-12");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .05, "SPAS-12", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Remington 870 Shotgun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .1, "Remington 870", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("KS-23");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .15, "KS-23", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Custom-made 3 gauge shotgun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.SLOW_RELOAD, .1, "custom shotgun", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M27-IAR");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE, .05, "M27", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("HK21");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE, -.075, "HK21", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("LSAT");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.LONG_RANGE, .075, "LSAT", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M60");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CUMBERSOME|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, .025, "M60", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
if (t.config.triggerEgg(.5+(t.gen.nextDouble()/2)))
{
b=new Button(t);
b.setText("M134");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE, t.gen.nextBoolean() ? "minigun" : "M134", null));
t.user.weapon.strengthModifier=.5;
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
b=new Button(t);
b.setText("RPG-7 Launcher");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, "RPG", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Bazooka");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .01, "bazooka", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Panzerschreck rocket launcher");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .05, "panzerschreck", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Shoulder launched Multipurpose Assault Weapon");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .1, "SMAW", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("FIM-92");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE, .075, "Stinger", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M67 Fragmentation Grenade");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD, .175, "frag", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("MK-54");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_NUCLEAR, Cweapon.LIGHT, "Davy Crockett nuke", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Lightsaber");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.config.triggerEgg(.5-(t.gen.nextDouble()/2))) // We do NOT always want a working lightsaber.
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_FUTURE, Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT, "lightsaber", null));
else
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_BLUNT, Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT|Cweapon.LEGENDARY, (t.gen.nextBoolean() ? "broken" : "model")+" lightsaber", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Keep your current weapon");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 36:
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (inputted==-1)
t.say("You examine your new "+t.user.weapon+", and put your old "+t.user.weapon.backup+" away, making room for your new main weapon, but still keeping your backup within reach.");
else
t.say("You decide your "+t.user.weapon+" is better than any weapon in the gunstore, and move off toward the valley.");
}
});
t.th.start();
prepContinueButton();
break;
case 37:
if (onMove(58))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("The Valley", "You move away from the gunstore.\n\n\tAfter a good amount of walking, you finally enter the lush valley.\n\tYou find yourself surrounded by greenery and life, but the valley is much smaller than it seemed from a distance. Unfortunately, you need to leave it.\n\n\n\tYou search for a way away.\n\n\tStraight away from the path that leads to the gunstore is a downtrodden set of stones, almost as a staircase, leading to a familiar skyline.\n\n\tFacing it, you see smoke out of the corner of your eye. Turning to your right, you see the light of a huge, hellish inferno on the horizon. You can almost see the fires. A large highway leads directly towards this pit.");
}
});
t.th.start();
prepContinueButton();
break;
case 38:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Go to familiarity");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Take the highway");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Return to the gunstore, and grab another weapon");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
stage=34;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 39:
if (inputted==0)
{
if (onMove(1+t.gen.nextInt(10)))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String str=new String();
boolean say=true;
if (t.user.weapon.type<=Cweapon.TYPE_BLUNT)
{
if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT) // We do not want to discuss trying to walk the chain of backups with the user. Just kill them.
{
t.user.dead=true;
say=false; // Prevent the usual speech.
t.say("Familiarity", "You barely manage to reach the summit of the staircase, gazing upon a line of destroyed buildings.\n\n\tAmong the ruined houses and fragmented skyscrapers, you see Gandalf running towards you, as if he was running late to meet you thanks to your choice of weapons, and miss the beast which destroys you.");
}
else
{
str=", watching your "+t.user.weapon+" slip out of your hand, seemingly floating away.\n\n\tYou feel yourself start to come to earth";
t.user.weapon=t.user.weapon.backup; // Remove the primary from existence. We don't need any TYPE_BLUNTs floating around.
}
}
else if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT) // We know we don't need to walk the chain of weapon backups, since the prior if specifies that we already have a valid weapon in hand.
{
str=", gazing at your "+t.user.weapon.backup+" as it drifts out of its sheath and disappears.\n\n\tYou watch as you float away from familiarity";
if (t.user.weapon.backup.backup!=null && t.user.weapon.backup.backup.type>Cweapon.TYPE_BLUNT) // Transparently allow a valid weapon to be swapped in if its only one layer away from being valid.
t.user.weapon.backup=t.user.weapon.backup.backup;
else // Just remove the existence of a backup
t.user.weapon.backup=null;
}
if (say)
t.say("Familiarity", "You go to familiarity.\n\n\n\n\tAs you reach the summit of the stairs, you see a destroyed line of buildings, from tall skyscrapers fallen into pieces, to houses in shambles.\n\n\tBefore you can continue further, Gandalf appears!\n\tHe yells,\n\n\t\tNo!\n\t\tYou must not!\n\t\tYour journey is not complete!\n\n\tBefore you can reply, he slaps you.\n\n\tYou go flying"+str+", and land in the pits.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=41;
runStage();
}
});
t.th.start();
}
});
}
else
{
if (onMove(80))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("The Highway", "You take the Highway towards the fiery pits.\n\n\tAlong the way, you see a shadow!\n\n\tIt approaches you menacingly.");
}
});
t.th.start();
prepContinueButton();
}
break;
case 40:
runShadows((byte)((t.config.difficultyMult*t.gen.nextInt(10))+3), (byte)0, (byte)0);
break;
case 41:
if (onMove(85))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say(t.gen.nextBoolean() ? "The Pits" : "Hell", "You arrive in the fiery pits.\n\n\tYour first impression of them is hellish, full of fire everywhere, and generally not the place any person should ever be.\n\n\tSomehow, your second impression is even worse.\n\n\tOff in the distance, you see a structure of some sort, surrounded by shadows: Probably their home.\n\n\tBesides that, there is little more than ruins to be explored.");
}
});
t.th.start();
prepContinueButton();
break;
case 42:
runPits((byte)(t.gen.nextInt(6)+3), (byte)0, (byte)0, (byte)0, false);
break;
default:
t.logWarning("Unknown stage: "+stage);
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
String who=t.gen.nextBoolean() ? "Author" : "Programmer";
String occurrence;
if (t.gen.nextBoolean())
{
if (t.gen.nextBoolean())
occurrence="a meteor appears, and flattens you.";
else
occurrence="a lightning bolt strikes you, and fries you.";
}
else
{
if (t.gen.nextBoolean())
occurrence="a dinosaur appears, and eats you.";
else
occurrence="a nuclear bomb appears under your feet and explodes, vaporizing you.";
}
t.say("The End of the World...?","The "+who+" has run out of ideas, so "+occurrence);
}
});
t.th.start();
t.user.dead=true;
prepContinueButton();
}
++stage;
if (stage%(t.gen.nextInt(5)+2)==0 || t.gen.nextInt(100)==0)
t.config.requestDifficultyUpdate();
else
t.config.updateDifficultyOnce();
}
public static void signalGameContinue ()
{
if (!Thread.interrupted())
t.runOnUiThread (new Runnable ()
{
@Override
public void run()
{
View v=t.findViewById(R.id.gameContinueButton);
if (v==null)
{
t.displayHandler.removeMessages(1);
return;
}
((TextView)v).setTextColor(Color.GREEN);
}
});
}
public static void unSignalGameContinue () // Undoes the above signaling. Necessary for the use of sayWhat() in non-say() contexts.
{
if (!Thread.interrupted())
t.runOnUiThread (new Runnable ()
{
@Override
public void run()
{
View v=t.findViewById(R.id.gameContinueButton);
if (v==null)
{
t.displayHandler.removeMessages(1);
return;
}
((TextView)v).setTextColor(Color.RED);
}
});
}
public void runArthur(final byte stage, String input)
{
t.user.isArthur=true;
switch (stage)
{
case 0:
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Bridge of Death", "What is your quest?");
t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
EditText ev=new EditText(t);
ev.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus && t.config.fullscreen)
{
t.setUi();
TextView tv=((TextView)t.findViewById(R.id.gameTitle));
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams();
int result=0;
int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = t.getResources().getDimensionPixelSize(resourceId);
}
lp.topMargin=result+10;
tv.setAlpha(1);
}
}
});
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("What is your quest?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label.
ev.setImeOptions(EditorInfo.IME_ACTION_SEND);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
View v=t.findViewById(R.id.gameLayout);
if (v!=null)
((LinearLayout)v).addView(ev);
ev.requestFocus();
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open.
t.setUi(); // Doubly ensure sanity. See above comment.
ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter.
{
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event)
{
if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL)
{
view.setOnEditorActionListener(null);
final EditText ev=(EditText)view;
ev.setVisibility(View.GONE);
// Close the soft keyboard, now that there's nothing for it to write to.
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0);
final String str=ev.getText().toString().trim();
((TextView)t.findViewById(R.id.gameText)).append("\n\n\"" + str + "\"\n\n");
t.setUi();
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
runArthur((byte)1, str);
}
});
t.th.start();
return true;
}
return false;
}
});
t.config.computerPaused=true;
}
});
}
});
t.th.start();
break;
case 1:
if (!"To seek the Holy Grail".equalsIgnoreCase(input))
{
t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge.");
t.user.dead=true;
prepContinueButton();
return;
}
t.sayWhat("What is the air-speed velocity of an unladen swallow?");
t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
EditText ev=new EditText(t);
ev.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus && t.config.fullscreen)
{
t.setUi();
TextView tv=((TextView)t.findViewById(R.id.gameTitle));
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams();
int result=0;
int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = t.getResources().getDimensionPixelSize(resourceId);
}
lp.topMargin=result+10;
tv.setAlpha(1);
}
}
});
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("What is the air-speed velocity of an unladen swallow?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label.
ev.setImeOptions(EditorInfo.IME_ACTION_SEND);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
View v=t.findViewById(R.id.gameLayout);
if (v!=null)
((LinearLayout)v).addView(ev);
ev.requestFocus();
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open.
t.setUi(); // Doubly ensure sanity. See above comment.
ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter.
{
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event)
{
if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL)
{
view.setOnEditorActionListener(null);
final EditText ev=(EditText)view;
ev.setVisibility(View.GONE);
// Close the soft keyboard, now that there's nothing for it to write to.
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0);
final String str=ev.getText().toString().trim();
((TextView)t.findViewById(R.id.gameText)).append("\n\n\""+str+"\"\n\n");
t.setUi();
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
runArthur((byte)2, str);
}
});
t.th.start();
return true;
}
return false;
}
});
t.config.computerPaused=true;
}
});
break;
case 2:
if (!("What do you mean? An African or European swallow?".equalsIgnoreCase(input) || "What do you mean? African or European swallow?".equalsIgnoreCase(input)))
{
t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge.");
t.user.dead=true;
prepContinueButton();
return;
}
t.sayWhat("What? I don\'t know that!\n\tAuuuuuuuugh!\n\n\n\n");
t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE);
t.snooze(2500);
t.sayWhat("How do you know so much about swallows?");
t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
EditText ev=new EditText(t);
ev.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus && t.config.fullscreen)
{
t.setUi();
TextView tv=((TextView)t.findViewById(R.id.gameTitle));
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams();
int result=0;
int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = t.getResources().getDimensionPixelSize(resourceId);
}
lp.topMargin=result+10;
tv.setAlpha(1);
}
}
});
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("How do you know so much about swallows?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label.
ev.setImeOptions(EditorInfo.IME_ACTION_SEND);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
View v=t.findViewById(R.id.gameLayout);
if (v!=null)
((LinearLayout)v).addView(ev);
ev.requestFocus();
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open.
t.setUi(); // Doubly ensure sanity. See above comment.
ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter.
{
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event)
{
if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL)
{
view.setOnEditorActionListener(null);
final EditText ev=(EditText)view;
ev.setVisibility(View.GONE);
// Close the soft keyboard, now that there's nothing for it to write to.
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0);
final String str=ev.getText().toString().trim();
((TextView)t.findViewById(R.id.gameText)).append("\n\n\""+str+"\"\n\n");
t.setUi();
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
runArthur((byte)3, str);
}
});
t.th.start();
return true;
}
return false;
}
});
t.config.computerPaused=true;
}
});
break;
case 3:
if (!"Well, you have to know these things when you\'re a king you know".equalsIgnoreCase(input))
{
t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge.");
t.user.dead=true;
prepContinueButton();
return;
}
t.sayWhat("Ohh.");
prepContinueButton(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.name="Arthur"; // So the egg doesn't trigger again.
t.game.stage=0;
t.game.runStage();
}
});
t.th.start();
}
});
break;
}
}
public void runShadows(final byte number, final byte stage, final byte input)
{
if (t.config.autosave)
{
(new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occurring at once. Consider naming the save thread.
{
@Override
public void run()
{
t.saveGame();
}
})).start();
}
if (number==0)
runStage();
else
{
if (stage==0)
{
t.fadeout();
if (t.user.weapon.type<=Cweapon.TYPE_BLUNT)
{
if (t.user.weapon.backup==null || t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT)
{
t.user.dead=true;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Unprepared", "You prepare to engage the fearsome figure with your "+t.user.weapon+", but it only seems to laugh.\n\n\tDiscarding your weapon, you ready your "+(t.user.weapon.backup==null ? "body for hand-to-hand combat" : t.user.weapon.backup)+", and charge.");
}
});
t.th.start();
prepContinueButton();
return;
}
else
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Always prepared", "You prepare to fight the spirit with your "+t.user.weapon+".\n\n\n\tIt seemingly finds your effort humorous, as it pauses its approach to laugh.\n\n\n\n\tThinking your "+t.user.weapon.backup+" more suited to the task, you discard the "+t.user.weapon+", throwing it to the side and away from your presence, and draw your "+t.user.weapon.backup+".\n\n\tThe shadow thinks this a more serious threat, as it stops its laughter and prepares itself to engage you.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.user.weapon=t.user.weapon.backup;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, stage, input);
}
});
t.th.start();
}
});
return;
}
}
else if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("In your rush to prepare to defend yourself against the strange and mysterious figure before you, you fail to notice that your "+t.user.weapon.backup+" has slipped out of its holster.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (t.user.weapon.backup.backup!=null && t.user.weapon.backup.backup.type>Cweapon.TYPE_BLUNT)
t.user.weapon.backup=t.user.weapon.backup.backup;
else
t.user.weapon.backup=null;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, stage, input);
}
});
t.th.start();
}
});
return;
}
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
doCommitSuicide=true;
Button b=new Button(t);
b.setText("Fight the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" with your primary weapon, a "+t.user.weapon);
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, (byte)1, (byte)0);
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l, new Runnable()
{
@Override
public void run()
{
runShadows(number, stage, input);
}
});
b=new Button(t);
b.setText((t.gen.nextBoolean() ? "Run away" : "Flee")+" from the "+(t.gen.nextBoolean() ? "ghostly" : "shadowy")+" vision before you");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, (byte)1, (byte)1);
}
});
t.th.start();
}
});
l.addView(b);
if (t.config.triggerEgg((t.gen.nextInt(10)+1)/11))
{
b=new Button(t);
b.setText("Make friends with the creature");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, (byte)1, (byte)2);
}
});
t.th.start();
}
});
l.addView(b);
}
}
});
}
else
{
t.displayHandler.removeMessages(1);
if (Thread.interrupted() || onMove(t.gen.nextInt(85)+1))
return;
switch (input)
{
case 0:
Runnable r;
switch (t.user.weapon.type)
{
case Cweapon.TYPE_SHARP:
t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT)*.5);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("Swordfight", "You swing at the "+(t.gen.nextBoolean() ? "shadow" : "vision")+", and miss.\n\n\tBefore you can ready yourself, the shadow consumes you, and you are no more.");
else
{
String word;
switch (t.gen.nextInt(3))
{
case 0:
word="even ";
break;
case 1:
word="yet ";
break;
case 2:
word="";
break;
default:
word="considerably ";
}
t.say("Close call", "You swing your sword, and connect.\n\n\n\tThe moment your sword touches the "+(t.gen.nextBoolean() ? "shadow" : "shape")+", the creature dissolves into a swirl of smoke, and your sword continues as if it wasn\'t there.\n\n\n\n\n\tYou shiver, questioning reality, and your sanity, "+word+"more than you already were.\n\n\n\n\n\n\n\tTrying to walk it off, you decide to continue along the highway.");
}
}
};
break;
case Cweapon.TYPE_ARCHERY:
t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE), 3);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("Bowman", "You ready your "+t.user.weapon+", and aim it at the shadow.\n\tJust as you loose the arrow, almost as if it were inside your mind, the shadow dodges, and lunges at you.\n\n\tThe last thing you hear is your "+t.user.gold+" spilling onto the highway.");
else
t.say("Deadeye", "You bring your "+t.user.weapon+" up to bear, and fire it at the shadow.\n\n\n\tThe projectile soars to the shadow, hitting it.\n\n\tThe moment it touches the vision, the shadow disappears into a swirl of smoke, and the arrow falls straight to the ground, as if it had hit an invisible wall.\n\n\n\n\tBy the time you reach it, it\'s gone.\n\n\n\n\n\tYou shiver.\n\n\tYou wonder how sane you are...");
}
};
break;
case Cweapon.TYPE_MODERN:
t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.QUICK_RELOAD), 4);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
if (t.config.triggerEgg(6))
t.say("Alas, poor Yorick...","...I knew that one once.\n\n\tThey also called that adventurer \""+t.user+"\".\n\n\n\tThen, one day, a shadow appeared along the Highway to Hell, and the "+t.user.weapon+" the poor fool was carrying jammed, and no more was poor Yorick.");
else
t.say("A shot and a miss", "You take aim, your sights leveled at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tJust as you pull the trigger, the pits rumble with fiery power, shaking the ground, making you miss.\n\n\n\tOne day, years later, when the pits will have cooled, a child will come across the spot where the shadow consumed you, and all "+(t.gen.nextBoolean() ? "he" : "she")+" will find of you is your "+t.user.weapon+".");
}
else
t.say("Sharpshooter","You level your "+t.user.weapon+" directly at the shadow, and fire.\n\n\tThe round hits it, and the shadow disappears into a swirl of smoke.\n\n\tThe fired round clatters straight to the ground, as the smoke dissipates.\n\n\n\tYou walk over to it, but you can\'t find the round.\n\n\tYou can\'t quite shake the feeling that what you know isn\'t real.");
}
};
break;
case Cweapon.TYPE_NUCLEAR:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("Doomsday", "You get out your "+t.user.weapon+", arm it, set the timer to one second, and start it.\n\n\tFrom familiarity, the shopkeepers gaze at the mushroom cloud from where you once stood, as the shadow of a dragon looms behind them.");
}
};
break;
case Cweapon.TYPE_FUTURE:
t.user.dead=false;
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY))
t.say("Jedi","You meet the "+(t.gen.nextBoolean() ? "shadow" : "vision")+", and swing your lightsaber.\n\n\tThe shadow disappears into smoke at the edges of your vision as the "+t.user.weapon+" slices through it.\n\n\tYou continue, not particularly caring if it was real.");
else
t.say(t.capitalize(t.user.weapon.toString())+" über alles", "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\tBy the time the splash from the impact of the shot clears, the shadow is gone, but strangely there\'s no ash.\n\n\tYou ignore it, not caring about your own sanity.");
}
};
break;
default:
t.logError("Invalid weapon code: "+t.user.weapon.type);
t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE;
r=new Runnable()
{
@Override
public void run()
{
t.say("Unknown","Your weapon "+(t.user.weapon.name==null || "".equals(t.user.weapon.name) ? "" : ", a "+t.user.weapon.name)+", is unknown to the universe, so...");
}
};
}
t.th=new Thread(r);
t.th.start();
prepContinueButton(new View.OnClickListener()
{
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.type==Cweapon.TYPE_USED_FOR_CONVENIENCE)
t.user.commitSuicide();
else if (t.user.dead)
{
t.game.stage=-1;
t.game.runStage();
}
else
runShadows((byte)(number-1), (byte)0, input);
}
});
t.th.start();
}
});
break;
case 1:
t.user.dead=true;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Deserter", "You try to run, but the shadow disappears, and reappears in front of you.");
}
});
t.th.start();
prepContinueButton();
break;
case 2:
t.user.dead=true;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.config.triggerEgg(0.5))
{
String[] weapons=new String[t.gen.nextInt(3)+3];
for (int i=0; i<weapons.length; ++i)
{
switch (t.gen.nextInt(8))
{
case 0:
weapons[i]="sword";
break;
case 1:
weapons[i]="crossbow";
break;
case 2:
weapons[i]="pistol";
break;
case 3:
weapons[i]="rifle";
break;
case 4:
weapons[i]="machine gun";
break;
case 5:
weapons[i]=((t.user.weapon.type!=Cweapon.TYPE_NUCLEAR && t.user.weapon.type!=Cweapon.TYPE_FUTURE) ? t.user.weapon.name : "strangely frightening weapon");
break;
case 6:
weapons[i]="M16";
break;
case 7:
weapons[i]="P90";
break;
default:
weapons[i]="sniper rifle";
}
}
String message="";
for (int i=1; i<weapons.length; ++i)
{
for (int n=0, m=(t.gen.nextInt(4)+2); n<m; ++n)
message+="\n";
message+="\tAfter a while of wandering along the Highway, yet another adventurer appears, this time with a "+weapons[i]+"!\n\n\tBegrudgingly, you kill "+(t.gen.nextBoolean() ? "him" : "her")+", and continue walking along the Highway, caring even less about the humans.";
}
t.say("Assimilation", "You try to make friends with the "+(t.gen.nextBoolean() ? "shadow" : "vision")+"...\n\n\tMiraculously, it accepts you!\n\n\n\tIt escorts you to the pits, where you are brought to the shadow headquarters.\n\n\tThe "+(t.gen.nextBoolean() ? "shadows" : "mystical beings")+" perform some sort of ritual, and you watch as your body slips away from you as you become one of them.\n\n\n\tYou move out to the Highway, and immediately, you\'re attacked by an adventurer with a "+weapons[0]+"!\n\n\tYou try to befriend "+(t.gen.nextBoolean() ? "him" : "her")+", but you\'re forced to retaliate.\n\n\tYou can\'t help but lose some faith in humans."+message+"\n\n\tSuddenly, you find an adventurer!\n\t"+(t.gen.nextBoolean() ? "He" : "She")+" tries to run, but you can\'t help but kill any adventurer in your path.\n\n\n\tBarely afterward, another comes along, and tries to make friends.\n\n\tPerhaps if you hadn\'t spent so long on the Highway, you\'d accept, but now...\n\tYou kill "+(t.gen.nextBoolean() ? "him" : "her")+".\n\n\n\tThree days later, an adventurer appears with a "+(t.gen.nextBoolean() ? "raygun" : "lightsaber")+", and ends you.\n\n\n\tGandalf nods in approval, as you disappear into a swirl of smoke.");
}
else
{
String address;
switch (t.gen.nextInt(3))
{
case 0:
address="shadow";
break;
case 1:
address="vision";
break;
case 2:
address="other";
break;
default:
address="creature";
}
t.say("Friendship", "Friends are not so easily earned.\n\n\tThe "+address+" is not interested.");
}
}
});
t.th.start();
if (t.config.easterEggs)
t.delay(50); // If the easter egg is triggered, processing might take some time. We delay the UI work just to be sure.
prepContinueButton();
}
}
}
}
public void runPits(final byte number, final byte stage, final byte input, final byte input2, final boolean hasAssaultedHQ)
{
if (t.config.autosave)
{
(new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occurring at once. Consider naming the save thread.
{
@Override
public void run()
{
t.saveGame();
}
})).start();
}
if (number==0)
runStage();
else
{
switch(stage)
{
case 0: // Stage 0: User input on direction
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
if (!hasAssaultedHQ)
{
b.setText("Mount an assault on the House of Shadows");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)1, (byte)0, input2, true);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
if (t.gen.nextBoolean())
{
b.setText("Explore to your left");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)1, (byte)1, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
if (t.gen.nextBoolean())
{
b.setText("Continue straight ahead");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)1, (byte)2, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
if (t.gen.nextBoolean())
{
b.setText("Explore to your right");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)1, (byte)3, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
b.setText("Make your way to the depression at the center of the pits");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits((byte)0, stage, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 1: // Stage 1: Describe findings
if (onMove(111))
return;
switch (input)
{
case 0: // Input 0: Assault HoS
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say(t.gen.nextBoolean() ? "Assault" : "Infiltration", "You charge the House of Shadows.\n\n\tAs you approach, you find more and more shadows.\n\n\tYou suspect that they know you\'re coming.\n\n\tYou try to sneak in, planning to use stealth to kill each shadow alone.\n\n\tUnfortunately, you\'re caught trying to enter by a sentry group of three shadows.\n\n\n\tInside the House, you see an object.\n\n\tUpon closer examination, you can read the label: \"US Army M183 Demolition Charge: 20 lbs.\"\n\n\tFrom what little you know about explosives, you think that that charge would be large enough to turn the House of Shadows into one large fragmentation grenade.\n\n\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadows" : "visions")+" ready for battle.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)2, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
break;
case 1: // Input 1: Explore left
if (t.gen.nextBoolean())
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Explorer", "You head to an abandoned shop in ruins...\n\n\tBut a shadow catches you along the way!");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)2, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
runPits(number, (byte)100, input, input2, hasAssaultedHQ);
break;
case 2: // Input 2: Continue straight
if (t.gen.nextBoolean())
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Conquest", "You march straight ahead, towards the destroyed remains of a household.\n\n\n\tA "+(t.gen.nextBoolean() ? "shadow" : "figure")+" blocks your path, guarding the ruined house as if it had been "+(t.gen.nextBoolean() ? "his" : "her")+" home.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)2, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
runPits(number, (byte)100, input, input2, hasAssaultedHQ);
break;
case 3: // Input 3: Explore right
if (t.gen.nextBoolean())
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Pits: The Final Frontier", "You travel towards what appears to be a bank.\n\n\tJust as you approach, a shadow opens the door.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)2, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
runPits(number, (byte)100, input, input2, hasAssaultedHQ);
break;
}
break;
case 2: // Stage 2: Combat
Runnable r;
switch (input)
{
case 0: // Input 0: Assault HoS
r=new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
doCommitSuicide=true;
Button b=new Button(t);
b.setText("Fight the trio of shadows with your primary "+t.user.weapon);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)0, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l, new Runnable()
{
@Override
public void run()
{
runPits(number, stage, input, input2, hasAssaultedHQ);
}
});
b=new Button(t);
b.setText("Make a run for the demolition charge");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)1, hasAssaultedHQ);
}
});
}
});
l.addView(b);
b=new Button(t);
b.setText(t.gen.nextBoolean() ? "Run away!" : "Flee");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
}
};
break;
case 1: // Input 1: Explore left
case 2: // Input 2: Continue straight
case 3: // Input 3: Explore right - All these are duplicate cases.
r=new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
doCommitSuicide=true;
Button b=new Button(t);
String word;
switch (t.gen.nextInt(4))
{
case 0:
word="shadow";
break;
case 1:
word="figure";
break;
case 2:
word="vision";
break;
case 3:
word="monster";
break;
default:
word="creature";
}
b.setText("Fight the "+word+" with your primary "+t.user.weapon);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)0, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l, new Runnable()
{
@Override
public void run()
{
runPits(number, stage, input, input2, hasAssaultedHQ);
}
});
b=new Button(t);
b.setText(t.gen.nextBoolean() ? "Run away" : "Flee");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)1, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
}
};
break;
default:
r=new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput("Your situation is unknown");
doCommitSuicide=true;
Button b=new Button(t);
b.setText("Try this again");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)0, (byte)0, (byte)0, true);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Be done with it");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.commitSuicide();
}
});
t.th.start();
}
});
l.addView(b);
}
};
}
t.fadeout();
t.runOnUiThread(r);
break;
case 3: // Stage 3: Results of combat
switch (input)
{
case 0:
switch (input2)
{
case 0:
if (t.user.weapon.type==Cweapon.TYPE_ARCHERY && .5>(t.config.difficultyMult*.75*t.user.weapon.getAbsoluteStrength()))
{
archeryMinigame((int)Math.ceil(t.gen.nextInt(40)+(t.config.difficultyMult*10)+5), ((20*(1-t.config.difficultyMult))+5)/5);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String title;
switch (t.gen.nextInt(3))
{
case 0:
title="Archer";
break;
case 1:
title="Bowman";
break;
case 2:
title="Outnumbered";
break;
default:
title="Outdone by the dark";
}
switch (t.gen.nextInt(3))
{
case 0:
t.say(title, "You turn to face the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", but you\'re immediately killed by the leading shadow.");
break;
case 1:
t.say(title, "You draw your "+t.user.weapon+", turning against the "+(t.gen.nextBoolean() ? "shadows" : "figures")+", shooting the leading one, and turning it to swirling smoke, but the others reach you before you can ready another shot.");
break;
case 2:
t.say(title, "You quickly turn and fire an arrow at the lead "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it into a cloud of smoke. Quickly, you dodge to the side of the remaining two attacks.\n\n\tYou ready and fire a second shot, eliminating another opponent, but the last defeats you.");
break;
default:
Log.wtf("Cgame at House of Shadows", "Invalid return from Random.nextInt()");
t.say(title, "The enemies that stand before you overpower you.");
}
}
else
t.say("Veteran", "Despite the odds against you, your archery skills prevail in a tale that will be sung throughout time: You shoot the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and dodge the attack of the next without pausing to watch the smoke swirl away.\n\n\tIn the blink of an eye, the second "+(t.gen.nextBoolean() ? "shadow" : "vision")+" recuperates, but you ready your "+t.user.weapon+" even faster, and shoot it too.\n\n\tThe third is upon you quickly, and you defend yourself by blocking with your "+t.user.weapon+", which gets tossed aside in the process.\n\n\n\tBefore the final "+(t.gen.nextBoolean() ? "shadow" : "creature")+" can "+(t.gen.nextBoolean() ? "attack" : "assault")+" you, you draw "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" from your stockpile, and stab it.\n\n\tIt vanishes in a swirling cloud of smoke.\n\n\tYou note your spent ammunition has disappeared entirely.\n\n\n\tBrushing this fact aside, you turn your attention to the House of Shadows.");
}
});
t.th.start();
if (t.user.dead)
prepContinueButton();
else
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)4, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
{
boolean undead=false;
switch (t.user.weapon.type)
{
case Cweapon.TYPE_SHARP:
t.determineUserDeath((t.user.weapon.getUnneededFlags(Cweapon.CLOSE_RANGE_ONLY, 5)+(1-t.user.weapon.getNeededFlags(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, 2)))*.99);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
switch (t.gen.nextInt(3))
{
case 0:
t.say("Outnumbered and outdone", "You face the creatures with your "+t.user.weapon+", fending them away, but one gets past you long before you can strike any.");
break;
case 1:
t.say("Death "+(t.gen.nextBoolean() ? "Unbounded" : "knows no bounds"), "You swing your sword at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and, miraculously, connect.\n\n\tThe lead shadow disappears in a swirl of smoke, and you turn to face the next, but you\'re caught from behind by the last.");
break;
case 2:
t.say("The Darkness of Death", "You move quickly, as quickly as you ever have in your life.\n\n\tYou turn the leading shadow into a swirl of smoke, then the second.\n\nThe third, however, evades your swing, not letting it touch, and ends you.");
break;
default:
Log.wtf("Cgame at House of Shadows", "Invalid result from Random.nextInt()");
t.say("Nonexistence", "You corrupt the state of the Universe and cease to exist.");
}
}
else
t.say(t.gen.nextBoolean() ? "Swordsman" : "Sword master", "You swing your sword as fast as humanly possible, turning one, then two, "+(t.gen.nextBoolean() ? "shadows" : "figures")+" into swirling smoke.\n\n\tThe last shadow charges toward you, but your sword nicks it, and it disappears.\n\n\tA booming voice, almost like Gandalf\'s, echoes from the clouds:\n\n\t\tWhy do you still carry that puny "+t.user.weapon+"??\n\t\tFind a new weapon.\n\t\tNow.\n\n\n\n\n\tYou turn your attention away from the voice, and to the House of Shadows.");
}
};
break;
case Cweapon.TYPE_ARCHERY:
t.determineUserDeath(.75*t.user.weapon.getAbsoluteStrength());
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String title;
switch (t.gen.nextInt(4))
{
case 0:
title="Archer";
break;
case 1:
title="Bowman";
break;
case 2:
title="Outnumbered";
break;
default:
title="Outdone by the dark";
}
switch (t.gen.nextInt(3))
{
case 0:
t.say(title, "You turn to face the shadows, but they easily defeat you before you get off a single shot.");
break;
case 1:
t.say(title, "You spin to face your enemy, and fire a single "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\tYour aim "+(t.gen.nextBoolean() ? "is true" : (t.gen.nextBoolean() ? "is that of a master" : "is masterful"))+", turning the leader of the trio into a swirl of smoke.\n\n\tHowever, before you can ready yourself again, the other two eliminate you.");
break;
case 2:
t.say(title, "You load one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+", and thoughtlessly fire it at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou\'ve practiced your archery considerably, and the shot flies directly into its target.\n\n\tYou ignore the sight as your opponent disappears into a swirling cloud of shadowy smoke, and dodge the advance of your second adversary, which you shoot shortly afterwards.\n\n\n\tAlas, you lost track of the third shadow, which comes from behind you, and kills you.");
break;
default:
Log.wtf("Cgame at the House of Shadows", "Invalid output from Random.nextInt()");
}
}
else
t.say((t.config.GoTEggs && t.config.triggerEgg(.8)) ? "Lightbringer" : "Defeater of Shadows", "You turn, snappily aiming your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and shooting it.\n\n\tPaying it no attention as it disappears into swirling smoke.\n\n\tInstead, as if by instinct, you roll towards the House of Shadows."+(t.gen.nextBoolean() ? "" : "\n\n\tYou quickly recover from the pain of your miscalculation after you slam into the outer wall.")+"\n\n\tWithout taking the time to stand, you adjust your aim, directly at the second enemy.\n\n\tQuickly, you release your shot, sending "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" flying into the second shape, then clattering to the ground as your opponent swirls away.\n\n\n\tThe third charges, but you pull one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" from your reserves, and drive it through your final adversary, noting the lack of resistance as it goes through.\n\n\tYou watch the remains of your opponent swirl away, and note your two fired shots have vanished.");
}
};
break;
case Cweapon.TYPE_MODERN:
final targetingMinigame.output res=aimMinigame();
undead=(res.type==targetingMinigame.output.BULLSEYE);
final String title=res.toString();
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.AUTOMATIC))
{
t.user.dead=(res.distance/(.8*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5);
if (t.user.dead)
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You fire a burst of bullets towards the shadows, but your aim is off, and the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" end you.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You turn at the shadows, and fire a burst of automatic fire. One shot hits the nearest "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it to a swirl of smoke, but the remaining two intercept you.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You fire at the shadows, grazing one, turning it to swirling smoke, and barely hitting another.\n\n\tThe last consumes you as the second disappears.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You fire at the shadows, hitting one with a solid shot, and "+(t.gen.nextBoolean() ? "turning" : "converting")+" it into a swirling cloud.\n\n\tAnother bullet strikes the second, eliminating it as well, but "+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "the recoil of your "+t.user.weapon+" throws off your aim." : "the last shadow moves out of your sights too quickly."));
break;
case targetingMinigame.output.GOOD:
t.say(title, "You hit two shadows with near perfect shots.\n\n\tThe shadows disappear into swirling smoke, as the third approaches you.\n\n\n\n\n\tYou quickly twist, aiming directly at the last shadow.\n\n\n\n\n\n\tYou pull the trigger, just as it reaches you."+(t.config.triggerEgg(.5) ? "\n\n\n\tThe shadow of a dragon looms over the pits, the rush of air stirring everything around, as you both become swirling smoke, and "+t.user.gold+", along with your "+t.user.weapon+", clatter to the ground." : ""));
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You hit the first two shadows with perfect shots, but find that the third seems to have disappeared.\n\n\tYou twist and turn, searching for it, "+(t.config.triggerEgg(.75) ? "and feel a thud, and a weight.\n\n\tYou fall, watching the shadow run, and attempt to give chase.\n\n\tSoon, it leaves your sight. Contented, you enter the House of Shadows, grabbing the detonator, assuming that the charge is at it was.\n\n\n\n\tYou walk clear of the House, wondering why you feel as if there is a huge weight on your back.\n\n\n\tYou realize that the shadow planted the charge on your back a moment too late, as you trigger the explosive." : "and soon finding it, right behind you.\n\n\tYou dodge its lunge, dropping your "+t.user.weapon+" in your haste to "+(t.gen.nextBoolean() ? "escape" : "survive")+", and, just as you think you\'ve escaped, you trip, rolling down a hill, coming to a stop in a ditch full of a hundred shadows."));
break;
case targetingMinigame.output.BULLSEYE:
t.user.dead=false;
t.say(title+", despite impossibility", "You fire three utterly perfect shots, cleanly converting two shadows into swirling smoke, and then you fire a hail of bullets into the third, ending it as well.\n\n\tDespite the incredibly difficult odds against you, you have prevailed.");
break;
default:
t.say("Gunshot", "You are easily defeated by the shadows.");
}
}
else
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You miss every shot in your magazine, yet manage to kill all three shadows by using your "+t.user.weapon+" as a club.\n\n\n\tFrom the clouds, a booming voice, almost like Gandalf\'s, echoes through the pits:\n\n\t\tGet better aim!!\n\t\tSeriously, go to target practice or something...\n\t\tThat was ridiculous.\n\n\n\n\n\n\tYou shake it off and turn your attention to the House of Shadows.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You fire at the enemies, full automatic fire, and yet the shadows keep managing to dodge your fire.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "You suspect that its because your "+t.user.weapon+" has too much recoil.\n\n\t" : "")+"Just as you begin to worry about the need to reload, one bullet grazes the leading shadow.\n\tSomehow, to your surprise, it disappears, turning into swirling smoke.\n\n\n\n\tThe remaining "+(t.gen.nextBoolean() ? "shadows" : "figures")+" mirror your surprise: They pause in shock.\n\n\tYou take advantage of their surprise to fire "+(t.gen.nextBoolean() ? "a trio" : "a hail")+" of "+(t.gen.nextBoolean() ? "rounds" : "bullets")+" at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+".\n\n\tIt disappears into a swirling cloud of smoke, and you continue firing, now at the last enemy, and barely manage to graze it.\n\n\n\tIgnoring what is now just a cloud of smoke, you turn on the House of Shadows.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You level the sights of your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a "+(t.gen.nextBoolean() ? "hail" : "number")+" of rounds into it.\n\n\n\tIt "+(t.gen.nextBoolean() ? "becomes" : "disappears into")+" a swirling cloud of smoke, as you turn your attention to the second enemy.\n\n\tIt approaches "+(t.gen.nextBoolean() ? "menacingly" : "threateningly")+", but you "+(t.gen.nextBoolean() ? "are able" : "manage")+" to level your sights at it, and you squeeze the trigger, watching the bullets barely hit the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tLuckily, it seems that any hit will "+(t.gen.nextBoolean() ? "dissolve" : "destroy")+" the shadow, and you watch as it disappears into a swirling cloud of smoke.\n\n\n\n\n\tUnfortunately, you seem to have lost track of the third...\n\n\n\n\tYou look left...\n\n\t...and right...\n\n\t...left...\n\n\t...and there it is!\n\n\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "figure")+" "+(t.gen.nextBoolean() ? "shows itself" : "appears")+" immediately just in front of you!\n\n\n\n\n\n\tYou hastily fire your "+t.user.weapon+", and turn it to smoke, barely surviving the encounter.\n\n\tYou shake yourself off, and turn to face the House of Shadows.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You aim your "+t.user.weapon+" directly at the leading enemy, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\tA "+(t.gen.nextBoolean() ? "burst" : "number")+" of rounds fly directly at it, and strike it, turning it into a swirling cloud of smoke.\n\n\tYou quickly turn, and aim at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and manage to send a hail of "+(t.gen.nextBoolean() ? "rounds" : "fire")+" flying directly at it.\n\n\n\tYou pause for a split second to watch as the "+(t.gen.nextBoolean() ? "apparition" : "shadow")+" dissolves into a cloud of smoke.\n\n\tThe final shadow seems to have disappeared.\n\n\t"+(t.gen.nextBoolean() ? "You" : "Your "+t.user.weapon)+" feels light, "+(t.user.weapon.characteristicSet(Cweapon.QUICK_RELOAD) ? "so you quickly switch cartridges." : "but you decide it would take too long to reload it.")+"\n\n\n\n\tYou return your attention to where it probably should be, the rather deadly "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" that could reappear and kill you at any moment.\n\tSuddenly, it reappears: Right in front of you!\n\n\n\n\tYou quickly pull the trigger, firing several shots into the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" before you.\n\n\n\tYou turn to oppose the House of Shadows as it disappears into a swirling cloud of smoke.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You aim, and fire your "+t.user.weapon+" directly at the "+(t.gen.nextBoolean() ? "nearest" : (t.gen.nextBoolean() ? "closest" : "nearest"))+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", sending a hail of bullets flying directly at its core.\n\n\n\tThe first round out of your "+(t.gen.nextBoolean() ? "weapon" : t.user.weapon)+" hits it, turning it into a swirling cloud of smoke.\n\n\n\tYou quickly shift your aim, leveling your sights at the next target, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring a solid hit, and turning the shadow into a swirling cloud of smoke.\n\n\n\tThe third shadow comes around to face you, and dodges your first burst.\n\n\n\tYou quickly adjust your aim, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring another hit and ending the shadow.\n\n\n\tYou turn to face the House of Shadows as it turns to swirling smoke.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a hail of rounds from your "+t.user.weapon+", scoring an extremely solid shot and dissolving it.\n\n\n\tAs it disappears into smoke, you adjust your aim, aiming for the next "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire a trio of bullets into its core, turning it into a swirling cloud of smoke.\n\n\n\n\tThe last shadow attempts to disappear, to catch you from behind, but you fire, and hit it precisely in its center of mass.\n\n\n\tAs it dissolves into swirling smoke, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.BULLSEYE:
t.say(title, "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "nearest")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger, sending a hail of bullets flying directly towards it, striking it perfectly between the two glowing spots that pass for eyes.\n\n\tAs it disappears into swirling smoke, you let off the trigger, and adjust your aim, ready to eliminate the second one.\n\n\n\n\tJust as it begins to approach you, you fire again, and a trio of bullets score a perfect hit on your target.\n\n\n\tIt disappears into smoke, and you aim directly at the last target.\n\n\tIt attempts to flee, but you don\'t allow it the chance: You "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, sending a single round into the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", hitting its forehead dead-center, and converting it into a swirling cloud of smoke.\n\n\n\n\tYou turn to face the House of Shadows.");
break;
default:
t.say("A "+t.user.weapon+" to a shadowfight", "You manage to defeat the shadows.");
}
}
}
else
{
t.user.dead=(res.distance/(.6*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5);
if (t.user.dead)
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "figure" : "shadow")+", and fire.\n\n\tYou miss.\n\tBadly.\n\n\t"+(t.config.triggerEgg(.5) ? ("Years from now, after the Fall of the Shadows, and after another explorer, perhaps even one called "+t.user+", has liberated the Great Familiar City, a small "+(t.gen.nextBoolean() ? "boy, and his" : "girl, and her")+" "+(t.gen.nextBoolean() ? "mother" : (t.config.triggerEgg(.2) ? "Big Daddy" : "father"))+" will come across the spot where you faced the shadows, and they will take all they find, your "+t.user.weapon+", home as a souvenir.") : (t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "Before you can cycle the action, they are upon you." : "They take the chance to consume you.")));
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You level your "+t.user.weapon+" at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\n\tA single round flies into the side of it, and it vanishes from the slightest impact.\n\n\tIt would appear that the slightest impact will eliminate a shadow.\n\n\n\n\tYou level your weapon at the second shadow, but you have just enough time to notice that the third has disappeared from your sight when it appears behind you, and ends you.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You place the sights of your "+t.user.weapon+" at the leading "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", and pull the trigger.\n\n\n\tAlmost as if by instinct, you find that you're adjusting your aim to fire at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\tAlas, your instinct is not as skilled as your hand, and your shot flies wide.\n\n\n\n\tYou try to readjust your aim, but the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" are too fast.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You aim towards the leading shadow, and pull the trigger, sending a single round flying into it.\n\n\tThe shot scores a solid hit, and turns the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" into a swirling cloud of smoke.\n\n\tWithout pausing to watch it, you adjust your aim, leveling your "+t.user.weapon+" at your second opponent.\n\n\tYou fire a shot, and barely nick it, turning it into smoke.\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" seems to have disappeared.\n\n\tYou look left..\n\t..and right..\n\n\n\n\t...left...\n\t...and right...\n\n\n\tCautiously, you turn to face the House of Shadows, only to find it in mid-air, flying directly towards you.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You direct your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "lead" : "first")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\n\tA single round flies towards it, striking it right in the chest.\n\n\n\tAs it disappears into swirling smoke, you twist to aim at the second.\n\n\tJust as it lines up with your sight, you squeeze the trigger, and a "+(t.gen.nextBoolean() ? "single" : "solitary")+" round flies straight and true, "+(t.gen.nextBoolean() ? "hitting" : "striking")+" it right where its heart should be, and turning it to a swirling cloud of smoke.\n\n\n\tYou aim at the third, firing another round, but the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "Before you can switch magazines, " : "Before you can get off another round, ")+"it is upon you.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You aim your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "primary")+" "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire.\n\n\n\tYour aim was true, and your round flies directly into its head, turning it into swirling smoke.\n\n\n\tThe second shadow "+(t.gen.nextBoolean() ? "tries" : "attempts")+" to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot, but you are too skilled a "+(t.gen.nextBoolean() ? "gunslinger" : "sharpshooter")+", and it vanishes into swirling smoke.\n\n\n\tYou turn yor attention to the third.\n\n\n\n\n\tIt seems to have disappeared.\n\n\tYou look left...\n\t...and right...\n\n\n\n\t...left...\n\t...and right...\n\n\n\n\n\t...Suddenly, its in front of you!\n\n\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE) ? "You jump away, bringing your "+t.user.weapon+" to bear.\n\n\n\n\tYou manage to get off a shot just as it is upon you, turning the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" into swirling smoke, just as your life is prematurely ended by it.\n\n\n\n\t" : "You try to get off a shot with your "+t.user.weapon+", but you find that it is too cumbersome to be used effectively at close range, and the shadow consumes you.\n\n\t")+t.capitalize(t.user.gold.toString())+" and your "+t.user.weapon+" clatter to the ground."+(t.config.triggerEgg(.4) ? "\n\n\n\tSomeday, years after the Great Shadow War, and after the Great Familiar City has been conquered by the Army of the Second Coming, a Little Sister of the Rapture, along with her Big Daddy, will come across the remnants of the Pits, and all they will find of you is "+t.user.gold+" and your "+t.user.weapon+"." : "Somewhere in the distance, another adventurer approaches the Pits."));
break;
case targetingMinigame.output.BULLSEYE:
t.user.dead=false;
t.say(title+" against the odds", "You level your "+t.user.weapon+" at the shadows.\n\n\n\n\tDespite the impossibility of the odds, you ready yourself to fight.\n\n\n\tIn quick succession, you fire a round at each shadow, adjusting your aim without pausing to see if your aim is true, hitting each shadow right where the bright spots that pass for their eyes are.\n\n\n\n\tDespite the impossibility of how outmatched you are by the shadows, you have emerged victorious.");
break;
default:
t.say("Absorbed", "Your aim is out of this world!\n\n\n\tNo, seriously, that shot was... I don't even know.\n\n\n\tLet\'s just say this...");
}
}
else
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You fire one round at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\n\tYou miss."+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "You opt to forgo loading another shot, instead using your "+t.user.weapon+" as if it were a club." : "You aim again, and once more, you miss.\n\n\n\tThis process repeats itself over and over, until the "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" cease to worry about your shots, and instead process to laugh at you and your "+t.user.weapon+".\n\n\tAt that point, you decide it is better used as a club.")+"\n\n\n\tYou rush the shadows, striking one, and then proceeding to fight the others.\n\n\n\tMiraculously, it works.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "last" : "final")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into swirling smoke, a voice, a great and majestic voice, echoes through the Pits:\n\n\n\n\t\tLearn to aim!!\n\t\tThat was awful!\n\t\tGo to the shooting range or something.\n\t\tNow!!\n\n\tIgnoring the voice, shaking off the fright, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You level your "+t.user.weapon+" at the nearest "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\tThe round flies straight and true, flying towards its target.\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", as if it had sensed that you were shooting at it, "+(t.gen.nextBoolean() ? "dodging" : "evading")+" the shot.\n\n\tUnfortunately, at least for it, the round barely grazes it.\n\n\n\n\tApparently, even such a small impact is plenty to end it, turning it into a swirling cloud of smoke.\n\n\n\tThe second pauses, if only for a split second, and you take the opportunity to aim at the second one.\n\n\tYour shot is imperfect, and the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\n\tSwearing quietly, you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your "+t.user.weapon : "adjust your aim")+", firing again just in time to hit the second before it gets close.\n\n\n\n\tWithout pausing to watch it disappear into a cloud of smoke, you roll to the side, evading the lunge of the last "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou manage to bring your "+t.user.weapon+" to bear, and fire a single shot, managing to end it.\n\n\n\tShaking off your close encounter, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You aim your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire.\n\n\n\tThe round flies at its target, hitting it off center, and turning it into a swirling cloud of smoke, as you adjust your aim to hit the second enemy.\n\n\n\tThe second "+(t.gen.nextBoolean() ? "figure" : "shadow")+" faces you as you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your"+t.user.weapon : "steady your aim")+", approaching as you do.\n\n\t"+(t.gen.nextBoolean() ? "Luckily" : "Fortunately")+", you\'re able to get off the shot before it gets close.\n\n\tThe round hits the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", barely, turning it into a swirling cloud of smoke.\n\n\tThe final shadow turns to flee, as you level your "+t.user.weapon+" directly at it.\n\n\n\tYou fire before it gets out of range or into cover, and the final shadow disappears into swirling smoke.\n\n\n\n\n\tSatisfied with your victory, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You ready yourself, aiming directly at the closest "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\n\tYou quickly fire a shot, fully aware of the threat of the two remaining shadows, and watch only for a moment as the round flies through the air, and hits its mark.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into a swirling cloud of smoke, and you swing your "+t.user.weapon+" to fire at its lieutenant.\n\n\n\tYour enemy advances towards you, and you calmly "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tYour aim was near-perfect, but the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" sees it coming, and moves to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\tThe shadow is not quite quick enough, and the round strikes it, turning it to smoke.\n\n\n\tThe final shadow seems to have disappeared, but you see a hint of motion in the corner of your eye, and, almost as if by instinct, turn to face it.\n\n\n\n\n\n\tThe shadow is charging at you, doing its best to end you and defend the House of Shadows, but you are too quick for it, deftly pulling the trigger, and turning the shadow into a cloud of smoke.\n\n\n\tAfter contently watching it swirl away, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You quickly survey the field before you, and the three shadows that are before you.\n\n\n\tYou adjust your aim, leveling your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", prepared to fire.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "figures" : "shadows")+" begin to approach you, you grin ever-so-slightly, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tThe round glides smoothly towards its target, impacting it, and converting it into a swirling cloud of smoke.\n\n\n\tYou turn slightly, ready to fire at the next enemy, and "+(t.gen.nextBoolean() ? "adjust" : "calibrate")+" your aim.\n\n\n\n\tWhen your sights are in place, you fire, and turn the second "+(t.gen.nextBoolean() ? "enemy" : "apparition")+" into swirling smoke.\n\n\n\n\tYou frown slightly.\n\n\tYou could have sworn there where three, yet an empty battlefield and two kills seems to suggest otherwise.\n\n\n\tYou cautiously survey the area, then slowly start to move towards the House of Shadows.\n\n\n\tSuddenly, you see a dark smudge on the edge of your vision, and you turn to grab a better look.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", seeing that you found it, charges, as if it was hoping to eliminate you before you can do the same to it, but you fire, and it vanishes, replaced only by smoke.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You stare down the three approaching "+(t.gen.nextBoolean() ? "shadows" : "figures")+", sizing up your opposition.\n\n\n\tThe moment they move to attack, you start to fire, cleanly eliminating your leading "+(t.gen.nextBoolean() ? "target" : "enemy")+", and adjust your aim, targeting the second.\n\n\tIt makes an attempt to flee, but you fire, hitting it in what passes as its head.\n\n\n\tThe last shadow attempts to dodge your line of sight, but you follow it, and eliminate it too.\n\n\n\n\n\tYou pause for only a second to watch the trio disappear into swirling smoke as it diffuses, then turn towards the House of Shadows.");
break;
case targetingMinigame.output.BULLSEYE:
t.say(title, "You effortlessly fire a perfect shot at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+"shadow, a single blast from your"+t.user.weapon+" turning it to smoke.\n\n\tThe remaining shadows hesitate, and thus, you get in a shot at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+", turning it as well into a swirling cloud of smoke.\n\n\n\tThe last one attempts to flee, but you allow it no such luxury.\n\n\n\n\tWith all three shadows dispatched, you turn to face the House of Shadows.");
break;
default:
t.say("The brightness of a "+t.user.weapon, "In a long and drawn-out engagement, you and your "+t.user.weapon+" outshine the darkness of the shadows.\n\n\n\tFeeling invincible, you turn to face the House of Shadows.");
}
}
}
}
};
break;
case Cweapon.TYPE_NUCLEAR:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("A"+(t.gen.nextBoolean() ? " second" : "nother")+" sun", "You hit the detonator on your "+t.user.weapon+".\n\n\n\tA second fireball appears on the horizon, as the people stand in a familiar landscape, and watch you disappear.\n\n\n\tBehind them, the deadly, sickly glow illuminates a terrifying figure.");
}
};
break;
case Cweapon.TYPE_FUTURE:
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // CLOSE_RANGE_ONLY is the identifying flag for future weapons. If it's set, we're dealing with a lightsaber. Else, we (probably) have a raygun. These two get different dialogue.
t.say("Sword of light", "You charge the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", holding your "+t.user.weapon+" up on high.\n\n\n\tThe leading shadow, seemingly feeling courageous, steps toward you, but you counter its approach, dissolving it.\n\n\n\tThe other two "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" step away, deterred slightly by your charge, but not far enough.\n\n\n\n\n\tA lunge and a quick extension of the arm is enough to turn the shadow to ash almost akin to a hallucination.\n\n\tThe third shadow begins full flight, perhaps attempting to survive, perhaps attempting to draw you away from the House of Shadows.\n\tTo you, it doesn't matter: You chase it down, and eliminate it.\n\n\n\n\tHaving won a simple victory, you grin, and move towards the House of Shadows.");
else
t.say("The "+t.capitalize(t.user.weapon.name), "You aim your "+t.user.weapon+" directly at the leading "+t.user.weapon+", and pull the trigger.\n\n\n\tThe bolt of brilliant energy glides to its target, and hits it squarely.\n\n\n\tIt disappears into a mere wisp of smoke, leaving not a mere grain of ash.\n\n\n\n\tThe second and third shadows each seem afraid of you, and your "+t.user.weapon+", but you pay them no attention.\n\n\tYou place your sights in between the bright spots on the second "+(t.gen.nextBoolean() ? "apparition" : "figure")+", and pull the trigger.\n\n\n\tIt attempts to maneuver out of the way, but the bolt strikes it nonetheless, and it disappears as if it were never there.\n\n\n\tThe third turns to "+(t.gen.nextBoolean() ? "escape" : "run away")+", but your bolt outruns it by a factor of several million, and disintegrates it.\n\n\n\n\n\t"+(t.gen.nextBoolean() ? "Victorious" : "Feeling invincible")+", you turn towards the House of Shadows.");
}
};
break;
default:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("Unknowable", "You suddenly find yourself unable to "+(t.gen.nextBoolean() ? "use" : (t.gen.nextBoolean() ? "grip" : "hold"))+" your "+t.user.weapon+".");
}
};
}
t.th=new Thread(r);
t.th.start();
t.snooze(25); // We need a bit longer to insure processing finishes.
if (t.user.dead && !undead)
prepContinueButton();
else
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)4, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
break;
case 1:
t.th.interrupt();
Runnable r1;
if (t.config.triggerEgg(.05))
{
t.user.dead=false;
r1=new Runnable()
{
@Override
public void run()
{
t.say("Impossible", "You face the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" for only a split second before turning, and sprinting for the House of Shadows.\n\n\tYou "+(t.gen.nextBoolean() ? "grab" : "snatch")+" the detonator from its resting place, glancing only for an instant at the cratering charge it controls.\n\n\n\n\tClosely followed by the shadows, you grimace, hoping your distance from the charge is sufficient.\n\n\n\n\n\n\tYou hit the detonator, and the charge goes off, destroying the House and the shadows with it.\n\n\tThe three shadows that had assaulted you are not alone in disappearing, as an invisible wave passes over the pits, turning each shadow it finds into swirling smoke.\n\n\tUnfortunately, you were not quite far enough from the charge, and it throws you up and away, towards the center of the Pits.\n\n\n\n\n\n\n\tIn the mere seconds of flight you get, you resign yourself to your fate of dying, and of never finding out what exists beyond the image of the familiar landscape.\n\n\tAs soon as you do, as if it had been waiting, a strange force slows you and gently redirects your path.\n\n\tYou land, safe but not intact, in the center of "+(t.gen.nextBoolean() ? "Hell." : "the Pits."));
}
};
}
else
{
t.user.dead=true;
r1=new Runnable()
{
@Override
public void run()
{
t.say("Foolhardy", "You quickly turn and sprint towards the House of Shadows.\n\n\n\tUnfortunately, the "+(t.gen.nextBoolean() ? "apparitions" : "shadows")+" sense your advance, and absorb you.");
}
};
}
t.th.interrupt();
t.th=new Thread(r1);
t.th.start();
if (t.user.dead)
prepContinueButton();
else
{
prepContinueButton(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits((byte)0, stage, input, input2, true);
}
});
t.th.start();
}
});
}
break;
case 2:
t.user.dead=true;
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Outdone", "You attempt to flee from the shadows. They give chase, herding you using their superior numbers.\n\n\tJust when you think you\'ve lost them, you trip on a well, or poorly, placed rock, and tumble down a hill.\n\n\n\n\tWhen you stop, you look at a black sky, only to realize that you\'re staring at a shadow.");
}
});
t.th.start();
prepContinueButton();
break;
default:
dataError();
}
break;
case 1:
switch (input2)
{
case 0:
if (t.user.weapon.type==Cweapon.TYPE_ARCHERY && .65>(t.config.difficultyMult*.75*t.user.weapon.getAbsoluteStrength()))
{
archeryMinigame((int)Math.ceil(t.gen.nextInt(40)+(t.config.difficultyMult*10)+5), ((20*(1-t.config.difficultyMult))+5)/5);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String title;
switch (t.gen.nextInt(3))
{
case 0:
title="Archer";
break;
case 1:
title="Bowman";
break;
case 2:
title="Shoplifter";
break;
default:
title="Outdone by the dark";
}
if (t.user.weapon.characteristicSet(Cweapon.SLOW_RELOAD)) // Crossbow
t.say(title, "You "+(t.gen.nextBoolean() ? "bring" : "swing")+" your "+t.user.weapon+" to bear, and fire it at your target.\n\n\tThe bolt flies straight and true, towards a point just slightly away from the "+(t.gen.nextBoolean() ? "shadow" : "being")+".\n\n\tYou quickly "+(t.gen.nextBoolean() ? "grab" : "snatch")+" another bolt, trying your best to load your weapon.\n\n\tJust when you\'re ready, you look up to find a pair of glowing eyes staring into your soul.");
else
t.say(title, "You immediately draw an arrow, bringing it to bear against your foe.\n\n\tUnfortunately, you miss.\n\tYou quickly "+(t.gen.nextBoolean() ? "draw" : "grab")+" another "+(t.gen.nextBoolean() ? "arrow" : "shot")+", and barely manage to draw your "+t.user.weapon+" before the "+(t.gen.nextBoolean() ? "shadow " : "figure ")+(t.gen.nextBoolean() ? "absorbs" : "ends")+" you.");
}
else
t.say(t.gen.nextBoolean() ? "Shopkeeper" : "Veteran", "Your "+(t.gen.nextBoolean() ? "enemy" : "foe")+" charges at you, swaying to "+(t.gen.nextBoolean() ? "evade" : "avoid")+" your line of fire.\n\n\tUnfortunately, for it, you manage to follow its movements, and thusly "+(t.gen.nextBoolean() ? "end" : "kill")+" it, turning it into swirling smoke. You turn your gaze towards the now-cleared shop.");
}
});
t.th.start();
if (t.user.dead)
prepContinueButton();
else
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)4, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
{
boolean undead=false;
switch (t.user.weapon.type)
{
case Cweapon.TYPE_SHARP:
t.determineUserDeath((1-t.user.weapon.getNeededFlags(Cweapon.CLOSE_RANGE|Cweapon.LIGHT, 2))*.99);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
if (t.gen.nextBoolean())
t.say("You swing your "+(t.gen.nextBoolean() ? "blade" : t.user.weapon)+", catching the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" off guard."+t.multiplyString('\n', t.gen.nextInt(5)+2)+"\tUnfortunately, it manages to dance its way out of the way, and it ends you.");
else
t.say(t.gen.nextBoolean() ? "Newcomer" : "Novice", "You bring your "+t.user.weapon+" to bear, fumbling only slightly, then beginning to "+(t.gen.nextBoolean() ? "slash" : "stab")+" at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", but it evades you at every thrust."+t.multiplyString('\n', t.gen.nextInt(4)+2)+"\tFinally, after a number of mistakes, it outmaneuvers you."+t.multiplyString('\n', t.gen.nextInt(5)+2)+"\tThe last thought in your head before your "+(t.gen.nextBoolean() ? "time" : "existence")+" is ended, "+((t.config.litEggs && t.config.triggerEgg(.8)) ? ("if you had been allowed to give an utterance to the thoughts that were inspiring you, and they were prophetic, they would have been these:"+t.multiplyString('\n', 2+t.gen.nextInt(3))+"\t\t\"I see a great evil fall across a skyline, a city I thought I used to know.\n\t\t\"I see a man, old, bearded, watching in disappointment as the blots form on my name. I see him, foremost of judges and honored men, bringing another, all too much like me, to this place - Then fair to look upon, without a trace of this day\'s disfigurement - and I hear him tell my replacement my story, with a disappointed and somber voice.\n\t\t\"It is a far, far, sorrier thing that I do, than I have ever done; it is a far, far more dismaying rest that I go to than I have ever known.\""+t.multiplyString('\n', t.gen.nextInt(4)+2)+"\tUnfortunately for your memory, you failed to realize that this was not, in fact, \"A Tale of Two Shadows\".") /* Note that adding some gender-specific pronouns to that might not be the worst idea. */ : "is one of sadness: Sadness that you were never able to properly use your "+t.user.weapon+" well enough to defeat the Shadow in the Pits."));
}
else
t.say(t.gen.nextBoolean() ? "Swordsman" : "Sword master", "You swing your sword as fast as humanly possible, turning one, then two, "+(t.gen.nextBoolean() ? "shadows" : "figures")+" into swirling smoke.\n\n\tThe last shadow charges toward you, but your sword nicks it, and it disappears.\n\n\tA booming voice, almost like Gandalf\'s, echoes from the clouds:\n\n\t\tWhy do you still carry that puny "+t.user.weapon+"??\n\t\tFind a new weapon.\n\t\tNow.\n\n\n\n\n\tYou turn your attention away from the voice, and to the House of Shadows.");
}
};
break;
case Cweapon.TYPE_ARCHERY:
t.determineUserDeath(.75*t.user.weapon.getAbsoluteStrength());
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String title;
switch (t.gen.nextInt(4))
{
case 0:
title="Archer";
break;
case 1:
title="Bowman";
break;
case 2:
title="Outnumbered";
break;
default:
title="Outdone by the dark";
}
switch (t.gen.nextInt(3))
{
case 0:
t.say(title, "You turn to face the shadows, but they easily defeat you before you get off a single shot.");
break;
case 1:
t.say(title, "You spin to face your enemy, and fire a single "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\tYour aim "+(t.gen.nextBoolean() ? "is true" : (t.gen.nextBoolean() ? "is that of a master" : "is masterful"))+", turning the leader of the trio into a swirl of smoke.\n\n\tHowever, before you can ready yourself again, the other two eliminate you.");
break;
case 2:
t.say(title, "You load one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+", and thoughtlessly fire it at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou\'ve practiced your archery considerably, and the shot flies directly into its target.\n\n\tYou ignore the sight as your opponent disappears into a swirling cloud of shadowy smoke, and dodge the advance of your second adversary, which you shoot shortly afterwards.\n\n\n\tAlas, you lost track of the third shadow, which comes from behind you, and kills you.");
break;
default:
Log.wtf("Cgame at the House of Shadows", "Invalid output from Random.nextInt()");
}
}
else
t.say((t.config.GoTEggs && t.config.triggerEgg(.8)) ? "Lightbringer" : "Defeater of Shadows", "You turn, snappily aiming your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and shooting it.\n\n\tPaying it no attention as it disappears into swirling smoke.\n\n\tInstead, as if by instinct, you roll towards the House of Shadows."+(t.gen.nextBoolean() ? "" : "\n\n\tYou quickly recover from the pain of your miscalculation after you slam into the outer wall.")+"\n\n\tWithout taking the time to stand, you adjust your aim, directly at the second enemy.\n\n\tQuickly, you release your shot, sending "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" flying into the second shape, then clattering to the ground as your opponent swirls away.\n\n\n\tThe third charges, but you pull one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" from your reserves, and drive it through your final adversary, noting the lack of resistance as it goes through.\n\n\tYou watch the remains of your opponent swirl away, and note your two fired shots have vanished.");
}
};
break;
case Cweapon.TYPE_MODERN:
final targetingMinigame.output res=aimMinigame();
undead=(res.type==targetingMinigame.output.BULLSEYE);
final String title=res.toString();
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.AUTOMATIC))
{
t.user.dead=(res.distance/(.8*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5);
if (t.user.dead)
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You fire a burst of bullets towards the shadows, but your aim is off, and the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" end you.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You turn at the shadows, and fire a burst of automatic fire. One shot hits the nearest "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it to a swirl of smoke, but the remaining two intercept you.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You fire at the shadows, grazing one, turning it to swirling smoke, and barely hitting another.\n\n\tThe last consumes you as the second disappears.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You fire at the shadows, hitting one with a solid shot, and "+(t.gen.nextBoolean() ? "turning" : "converting")+" it into a swirling cloud.\n\n\tAnother bullet strikes the second, eliminating it as well, but "+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "the recoil of your "+t.user.weapon+" throws off your aim." : "the last shadow moves out of your sights too quickly."));
break;
case targetingMinigame.output.GOOD:
t.say(title, "You hit two shadows with near perfect shots.\n\n\tThe shadows disappear into swirling smoke, as the third approaches you.\n\n\n\n\n\tYou quickly twist, aiming directly at the last shadow.\n\n\n\n\n\n\tYou pull the trigger, just as it reaches you."+(t.config.triggerEgg(.5) ? "\n\n\n\tThe shadow of a dragon looms over the pits, the rush of air stirring everything around, as you both become swirling smoke, and "+t.user.gold+", along with your "+t.user.weapon+", clatter to the ground." : ""));
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You hit the first two shadows with perfect shots, but find that the third seems to have disappeared.\n\n\tYou twist and turn, searching for it, "+(t.config.triggerEgg(.75) ? "and feel a thud, and a weight.\n\n\tYou fall, watching the shadow run, and attempt to give chase.\n\n\tSoon, it leaves your sight. Contented, you enter the House of Shadows, grabbing the detonator, assuming that the charge is at it was.\n\n\n\n\tYou walk clear of the House, wondering why you feel as if there is a huge weight on your back.\n\n\n\tYou realize that the shadow planted the charge on your back a moment too late, as you trigger the explosive." : "and soon finding it, right behind you.\n\n\tYou dodge its lunge, dropping your "+t.user.weapon+" in your haste to "+(t.gen.nextBoolean() ? "escape" : "survive")+", and, just as you think you\'ve escaped, you trip, rolling down a hill, coming to a stop in a ditch full of a hundred shadows."));
break;
case targetingMinigame.output.BULLSEYE:
t.user.dead=false;
t.say(title+", despite impossibility", "You fire three utterly perfect shots, cleanly converting two shadows into swirling smoke, and then you fire a hail of bullets into the third, ending it as well.\n\n\tDespite the incredibly difficult odds against you, you have prevailed.");
break;
default:
t.say("Gunshot", "You are easily defeated by the shadows.");
}
}
else
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You miss every shot in your magazine, yet manage to kill all three shadows by using your "+t.user.weapon+" as a club.\n\n\n\tFrom the clouds, a booming voice, almost like Gandalf\'s, echoes through the pits:\n\n\t\tGet better aim!!\n\t\tSeriously, go to target practice or something...\n\t\tThat was ridiculous.\n\n\n\n\n\n\tYou shake it off and turn your attention to the House of Shadows.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You fire at the enemies, full automatic fire, and yet the shadows keep managing to dodge your fire.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "You suspect that its because your "+t.user.weapon+" has too much recoil.\n\n\t" : "")+"Just as you begin to worry about the need to reload, one bullet grazes the leading shadow.\n\tSomehow, to your surprise, it disappears, turning into swirling smoke.\n\n\n\n\tThe remaining "+(t.gen.nextBoolean() ? "shadows" : "figures")+" mirror your surprise: They pause in shock.\n\n\tYou take advantage of their surprise to fire "+(t.gen.nextBoolean() ? "a trio" : "a hail")+" of "+(t.gen.nextBoolean() ? "rounds" : "bullets")+" at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+".\n\n\tIt disappears into a swirling cloud of smoke, and you continue firing, now at the last enemy, and barely manage to graze it.\n\n\n\tIgnoring what is now just a cloud of smoke, you turn on the House of Shadows.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You level the sights of your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a "+(t.gen.nextBoolean() ? "hail" : "number")+" of rounds into it.\n\n\n\tIt "+(t.gen.nextBoolean() ? "becomes" : "disappears into")+" a swirling cloud of smoke, as you turn your attention to the second enemy.\n\n\tIt approaches "+(t.gen.nextBoolean() ? "menacingly" : "threateningly")+", but you "+(t.gen.nextBoolean() ? "are able" : "manage")+" to level your sights at it, and you squeeze the trigger, watching the bullets barely hit the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tLuckily, it seems that any hit will "+(t.gen.nextBoolean() ? "dissolve" : "destroy")+" the shadow, and you watch as it disappears into a swirling cloud of smoke.\n\n\n\n\n\tUnfortunately, you seem to have lost track of the third...\n\n\n\n\tYou look left...\n\n\t...and right...\n\n\t...left...\n\n\t...and there it is!\n\n\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "figure")+" "+(t.gen.nextBoolean() ? "shows itself" : "appears")+" immediately just in front of you!\n\n\n\n\n\n\tYou hastily fire your "+t.user.weapon+", and turn it to smoke, barely surviving the encounter.\n\n\tYou shake yourself off, and turn to face the House of Shadows.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You aim your "+t.user.weapon+" directly at the leading enemy, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\tA "+(t.gen.nextBoolean() ? "burst" : "number")+" of rounds fly directly at it, and strike it, turning it into a swirling cloud of smoke.\n\n\tYou quickly turn, and aim at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and manage to send a hail of "+(t.gen.nextBoolean() ? "rounds" : "fire")+" flying directly at it.\n\n\n\tYou pause for a split second to watch as the "+(t.gen.nextBoolean() ? "apparition" : "shadow")+" dissolves into a cloud of smoke.\n\n\tThe final shadow seems to have disappeared.\n\n\t"+(t.gen.nextBoolean() ? "You" : "Your "+t.user.weapon)+" feels light, "+(t.user.weapon.characteristicSet(Cweapon.QUICK_RELOAD) ? "so you quickly switch cartridges." : "but you decide it would take too long to reload it.")+"\n\n\n\n\tYou return your attention to where it probably should be, the rather deadly "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" that could reappear and kill you at any moment.\n\tSuddenly, it reappears: Right in front of you!\n\n\n\n\tYou quickly pull the trigger, firing several shots into the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" before you.\n\n\n\tYou turn to oppose the House of Shadows as it disappears into a swirling cloud of smoke.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You aim, and fire your "+t.user.weapon+" directly at the "+(t.gen.nextBoolean() ? "nearest" : (t.gen.nextBoolean() ? "closest" : "nearest"))+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", sending a hail of bullets flying directly at its core.\n\n\n\tThe first round out of your "+(t.gen.nextBoolean() ? "weapon" : t.user.weapon)+" hits it, turning it into a swirling cloud of smoke.\n\n\n\tYou quickly shift your aim, leveling your sights at the next target, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring a solid hit, and turning the shadow into a swirling cloud of smoke.\n\n\n\tThe third shadow comes around to face you, and dodges your first burst.\n\n\n\tYou quickly adjust your aim, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring another hit and ending the shadow.\n\n\n\tYou turn to face the House of Shadows as it turns to swirling smoke.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a hail of rounds from your "+t.user.weapon+", scoring an extremely solid shot and dissolving it.\n\n\n\tAs it disappears into smoke, you adjust your aim, aiming for the next "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire a trio of bullets into its core, turning it into a swirling cloud of smoke.\n\n\n\n\tThe last shadow attempts to disappear, to catch you from behind, but you fire, and hit it precisely in its center of mass.\n\n\n\tAs it dissolves into swirling smoke, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.BULLSEYE:
t.say(title, "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "nearest")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger, sending a hail of bullets flying directly towards it, striking it perfectly between the two glowing spots that pass for eyes.\n\n\tAs it disappears into swirling smoke, you let off the trigger, and adjust your aim, ready to eliminate the second one.\n\n\n\n\tJust as it begins to approach you, you fire again, and a trio of bullets score a perfect hit on your target.\n\n\n\tIt disappears into smoke, and you aim directly at the last target.\n\n\tIt attempts to flee, but you don\'t allow it the chance: You "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, sending a single round into the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", hitting its forehead dead-center, and converting it into a swirling cloud of smoke.\n\n\n\n\tYou turn to face the House of Shadows.");
break;
default:
t.say("A "+t.user.weapon+" to a shadowfight", "You manage to defeat the shadows.");
}
}
}
else
{
t.user.dead=(res.distance/(.6*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5);
if (t.user.dead)
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "figure" : "shadow")+", and fire.\n\n\tYou miss.\n\tBadly.\n\n\t"+(t.config.triggerEgg(.5) ? ("Years from now, after the Fall of the Shadows, and after another explorer, perhaps even one called "+t.user+", has liberated the Great Familiar City, a small "+(t.gen.nextBoolean() ? "boy, and his" : "girl, and her")+" "+(t.gen.nextBoolean() ? "mother" : (t.config.triggerEgg(.2) ? "Big Daddy" : "father"))+" will come across the spot where you faced the shadows, and they will take all they find, your "+t.user.weapon+", home as a souvenir.") : (t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "Before you can cycle the action, they are upon you." : "They take the chance to consume you.")));
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You level your "+t.user.weapon+" at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\n\tA single round flies into the side of it, and it vanishes from the slightest impact.\n\n\tIt would appear that the slightest impact will eliminate a shadow.\n\n\n\n\tYou level your weapon at the second shadow, but you have just enough time to notice that the third has disappeared from your sight when it appears behind you, and ends you.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You place the sights of your "+t.user.weapon+" at the leading "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", and pull the trigger.\n\n\n\tAlmost as if by instinct, you find that you're adjusting your aim to fire at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\tAlas, your instinct is not as skilled as your hand, and your shot flies wide.\n\n\n\n\tYou try to readjust your aim, but the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" are too fast.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You aim towards the leading shadow, and pull the trigger, sending a single round flying into it.\n\n\tThe shot scores a solid hit, and turns the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" into a swirling cloud of smoke.\n\n\tWithout pausing to watch it, you adjust your aim, leveling your "+t.user.weapon+" at your second opponent.\n\n\tYou fire a shot, and barely nick it, turning it into smoke.\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" seems to have disappeared.\n\n\tYou look left..\n\t..and right..\n\n\n\n\t...left...\n\t...and right...\n\n\n\tCautiously, you turn to face the House of Shadows, only to find it in mid-air, flying directly towards you.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You direct your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "lead" : "first")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\n\tA single round flies towards it, striking it right in the chest.\n\n\n\tAs it disappears into swirling smoke, you twist to aim at the second.\n\n\tJust as it lines up with your sight, you squeeze the trigger, and a "+(t.gen.nextBoolean() ? "single" : "solitary")+" round flies straight and true, "+(t.gen.nextBoolean() ? "hitting" : "striking")+" it right where its heart should be, and turning it to a swirling cloud of smoke.\n\n\n\tYou aim at the third, firing another round, but the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "Before you can switch magazines, " : "Before you can get off another round, ")+"it is upon you.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You aim your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "primary")+" "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire.\n\n\n\tYour aim was true, and your round flies directly into its head, turning it into swirling smoke.\n\n\n\tThe second shadow "+(t.gen.nextBoolean() ? "tries" : "attempts")+" to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot, but you are too skilled a "+(t.gen.nextBoolean() ? "gunslinger" : "sharpshooter")+", and it vanishes into swirling smoke.\n\n\n\tYou turn yor attention to the third.\n\n\n\n\n\tIt seems to have disappeared.\n\n\tYou look left...\n\t...and right...\n\n\n\n\t...left...\n\t...and right...\n\n\n\n\n\t...Suddenly, its in front of you!\n\n\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE) ? "You jump away, bringing your "+t.user.weapon+" to bear.\n\n\n\n\tYou manage to get off a shot just as it is upon you, turning the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" into swirling smoke, just as your life is prematurely ended by it.\n\n\n\n\t" : "You try to get off a shot with your "+t.user.weapon+", but you find that it is too cumbersome to be used effectively at close range, and the shadow consumes you.\n\n\t")+t.capitalize(t.user.gold.toString())+" and your "+t.user.weapon+" clatter to the ground."+(t.config.triggerEgg(.4) ? "\n\n\n\tSomeday, years after the Great Shadow War, and after the Great Familiar City has been conquered by the Army of the Second Coming, a Little Sister of the Rapture, along with her Big Daddy, will come across the remnants of the Pits, and all they will find of you is "+t.user.gold+" and your "+t.user.weapon+"." : "Somewhere in the distance, another adventurer approaches the Pits."));
break;
case targetingMinigame.output.BULLSEYE:
t.user.dead=false;
t.say(title+" against the odds", "You level your "+t.user.weapon+" at the shadows.\n\n\n\n\tDespite the impossibility of the odds, you ready yourself to fight.\n\n\n\tIn quick succession, you fire a round at each shadow, adjusting your aim without pausing to see if your aim is true, hitting each shadow right where the bright spots that pass for their eyes are.\n\n\n\n\tDespite the impossibility of how outmatched you are by the shadows, you have emerged victorious.");
break;
default:
t.say("Absorbed", "Your aim is out of this world!\n\n\n\tNo, seriously, that shot was... I don't even know.\n\n\n\tLet\'s just say this...");
}
}
else
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You fire one round at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\n\tYou miss."+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "You opt to forgo loading another shot, instead using your "+t.user.weapon+" as if it were a club." : "You aim again, and once more, you miss.\n\n\n\tThis process repeats itself over and over, until the "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" cease to worry about your shots, and instead process to laugh at you and your "+t.user.weapon+".\n\n\tAt that point, you decide it is better used as a club.")+"\n\n\n\tYou rush the shadows, striking one, and then proceeding to fight the others.\n\n\n\tMiraculously, it works.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "last" : "final")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into swirling smoke, a voice, a great and majestic voice, echoes through the Pits:\n\n\n\n\t\tLearn to aim!!\n\t\tThat was awful!\n\t\tGo to the shooting range or something.\n\t\tNow!!\n\n\tIgnoring the voice, shaking off the fright, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You level your "+t.user.weapon+" at the nearest "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\tThe round flies straight and true, flying towards its target.\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", as if it had sensed that you were shooting at it, "+(t.gen.nextBoolean() ? "dodging" : "evading")+" the shot.\n\n\tUnfortunately, at least for it, the round barely grazes it.\n\n\n\n\tApparently, even such a small impact is plenty to end it, turning it into a swirling cloud of smoke.\n\n\n\tThe second pauses, if only for a split second, and you take the opportunity to aim at the second one.\n\n\tYour shot is imperfect, and the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\n\tSwearing quietly, you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your "+t.user.weapon : "adjust your aim")+", firing again just in time to hit the second before it gets close.\n\n\n\n\tWithout pausing to watch it disappear into a cloud of smoke, you roll to the side, evading the lunge of the last "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou manage to bring your "+t.user.weapon+" to bear, and fire a single shot, managing to end it.\n\n\n\tShaking off your close encounter, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You aim your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire.\n\n\n\tThe round flies at its target, hitting it off center, and turning it into a swirling cloud of smoke, as you adjust your aim to hit the second enemy.\n\n\n\tThe second "+(t.gen.nextBoolean() ? "figure" : "shadow")+" faces you as you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your"+t.user.weapon : "steady your aim")+", approaching as you do.\n\n\t"+(t.gen.nextBoolean() ? "Luckily" : "Fortunately")+", you\'re able to get off the shot before it gets close.\n\n\tThe round hits the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", barely, turning it into a swirling cloud of smoke.\n\n\tThe final shadow turns to flee, as you level your "+t.user.weapon+" directly at it.\n\n\n\tYou fire before it gets out of range or into cover, and the final shadow disappears into swirling smoke.\n\n\n\n\n\tSatisfied with your victory, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You ready yourself, aiming directly at the closest "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\n\tYou quickly fire a shot, fully aware of the threat of the two remaining shadows, and watch only for a moment as the round flies through the air, and hits its mark.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into a swirling cloud of smoke, and you swing your "+t.user.weapon+" to fire at its lieutenant.\n\n\n\tYour enemy advances towards you, and you calmly "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tYour aim was near-perfect, but the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" sees it coming, and moves to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\tThe shadow is not quite quick enough, and the round strikes it, turning it to smoke.\n\n\n\tThe final shadow seems to have disappeared, but you see a hint of motion in the corner of your eye, and, almost as if by instinct, turn to face it.\n\n\n\n\n\n\tThe shadow is charging at you, doing its best to end you and defend the House of Shadows, but you are too quick for it, deftly pulling the trigger, and turning the shadow into a cloud of smoke.\n\n\n\tAfter contently watching it swirl away, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You quickly survey the field before you, and the three shadows that are before you.\n\n\n\tYou adjust your aim, leveling your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", prepared to fire.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "figures" : "shadows")+" begin to approach you, you grin ever-so-slightly, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tThe round glides smoothly towards its target, impacting it, and converting it into a swirling cloud of smoke.\n\n\n\tYou turn slightly, ready to fire at the next enemy, and "+(t.gen.nextBoolean() ? "adjust" : "calibrate")+" your aim.\n\n\n\n\tWhen your sights are in place, you fire, and turn the second "+(t.gen.nextBoolean() ? "enemy" : "apparition")+" into swirling smoke.\n\n\n\n\tYou frown slightly.\n\n\tYou could have sworn there where three, yet an empty battlefield and two kills seems to suggest otherwise.\n\n\n\tYou cautiously survey the area, then slowly start to move towards the House of Shadows.\n\n\n\tSuddenly, you see a dark smudge on the edge of your vision, and you turn to grab a better look.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", seeing that you found it, charges, as if it was hoping to eliminate you before you can do the same to it, but you fire, and it vanishes, replaced only by smoke.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You stare down the three approaching "+(t.gen.nextBoolean() ? "shadows" : "figures")+", sizing up your opposition.\n\n\n\tThe moment they move to attack, you start to fire, cleanly eliminating your leading "+(t.gen.nextBoolean() ? "target" : "enemy")+", and adjust your aim, targeting the second.\n\n\tIt makes an attempt to flee, but you fire, hitting it in what passes as its head.\n\n\n\tThe last shadow attempts to dodge your line of sight, but you follow it, and eliminate it too.\n\n\n\n\n\tYou pause for only a second to watch the trio disappear into swirling smoke as it diffuses, then turn towards the House of Shadows.");
break;
case targetingMinigame.output.BULLSEYE:
t.say(title, "You effortlessly fire a perfect shot at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+"shadow, a single blast from your"+t.user.weapon+" turning it to smoke.\n\n\tThe remaining shadows hesitate, and thus, you get in a shot at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+", turning it as well into a swirling cloud of smoke.\n\n\n\tThe last one attempts to flee, but you allow it no such luxury.\n\n\n\n\tWith all three shadows dispatched, you turn to face the House of Shadows.");
break;
default:
t.say("The brightness of a "+t.user.weapon, "In a long and drawn-out engagement, you and your "+t.user.weapon+" outshine the darkness of the shadows.\n\n\n\tFeeling invincible, you turn to face the House of Shadows.");
}
}
}
}
};
break;
case Cweapon.TYPE_NUCLEAR:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("A"+(t.gen.nextBoolean() ? " second" : "nother")+" sun", "You hit the detonator on your "+t.user.weapon+".\n\n\n\tA second fireball appears on the horizon, as the people stand in a familiar landscape, and watch you disappear.\n\n\n\tBehind them, the deadly, sickly glow illuminates a terrifying figure.");
}
};
break;
case Cweapon.TYPE_FUTURE:
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // CLOSE_RANGE_ONLY is the identifying flag for future weapons. If it's set, we're dealing with a lightsaber. Else, we (probably) have a raygun. These two get different dialogue.
t.say("Sword of light", "You charge the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", holding your "+t.user.weapon+" up on high.\n\n\n\tThe leading shadow, seemingly feeling courageous, steps toward you, but you counter its approach, dissolving it.\n\n\n\tThe other two "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" step away, deterred slightly by your charge, but not far enough.\n\n\n\n\n\tA lunge and a quick extension of the arm is enough to turn the shadow to ash almost akin to a hallucination.\n\n\tThe third shadow begins full flight, perhaps attempting to survive, perhaps attempting to draw you away from the House of Shadows.\n\tTo you, it doesn't matter: You chase it down, and eliminate it.\n\n\n\n\tHaving won a simple victory, you grin, and move towards the House of Shadows.");
else
t.say("The "+t.capitalize(t.user.weapon.name), "You aim your "+t.user.weapon+" directly at the leading "+t.user.weapon+", and pull the trigger.\n\n\n\tThe bolt of brilliant energy glides to its target, and hits it squarely.\n\n\n\tIt disappears into a mere wisp of smoke, leaving not a mere grain of ash.\n\n\n\n\tThe second and third shadows each seem afraid of you, and your "+t.user.weapon+", but you pay them no attention.\n\n\tYou place your sights in between the bright spots on the second "+(t.gen.nextBoolean() ? "apparition" : "figure")+", and pull the trigger.\n\n\n\tIt attempts to maneuver out of the way, but the bolt strikes it nonetheless, and it disappears as if it were never there.\n\n\n\tThe third turns to "+(t.gen.nextBoolean() ? "escape" : "run away")+", but your bolt outruns it by a factor of several million, and disintegrates it.\n\n\n\n\n\t"+(t.gen.nextBoolean() ? "Victorious" : "Feeling invincible")+", you turn towards the House of Shadows.");
}
};
break;
default:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("Unknowable", "You suddenly find yourself unable to "+(t.gen.nextBoolean() ? "use" : (t.gen.nextBoolean() ? "grip" : "hold"))+" your "+t.user.weapon+".");
}
};
}
t.th=new Thread(r);
t.th.start();
t.snooze(25); // We need a bit longer to insure processing finishes.
if (t.user.dead && !undead)
prepContinueButton();
else
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)4, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
break;
case 1:
t.th.interrupt();
Runnable r1;
if (t.config.triggerEgg(.05))
{
t.user.dead=false;
r1=new Runnable()
{
@Override
public void run()
{
t.say("Impossible", "You face the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" for only a split second before turning, and sprinting for the House of Shadows.\n\n\tYou "+(t.gen.nextBoolean() ? "grab" : "snatch")+" the detonator from its resting place, glancing only for an instant at the cratering charge it controls.\n\n\n\n\tClosely followed by the shadows, you grimace, hoping your distance from the charge is sufficient.\n\n\n\n\n\n\tYou hit the detonator, and the charge goes off, destroying the House and the shadows with it.\n\n\tThe three shadows that had assaulted you are not alone in disappearing, as an invisible wave passes over the pits, turning each shadow it finds into swirling smoke.\n\n\tUnfortunately, you were not quite far enough from the charge, and it throws you up and away, towards the center of the Pits.\n\n\n\n\n\n\n\tIn the mere seconds of flight you get, you resign yourself to your fate of dying, and of never finding out what exists beyond the image of the familiar landscape.\n\n\tAs soon as you do, as if it had been waiting, a strange force slows you and gently redirects your path.\n\n\tYou land, safe but not intact, in the center of "+(t.gen.nextBoolean() ? "Hell." : "the Pits."));
}
};
}
else
{
t.user.dead=true;
r1=new Runnable()
{
@Override
public void run()
{
t.say("Foolhardy", "You quickly turn and sprint towards the House of Shadows.\n\n\n\tUnfortunately, the "+(t.gen.nextBoolean() ? "apparitions" : "shadows")+" sense your advance, and absorb you.");
}
};
}
t.th.interrupt();
t.th=new Thread(r1);
t.th.start();
if (t.user.dead)
prepContinueButton();
else
{
prepContinueButton(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits((byte)0, stage, input, input2, true);
}
});
t.th.start();
}
});
}
break;
case 2:
t.user.dead=true;
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Outdone", "You attempt to flee from the shadows. They give chase, herding you using their superior numbers.\n\n\tJust when you think you\'ve lost them, you trip on a well, or poorly, placed rock, and tumble down a hill.\n\n\n\n\tWhen you stop, you look at a black sky, only to realize that you\'re staring at a shadow.");
}
});
t.th.start();
prepContinueButton();
break;
default:
dataError();
}
break;
}
break;
}
}
}
public void inputClear()
{
if (doCommitSuicide)
t.user.commitSuicide();
else
{
stage-=2;
runStage();
}
}
public void dataError() // Called when a switch goes to a default case, when this is nonsensical of course.
{
t.user.dead=true;
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say(t.gen.nextBoolean() ? "Unknowable" : "Legend", "A vortex of Infinite Improbability opens, and consumes you.\n\n\n\n\n\n");
t.snooze(750+t.gen.nextInt(500));
Cgame.unSignalGameContinue();
t.snooze(2500);
t.sayWhat("That means you have a bug.\n\n");
Cgame.unSignalGameContinue();
t.snooze(1500);
t.sayWhat("Specifically, the game engine managed to set your state to one that makes negative amounts of sense.\n\n");
Cgame.unSignalGameContinue();
t.snooze(500);
t.sayWhat("Look buddy, you got a kill-bug.\n\tJust play it again, hopefully the bug won\'t rear its ugly head.");
}
});
}
public void prepContinueButton()
{
t.snooze(AnimationUtils.loadAnimation(t, R.anim.fadeout).getDuration());
while(t.waiting)
t.frameTick();
t.delay(t.gen.nextInt(250)+250);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
View v=t.findViewById(R.id.gameContinueButton);
if (v!=null)
{
Button b=(Button)v;
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
inputted=-1;
t.th.interrupt();
t.displayHandler.removeMessages(1);
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
t.displayHandler.removeMessages(1);
if (t.user.dead)
{
stage=-1;
t.config.computerPaused=true;
}
else
t.config.computerPaused=false;
runStage();
}
});
t.th.start();
}
});
b.setVisibility(View.VISIBLE);
}
else
t.logError("prepContinueButton() called, but could not find button.");
}
});
}
public void prepContinueButton(final View.OnClickListener onClick)
{
t.snooze(AnimationUtils.loadAnimation(t, R.anim.fadeout).getDuration());
while(t.waiting)
t.frameTick();
t.delay(t.gen.nextInt(250)+250);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
View v=t.findViewById(R.id.gameContinueButton);
if (v!=null)
{
Button b=(Button)v;
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
inputted=-1;
t.th.interrupt();
t.displayHandler.removeMessages(1);
onClick.onClick(v);
}
});
b.setVisibility(View.VISIBLE);
}
else
t.logError("prepContinueButton() called, but could not find button.");
}
});
}
private static LinearLayout prepInput()
{
t.setContentView(R.layout.input);
t.currentView=R.id.inputLayout;
t.setUi();
return (LinearLayout)t.findViewById(R.id.inputButtonBar);
}
private static LinearLayout prepInput(String inputTitle)
{
t.setContentView(R.layout.input);
t.currentView=R.id.inputLayout;
((TextView)t.findViewById(R.id.inputTitle)).setText(inputTitle);
t.setUi();
return (LinearLayout)t.findViewById(R.id.inputButtonBar);
}
private static void eatenByGrue()
{
t.user.dead=true;
t.config.computerPaused=true;
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
t.setContentView(R.layout.grue);
t.currentView=R.id.grueLayout;
t.setUi();
if (t.config.triggerEgg(1, 3))
((TextView)t.findViewById(R.id.grueContent)).setTextColor(Color.rgb(255, t.gen.nextInt(256), t.gen.nextInt(256)));
}
});
}
public boolean onMove(double IBOdds)
{
t.user.gold.accrueInterest();
if (t.config.schoolEggs && t.config.triggerEgg(IBOdds))
{
t.user.dead=!t.config.triggerEgg(99);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String message="You black out, and wake up in an IB HL English classroom.\n\n\tAs you look around in confusion, the teacher says,\n\n\t\tEssay test today!\n\t\tHere\'s the book!\n\n\tAs the students prepare themselves for an essay test, and the teacher passes out their books, you decide you have no choice.\n\n\tYou close your eyes...";
if (t.user.weapon.type==Cweapon.TYPE_FUTURE)
{
if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // This is the identifying trait of the lightsaber.
message+="\n\n\n\n\n\n\t...And draw your "+t.user.weapon+"!\n\n\tYou charge at the teacher, intending to fight your way out.\n\n\tAll of a sudden, a student blocks your path, hitting you, saying something about the teacher not yet having handed out the homework.\n\n\tAs you try to stop, your lightsaber slices cleanly through a girl next to you.\n\n\tShe collapses, dead.\n\n\tBefore you can react, ";
else
message+="\n\n\n\n\n\t...And draw your "+t.user.weapon+"!\n\n\tYou aim at the teacher, and tense.\n\n\n\tJust as you\'re ready to fire, a student hits you, yelling something about the homework needing explanation.\n\n\t"+(t.gen.nextBoolean() ? "She" : "He")+" throws off your balance, and your aim as well.\n\n\n\tYour shot strikes another student, turning "+(t.gen.nextBoolean() ? "him" : "her")+" into ash.\n\n\tSuddenly, ";
message+="Gandalf appears.\n\n\tHe yells,\n\n\t\tHow dare you do this!\n\t\tYou are unworthy!!!\n\n\tWith that...";
}
t.say("Baccalaureate", message);
}
else
{
String[] topics={
"differentiation",
"integration",
"the Fundamental Theorem of Calculus",
"how to find volume via integrals",
"Riemann sums",
"limits",
"relative rates",
"Taylor polynomials",
"series",
"vectors",
"proof by induction",
"differential equations",
"optimization"
};
t.say("The Diploma", "You black out, and awake in an IB HL Math classroom.\n\n\tAs you look around in confusion, the teacher begins to teach "+topics[t.gen.nextInt(topics.length)]+".\n\n\tYou feel...\n\tMotivated, strangely enough.\n\n\n\n\tThrough hard work, perseverance, and worship of Lord 2-19, you get the IB diploma.");
}
}
});
t.th.start();
prepContinueButton(t.user.dead ? new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.type==Cweapon.TYPE_FUTURE)
{
t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE;
t.user.commitSuicide();
}
else if (t.config.triggerEgg(.2))
t.user.commitSuicide();
else
{
stage=-1;
runStage();
}
}
});
t.th.start();
}
} : onWin);
return true;
}
return false;
}
public boolean onMove (double IBNumerator, double IBDenominator)
{
return onMove(IBNumerator/IBDenominator);
}
public boolean onMove (int oneIn)
{
return onMove(1, oneIn);
}
public OnClickListener onWin=new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.setContentView(R.layout.quit);
t.currentView=R.id.quitLayout;
t.setUi();
((TextView)t.findViewById(R.id.quitTitle)).setText("You win!!");
((Button)t.findViewById(R.id.quitContinueButton)).setText("Play again");
}
};
private boolean archeryMinigame (final int threshold, final double time) // Reimplement this like KEYSEC.
{
final keypressMinigame game=new keypressMinigame((threshold/time)*.25);
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
t.setContentView(R.layout.archery);
t.currentView=R.id.archeryLayout;
t.setUi();
game.button=t.findViewById(R.id.archeryBullseye);
((TextView)t.findViewById(R.id.archeryThreshold)).setText(Integer.toString(threshold));
((TextView)t.findViewById(R.id.archeryCurrent)).setText("0");
((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
if (t.snooze((long)((1000*game.timeRemaining)-((long)(1000*game.timeRemaining)))))
return true;
while (game.timeRemaining>=1)
{
if (t.snooze(1000))
return true;
--game.timeRemaining;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
}
game.timeRemaining=time;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Configuration c=t.getResources().getConfiguration();
boolean landscape=(c.orientation==Configuration.ORIENTATION_LANDSCAPE); // If we're in landscape mode, we need all the space we can get.
t.findViewById(R.id.archeryWait).setVisibility(landscape || t.gen.nextBoolean() ? View.GONE : View.INVISIBLE);
((TextView)t.findViewById(R.id.archeryTimingLabel)).setText("Time ends in:");
((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining));
game.button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
game.deltaX+=Math.copySign(Math.max(Math.abs(t.gen.nextGaussian()), t.gen.nextDouble()), game.deltaX);
game.deltaY+=Math.copySign(Math.max(Math.abs(t.gen.nextGaussian()), t.gen.nextDouble()), game.deltaY);
++game.presses;
((TextView)t.findViewById(R.id.archeryCurrent)).setText(Integer.toString(game.presses));
}
});
}
});
Thread ticker=new Thread(new Runnable()
{
@Override
public void run()
{
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)game.button.getLayoutParams();
Runnable r=new Runnable()
{
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void run()
{
if (!(Build.VERSION.SDK_INT>=18 && game.button.isInLayout()))
game.button.requestLayout();
}
};
while (!game.done)
{
double factor=60.0/MainActivity.TARGET_FPS;
int dX=(int)Math.round(game.deltaX*factor);
int dY=(int)Math.round(game.deltaY*factor);
if ((lp.leftMargin+dX)<0 || (lp.leftMargin+dX)>(t.findViewById(R.id.archeryBullseyeLayout).getWidth()-game.button.getWidth()))
{
game.deltaX*=-1;
dX*=-1;
}
if ((lp.topMargin+dY)<0 || (lp.topMargin+dY)>(t.findViewById(R.id.archeryBullseyeLayout).getHeight()-game.button.getHeight()))
{
game.deltaY*=-1;
dY*=-1;
}
lp.topMargin+=dY;
lp.leftMargin+=dX;
t.runOnUiThread(r);
if (t.frameTick())
return;
}
}
});
ticker.start();
t.snooze((long)(1000*(game.timeRemaining-Math.floor(game.timeRemaining))));
game.timeRemaining=Math.floor(game.timeRemaining);
while (game.timeRemaining>=1)
{
t.snooze(1000);
--game.timeRemaining;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
}
game.done=true;
t.user.dead=(game.presses<threshold);
return t.user.dead;
}
public targetingMinigame.output aimMinigame()
{
final targetingMinigame game=new targetingMinigame();
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
t.setContentView(R.layout.aimer);
t.currentView=R.id.aimerLayout;
game.crosshairs=t.findViewById(R.id.aimerCrosshairs);
game.layout=t.findViewById(R.id.aimerBullseyeLayout);
game.bullseye=t.findViewById(R.id.aimerBullseye);
game.crosshairCoord=(RelativeLayout.LayoutParams)game.crosshairs.getLayoutParams();
((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)Math.floor(game.timeRemaining)));
Configuration c=t.getResources().getConfiguration();
if (c.orientation==Configuration.ORIENTATION_LANDSCAPE)
game.layout.getLayoutParams().width=game.layout.getHeight();
}
});
if (t.snooze((long)((1000*game.timeRemaining)-((long)(1000*game.timeRemaining)))))
return new targetingMinigame.output();
game.timeRemaining=Math.floor(game.timeRemaining);
while (game.timeRemaining>=1)
{
if (t.snooze(1000))
return new targetingMinigame.output();
--game.timeRemaining;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
}
game.timeRemaining=t.gen.nextGaussian()+(t.config.difficultyMult*8)+5;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
game.crosshairs.setVisibility(View.VISIBLE);
((TextView)t.findViewById(R.id.aimerTimingTitle)).setText("Time remaining:");
((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)Math.floor(game.timeRemaining)));
game.crosshairCoord.leftMargin=t.gen.nextInt(game.layout.getWidth()-game.crosshairs.getWidth());
game.crosshairCoord.topMargin=t.gen.nextInt(game.layout.getHeight()-game.crosshairs.getHeight());
t.findViewById(R.id.aimerUpArrow).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaY)));
if (game.crosshairCoord.topMargin<=delta)
game.crosshairCoord.topMargin=0;
else
game.crosshairCoord.topMargin-=delta;
}
});
t.findViewById(R.id.aimerRightArrow).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaX)));
if (game.crosshairCoord.topMargin+delta+game.crosshairs.getHeight()>=game.layout.getHeight())
game.crosshairCoord.topMargin=game.layout.getHeight()-game.crosshairs.getHeight();
else
game.crosshairCoord.leftMargin+=delta;
}
});
t.findViewById(R.id.aimerDownArrow).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaY)));
if (game.crosshairCoord.topMargin+delta+game.crosshairs.getHeight()>=game.layout.getHeight())
game.crosshairCoord.topMargin=game.layout.getHeight()-game.crosshairs.getHeight();
else
game.crosshairCoord.topMargin+=delta;
}
});
t.findViewById(R.id.aimerLeftArrow).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaX)));
if (game.crosshairCoord.topMargin<=delta)
game.crosshairCoord.topMargin=0;
else
game.crosshairCoord.leftMargin-=delta;
}
});
}
});
game.startSway();
t.snooze((long)(1000*(game.timeRemaining-Math.floor(game.timeRemaining))));
game.timeRemaining=Math.floor(game.timeRemaining);
while (game.timeRemaining>=1)
{
t.snooze(1000);
--game.timeRemaining;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
}
game.swayer.interrupt();
game.swayer=null;
return game.result();
}
@Override
public int describeContents ()
{
return 4;
}
@Override
public void writeToParcel (Parcel out, int n)
{
out.writeInt(--stage);
out.writeInt(line);
out.writeInt(inputted);
}
public static final Parcelable.Creator<Cgame> CREATOR=new Parcelable.Creator<Cgame> ()
{
@Override
public Cgame createFromParcel (Parcel in)
{
return new Cgame(in);
}
@Override
public Cgame[] newArray (int n)
{
return new Cgame[n];
}
};
// Data-Only classes: NOT CONSERVED through onRestoreInstanceState()
private static class keypressMinigame
{
public int presses;
public double deltaX;
public double deltaY;
public double timeRemaining;
public boolean done;
public View button;
public keypressMinigame()
{
presses=0;
deltaX=t.gen.nextGaussian();
deltaY=t.gen.nextGaussian();
timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian();
done=false;
}
public keypressMinigame(double speedMult)
{
presses=0;
deltaX=speedMult*t.gen.nextGaussian();
deltaY=speedMult*t.gen.nextGaussian();
timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian();
done=false;
}
}
private static class targetingMinigame
{
public static class output // The type for returned data.
{
public double distance; // Distance from a true bullseye
public int type; // The classification of this shot
public output()
{
distance=-1;
type=-1;
MAX_DISTANCE=-1;
}
public static final int MISSED=6;
public static final int GRAZED=5;
public static final int POOR=4;
public static final int HIT=3;
public static final int GOOD=2;
public static final int CRITICAL=1;
public static final int BULLSEYE=0;
public static double MAX_DISTANCE;
public static String toString (int n)
{
switch (n)
{
case MISSED:
return t.gen.nextBoolean() ? "Miss" : "Fail";
case GRAZED:
return "Close"+(t.gen.nextBoolean() ? (" only counts in "+(t.config.triggerEgg(1, 3) ? "handshoes and horse grenades" : "horseshoes and hand grenades")) : ", but no cigar");
case POOR:
return t.gen.nextBoolean() ? "Needs practice" : "Just barely";
case HIT:
return "Solid "+(t.gen.nextBoolean() ? "shot" : "hit");
case GOOD:
return "Good "+(t.gen.nextBoolean() ? "shot" : "hit");
case CRITICAL:
String[] roots={
"Critical",
"Excellent",
"Great",
"Incredible",
"Sharpshooter\'s",
"Master\'s",
"Masterful"
};
String[] suffixes={
"hit",
"shot",
"impact"
};
return roots[t.gen.nextInt(roots.length)]+" "+suffixes[t.gen.nextInt(suffixes.length)];
case BULLSEYE:
return t.gen.nextBoolean() ? "Bullseye" : "Perfect "+(t.gen.nextBoolean() ? "shot" : "aim");
default:
return "Gunshot";
}
}
public static String toString(output o)
{
return o.toString();
}
@Override
public String toString()
{
return toString(type);
}
}
public View crosshairs;
public View bullseye;
public View layout;
RelativeLayout.LayoutParams crosshairCoord;
public double weaponSwayMultiplier;
public int weaponSwayMaximum;
public double timeRemaining;
public double deltaX;
public double deltaY;
public Thread swayer;
public targetingMinigame()
{
weaponSwayMultiplier=.75+(.25*t.gen.nextGaussian());
weaponSwayMaximum=3+t.gen.nextInt(4);
timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian();
deltaX=2*(t.gen.nextDouble()+t.gen.nextInt(21)+10);
deltaY=2*(t.gen.nextDouble()+t.gen.nextInt(21)+10);
}
public void startSway()
{
if (swayer!=null)
swayer.interrupt();
swayer=new Thread(new Runnable() // Improvement target
{
@Override
public void run()
{
final Runnable r=new Runnable()
{
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void run()
{
if (!(Build.VERSION.SDK_INT>=18 && layout.isInLayout()))
layout.requestLayout();
}
};
double angle=t.gen.nextDouble()*2*Math.PI;
while (!Thread.interrupted())
{
double velocity=weaponSwayMultiplier*weaponSwayMaximum*Math.max(.25, t.gen.nextDouble())*(MainActivity.TARGET_FPS/60.0);
if (0==t.gen.nextInt((int)(MainActivity.TARGET_FPS+1)))
{
angle+=Math.max(Math.PI/6, t.gen.nextDouble()*Math.PI)*(t.gen.nextBoolean() ? -1 : 1);
velocity*=.5;
}
crosshairCoord.leftMargin=(int)Math.round(Math.max(0, Math.min(layout.getWidth()-crosshairs.getWidth(), crosshairCoord.leftMargin+(Math.cos(angle)*velocity))));
crosshairCoord.topMargin=(int)Math.round(Math.max(0, Math.min(layout.getHeight()-crosshairs.getHeight(), crosshairCoord.topMargin-(Math.sin(angle)*velocity))));
t.runOnUiThread(r);
t.frameTick(1);
}
}
});
swayer.start();
}
public output result()
{
output out=new output();
RelativeLayout.LayoutParams bulls=(RelativeLayout.LayoutParams)bullseye.getLayoutParams();
RelativeLayout.LayoutParams cross=(RelativeLayout.LayoutParams)crosshairs.getLayoutParams();
double tmp=(bulls.leftMargin+(bullseye.getWidth()*.5))-(cross.leftMargin+(crosshairs.getWidth()*.5));
double num=(bulls.topMargin+(bullseye.getHeight()*.5))-(cross.topMargin+(crosshairs.getHeight()*.5));
out.distance=Math.sqrt((tmp*tmp)+(num*num));
output.MAX_DISTANCE=.5*bullseye.getWidth();
// out.type=(int)Math.ceil(out.distance/bullseye.getWidth()/12); // Mathematical way. Found to be buggy and disabled: If fixed, this will be more efficient.
double diff=bullseye.getWidth()/10;
if (out.distance==0)
out.type=output.BULLSEYE;
else if (out.distance<diff)
out.type=output.CRITICAL;
else if (out.distance<(2*diff))
out.type=output.GOOD;
else if (out.distance<(3*diff))
out.type=output.HIT;
else if (out.distance<(4*diff))
out.type=output.POOR;
else if (out.distance<(5*diff))
out.type=output.GRAZED;
else
out.type=output.MISSED;
return out;
}
}
} |
package org.wikipedia;
public final class Constants {
// Keep loader IDs unique to each loader. If the loader specified by the ID already exists, the
// last created loader is reused.
public static final int HISTORY_FRAGMENT_LOADER_ID = 100;
public static final int RECENT_SEARCHES_FRAGMENT_LOADER_ID = 101;
public static final int USER_OPTION_ROW_FRAGMENT_LOADER_ID = 102;
public static final String WIKIPEDIA_URL = "https://wikipedia.org/";
public static final String PLAIN_TEXT_MIME_TYPE = "text/plain";
public static final String ACCEPT_HEADER_PREFIX = "accept: application/json; charset=utf-8; "
+ "profile=\"https:
public static final String ACCEPT_HEADER_SUMMARY = ACCEPT_HEADER_PREFIX + "Summary/1.2.0\"";
public static final int ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 44;
public static final int ACTIVITY_REQUEST_VOICE_SEARCH = 45;
public static final int ACTIVITY_REQUEST_LANGLINKS = 50;
public static final int ACTIVITY_REQUEST_EDIT_SECTION = 51;
public static final int ACTIVITY_REQUEST_GALLERY = 52;
public static final int ACTIVITY_REQUEST_LOGIN = 53;
public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT_SUCCESS = 54;
public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT = 55;
public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT_TUTORIAL = 56;
public static final int ACTIVITY_REQUEST_OFFLINE_TUTORIAL = 57;
public static final String INTENT_RETURN_TO_MAIN = "returnToMain";
public static final String INTENT_SEARCH_FROM_WIDGET = "searchFromWidget";
public static final String INTENT_FEATURED_ARTICLE_FROM_WIDGET = "featuredArticleFromWidget";
public static final String INTENT_APP_SHORTCUT_SEARCH = "appShortcutSearch";
public static final String INTENT_APP_SHORTCUT_CONTINUE_READING = "appShortcutContinueReading";
public static final String INTENT_APP_SHORTCUT_RANDOM = "appShortcutRandom";
public static final String INTENT_EXTRA_REVERT_QNUMBER = "revertQNumber";
public static final String INTENT_EXTRA_DELETE_READING_LIST = "deleteReadingList";
public static final int PROGRESS_BAR_MAX_VALUE = 10_000;
public static final int MAX_SUGGESTION_RESULTS = 3;
public static final int SUGGESTION_REQUEST_ITEMS = 5;
public static final int API_QUERY_MAX_TITLES = 50;
public static final int PREFERRED_THUMB_SIZE = 320;
public static final int MAX_TABS = 100;
private Constants() { }
} |
import java.io.Writer;
import java.io.PrintWriter;
public class SimpleIA32Generator extends AssemblyGenerator {
public int getSystemIntSize() {
return 4;
}
public int getPointerSize() {
return 4;
}
public int getFunctionSize() {
return 4;
}
PrintWriter out;
private String currentFunctionName;
private int nextLabelId;
private String getNextLabel() {
return "stoa.label." + (nextLabelId++);
}
public void generateAssembly(Writer out,
StaticVariable[] staticVariableDefinitionList,
Function[] functionDefinitionList) {
this.out = new PrintWriter(out);
nextLabelId = 0;
this.out.println(".section .text");
for (int i = 0; i < functionDefinitionList.length; i++) {
generateFunction(functionDefinitionList[i]);
}
this.out.println(".section .bss");
for (int i = 0; i < staticVariableDefinitionList.length; i++) {
StaticVariable sv = staticVariableDefinitionList[i];
this.out.println(".comm " + sv.getName() + ", " + sv.getDataType().getWidth());
}
this.out.flush();
}
private void generateFunction(Function func) {
currentFunctionName = func.getName();
out.println(".globl " + currentFunctionName);
out.println(currentFunctionName + ":");
int instNum = func.getInstructionNumber();
for (int i = 0; i < instNum; i++) {
generateInstruction(func.getInstruction(i));
}
out.println("stoa.funcend." + currentFunctionName + ":");
out.println("\tret");
}
private void generateInstruction(Instruction inst) {
if (inst instanceof NormalExpression) {
Expression expr = ((NormalExpression)inst).getExpression();
generateExpressionEvaluation(expr);
out.println("\tpop %eax");
} else if (inst instanceof ReturnInstruction) {
ReturnInstruction ret = (ReturnInstruction)inst;
if (ret.hasExpression()) {
generateExpressionEvaluation(ret.getExpression());
out.println("\tpop %eax");
}
out.println("\tjmp stoa.funcend." + currentFunctionName);
} else if (inst instanceof ConditionalBranch) {
ConditionalBranch cb = (ConditionalBranch)inst;
int insNum;
generateExpressionEvaluation(cb.getCondition());
out.println("\tpop %eax");
out.println("\ttest %eax, %eax");
String label1 = getNextLabel();
String label2 = getNextLabel();
String label3 = null;
out.println("\tjnz " + label1);
out.println("\tjmp " + label2);
out.println(label1 + ":");
insNum = cb.getThenInstructionNumber();
for (int i = 0; i < insNum; i++) {
generateInstruction(cb.getThenInstruction(i));
}
if (cb.hasElse()) {
label3 = getNextLabel();
out.println("\tjmp " + label3);
}
out.println(label2 + ":");
if (cb.hasElse()) {
insNum = cb.getElseInstructionNumber();
for (int i = 0; i < insNum; i++) {
generateInstruction(cb.getElseInstruction(i));
}
out.println(label3 + ":");
}
} else if (inst instanceof InfiniteLoop) {
InfiniteLoop infLoop = (InfiniteLoop)inst;
int insNum = infLoop.getInstructionNumber();
String label = getNextLabel();
out.println(label + ":");
for (int i = 0; i < insNum; i++) {
generateInstruction(infLoop.getInstruction(i));
}
out.println("\tjmp " + label);
} else if (inst instanceof WhileLoop) {
WhileLoop wLoop = (WhileLoop)inst;
int insNum = wLoop.getInstructionNumber();
String label1 = getNextLabel();
String label2 = getNextLabel();
String label3 = getNextLabel();
out.println(label1 + ":");
generateExpressionEvaluation(wLoop.getCondition());
out.println("\tpop %eax");
out.println("\ttest %eax, %eax");
out.println("\tjnz " + label3);
out.println("\tjmp " + label2);
out.println(label3 + ":");
for (int i = 0; i < insNum; i++) {
generateInstruction(wLoop.getInstruction(i));
}
out.println("\tjmp " + label1);
out.println(label2 + ":");
} else if (inst instanceof BreakInstruction) {
throw new SystemLimitException("BreakInstruction not implemented yet");
} else if (inst instanceof ContinueInstruction) {
throw new SystemLimitException("ContinueInstruction not implemented yet");
}
}
private void generateExpressionEvaluation(Expression expr) {
generateExpressionEvaluation(expr, false);
}
private void generateExpressionEvaluation(Expression expr, boolean wantAddress) {
if (expr instanceof BinaryOperator) {
BinaryOperator op = (BinaryOperator)expr;
generateExpressionEvaluation(op.getLeft(), op.getKind() == BinaryOperator.Kind.OP_ASSIGN);
if (op.getKind() != BinaryOperator.Kind.OP_LOGICAL_AND &&
op.getKind() != BinaryOperator.Kind.OP_LOGICAL_OR) {
generateExpressionEvaluation(op.getRight(), false);
out.println("\tpop %ecx");
}
out.println("\tpop %eax");
String comparisionOperatorInstruction = null;
switch(op.getKind()) {
case OP_ARRAY:
throw new SystemLimitException("OP_ARRAY not implemented yet");
case OP_MUL:
if (((IntegerType)expr.getDataType()).isSigned()) {
out.println("\timul %ecx");
} else {
out.println("\tmul %ecx");
}
case OP_DIV:
if (((IntegerType)expr.getDataType()).isSigned()) {
out.println("\tcdq");
out.println("\tidiv %ecx");
} else {
out.println("xor %edx, %edx");
out.println("\tdiv %ecx");
}
case OP_MOD:
if (((IntegerType)expr.getDataType()).isSigned()) {
out.println("\tcdq");
out.println("\tidiv %ecx");
} else {
out.println("xor %edx, %edx");
out.println("\tdiv %ecx");
}
out.println("\tmov %edx, %eax");
case OP_ADD:
out.println("\tadd %ecx, %eax");
break;
case OP_SUB:
out.println("\tsub %ecx, %eax");
break;
case OP_LEFT_SHIFT:
throw new SystemLimitException("OP_LEFT_SHIFT not implemented yet");
case OP_RIGHT_SHIFT_ARITIMETIC:
throw new SystemLimitException("OP_RIGHT_SHIFT_ARITIMETIC not implemented yet");
case OP_RIGHT_SHIFT_LOGICAL:
throw new SystemLimitException("OP_RIGHT_SHIFT_LOGICAL not implemented yet");
case OP_LEFT_ROTATE:
throw new SystemLimitException("OP_LEFT_ROTATE not implemented yet");
case OP_RIGHT_ROTATE:
throw new SystemLimitException("OP_RIGHT_ROTATE not implemented yet");
case OP_BIT_AND:
throw new SystemLimitException("OP_BIT_AND not implemented yet");
case OP_BIT_OR:
throw new SystemLimitException("OP_BIT_OR not implemented yet");
case OP_BIT_XOR:
throw new SystemLimitException("OP_BIT_XOR not implemented yet");
case OP_ASSIGN:
out.println("\txchg %ecx, %eax");
out.println("\tmov %eax, (%ecx)");
break;
case OP_GT:
comparisionOperatorInstruction = ((IntegerType)expr.getDataType()).isSigned() ? "jng" : "jna";
break;
case OP_GTE:
comparisionOperatorInstruction = ((IntegerType)expr.getDataType()).isSigned() ? "jnge" : "jnae";
break;
case OP_LT:
comparisionOperatorInstruction = ((IntegerType)expr.getDataType()).isSigned() ? "jnl" : "jnb";
break;
case OP_LTE:
comparisionOperatorInstruction = ((IntegerType)expr.getDataType()).isSigned() ? "jnle" : "jnbe";
break;
case OP_EQUAL:
comparisionOperatorInstruction = "jne";
break;
case OP_NOT_EQUAL:
comparisionOperatorInstruction = "je";
break;
case OP_LOGICAL_AND:
throw new SystemLimitException("OP_LOGICAL_AND not implemented yet");
case OP_LOGICAL_OR:
throw new SystemLimitException("OP_LOGICAL_OR not implemented yet");
default:
throw new SystemLimitException("unexpected kind of BinaryOperator: " + op.getKind());
}
if (comparisionOperatorInstruction != null) {
String label = getNextLabel();
out.println("\tcmp %ecx, %eax");
out.println("\tmov $0, %eax");
out.println("\t" + comparisionOperatorInstruction + " " + label);
out.println("\tinc %eax");
out.println(label + ":");
}
out.println("\tpush %eax");
} else if (expr instanceof UnaryOperator) {
throw new SystemLimitException("UnaryOperator not implemented yet");
} else if (expr instanceof FunctionCallOperator) {
FunctionCallOperator funcCall = (FunctionCallOperator)expr;
int argumentNum = funcCall.getArgumentsNum();
for (int i = argumentNum - 1; i >= 0; i
generateExpressionEvaluation(funcCall.getArgument(i));
}
generateExpressionEvaluation(funcCall.getFunction());
out.println("\tpop %eax");
out.println("\tcall *%eax");
out.println("\tadd $" + (4 * argumentNum) + ", %esp");
out.println("\tpush %eax");
} else if (expr instanceof CastOperator) {
throw new SystemLimitException("CastOperator not implemented yet");
} else if (expr instanceof VariableAccess) {
if (expr.getDataType().getWidth() != 4) {
throw new SystemLimitException("currently only 4-byte variable is supported");
}
Identifier ident = ((VariableAccess)expr).getIdentifier();
if (ident instanceof StaticVariable) {
if (wantAddress || expr.getDataType() instanceof FunctionType) {
out.println("\tpushl $" + ident.getName());
} else {
out.println("\tpushl (" + ident.getName() + ")");
}
} else if (ident instanceof AutomaticVariable) {
throw new SystemLimitException("AutomaticVariable not implemented yet");
} else if (ident instanceof DefinedValue) {
out.println("\tpushl $" + ((DefinedValue)ident).getValue());
} else if (ident instanceof AddressVariable) {
if (wantAddress) {
out.println("\tpushl $" + ((AddressVariable)ident).getAddress());
} else {
out.println("\tpushl (" + ((AddressVariable)ident).getAddress() + ")");
}
}
} else if (expr instanceof IntegerLiteral) {
out.println("\tpushl $" + ((IntegerLiteral)expr).getValue());
} else if (expr instanceof StringLiteral) {
throw new SystemLimitException("StringLiteral not implemented yet");
}
}
} |
package FlightScheduler;
// INPUT.JAVA
// Input reader for Lab 4b airport and flight data
// To read all the information necessary for this lab:
// (1) Create an object (say, "input") of type Input.
// (2) Call input.readAirports(<airportFileName>)
// (3) Call input.readFlights(<flightFileName>)
// Note that you *must* do (3) after (2).
// If all goes well, you will then have access to
// * input.airports -- an array of Airport objects
// * input.flights -- an array of Flight objects
// * input.airportMap -- a HashMap mapping airport codes to the
// corresponding Airport objects
import java.util.*;
class Input {
// Airport information
class Airport {
public String name; // name of airport (3-letter code)
public int offset; // offset of local time from GMT (in minutes)
public int id; // convenient integer identifier
}
// Flight information
// NB: all times are GMT, in minutes since midnight
class Flight {
public String name; // flight name
public Airport startAirport, endAirport; // flight termini
public int startTime, endTime; // departure and arrival times
}
// array of all airports read from input
public Airport airports[];
// array of all flights read from input
public Flight flights[];
// mapping from airport codes (strings) to Airport objects
public HashMap<String,Airport> airportMap;
// constructor
public Input()
{
airportMap = new HashMap<String,Airport>();
}
// readAirports()
// Read the airport file
public void readAirports(String filename)
{
FileParser fp = new FileParser(filename);
// hold the airports as they are read
ArrayList<Airport> aplist = new ArrayList<Airport>();
while (!fp.isEof())
{
Airport ap = new Airport();
ap.name = fp.readWord();
ap.offset = (fp.readInt() / 100) * 60;
if (!fp.isEof())
{
// crete mapping from names to objects
airportMap.put(ap.name, ap);
aplist.add(ap);
}
}
airports = new Airport [aplist.size()];
aplist.toArray(airports);
}
// readFlights()
// read the flight file
public void readFlights(String filename)
{
FileParser fp = new FileParser(filename);
// hold the flights as they are read
ArrayList<Flight> fllist = new ArrayList<Flight>();
// read the flights and store their times in GMT
while (!fp.isEof())
{
Flight fl = new Flight();
String airline;
int flightno;
airline = fp.readWord();
flightno = fp.readInt();
fl.name = airline + "-" + flightno;
if (fp.isEof())
break;
String code;
int tm;
String ampm;
code = fp.readWord();
fl.startAirport = airportMap.get(code);
tm = fp.readInt();
ampm = fp.readWord();
fl.startTime = toTime(tm, ampm, fl.startAirport.offset);
code = fp.readWord();
fl.endAirport = airportMap.get(code);
tm = fp.readInt();
ampm = fp.readWord();
fl.endTime = toTime(tm, ampm, fl.endAirport.offset);
fllist.add(fl);
}
flights = new Flight [fllist.size()];
fllist.toArray(flights);
}
// toTime()
// convert raw time value and AM/PM in local time, to minutes
// since midnight in GMT, using supplied offset from GMT.
int toTime(int timeRaw, String ampm, int offset)
{
int hour = (timeRaw / 100) % 12;
int minute = timeRaw % 100;
boolean isPM = (ampm.charAt(0) == 'P');
int minutes = hour * 60 + minute;
if (isPM) minutes += 12 * 60;
int finalTime = (minutes - offset + 24 * 60) % (24 * 60);
return finalTime;
}
} |
package edu.duke.cabig.c3pr.web.admin;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import edu.duke.cabig.c3pr.constants.ContactMechanismType;
import edu.duke.cabig.c3pr.constants.NotificationEventTypeEnum;
import edu.duke.cabig.c3pr.constants.NotificationFrequencyEnum;
import edu.duke.cabig.c3pr.dao.HealthcareSiteDao;
import edu.duke.cabig.c3pr.dao.InvestigatorDao;
import edu.duke.cabig.c3pr.dao.PlannedNotificationDao;
import edu.duke.cabig.c3pr.dao.ResearchStaffDao;
import edu.duke.cabig.c3pr.dao.UserDao;
import edu.duke.cabig.c3pr.domain.ContactMechanism;
import edu.duke.cabig.c3pr.domain.ContactMechanismBasedRecipient;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.Investigator;
import edu.duke.cabig.c3pr.domain.Organization;
import edu.duke.cabig.c3pr.domain.PlannedNotification;
import edu.duke.cabig.c3pr.domain.ResearchStaff;
import edu.duke.cabig.c3pr.domain.UserBasedRecipient;
import edu.duke.cabig.c3pr.domain.repository.impl.CSMUserRepositoryImpl.C3PRNoSuchUserException;
import edu.duke.cabig.c3pr.domain.scheduler.runtime.job.ScheduledNotificationJob;
import edu.duke.cabig.c3pr.service.OrganizationService;
import edu.duke.cabig.c3pr.tools.Configuration;
import edu.duke.cabig.c3pr.utils.ConfigurationProperty;
import edu.duke.cabig.c3pr.utils.StringUtils;
import edu.duke.cabig.c3pr.utils.web.propertyeditors.EnumByNameEditor;
import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.InPlaceEditableTab;
/*
* @author Vinay Gangoli
*
* This controller persists the created Notification to the planned_notfns table.
* called from the admin/createNotification flow.
* Uses the Organization as the mapped hibernate object for persistence.
*/
public class CreateNotificationController extends SimpleFormController {
private static Log log = LogFactory.getLog(CreateNotificationController.class);
private HealthcareSiteDao healthcareSiteDao;
private ResearchStaffDao researchStaffDao;
private InvestigatorDao investigatorDao;
private PlannedNotificationDao plannedNotificationDao;
private OrganizationService organizationService;
private ConfigurationProperty configurationProperty;
private Configuration configuration;
private UserDao userDao;
private InPlaceEditableTab<Organization> page;
//constants for the Cron Triggers
public static final String WEEKLY = "0 00 12 ? * FRI";
public static final String MONTHLY ="0 0 12 L * ?";
public static final String ANNUAL ="0 0 12 L DEC ?";
public static final Long REPEAT_INTERVAL_IN_MILLI_SECONDS= 10*60*1000L;
public static final Integer REPEAT_COUNT= 3;
//job related declarations
private Scheduler scheduler;
protected Object formBackingObject(HttpServletRequest request) throws Exception {
gov.nih.nci.security.authorization.domainobjects.User user = (gov.nih.nci.security.authorization.domainobjects.User) request
.getSession().getAttribute("userObject");
ResearchStaff researchStaff = null;
try {
//get the logged in users site.
researchStaff = (ResearchStaff)userDao.getByLoginId(user.getUserId().longValue());
return researchStaff.getHealthcareSite();
} catch (C3PRNoSuchUserException e) {
log.debug(e.getMessage());
//if logged in user has no site(e.g: c3pr_admin) get the hosting site.
String localNciCode = this.configuration.get(Configuration.LOCAL_NCI_INSTITUTE_CODE);
Organization org = healthcareSiteDao.getByPrimaryIdentifier(localNciCode);
return org;
}
}
protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
Map<String, Object> configMap = configurationProperty.getMap();
Map<String, Object> refdata = new HashMap<String, Object>();
refdata.put("notificationEventsRefData", configMap.get("notificationEventsRefData"));
refdata.put("notificationFrequencyRefData", configMap.get("notificationFrequencyRefData"));
refdata.put("notificationPersonnelRoleRefData", configMap.get("notificationPersonnelRoleRefData"));
refdata.put("notificationEmailSubstitutionVariablesRefData", configMap.get("notificationEmailSubstitutionVariablesRefData"));
refdata.put("notificationStudyAccrualRefData", configMap.get("notificationStudyAccrualRefData"));
refdata.put("notificationStudySiteAccrualRefData", configMap.get("notificationStudySiteAccrualRefData"));
refdata.put("notificationReportEventsRefData", configMap.get("notificationReportEventsRefData"));
gov.nih.nci.security.authorization.domainobjects.User user = (gov.nih.nci.security.authorization.domainobjects.User) request
.getSession().getAttribute("userObject");
ResearchStaff researchStaff = (ResearchStaff)userDao.getByLoginId(user.getUserId().longValue());
refdata.put("assignedIdentifier", researchStaff.getAssignedIdentifier());
return refdata;
}
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
binder.registerCustomEditor(NotificationEventTypeEnum.class, new EnumByNameEditor(
NotificationEventTypeEnum.class));
binder.registerCustomEditor(NotificationFrequencyEnum.class, new EnumByNameEditor(
NotificationFrequencyEnum.class));
}
/*
* This is the method that gets called on form submission. All it does it cast the command into
* Organization and call the service to persist.
* On succesful submission it sets the type attribute to confirm which is used to show the
* confirmation screen.
*/
protected ModelAndView processFormSubmission(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
gov.nih.nci.security.authorization.domainobjects.User user = (gov.nih.nci.security.authorization.domainobjects.User) request
.getSession().getAttribute("userObject");
ResearchStaff researchStaff = null;
HealthcareSite hcs = null;
try {
researchStaff = (ResearchStaff)userDao.getByLoginId(user.getUserId().longValue());
//Get the logged in users site....
hcs = researchStaff.getHealthcareSite();
} catch (C3PRNoSuchUserException e) {
log.debug(e.getMessage());
//if logged in user has no site(e.g: c3pr_admin) get the hosting site.
String localNciCode = this.configuration.get(Configuration.LOCAL_NCI_INSTITUTE_CODE);
hcs = healthcareSiteDao.getByPrimaryIdentifier(localNciCode);
}
if (isAjaxRequest(request)) {
request.getParameter("_asynchronous");
ModelAndView modelAndView = page.postProcessAsynchronous(request,
(Organization) command, errors);
if(((Organization)command).getId() != null){
command = organizationService.merge((Organization) command);
}else {
organizationService.saveNotification((Organization) command);
}
request.getSession().setAttribute(getFormSessionAttributeName(), command);
if (isAjaxResponseFreeText(modelAndView)) {
respondAjaxFreeText(modelAndView, response);
return null;
}
return modelAndView;
} else {
Organization organization = null;
if (command instanceof Organization) {
organization = (Organization) command;
}
else {
log.error("Incorrect Command object passsed into CreateNotificationController.");
return new ModelAndView(getFormView());
}
//assign the Rs or Inv to the userBasedRecpients
ResearchStaff rs = null;
Investigator investigator = null;
Trigger trigger = null;
PlannedNotification pn = null;
for(int i = 0; i < organization.getPlannedNotifications().size(); i++){
pn = organization.getPlannedNotifications().get(i);
if(pn.getHealthcareSite() == null && hcs != null){
pn.setHealthcareSite(hcs);
}
//set the freq to Immediate as default. It is null sometimes when the select is manipulated by the javascript.
//fix this so the javascript manipulation doesnt nullify the freq value.
if(pn.getFrequency() == null){
pn.setFrequency(NotificationFrequencyEnum.IMMEDIATE);
}
//set the contactMechnism Type for the contactMechanismBasedRecipient Emails
if(pn.getContactMechanismBasedRecipient() != null){
for(ContactMechanismBasedRecipient cmbr: pn.getContactMechanismBasedRecipient()){
for(ContactMechanism cm: cmbr.getContactMechanisms()){
if(cm != null && cm.getValue() != null){
cm.setType(ContactMechanismType.EMAIL);
}
}
}
}
for(UserBasedRecipient ubr: pn.getUserBasedRecipient()){
if(!StringUtils.isBlank(ubr.getEmailAddress())){
//TODO: This method is removed from researchstaff dao. Check CPR-1570.
//rs = researchStaffDao.getByEmailAddressFromLocal(ubr.getEmailAddress());
//TODO: This method is removed from investigator dao. Check CPR-1568.
//investigator = investigatorDao.getByEmailAddressFromLocal(ubr.getEmailAddress());
}
if(rs != null){
ubr.setResearchStaff(rs);
}else if(investigator != null){
ubr.setInvestigator(investigator);
}
}
if(pn.getFrequency() != NotificationFrequencyEnum.IMMEDIATE && pn.getId() == null){
//generate the cron Triggers and jobs for Report based events if the pn is new.
plannedNotificationDao.saveOrUpdate(pn);
trigger = generateTriggerForReportBasedEvents(pn);
scheduleJobsForReportBasedEvents(pn, trigger);
} else {
//do not create triggers/jobs if the pn was pre-existing
plannedNotificationDao.saveOrUpdate(pn);
}
}
// if(organization.getId() != null){
// organizationService.mergeNotification(organization);
// }else {
// organizationService.saveNotification(organization);
// for(int i = 0; i < organization.getPlannedNotifications().size(); i++){
// pn = organization.getPlannedNotifications().get(i);
// trigger = generateTriggerForReportBasedEvents(pn, i);
// scheduleJobsForReportBasedEvents(pn, trigger, i);
Map map = errors.getModel();
map.put("command", organization);
ModelAndView mv = new ModelAndView(getSuccessView(), map);
return mv;
}
}
/* Create the Cron Triggers for (non-event based)report notifications.
*/
private Trigger generateTriggerForReportBasedEvents(PlannedNotification pn){
Trigger t = null;
try {
if(pn.getFrequency().equals(NotificationFrequencyEnum.WEEKLY)){
//all ids are of the form "TW:Event-Freq-id:"
//every Friday at 12:00pm
t = new CronTrigger("TW: " + getUniqueIdForTrigger(pn), "TGW" + getUniqueIdForTrigger(pn), WEEKLY);
}
if(pn.getFrequency().equals(NotificationFrequencyEnum.MONTHLY)){
//every last day of month at 12:00pm
t = new CronTrigger("TM" + getUniqueIdForTrigger(pn), "TGM" + getUniqueIdForTrigger(pn), MONTHLY);
}
if(pn.getFrequency().equals(NotificationFrequencyEnum.ANNUAL)){
//every last day December at 12:00pm
t = new CronTrigger("TA" + getUniqueIdForTrigger(pn), "TGA" + getUniqueIdForTrigger(pn), ANNUAL);
}
} catch (ParseException e) {
log.error(e.getMessage());
}
return t;
}
/*
* Generates the unique key for Trigger based on plannedNotification Object
*/
private String getUniqueIdForTrigger(PlannedNotification pn){
return pn.getEventName().getDisplayName() + "-" + pn.getFrequency().getDisplayName() + "-" + pn.getId().toString();
}
private void scheduleJobsForReportBasedEvents(PlannedNotification pn, Trigger trigger){
// create job detail and set the map values
String jobName = "J:" + pn.getEventName().getDisplayName() + "-" + pn.getFrequency().getDisplayName() + "-" + pn.getId().toString();
String jobGroupName = "JG:" + pn.getEventName().getDisplayName() + "-" + pn.getFrequency().getDisplayName() + "-" + pn.getId().toString();
JobDetail jobDetail = new JobDetail(jobName, jobGroupName, ScheduledNotificationJob.class);
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("plannedNotificationId", pn.getId());
// schedule the jobs
log.info("Scheduling the job (jobFullName : " + jobDetail.getFullName() + ")");
try {
scheduler.scheduleJob(jobDetail, trigger);
} catch (SchedulerException e) {
log.error(e.getMessage());
}
}
public OrganizationService getOrganizationService() {
return organizationService;
}
public void setOrganizationService(OrganizationService organizationService) {
this.organizationService = organizationService;
}
public ConfigurationProperty getConfigurationProperty() {
return configurationProperty;
}
public void setConfigurationProperty(ConfigurationProperty configurationProperty) {
this.configurationProperty = configurationProperty;
}
public Configuration getConfiguration() {
return configuration;
}
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
public InPlaceEditableTab<Organization> getPage() {
return page;
}
public void setPage(InPlaceEditableTab<Organization> page) {
this.page = page;
}
protected ModelAndView onSynchronousSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
if (getSuccessView() == null) {
throw new ServletException("successView isn't set");
}
return new ModelAndView(getSuccessView(), errors.getModel());
}
protected boolean isAjaxRequest(HttpServletRequest request) {
if ("true".equalsIgnoreCase(request.getParameter(getAjaxRequestParamName()))){
return true;
}
return false;
}
protected void setAjaxModelAndView(HttpServletRequest request, ModelAndView modelAndView) {
request.setAttribute(getAjaxModelAndViewAttr(), modelAndView);
}
protected ModelAndView getAjaxModelAndView(HttpServletRequest request) {
return (ModelAndView) request.getAttribute(getAjaxModelAndViewAttr());
}
protected boolean isAjaxResponseFreeText(ModelAndView modelAndView) {
if (StringUtils.isBlank(modelAndView.getViewName())) {
return true;
}
return false;
}
protected void respondAjaxFreeText(ModelAndView modelAndView, HttpServletResponse response)
throws Exception {
PrintWriter pr = response.getWriter();
pr.println(modelAndView.getModel().get(getFreeTextModelName()));
pr.flush();
}
protected String getAjaxRequestParamName() {
return "_asynchronous";
}
protected String getAjaxModelAndViewAttr() {
return "async_model_and_view";
}
protected String getFreeTextModelName() {
return "free_text";
}
protected ModelAndView postProcessAsynchronous(HttpServletRequest request,
Organization command, Errors error) throws Exception {
return new ModelAndView(getAjaxViewName(request));
}
protected String getAjaxViewName(HttpServletRequest request) {
return request.getParameter(getAjaxViewParamName());
}
protected String getAjaxViewParamName() {
return "_asyncViewName";
}
protected boolean shouldSave(HttpServletRequest request, Organization command) {
return true;
}
public InvestigatorDao getInvestigatorDao() {
return investigatorDao;
}
public void setInvestigatorDao(InvestigatorDao investigatorDao) {
this.investigatorDao = investigatorDao;
}
public ResearchStaffDao getResearchStaffDao() {
return researchStaffDao;
}
public void setResearchStaffDao(ResearchStaffDao researchStaffDao) {
this.researchStaffDao = researchStaffDao;
}
public PlannedNotificationDao getPlannedNotificationDao() {
return plannedNotificationDao;
}
public void setPlannedNotificationDao(
PlannedNotificationDao plannedNotificationDao) {
this.plannedNotificationDao = plannedNotificationDao;
}
public HealthcareSiteDao getHealthcareSiteDao() {
return healthcareSiteDao;
}
public void setHealthcareSiteDao(HealthcareSiteDao healthcareSiteDao) {
this.healthcareSiteDao = healthcareSiteDao;
}
public Scheduler getScheduler() {
return scheduler;
}
public void setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
} |
package com.artemis.link;
import com.artemis.*;
import com.artemis.utils.Bag;
import com.artemis.utils.reflect.ClassReflection;
import com.artemis.utils.reflect.Field;
import com.artemis.utils.reflect.ReflectionException;
import static com.artemis.Aspect.all;
/**
* <p>Maintains relationships between entities. By default, all entities
* are considered when intercepting relationships. To only consider a sub-set
* of entities, this system can be fed a custom <code>aspect</code>.</p>
*
* <p>This system is optional and must be manually registered with
* the world instance.</p>
*
* @see com.artemis.annotations.EntityId
*
*/
public class EntityLinkManager extends BaseEntitySystem {
final Bag<LinkSite> singleLinkSites = new Bag<LinkSite>();
final Bag<Bag<LinkSite>> multiLinkSites = new Bag<Bag<LinkSite>>();
public EntityLinkManager(Aspect.Builder aspect) {
super(aspect);
}
public EntityLinkManager() {
this(all());
}
@Override
protected void initialize() {
LinkCreateListener listener = new LinkCreateListener(this);
world.getComponentManager().getTypeFactory().register(listener);
}
@Override
protected void processSystem() {
processUni();
processMulti();
}
private void processUni() {
for (LinkSite ls : singleLinkSites) {
ls.process();
}
}
private void processMulti() {
for (Bag<LinkSite> ls : multiLinkSites) {
for (int i = 0, s = ls.size(); s > i; i++) {
ls.get(i).process();
}
}
}
public void register(Class<? extends Component> component, LinkListener listener) {
ComponentType ct = world.getComponentManager().getTypeFactory().getTypeFor(component);
for (LinkSite site : singleLinkSites) {
if (ct.equals(site.type)) {
site.listener = listener;
}
}
for (Bag<LinkSite> ls : multiLinkSites) {
for (int i = 0, s = ls.size(); s > i; i++) {
if (ct.equals(ls.get(i).type)) {
ls.get(i).process();
}
}
}
}
public void register(Class<? extends Component> component, String field, LinkListener listener) {
try {
Field f = ClassReflection.getDeclaredField(component, field);
ComponentType ct = world.getComponentManager().getTypeFactory().getTypeFor(component);
for (LinkSite site : singleLinkSites) {
if (ct.equals(site.type) && site.field.equals(f)) {
site.listener = listener;
}
}
for (Bag<LinkSite> ls : multiLinkSites) {
for (int i = 0, s = ls.size(); s > i; i++) {
LinkSite site = ls.get(i);
if (ct.equals(site.type) && site.field.equals(f)) {
ls.get(i).process();
}
}
}
} catch (ReflectionException e) {
throw new RuntimeException(e);
}
}
private static class LinkCreateListener implements ComponentTypeFactory.ComponentTypeListener {
private final EntityLinkManager elm;
private final LinkFactory linkFactory;
public LinkCreateListener(EntityLinkManager elm) {
this.elm = elm;
this.linkFactory = new LinkFactory(elm.getWorld());
}
@Override
public void initialize(Bag<ComponentType> types) {
for (int i = 0, s = types.size(); s > i; i++) {
onCreated(types.get(i));
}
}
@Override
public void onCreated(ComponentType type) {
Bag<LinkSite> links = linkFactory.create(type);
if (links.isEmpty())
return;
if (links.size() == 1) {
elm.singleLinkSites.add(links.get(0));
} else {
Bag<LinkSite> bag = new Bag<LinkSite>(links.size());
bag.addAll(links);
elm.multiLinkSites.add(bag);
}
}
}
} |
package org.xins.tests.common.text;
import java.net.URLDecoder;
import java.net.URLEncoder;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.common.text.FormatException;
import org.xins.common.text.NonASCIIException;
import org.xins.common.text.URLEncoding;
/**
* Tests for class <code>URLEncoding</code>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*/
public class URLEncodingTests extends TestCase {
// Class functions
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(URLEncodingTests.class);
}
// Constructor
/**
* Constructs a new <code>URLEncodingTests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public URLEncodingTests(String name) {
super(name);
}
// Methods
public void testURLEncodingDecode() throws Throwable {
try {
URLEncoding.decode(null);
fail("Expected IllegalArgumentException for URLEncoding.decode(null).");
return;
} catch (IllegalArgumentException exception) {
// as expected
}
assertEquals("", URLEncoding.decode(""));
// Test format failures
String[] erroneous = new String[] {
"%", "a%", "aa%", "aa%a", "%a", "%%12", "aa%00%ag", "%g1", "%1g8",
"%12abgg%Fg", "%GG", "%1G", "%G1"
};
for (int i = 0; i < erroneous.length; i++) {
String url = erroneous[i];
try {
URLEncoding.decode(url);
fail("Expected URLEncoding.decode(\"" + url + "\") to throw a FormatException.");
return;
} catch (FormatException exception) {
// as expected
}
}
// Test non-ASCII
String[] nonAscii = new String[] {
"abcd%c3%a7", "abcd%C3%A7", "%c3%a7", "%c3%a7", "%40", "abcd%40", "%40abcd", "%c3%a7%c3%a7aaaaa"
};
for (int i = 0; i < nonAscii.length; i++) {
String url = nonAscii[i];
try {
URLEncoding.decode(url);
} catch (FormatException exception) {
fail("Expected URLEncoding.decode(\"" + url + "\") to succeed.");
}
}
// Test success scenarios
String[] ok = new String[] {
"abcdABCD%20+", "abcdABCD ",
"%20", " ",
"+", " ",
"%2F%2f", "
"%2f%2F", "
};
for (int i = 0; i < (ok.length / 2); i+=2) {
String input = ok[i];
String actual = URLEncoding.decode(input);
String expected = ok[i+1];
String message = "Expected \""
+ expected
+ "\" instead of \""
+ actual
+ " for the input string \""
+ input
+ "\".";
assertEquals(message, expected, actual);
}
}
public void testEncode() throws Throwable {
// Test that a null argument fails
try {
URLEncoding.encode(null);
fail("URLEncoding.encode(null) should throw an IllegalArgumentException.");
} catch (IllegalArgumentException exception) { /* as expected */ }
// Test Unicode character
String input = "\u0090";
String result = URLEncoding.encode(input);
assertEquals("Incorrect result:" + result, "%c2%90", result);
input = "HelloThere0999";
result = URLEncoding.encode(input);
assertEquals(input, result);
input = "Hello there";
result = URLEncoding.encode(input);
assertEquals("Hello+there", result);
// Make sure java.net.URLEncoder produces an equivalent result
input = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"01234567890`-=[]\\;',./ ~!@
result = URLEncoding.encode(input);
assertEquals(URLEncoder.encode(input), result);
}
public void testDecode() throws Throwable {
// Test that a null argument fails
try {
URLEncoding.decode(null);
fail("URLEncoding.decode(null) should throw an IllegalArgumentException.");
} catch (IllegalArgumentException exception) { /* as expected */ }
// Special characters and characters higher than 127 are decoded as is
compareDecode("\u0080", "\u0080");
compareDecode("A\u0080", "A\u0080");
compareDecode("AA\u0080", "AA\u0080");
compareDecode("\u0080 ", "\u0080 ");
compareDecode("\u0080 1", "\u0080 1");
compareDecode("@", "@");
/*failDecode("\u0080");
failDecode("A\u0080");
failDecode("AA\u0080");
failDecode("\u0080 ");
failDecode("\u0080 1");*/
failDecode("%u80");
// Before-last character cannot be a percentage sign
failDecode("abcd%a");
// Test unicode characters
compareDecode("%c2%80", "\u0080");
compareDecode("a%c2%80", "a\u0080");
compareDecode("aa%C2%80", "aa\u0080");
compareDecode("%c2%80a", "\u0080a");
compareDecode("%c2%80aa", "\u0080aa");
compareDecode("HelloThere0999", "HelloThere0999");
compareDecode("+", " ");
compareDecode("a+", "a ");
compareDecode("aa+", "aa ");
compareDecode("+a", " a");
compareDecode("+aa", " aa");
compareDecode("+aa+", " aa ");
compareDecode("Hello+there", "Hello there");
compareDecode("Hello%20there", "Hello there");
// Make sure java.net.URLDecoder produces an equivalent result
String input = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"01234567890`-=[]\\;',./ ~!@
String result = URLEncoding.encode(input);
assertEquals(URLDecoder.decode(result), input);
assertEquals(URLDecoder.decode(result), URLEncoding.decode(result));
}
/**
* Compares if the input String is decoded as expected.
*/
private void compareDecode(String input, String expect) {
String result = URLEncoding.decode(input);
assertEquals("The input '" + input + "' was decoded to '" + result +
"' instead of '" + expect +"'.", expect, result);
}
/**
* Tests that a FormatException is thrown when we try to decode the input.
*/
private void failDecode(String input) {
try {
URLEncoding.decode(input);
fail("URLEncoding.decode(\"" + input + "\") should throw a FormatException.");
} catch (FormatException exception) { /* as expected */ }
}
} |
package uk.org.cinquin.mutinack.statistics;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import uk.org.cinquin.mutinack.SequenceLocation;
import uk.org.cinquin.mutinack.misc_util.Util;
import uk.org.cinquin.mutinack.output.json.StatsCollectorSerializer;
@JsonSerialize(using=StatsCollectorSerializer.class)
public class StatsCollector implements Serializable, Traceable, Actualizable {
private static final long serialVersionUID = -2681471547369656383L;
@JsonIgnore
private String tracePrefix = null;
public final @NonNull List<@NonNull LongAdderFormatter> values =
new ArrayList<>();
private @NonNull LongAdderFormatter get(int index) {
if (values.size() < index + 1) {
synchronized(values) {
while (values.size() < index + 1) {
values.add(new LongAdderFormatter());
}
}
}
LongAdderFormatter result = Util.nullableify(values.get(index));
if (result == null) {//Race condition can result in retrieval of null value
synchronized(values) {
result = values.get(index);
}
Objects.requireNonNull(result);
}
return result;
}
public void increment(@NonNull SequenceLocation location) {
if (tracePrefix != null) {
System.err.println(tracePrefix + "+1 at " + location);
}
get(location.contigIndex).increment();
}
public void add(@NonNull SequenceLocation location, long n) {
if (tracePrefix != null) {
System.err.println(tracePrefix + '+' + n + " at " + location);
}
get(location.contigIndex).add(n);
}
public long sum() {
try {
return values.stream().mapToLong(LongAdder::sum).sum();
} catch (Exception e) {//Problems can happen because of concurrent modification
synchronized(values) {
return values.stream().mapToLong(LongAdder::sum).sum();
}
}
}
@Override
public String toString() {
return toString(l -> l);
}
public String toString(@NonNull Function<Long, Long> transformer) {
return values.toString() + "; total: " + DoubleAdderFormatter.nf.get().format(
transformer.apply(sum()));
}
@Override
public void setPrefix(@Nullable String prefix) {
tracePrefix = prefix;
}
public String total;
@Override
public void actualize() {
total = DoubleAdderFormatter.nf.get().format(sum());
for (LongAdderFormatter laf: values) {
laf.actualize();
}
}
} |
package us.kbase.narrativejobservice.db;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.stream.Collectors;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.kbase.common.mongo.GetMongoDB;
import us.kbase.common.mongo.exceptions.InvalidHostException;
import us.kbase.common.mongo.exceptions.MongoAuthException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;
public class ExecEngineMongoDb {
private Jongo jongo;
private DBCollection taskCol;
private DBCollection logCol;
private DBCollection propCol;
private MongoCollection execTasks;
private MongoCollection execLogs;
private MongoCollection srvProps;
private static final Map<String, MongoClient> HOSTS_TO_CLIENT = new HashMap<>();
private static final String COL_EXEC_TASKS = "exec_tasks";
private static final String PK_EXEC_TASKS = "ujs_job_id";
private static final String COL_EXEC_LOGS = "exec_logs";
private static final String PK_EXEC_LOGS = "ujs_job_id";
private static final String COL_SRV_PROPS = "srv_props";
private static final String PK_SRV_PROPS = "prop_id";
private static final String SRV_PROPS_VALUE = "value";
private static final String SRV_PROP_DB_VERSION = "db_version";
private static final String DB_VERSION = "1.0";
private static final ObjectMapper MAPPER = new ObjectMapper();
// should really inject the DB, but worry about that later.
public ExecEngineMongoDb(
final String hosts,
final String db,
final String user,
final String pwd)
throws Exception {
final DB mongo = getDB(hosts, db, user, pwd, 0, 10);
taskCol = mongo.getCollection(COL_EXEC_TASKS);
logCol = mongo.getCollection(COL_EXEC_LOGS);
propCol = mongo.getCollection(COL_SRV_PROPS);
jongo = new Jongo(mongo);
execTasks = jongo.getCollection(COL_EXEC_TASKS);
execLogs = jongo.getCollection(COL_EXEC_LOGS);
srvProps = jongo.getCollection(COL_SRV_PROPS);
// Indexing
final BasicDBObject unique = new BasicDBObject("unique", true);
taskCol.createIndex(new BasicDBObject(PK_EXEC_TASKS, 1), unique);
logCol.createIndex(new BasicDBObject(PK_EXEC_LOGS, 1), unique);
propCol.createIndex(new BasicDBObject(PK_SRV_PROPS, 1), unique);
try {
// at some point check that the db ver = sw ver
propCol.insert(new BasicDBObject(PK_SRV_PROPS, SRV_PROP_DB_VERSION)
.append(SRV_PROPS_VALUE, DB_VERSION));
} catch (DuplicateKeyException e) {
//version is already there so do nothing
}
}
private Map<String, Object> toMap(final Object obj) {
return MAPPER.convertValue(obj, new TypeReference<Map<String, Object>>() {});
}
private DBObject toDBObj(final Object obj) {
return new BasicDBObject(toMap(obj));
}
public String[] getSubJobIds(String ujsJobId) throws Exception{
// there should be a null/empty check for the ujs id here
final DBCursor dbc = taskCol.find(
new BasicDBObject("parent_job_id", ujsJobId),
new BasicDBObject("ujs_job_id", 1));
List<String> idList = new ArrayList<String>();
for (final DBObject dbo: dbc) {
idList.add((String) dbo.get("ujs_job_id"));
}
return idList.toArray(new String[idList.size()]);
}
public ExecLog getExecLog(String ujsJobId) throws Exception {
// there should be a null/empty check for the ujs id here
// should make these strings constants
final DBObject log = logCol.findOne(
new BasicDBObject(PK_EXEC_LOGS, ujsJobId),
new BasicDBObject(PK_EXEC_LOGS, 1)
.append("original_line_count", 1)
.append("stored_line_count", 1));
final ExecLog ret;
if (log == null) {
ret = null;
} else {
ret = new ExecLog();
ret.setOriginalLineCount((Integer) log.get("original_line_count"));
ret.setStoredLineCount((Integer) log.get("stored_line_count"));
ret.setUjsJobId((String) log.get(PK_EXEC_LOGS));
}
return ret;
}
public void insertExecLog(ExecLog execLog) throws Exception {
// should be a null check here
insertExecLogs(Arrays.asList(execLog));
}
public void insertExecLogs(List<ExecLog> execLogList) throws Exception {
// should be a null collection contents check here
logCol.insert(execLogList.stream().map(l -> toDBObj(l)).collect(Collectors.toList()));
}
public void updateExecLogLines(String ujsJobId, int newLineCount,
List<ExecLogLine> newLines) throws Exception {
execLogs.update(String.format("{%s:#}", PK_EXEC_LOGS), ujsJobId).with(
String.format("{$set:{%s:#,%s:#},$push:{%s:{$each:#}}}",
"original_line_count", "stored_line_count", "lines"),
newLineCount, newLineCount, newLines);
}
public void updateExecLogOriginalLineCount(String ujsJobId, int newLineCount) throws Exception {
execLogs.update(String.format("{%s:#}", PK_EXEC_LOGS), ujsJobId).with(
String.format("{$set:{%s:#}}", "original_line_count"), newLineCount);
}
public List<ExecLogLine> getExecLogLines(String ujsJobId, int from, int count) throws Exception {
return execLogs.findOne(String.format("{%s:#}", PK_EXEC_LOGS), ujsJobId).projection(
String.format("{%s:{$slice:[#,#]}}", "lines"), from, count).as(ExecLog.class).getLines();
}
public void insertExecTask(ExecTask execTask) throws Exception {
execTasks.insert(execTask);
}
public void addExecTaskResult(
final String ujsJobId,
final Map<String, Object> result) {
execTasks.update(String.format("{%s: #}", PK_EXEC_TASKS), ujsJobId)
.with(String.format("{$set: {%s: #}}", "job_output"), result);
}
public ExecTask getExecTask(String ujsJobId) throws Exception {
List<ExecTask> ret = Lists.newArrayList(execTasks.find(
String.format("{%s:#}", PK_EXEC_TASKS), ujsJobId).as(ExecTask.class));
return ret.size() > 0 ? ret.get(0) : null;
}
public void updateExecTaskTime(String ujsJobId, boolean finishTime, long time) throws Exception {
execTasks.update(String.format("{%s:#}", PK_EXEC_TASKS), ujsJobId).with(
String.format("{$set:{%s:#}}", finishTime ? "finish_time" : "exec_start_time"), time);
}
public String getServiceProperty(String propId) throws Exception {
@SuppressWarnings("rawtypes")
List<Map> ret = Lists.newArrayList(srvProps.find(String.format("{%s:#}", PK_SRV_PROPS), propId)
.projection(String.format("{%s:1}", SRV_PROPS_VALUE)).as(Map.class));
if (ret.size() == 0)
return null;
return (String)ret.get(0).get(SRV_PROPS_VALUE);
}
public void setServiceProperty(String propId, String value) throws Exception {
srvProps.update(String.format("{%s:#}", PK_SRV_PROPS), propId).upsert().with(
String.format("{$set:{%s:#}}", SRV_PROPS_VALUE), value);
}
private synchronized static MongoClient getMongoClient(final String hosts)
throws UnknownHostException, InvalidHostException {
//Only make one instance of MongoClient per JVM per mongo docs
final MongoClient client;
if (!HOSTS_TO_CLIENT.containsKey(hosts)) {
// Don't print to stderr
java.util.logging.Logger.getLogger("com.mongodb")
.setLevel(Level.OFF);
@SuppressWarnings("deprecation")
final MongoClientOptions opts = MongoClientOptions.builder()
.autoConnectRetry(true).build();
try {
List<ServerAddress> addr = new ArrayList<ServerAddress>();
for (String s: hosts.split(","))
addr.add(new ServerAddress(s));
client = new MongoClient(addr, opts);
} catch (NumberFormatException nfe) {
//throw a better exception if 10gen ever fixes this
throw new InvalidHostException(hosts
+ " is not a valid mongodb host");
}
HOSTS_TO_CLIENT.put(hosts, client);
} else {
client = HOSTS_TO_CLIENT.get(hosts);
}
return client;
}
@SuppressWarnings("deprecation")
private static DB getDB(final String hosts, final String database,
final String user, final String pwd,
final int retryCount, final int logIntervalCount)
throws UnknownHostException, InvalidHostException, IOException,
MongoAuthException, InterruptedException {
if (database == null || database.isEmpty()) {
throw new IllegalArgumentException(
"database may not be null or the empty string");
}
final DB db = getMongoClient(hosts).getDB(database);
if (user != null && pwd != null) {
int retries = 0;
while (true) {
try {
db.authenticate(user, pwd.toCharArray());
break;
} catch (MongoException.Network men) {
if (retries >= retryCount) {
throw (IOException) men.getCause();
}
if (retries % logIntervalCount == 0) {
getLogger().info(
"Retrying MongoDB connection {}/{}, attempt {}/{}",
hosts, database, retries, retryCount);
}
Thread.sleep(1000);
}
retries++;
}
}
try {
db.getCollectionNames();
} catch (MongoException me) {
throw new MongoAuthException("Not authorized for database "
+ database, me);
}
return db;
}
private static Logger getLogger() {
return LoggerFactory.getLogger(GetMongoDB.class);
}
} |
package us.kbase.narrativejobservice.db;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.kbase.common.mongo.GetMongoDB;
import us.kbase.common.mongo.exceptions.InvalidHostException;
import us.kbase.common.mongo.exceptions.MongoAuthException;
import com.google.common.collect.Lists;
import com.mongodb.DB;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;
public class ExecEngineMongoDb {
private DB mongo;
private Jongo jongo;
private MongoCollection taskQueue;
private MongoCollection execApps;
private MongoCollection execTasks;
private MongoCollection execLogs;
private MongoCollection srvProps;
private static final Map<String, MongoClient> HOSTS_TO_CLIENT =
new HashMap<String, MongoClient>();
public static final String COL_TASK_QUEUE = "task_queue";
public static final String PK_TASK_QUEUE = "jobid";
public static final String COL_EXEC_APPS = "exec_apps";
public static final String PK_EXEC_APPS = "app_job_id";
public static final String FLD_EXEC_APPS_APP_JOB_STATE = "app_job_state";
public static final String COL_EXEC_TASKS = "exec_tasks";
public static final String PK_EXEC_TASKS = "ujs_job_id";
public static final String COL_EXEC_LOGS = "exec_logs";
public static final String PK_EXEC_LOGS = "ujs_job_id";
public static final String COL_SRV_PROPS = "srv_props";
public static final String PK_SRV_PROPS = "prop_id";
private static final String SRV_PROPS_VALUE = "value";
public static final String SRV_PROP_DB_VERSION = "db_version";
public static final String DB_VERSION = "1.0";
public ExecEngineMongoDb(String hosts, String db, String user, String pwd,
Integer mongoReconnectRetry) throws Exception {
mongo = getDB(hosts, db, user, pwd,
mongoReconnectRetry == null ? 0 : mongoReconnectRetry, 10);
jongo = new Jongo(mongo);
taskQueue = jongo.getCollection(COL_TASK_QUEUE);
execApps = jongo.getCollection(COL_EXEC_APPS);
execTasks = jongo.getCollection(COL_EXEC_TASKS);
execLogs = jongo.getCollection(COL_EXEC_LOGS);
srvProps = jongo.getCollection(COL_SRV_PROPS);
// Indexing
taskQueue.ensureIndex(String.format("{%s:1}", PK_TASK_QUEUE), "{unique:true}");
execTasks.ensureIndex(String.format("{%s:1}", PK_EXEC_TASKS), "{unique:true}");
execApps.ensureIndex(String.format("{%s:1}", PK_EXEC_APPS), "{unique:true}");
execApps.ensureIndex(String.format("{%s:1}", FLD_EXEC_APPS_APP_JOB_STATE), "{unique:false}");
execLogs.ensureIndex(String.format("{%s:1}", PK_EXEC_LOGS), "{unique:true}");
srvProps.ensureIndex(String.format("{%s:1}", PK_SRV_PROPS), "{unique:true}");
try {
srvProps.insert(String.format("{%s:
PK_SRV_PROPS, SRV_PROPS_VALUE),
SRV_PROP_DB_VERSION, DB_VERSION);
} catch (DuplicateKeyException e) {
//version is already there so do nothing
}
}
public List<QueuedTask> getQueuedTasks() throws Exception {
return Lists.newArrayList(taskQueue.find("{}").as(QueuedTask.class));
}
public void insertQueuedTask(QueuedTask task) throws Exception {
taskQueue.insert(task);
}
public void deleteQueuedTask(String jobId) throws Exception {
taskQueue.remove(String.format("{%s:#}", PK_TASK_QUEUE), jobId);
}
public void insertExecApp(ExecApp execApp) throws Exception {
execApps.insert(execApp);
}
public ExecApp getExecApp(String appJobId) throws Exception {
List<ExecApp> ret = Lists.newArrayList(execApps.find(
String.format("{%s:#}", PK_EXEC_APPS), appJobId).as(ExecApp.class));
return ret.size() > 0 ? ret.get(0) : null;
}
public void updateExecAppData(String appJobId, String appJobState,
String appStateData) throws Exception {
ExecApp execApp = getExecApp(appJobId);
if (execApp == null)
throw new IllegalStateException("App id=" + appJobId + " wasn't found in database");
execApp.setAppJobState(appJobState);
execApp.setAppStateData(appStateData);
execApp.setModificationTime(System.currentTimeMillis());
execApps.update(String.format("{%s:#}", PK_EXEC_APPS), appJobId).with("#", execApp);
}
public List<ExecApp> getExecAppsWithState(String appJobState) throws Exception {
return Lists.newArrayList(execApps.find(
String.format("{%s:#}", FLD_EXEC_APPS_APP_JOB_STATE), appJobState).as(ExecApp.class));
}
public ExecLog getExecLog(String ujsJobId) throws Exception {
List<ExecLog> ret = Lists.newArrayList(execLogs.find(
String.format("{%s:#}", PK_EXEC_LOGS), ujsJobId)
.projection(String.format("{%s:1,%s:1,%s:1}", PK_EXEC_LOGS,
"original_line_count", "stored_line_count")).as(ExecLog.class));
return ret.size() > 0 ? ret.get(0) : null;
}
public void insertExecLog(ExecLog execLog) throws Exception {
execLogs.insert(execLog);
}
public void insertExecLogs(List<ExecLog> execLogList) throws Exception {
Object[] execLogArray = execLogList.toArray(new Object[execLogList.size()]);
execLogs.insert(execLogArray);
}
public void updateExecLogLines(String ujsJobId, int newLineCount,
List<ExecLogLine> newLines) throws Exception {
execLogs.update(String.format("{%s:#}", PK_EXEC_LOGS), ujsJobId).with(
String.format("{$set:{%s:#,%s:#},$push:{%s:{$each:#}}}",
"original_line_count", "stored_line_count", "lines"),
newLineCount, newLineCount, newLines);
}
public void updateExecLogOriginalLineCount(String ujsJobId, int newLineCount) throws Exception {
execLogs.update(String.format("{%s:#}", PK_EXEC_LOGS), ujsJobId).with(
String.format("{$set:{%s:#}}", "original_line_count"), newLineCount);
}
public List<ExecLogLine> getExecLogLines(String ujsJobId, int from, int count) throws Exception {
return execLogs.findOne(String.format("{%s:#}", PK_EXEC_LOGS), ujsJobId).projection(
String.format("{%s:{$slice:[#,#]}}", "lines"), from, count).as(ExecLog.class).getLines();
}
public void insertExecTask(ExecTask execTask) throws Exception {
execTasks.insert(execTask);
}
public ExecTask getExecTask(String ujsJobId) throws Exception {
List<ExecTask> ret = Lists.newArrayList(execTasks.find(
String.format("{%s:#}", PK_EXEC_TASKS), ujsJobId).as(ExecTask.class));
return ret.size() > 0 ? ret.get(0) : null;
}
public void updateExecTaskTime(String ujsJobId, boolean finishTime, long time) throws Exception {
execTasks.update(String.format("{%s:#}", PK_EXEC_TASKS), ujsJobId).with(
String.format("{$set:{%s:#}}", finishTime ? "finish_time" : "exec_start_time"), time);
}
public String getServiceProperty(String propId) throws Exception {
@SuppressWarnings("rawtypes")
List<Map> ret = Lists.newArrayList(srvProps.find(String.format("{%s:#}", PK_SRV_PROPS), propId)
.projection(String.format("{%s:1}", SRV_PROPS_VALUE)).as(Map.class));
if (ret.size() == 0)
return null;
return (String)ret.get(0).get(SRV_PROPS_VALUE);
}
public void setServiceProperty(String propId, String value) throws Exception {
srvProps.update(String.format("{%s:#}", PK_SRV_PROPS), propId).upsert().with(
String.format("{$set:{%s:#}}", SRV_PROPS_VALUE), value);
}
private synchronized static MongoClient getMongoClient(final String hosts)
throws UnknownHostException, InvalidHostException {
//Only make one instance of MongoClient per JVM per mongo docs
final MongoClient client;
if (!HOSTS_TO_CLIENT.containsKey(hosts)) {
// Don't print to stderr
java.util.logging.Logger.getLogger("com.mongodb")
.setLevel(Level.OFF);
@SuppressWarnings("deprecation")
final MongoClientOptions opts = MongoClientOptions.builder()
.autoConnectRetry(true).build();
try {
List<ServerAddress> addr = new ArrayList<ServerAddress>();
for (String s: hosts.split(","))
addr.add(new ServerAddress(s));
client = new MongoClient(addr, opts);
} catch (NumberFormatException nfe) {
//throw a better exception if 10gen ever fixes this
throw new InvalidHostException(hosts
+ " is not a valid mongodb host");
}
HOSTS_TO_CLIENT.put(hosts, client);
} else {
client = HOSTS_TO_CLIENT.get(hosts);
}
return client;
}
@SuppressWarnings("deprecation")
private static DB getDB(final String hosts, final String database,
final String user, final String pwd,
final int retryCount, final int logIntervalCount)
throws UnknownHostException, InvalidHostException, IOException,
MongoAuthException, InterruptedException {
if (database == null || database.isEmpty()) {
throw new IllegalArgumentException(
"database may not be null or the empty string");
}
final DB db = getMongoClient(hosts).getDB(database);
if (user != null && pwd != null) {
int retries = 0;
while (true) {
try {
db.authenticate(user, pwd.toCharArray());
break;
} catch (MongoException.Network men) {
if (retries >= retryCount) {
throw (IOException) men.getCause();
}
if (retries % logIntervalCount == 0) {
getLogger().info(
"Retrying MongoDB connection {}/{}, attempt {}/{}",
hosts, database, retries, retryCount);
}
Thread.sleep(1000);
}
retries++;
}
}
try {
db.getCollectionNames();
} catch (MongoException me) {
throw new MongoAuthException("Not authorized for database "
+ database, me);
}
return db;
}
private static Logger getLogger() {
return LoggerFactory.getLogger(GetMongoDB.class);
}
} |
package logic;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.text.*;
public class AutoCompletion extends PlainDocument {
JComboBox comboBox;
ComboBoxModel model;
JTextComponent editor;
// flag to indicate if setSelectedItem has been called
// subsequent calls to remove/insertString should be ignored
boolean selecting = false;
boolean hidePopupOnFocusLoss;
boolean hitBackspace = false;
boolean hitBackspaceOnSelection;
KeyListener editorKeyListener;
FocusListener editorFocusListener;
public AutoCompletion(final JComboBox comboBox) {
this.comboBox = comboBox;
model = comboBox.getModel();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if (!selecting) highlightCompletedText(0);
}
});
comboBox.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals("editor")) {
configureEditor((ComboBoxEditor) e.getNewValue());
}
if (e.getPropertyName().equals("model")) {
model = (ComboBoxModel) e.getNewValue();
}
}
});
editorKeyListener = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER: {
setText(model.getSelectedItem().toString());
}
highlightCompletedText(model.getSelectedItem().toString().length());
break;
}
}
};
// editorKeyListener = new KeyAdapter() {
// public void keyPressed(KeyEvent e) {
// if (comboBox.isDisplayable()) comboBox.setPopupVisible(true);
// hitBackspace=false;
// switch (e.getKeyCode()) {
// // determine if the pressed key is backspace (needed by the remove method)
// case KeyEvent.VK_BACK_SPACE : hitBackspace=false;
// hitBackspaceOnSelection=editor.getSelectionStart()!=editor.getSelectionEnd();
// break;
// // ignore delete key
// case KeyEvent.VK_DELETE : e.consume();
// comboBox.getToolkit().beep();
// break;
// // Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out
// hidePopupOnFocusLoss=System.getProperty("java.version").startsWith("1.5");
// // Highlight whole text when gaining focus
// editorFocusListener = new FocusAdapter() {
// public void focusGained(FocusEvent e) {
// highlightCompletedText(0);
// public void focusLost(FocusEvent e) {
// // Workaround for Bug 5100422 - Hide Popup on focus loss
// if (hidePopupOnFocusLoss) comboBox.setPopupVisible(false);
configureEditor(comboBox.getEditor());
// Handle initially selected object
Object selected = comboBox.getSelectedItem();
if (selected != null) {
setText(selected.toString());
}
highlightCompletedText(0);
}
public static void enable(JComboBox comboBox) {
// has to be editable
comboBox.setEditable(true);
// change the editor's document
new AutoCompletion(comboBox);
}
void configureEditor(ComboBoxEditor newEditor) {
if (editor != null) {
editor.removeKeyListener(editorKeyListener);
editor.removeFocusListener(editorFocusListener);
}
if (newEditor != null) {
editor = (JTextComponent) newEditor.getEditorComponent();
editor.addKeyListener(editorKeyListener);
editor.addFocusListener(editorFocusListener);
editor.setDocument(this);
}
}
public void remove(int offs, int len) throws BadLocationException {
// return immediately when selecting an item
if (selecting) {
return;
}
if (hitBackspace) {
// user hit backspace => move the selection backwards
// old item keeps being selected
if (offs > 0) {
if (hitBackspaceOnSelection) {
offs
}
} else {
// User hit backspace with the cursor positioned on the start => beep
comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
}
highlightCompletedText(offs);
} else {
super.remove(offs, len);
}
}
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
// return immediately when selecting an item
if (selecting) {
return;
}
// insert the string into the document
super.insertString(offs, str, a);
// lookup and select a matching item
Object item = lookupItem(getText(0, getLength()));
if (item != null) {
setSelectedItem(item);
} else {
// keep old item selected if there is no match
item = comboBox.getSelectedItem();
// imitate no insert (later on offs will be incremented by str.length(): selection won't move forward)
offs = offs - str.length();
// provide feedback to the user that his input has been received but can not be accepted
comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
}
setText(item.toString());
// select the completed part
highlightCompletedText(offs + str.length());
}
private void setText(String text) {
try {
// remove all text and insert the completed string
super.remove(0, getLength());
super.insertString(0, text, null);
} catch (BadLocationException e) {
throw new RuntimeException(e.toString());
}
}
private void highlightCompletedText(int start) {
editor.setCaretPosition(getLength());
editor.moveCaretPosition(start);
}
private void setSelectedItem(Object item) {
selecting = true;
model.setSelectedItem(item);
selecting = false;
}
private Object lookupItem(String pattern) {
Object selectedItem = model.getSelectedItem();
// only search for a different item if the currently selected does not match
if (selectedItem != null && startsWithIgnoreCase(selectedItem.toString(), pattern)) {
return selectedItem;
} else {
// iterate over all items
for (int i = 0, n = model.getSize(); i < n; i++) {
Object currentItem = model.getElementAt(i);
// current item starts with the pattern?
if (currentItem != null && startsWithIgnoreCase(currentItem.toString(), pattern)) {
return currentItem;
}
}
}
// no item starts with the pattern => return null
// add return parent to add own items
return pattern;
}
// checks if str1 starts with str2 - ignores case
private boolean startsWithIgnoreCase(String str1, String str2) {
return str1.toUpperCase().startsWith(str2.toUpperCase());
}
} |
package View;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import backendExceptions.BackendException;
import GUIFunctions.Add;
import GUIFunctions.AddTurtle;
import GUIFunctions.AskForInitialFile;
import GUIFunctions.BackgroundColor;
import GUIFunctions.BottomFunctions;
import GUIFunctions.ClearFunction;
import GUIFunctions.ClearStamps;
import GUIFunctions.Function;
import GUIFunctions.GUIFunction;
import GUIFunctions.HelpPage;
import GUIFunctions.LanguageMenu;
import GUIFunctions.PenStyle;
import GUIFunctions.PenThickness;
import GUIFunctions.PersonalizeMenu;
import GUIFunctions.SetBackgroundImage;
import GUIFunctions.SetLanguage;
import GUIFunctions.SetPenDown;
import GUIFunctions.SetPenUp;
import GUIFunctions.Stamp;
import GUIFunctions.ToggleGridLines;
import GUIFunctions.TurtleImageChange;
import GUIFunctions.Undo;
import GUIFunctions.TurtleVariablesTable;
import GUIFunctions.UserInput;
import GUIFunctions.Variable;
import GUIFunctions.VariableTable;
import communicator.MainController;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class SlogoView {
private GridFactory myGridFactory;
private GridTracker myGrids;
private MainController myController;
private TabsOfGrids myGridTabs=new TabsOfGrids();
//a Group for all the components of the GUI to be added to
private Group root=new Group();
//an ArrayList of all the working commands given by the user
public Queue<ButtonTemplate> myCommands=new LinkedList<ButtonTemplate>();
private ColorSelection colorSelection;
private Scene myScene;
private TextField commandLine;
//used to display Turtles most recent stats
private Text lastX, lastY, lastOrientation;
HashMap<String, GUIFunction> myUserFunctions=new HashMap<String, GUIFunction>();
private VBox commandHistoryBox;
private MenuTemplate userCommands;
private Map<String, String> userCommandMap = new HashMap<>();
private ResourceBundle myResources;
private Stage myStage;
private VariableTable myVariableTable;
private final static Dimension DEFAULT_SIZE=new Dimension(1000,600);
private static final int MAX_COMMAND_HISTORY = 5;
public static final String DEFAULT_RESOURCE_PACKAGE = "resources/";
public SlogoView() throws ClassNotFoundException{
myResources = ResourceBundle.getBundle(DEFAULT_RESOURCE_PACKAGE+"Buttons");
myGrids=new GridTracker();
colorSelection = new ColorSelection(myGrids);
makeListOfFunctions();
myGridFactory=new GridFactory(DEFAULT_SIZE.height, DEFAULT_SIZE.width, this.build(5), myUserFunctions);
myController=new MainController(this);
Timeline myTime=new Timeline();
myTime.setCycleCount(Timeline.INDEFINITE);
myTime.getKeyFrames().add(this.build(40));
myTime.play();
}
/**
*
* @return A KeyFrame for the TimeLine of the program
*/
private KeyFrame build(int fps){
Duration speed=Duration.millis(1000/fps);
final EventHandler<ActionEvent> loop=new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent evt){
if (!myGrids.getActiveGrid().equals(myGridTabs.getActiveGrid())){
myGrids.setActiveGrid(myGridTabs.getActiveGrid());
myController.setGridAsActive(myGrids.getActiveGrid().getID());
}
}
};
return new KeyFrame(speed, loop);
}
public void initialize(Stage mainStage) {
addGrid();
addTurtle();
myVariableTable=new VariableTable();
myGridFactory.setGridMap(myUserFunctions);
myStage=mainStage;
BorderPane mainLayout=new BorderPane();
mainLayout.setPrefSize(DEFAULT_SIZE.width, DEFAULT_SIZE.height);
mainLayout.setTop(addMenuBar());
mainLayout.setCenter(myGrids.getActiveGrid());
mainLayout.setLeft(setTextArea());
mainLayout.setBottom(addButtons());
root.getChildren().add(mainLayout);
root.getChildren().add(myGridTabs);
myScene=new Scene(root, DEFAULT_SIZE.width, DEFAULT_SIZE.height);
myStage.setScene(myScene);
TurtleVariablesTable myTable=new TurtleVariablesTable(myGrids);
}
/**
* Displays the error message "message" on the screen
*
*/
public void showError(String message){
JOptionPane.showMessageDialog(null, message);
}
/**
*Passes the commands from the textbox on the GUI to the controller for parsing.
* @param s String representing the command to send that was inputed by the user
*
*/
private void sendCommandAndMakeButton(String command){
sendCommand(command);
ButtonTemplate mostRecent = new ButtonTemplate(command, 0, 0, (event -> sendCommandAndMakeButton(command)), 180, 10);
myCommands.add(mostRecent);
commandLine.clear();
updateCommandHistory();
}
private void sendCommand(String myCommand){
myController.receiveCommand(myCommand);
}
public void enable(){
myStage.getScene().getRoot().setDisable(false);
}
private MenuBar addMenuBar(){
MenuBar myMenu=new MenuBar();
myMenu.setStyle( "-fx-border-width: 5");
myMenu.setPrefSize(DEFAULT_SIZE.width, 30);
MenuTemplate fileMenu=this.createfileMenu();
MenuTemplate languages = new MenuTemplate("Languages");
MenuTemplate personalize=new MenuTemplate("Personalize");
MenuTemplate pen=new MenuTemplate("Pen");
MenuTemplate add=new MenuTemplate("Add");
MenuTemplate help = new MenuTemplate("Help");
help.addMenuItem("Help Page", event->myUserFunctions.get("Help").doAction());
userCommands = new MenuTemplate("User Commands");
makeAddMenu(add);
this.makeLanguageMenu(LanguageMenu.class, languages);
this.makeMenu(PersonalizeMenu.class, personalize);
this.makeMenu(PenMenu.class, pen);
myMenu.getMenus().addAll(fileMenu, languages, userCommands, pen, personalize, help, add);
return myMenu;
}
public void setDisable(Boolean toDisable){
for (Node myNode: root.getChildren()){
myNode.setDisable(toDisable);
}
}
private void makeLanguageMenu(Class myClass, MenuTemplate myMenu){
for (String myName: myUserFunctions.keySet()){
if (myUserFunctions.get(myName) instanceof LanguageMenu){
LanguageMenu languageFunction=(LanguageMenu) myUserFunctions.get(myName);
myMenu.addMenuItem(myName, event->myController.loadLanguage(languageFunction.doAction(myResources.getString(myName))));
}
}
}
public void addVariables(Map<String, Double> myVariables){
ArrayList<UserInput> myVars=new ArrayList<UserInput>();
for (String name: myVariables.keySet()){
Variable myNewVariable=new Variable(name, myVariables.get(name));
myVars.add(myNewVariable);
}
myVariableTable.addInput(myVars);
}
public void addUserFunctions(List<String> myFunctions){
ArrayList<UserInput> myInputs=new ArrayList<UserInput>();
for (String myName: myFunctions){
UserInput myUserInput=new Function(myName);
myInputs.add(myUserInput);
}
myVariableTable.addInput(myInputs);
}
private void makeAddMenu(MenuTemplate myAdd){
myAdd.addMenuItem("Add Grid", event->addGrid());
myAdd.addMenuItem("Add Turtle", event->addTurtle());
}
private void addTurtle(){
myController.addTurtle(myGrids.getActiveGrid().addTurtle(), myGrids.getActiveGrid().getID(), true);
}
public Grid addGrid() {
Grid myNewGrid;
try {
myNewGrid = myGridFactory.makeGrid("SingleGrid");
myGrids.setActiveGrid((SingleGrid)myNewGrid);
myGrids.setActiveGrid((SingleGrid)myNewGrid);
myGridTabs.addTab("GRID", (SingleGrid)myNewGrid);
myController.addGrid((SingleGrid)myNewGrid, true);
return myNewGrid;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private Pane setTextArea(){
Pane myTextArea=new Pane();
myTextArea.setStyle("-fx-background-color: #000080; -fx-border-color: BLACK; -fx-border-width: 5");
myTextArea.setPrefSize(200, DEFAULT_SIZE.height-200);
// create command line
Label label = new Label("Commands:");
label.setTextFill(Color.WHITE);
label.setStyle("-fx-font-size: 25");
label.setPrefSize(200, 50);
label.relocate(10, 5);
commandLine = new TextField();
EventHandler enterEvent=new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if(event.getCode().equals(KeyCode.ENTER))
sendCommandAndMakeButton(commandLine.getText());
}
};
commandLine.addEventHandler(KeyEvent.KEY_PRESSED,enterEvent);
String[] value=myResources.getString("enter").split(";");
Button enter = new Button (value[0]);
enter.relocate(Double.parseDouble(value[1]), Double.parseDouble(value[2]));
enter.setOnAction(event->this.sendCommandAndMakeButton(commandLine.getText()));
enter.setPrefSize(70, 30);
commandLine.relocate(5, 60);
commandLine.setPrefSize(190,100);
value=myResources.getString("makeCommand").split(";");
Button makeCommand = new Button(value[0]);
makeCommand.setOnAction(event-> makeUserCommand(commandLine.getText()));
makeCommand.setPrefSize(120, 30);
makeCommand.relocate(Double.parseDouble(value[1]),Double.parseDouble(value[2]));
commandHistoryBox = new VBox();
Text history = new Text(" Command History");
history.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
history.setFill(Color.WHITE);
history.relocate(0, 350);
commandHistoryBox.setSpacing(10);
updateCommandHistory();
commandHistoryBox.relocate(0, 380);
myTextArea.getChildren().addAll(label, commandLine, enter, makeCommand,
history, colorSelection, commandHistoryBox);
return myTextArea;
}
private Pane addButtons() {
Pane myButtonPanel=new Pane();
myButtonPanel.setPrefSize(DEFAULT_SIZE.width, 75);
myButtonPanel.setStyle("-fx-background-color: #000080; -fx-border-color: BLACK; -fx-border-width: 5");
myButtonPanel.getChildren().addAll(this.makeButtons(BottomFunctions.class, "BottomPanel"));
myButtonPanel.getChildren().addAll(this.makeSlidingBars());
return myButtonPanel;
}
public void updateTurtleStats(int x, int y, int or){
lastX.setText("X Position: " + x);
lastY.setText("Y Position: " + y);
lastOrientation.setText("Orientation " + or);
}
public void updateCommandHistory(){
commandHistoryBox.getChildren().clear();
if(myCommands.size() > MAX_COMMAND_HISTORY){
myCommands.poll();
}
for(ButtonTemplate b : myCommands){
commandHistoryBox.getChildren().add(b);
}
}
public void setBackgroundColor(String color){
myGrids.getActiveGrid().setBackgroundColor(color);
}
public void makeUserCommand(String command){
String name = JOptionPane.showInputDialog("Give a Name for your Command");
userCommandMap.put(name, commandLine.getText());
commandLine.clear();
userCommands.addMenuItem(name, event->executeUserCommand(userCommandMap.get(name)));
}
public void executeUserCommand(String command){
myController.receiveCommand(command);
commandLine.setText(command);
ButtonTemplate mostRecent = new ButtonTemplate(command,
0, 0, (event -> sendCommandAndMakeButton(command)), 180,10);
myCommands.add(mostRecent);
commandLine.clear();
updateCommandHistory();
}
private ArrayList<ButtonTemplate> makeButtons(Class myClass, String location){
Properties prop=new Properties();
InputStream stream = getClass().getClassLoader().getResourceAsStream("./resources/"+location+".Properties");
try {
prop.load(stream);
ArrayList<ButtonTemplate> myButtons=new ArrayList<ButtonTemplate>();
for (String s: myUserFunctions.keySet()){
if (myUserFunctions.get(s).getClass().getSuperclass().equals(myClass)){
String[] value=prop.getProperty(s).split(";");
myButtons.add(new ButtonTemplate(value[0], Double.parseDouble(value[1]), Double.parseDouble(value[2]), myUserFunctions.get(s)));
}
}
return myButtons;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void makeMenu(Class myClass, MenuTemplate myMenu){
for (String s: myUserFunctions.keySet()){
Class<? extends GUIFunction> myFunctionClass=(Class<? extends GUIFunction>) myUserFunctions.get(s).getClass().getSuperclass();
if (myFunctionClass.equals(myClass)){
myMenu.addMenuItem(s, event->myUserFunctions.get(s).doAction());
}
}
}
private Collection<ScrollingBar> makeSlidingBars(){
Collection<ScrollingBar> myListOfBars=new ArrayList<ScrollingBar>();
ScrollingBar myPenBar=new PenScrollingBar(myResources.getString("penThickness"), 250, 20, myUserFunctions.get("penThickness"));
myListOfBars.add(myPenBar);
return myListOfBars;
}
private void makeListOfFunctions(){
myUserFunctions.put("penDown", new SetPenDown(myGrids));
myUserFunctions.put("undo", new Undo(myGrids));
myUserFunctions.put("clear", new ClearFunction(myGrids));
myUserFunctions.put("penUp", new SetPenUp(myGrids));
myUserFunctions.put("uploadBackgroundImage", new SetBackgroundImage(myGrids, myStage));
myUserFunctions.put("toggleReferenceGrid", new ToggleGridLines(myGrids, 50));
myUserFunctions.put("uploadTurtleImage", new TurtleImageChange(myGrids, myStage));
myUserFunctions.put("addTurtle", new AddTurtle(myGrids));
myUserFunctions.put("dottedPenStyle", new PenStyle(myGrids,"Dotted"));
myUserFunctions.put("solidPenStyle", new PenStyle(myGrids, "Solid"));
myUserFunctions.put("dashedPenStyle", new PenStyle(myGrids, "Dashed"));
myUserFunctions.put("stampTurtle", new Stamp(myGrids));
myUserFunctions.put("helpPage", new HelpPage());
myUserFunctions.put("backgroundColor", new BackgroundColor(myGrids, colorSelection));
myUserFunctions.put("penColor", new PenColor(myGrids,colorSelection));
myUserFunctions.put("penThickness", new PenThickness(myGrids));
myUserFunctions.put("setPalette", new SetPalette(colorSelection));
myUserFunctions.put("uploadFile", new AskForInitialFile());
myUserFunctions.put("clearStamp", new ClearStamps(myGrids));
addLanguages();
}
private void addLanguages(){
try {
Properties prop = new Properties();
InputStream stream = getClass().getClassLoader().getResourceAsStream("./resources/Languages.Properties");
prop.load(stream);
for(Object language : prop.keySet()){
myUserFunctions.put((String) language, new SetLanguage());
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Language File not Found, using default colors");
}
}
private MenuTemplate createfileMenu(){
MenuTemplate file=new MenuTemplate("File");
file.addMenuItem("Export", event->saveFileToController(saveFile()));
AskForInitialFile myFunction=(AskForInitialFile)myUserFunctions.get("uploadFile");
file.addMenuItem(myResources.getString("uploadFile"),event->checkNullFile(myFunction.sendFile()));
return file;
}
private String saveFile(){
return JOptionPane.showInputDialog(null, "Name of desired file to save to:");
}
private void saveFileToController(String fileName){
try {
myController.savePreferences(fileName);
} catch (BackendException e) {
JOptionPane.showMessageDialog(null, "No input");
}
}
private void checkNullFile(File myFile){
if (myFile!=null){
try {
myController.loadPreferences(myFile);
} catch (BackendException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "The file was null");
}
}
else{
JOptionPane.showMessageDialog(null, "The file was null");
}
}
//private void
} |
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.docusign.esign.model.*;
import com.docusign.esign.api.*;
import com.docusign.esign.client.ApiException;
import com.docusign.esign.client.JSON;
public class WebhookLib {
// Settings
public String dsUserEmail = "***";
public String dsUserPw = "***";
public String dsIntegrationId = "***";
public String dsSigner1Name = "***"; // Set signer info here or leave as is
// to use example signers
public String dsSigner1Email = "***";
public String dsCC1Name = "***"; // Set a cc recipient here or leave as is
// to use example recipients
public String dsCC1Email = "***";
public String dsAccountId; // Set during login process or explicitly by
// configuration here.
// Note that many customers have more than one account!
// A username/pw can access multiple accounts!
public String dsBaseUrl; // The base url associated with the account_id.
public String dsAuthHeader;
public String myUrl; // The url for this script. Must be accessible from the
// internet!
// Can be set here or determined dynamically
public String webhookUrl;
public String docFilename = "sample_documents_master/NDA.pdf";
public String docDocumentName = "NDA.pdf";
public String docFiletype = "application/pdf";
private DsRecipeLib dsRecipeLib;
private String webhookSuffix = "?op=webhook";
private String xmlFileDir = "files/";
private String docPrefix = "doc_";
final static Logger logger = LoggerFactory.getLogger(WebhookLib.class);
public WebhookLib() {
dsRecipeLib = new DsRecipeLib(dsUserEmail, dsUserPw, dsIntegrationId, dsAccountId);
myUrl = dsRecipeLib.getMyUrl(myUrl);
}
public boolean send1(String url) {
// Prepares for sending the envelope
Map<String, String> result = login();
if ("false".equals(result.get("ok"))) {
return false;
}
myUrl = url;
webhookUrl = (myUrl != null && !myUrl.isEmpty()) ? myUrl + webhookSuffix
: "http://localhost:5000/" + webhookSuffix;
webhookUrl = "https://ds-webhook-java.herokuapp.com/" + webhookSuffix;
dsSigner1Name = dsRecipeLib.getSignerName(dsSigner1Name);
dsSigner1Email = dsRecipeLib.getSignerEmail(dsSigner1Email);
dsCC1Name = dsRecipeLib.getSignerName(dsCC1Name);
dsCC1Email = dsRecipeLib.getSignerEmail(dsCC1Email);
return true;
}
private Map<String, String> login() {
Map<String, String> map = new HashMap<>();
// Logs into DocuSign
Map<String, String> result = dsRecipeLib.login();
if ("true".equals(result.get("ok"))) {
dsAccountId = dsRecipeLib.getDsAccountId();
dsBaseUrl = dsRecipeLib.getDsBaseUrl();
dsAuthHeader = dsRecipeLib.getDsAuthHeader();
map.put("ok", "true");
} else {
map.put("ok", "false");
map.put("errMsg", result.get("errMsg"));
}
return map;
}
public String getDsAccountId() {
return dsAccountId;
}
public void setDsAccountId(String dsAccountId) {
this.dsAccountId = dsAccountId;
}
public String getDsSigner1Name() {
return dsSigner1Name;
}
public String getWebhookUrl() {
return webhookUrl;
}
public void webhookListener(String data) {
// Process the incoming webhook data. See the DocuSign Connect guide
// for more information
// Strategy: examine the data to pull out the envelopeId and
// time_generated fields.
// Then store the entire xml on our local file system using those
// fields.
// If the envelope status=="Completed" then store the files as doc1.pdf,
// doc2.pdf, etc
// This function could also enter the data into a dbms, add it to a
// queue, etc.
// Note that the total processing time of this function must be less
// than
// 100 seconds to ensure that DocuSign's request to your app doesn't
// time out.
// Tip: aim for no more than a couple of seconds! Use a separate queuing
// service
// if need be.
logger.info("Data received from DS Connect: " + data);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
org.w3c.dom.Document xml = builder.parse(new InputSource(new StringReader(data)));
xml.getDocumentElement ().normalize();
logger.info("Connect data parsed!");
Element envelopeStatus = (Element) xml.getElementsByTagName("EnvelopeStatus").item(0);
String envelopeId = envelopeStatus.getElementsByTagName("EnvelopeID").item(0).getChildNodes().item(0).getNodeValue();
logger.info("envelopeId=" + envelopeId);
String timeGenerated = envelopeStatus.getElementsByTagName("TimeGenerated").item(0).getChildNodes().item(0).getNodeValue();
logger.info("timeGenerated=" + timeGenerated);
// Store the file. Create directories as needed
// Some systems might still not like files or directories to start
// with numbers.
// So we prefix the envelope ids with E and the timestamps with T
// File filesDir = new File(System.getProperty("user.dir") + "/" +
// xmlFileDir);
File filesDir = new File("/tmp/" + xmlFileDir);
logger.info("filesDir=" + filesDir);
if (!filesDir.isDirectory()) {
if (!filesDir.mkdirs())
logger.info("Cannot create folder: " + filesDir);
filesDir.setReadable(true, false);
filesDir.setExecutable(true, false);
filesDir.setWritable(true, false);
}
File envelopeDir = new File("/tmp/" + xmlFileDir + "E" + envelopeId);
logger.info("envelopeDir=" + envelopeDir);
if (!envelopeDir.isDirectory()) {
if (!envelopeDir.mkdirs())
logger.info("Cannot create folder: " + envelopeDir);
envelopeDir.setReadable(true, false);
envelopeDir.setExecutable(true, false);
envelopeDir.setWritable(true, false);
}
String filename = "/tmp/" + xmlFileDir + "E" + envelopeId + "/T" + timeGenerated.replace(':', '_') + ".xml";
logger.info("filename=" + filename);
try {
File xmlFile = new File(filename);
FileWriter fw = new FileWriter(xmlFile);
try {
fw.write(data);
} finally {
fw.close();
}
} catch (Exception ex) {
// Couldn't write the file! Alert the humans!
logger.error("!!!!!! PROBLEM DocuSign Webhook: Couldn't store " + filename + " !");
return;
}
// log the event
logger.info("DocuSign Webhook: created " + filename);
if ("Completed".equals(envelopeStatus.getElementsByTagName("Status").item(0).getChildNodes().item(0).getNodeValue())) {
// Loop through the DocumentPDFs element, storing each document.
NodeList nodeList = xml.getElementsByTagName("DocumentPDFs").item(0).getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Element pdf = (Element) nodeList.item(i);
filename = docPrefix + pdf.getElementsByTagName("DocumentID").item(0).getChildNodes().item(0).getNodeValue() + ".pdf";
String fullFilename = envelopeDir + "/" + filename;
try {
File pdfFile = new File(fullFilename);
byte[] pdfBytes = Base64.getDecoder()
.decode(pdf.getElementsByTagName("PDFBytes").item(0).getChildNodes().item(0).getNodeValue());
FileOutputStream fos = new FileOutputStream(pdfFile);
try {
fos.write(pdfBytes);
} finally {
fos.close();
}
} catch (Exception ex) {
// Couldn't write the file! Alert the humans!
logger.error("!!!!!! PROBLEM DocuSign Webhook: Couldn't store " + filename + " !");
return;
}
}
}
} catch (Exception e) {
logger.error("!!!!!! PROBLEM DocuSign Webhook: Couldn't parse the XML sent by DocuSign Connect: " + e.getMessage());
}
}
public String send2(Map<String, String> params) {
// Send the envelope
// params --
// "ds_signer1_name"
// "ds_signer1_email"
// "ds_cc1_name"
// "ds_cc1_email"
// "webhook_url"
// "baseurl"
Map<String, String> result = login();
if ("false".equals(result.get("ok"))) {
return "{\"ok\": false, \"html\": \"<h3>Problem</h3><p>Couldn't login to DocuSign: " + result.get("errMsg")
+ "</p>\"}";
}
webhookUrl = params.get("webhook_url");
dsSigner1Name = params.get("ds_signer1_name");
dsSigner1Email = params.get("ds_signer1_email");
dsCC1Name = params.get("ds_cc1_name");
dsCC1Email = params.get("ds_cc1_email");
// The envelope request includes a signer-recipient and their tabs
// object,
// and an eventNotification object which sets the parameters for
// webhook notifications to us from the DocuSign platform
EnvelopeEvent envelopeEvent = new EnvelopeEvent();
envelopeEvent.setEnvelopeEventStatusCode("sent");
envelopeEvent.setEnvelopeEventStatusCode("delivered");
envelopeEvent.setEnvelopeEventStatusCode("completed");
envelopeEvent.setEnvelopeEventStatusCode("declined");
envelopeEvent.setEnvelopeEventStatusCode("voided");
envelopeEvent.setEnvelopeEventStatusCode("sent");
envelopeEvent.setEnvelopeEventStatusCode("sent");
List<EnvelopeEvent> envelopeEvents = new ArrayList<>();
envelopeEvents.add(envelopeEvent);
RecipientEvent recipientEvent = new RecipientEvent();
recipientEvent.setRecipientEventStatusCode("Sent");
recipientEvent.setRecipientEventStatusCode("Delivered");
recipientEvent.setRecipientEventStatusCode("Completed");
recipientEvent.setRecipientEventStatusCode("Declined");
recipientEvent.setRecipientEventStatusCode("AuthenticationFailed");
recipientEvent.setRecipientEventStatusCode("AutoResponded");
List<RecipientEvent> recipientEvents = new ArrayList<>();
recipientEvents.add(recipientEvent);
EventNotification eventNotification = new EventNotification();
eventNotification.setUrl(webhookUrl);
eventNotification.setLoggingEnabled("true");
eventNotification.setRequireAcknowledgment("true");
eventNotification.setUseSoapInterface("false");
eventNotification.setIncludeCertificateWithSoap("false");
eventNotification.setSignMessageWithX509Cert("false");
eventNotification.setIncludeDocuments("true");
eventNotification.setIncludeEnvelopeVoidReason("true");
eventNotification.setIncludeTimeZone("true");
eventNotification.setIncludeSenderAccountAsCustomField("true");
eventNotification.setIncludeDocumentFields("true");
eventNotification.setIncludeCertificateOfCompletion("true");
eventNotification.setEnvelopeEvents(envelopeEvents);
eventNotification.setRecipientEvents(recipientEvents);
byte[] fileBytes = null;
try {
Path path = Paths.get("./src/main/resources/public/" + docFilename);
fileBytes = Files.readAllBytes(path);
} catch (Exception ex) {
logger.error(ex.getMessage());
}
Document document = new Document();
String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
document.setDocumentId("1");
document.setName(docDocumentName);
document.setDocumentBase64(base64Doc);
List<Document> documents = new ArrayList<>();
documents.add(document);
Signer signer = new Signer();
signer.setEmail(dsSigner1Email);
signer.setName(dsSigner1Name);
signer.setRecipientId("1");
signer.setRoutingOrder("1");
signer.setTabs(getNdaFields());
List<Signer> signers = new ArrayList<>();
signers.add(signer);
CarbonCopy carbonCopy = new CarbonCopy();
carbonCopy.setEmail(dsCC1Email);
carbonCopy.setName(dsCC1Name);
carbonCopy.setRecipientId("2");
carbonCopy.setRoutingOrder("2");
List<CarbonCopy> carbonCopies = new ArrayList<>();
carbonCopies.add(carbonCopy);
Recipients recipients = new Recipients();
recipients.setSigners(signers);
recipients.setCarbonCopies(carbonCopies);
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
// We want to use the most friendly email subject line.
// The regexp below removes the suffix from the file name.
envelopeDefinition
.setEmailSubject("Please sign the " + docDocumentName.replaceAll("\\.[^.\\s]{3,4}", "") + " document");
envelopeDefinition.setDocuments(documents);
envelopeDefinition.setRecipients(recipients);
envelopeDefinition.setEventNotification(eventNotification);
envelopeDefinition.setStatus("sent");
// Send the envelope:
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary;
try {
envelopeSummary = envelopesApi.createEnvelope(dsAccountId, envelopeDefinition);
if (envelopeSummary == null || envelopeSummary.getEnvelopeId() == null) {
return "{\"ok\": false, \"html\": \"<h3>Problem</h3> \r\n <p>Error calling DocuSign</p>\"}";
}
String envelopeId = envelopeSummary.getEnvelopeId();
// Create instructions for reading the email
StringBuilder html = new StringBuilder();
html.append("<h2>Signature request sent!</h2><p>Envelope ID: " + envelopeId + "</p>");
html.append("<h2>Next steps</h2>" + "<h3>1. Open the Webhook Event Viewer</h3>");
html.append("<p><a href='" + (params.get("baseurl") != null ? params.get("baseurl") : "/")
+ "?op=status&envelope_id=" + URLEncoder.encode(envelopeId, "UTF-8") + "'");
html.append(" class='btn btn-primary' role='button' target='_blank' style='margin-right:1.5em;'>");
html.append("View Events</a> (A new tab/window will be used.)</p>");
html.append("<h3>2. Respond to the Signature Request</h3>");
String emailAccess = dsRecipeLib.getTempEmailAccess(dsSigner1Email);
if (emailAccess != null) {
// A temp account was used for the email
html.append("<p>Respond to the request via your mobile phone by using the QR code: </p>");
html.append("<p>" + dsRecipeLib.getTempEmailAccessQrcode(emailAccess) + "</p>");
html.append("<p> or via <a target='_blank' href='" + emailAccess + "'>your web browser.</a></p>");
} else {
// A regular email account was used
html.append("<p>Respond to the request via your mobile phone or other mail tool.</p>");
html.append("<p>The email was sent to " + dsSigner1Name + " <" + dsSigner1Email + "></p>");
}
return "{ \"ok\": true, \r\n \"envelope_id\": \"" + envelopeId + "\", \r\n \"html\": \"" + html.toString()
+ "\", \r\n \"js\": [{\"disable_button\": \"sendbtn\"}]}";
} catch (Exception e) {
if (e instanceof ApiException) {
logger.error(((ApiException) e).getResponseBody());
}
e.printStackTrace();
}
return "{ \"ok\": false, \r\n \"html\": \"Error while sending the envelope\" }";
}
private Tabs getNdaFields() {
// The fields for the sample document "NDA"
// Create 4 fields, using anchors
// * signer1sig
// * signer1name
// * signer1company
// * signer1date
// This method uses the SDK to create the fields data structure
SignHere signHereTab = new SignHere();
signHereTab.setAnchorString("signer1sig");
signHereTab.setAnchorXOffset("0");
signHereTab.setAnchorYOffset("0");
signHereTab.setAnchorUnits("mms");
signHereTab.setRecipientId("1");
signHereTab.setName("Please sign here");
signHereTab.setOptional("false");
signHereTab.setScaleValue(1);
signHereTab.setTabLabel("signer1sig");
List<SignHere> signHereTabs = new ArrayList<>();
signHereTabs.add(signHereTab);
FullName fullNameTab = new FullName();
fullNameTab.setAnchorString("signer1name");
fullNameTab.setAnchorYOffset("-6");
fullNameTab.setFontSize("Size12");
fullNameTab.setRecipientId("1");
fullNameTab.setTabLabel("Full Name");
fullNameTab.setName("Full Name");
List<FullName> fullNameTabs = new ArrayList<>();
fullNameTabs.add(fullNameTab);
Text textTab = new Text();
textTab.setAnchorString("signer1company");
textTab.setAnchorYOffset("-8");
textTab.setFontSize("Size12");
textTab.setRecipientId("1");
textTab.setTabLabel("Company");
textTab.setName("Company");
textTab.setRequired("false");
List<Text> textTabs = new ArrayList<>();
textTabs.add(textTab);
DateSigned dateSignedTab = new DateSigned();
dateSignedTab.setAnchorString("signer1date");
dateSignedTab.setAnchorYOffset("-6");
dateSignedTab.setFontSize("Size12");
dateSignedTab.setRecipientId("1");
dateSignedTab.setName("Date Signed");
dateSignedTab.setTabLabel("Company");
List<DateSigned> dateSignedTabs = new ArrayList<>();
dateSignedTabs.add(dateSignedTab);
Tabs fields = new Tabs();
fields.setSignHereTabs(signHereTabs);
fields.setFullNameTabs(fullNameTabs);
fields.setTextTabs(textTabs);
fields.setDateSignedTabs(dateSignedTabs);
return fields;
}
public String getDsSigner1Email() {
return dsSigner1Email;
}
public String getDsCC1Email() {
return dsCC1Email;
}
public String getDsCC1Name() {
return dsCC1Name;
}
public String statusItems(Map<String, String> params) {
// List of info about the envelope's event items received
String filesDirUrl = ((myUrl == null || myUrl.isEmpty()) ? "/" : myUrl.substring(0, myUrl.indexOf('/') + 1))
+ xmlFileDir;
// remove http or https
filesDirUrl = filesDirUrl.replace("http:", "").replace("https:", "");
logger.info("filesDirUrl=" + filesDirUrl);
File filesDir = new File("/tmp/" + xmlFileDir + "E" + params.get("envelope_id"));
logger.info("filesDir=" + filesDir);
String results = "";
if (!filesDir.isDirectory()) {
logger.info("results=" + results);
return results; // no results!
}
for (File file : filesDir.listFiles(new FileFilter() {
@Override
public boolean accept(File path) {
return path.isFile() && path.getName().toLowerCase().endsWith(".xml");
}
})) {
results = statusItem(file, file.getName(), filesDirUrl);
break;
}
logger.info("results=" + results);
return results;
}
private String statusItem(File file, String filename, String filesDirUrl) {
// summary info about the notification
String result = "";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
InputStream fis = new FileInputStream(file);
org.w3c.dom.Document xml = builder.parse(fis);
xml.getDocumentElement ().normalize();
Element envelopeStatus = (Element) xml.getElementsByTagName("EnvelopeStatus").item(0);
Element recipientStatuses = (Element) envelopeStatus.getElementsByTagName("RecipientStatuses").item(0);
// iterate through the recipients
String recipients = "{}";
NodeList nodeList = recipientStatuses.getElementsByTagName("RecipientStatus");
for (int i = 0; i < nodeList.getLength(); i++) {
Element recipient = (Element) nodeList.item(i);
recipients = "{" + "\"type\":\"" + recipient.getElementsByTagName("Type").item(0).getChildNodes().item(0).getNodeValue() + "\","
+ "\"email\":\"" + recipient.getElementsByTagName("Email").item(0).getChildNodes().item(0).getNodeValue() + "\","
+ "\"user_name\":\"" + recipient.getElementsByTagName("UserName").item(0).getChildNodes().item(0).getNodeValue() + "\","
+ "\"routing_order\":\"" + recipient.getElementsByTagName("RoutingOrder").item(0).getChildNodes().item(0).getNodeValue()
+ "\"," + "\"sent_timestamp\":\""
+ (recipient.getElementsByTagName("Sent").getLength()>0?recipient.getElementsByTagName("Sent").item(0).getChildNodes().item(0).getNodeValue():"") + "\","
+ "\"delivered_timestamp\":\""
+ (recipient.getElementsByTagName("Delivered").getLength()>0?recipient.getElementsByTagName("Delivered").item(0).getChildNodes().item(0).getNodeValue():"") + "\","
+ "\"signed_timestamp\":\"" + (recipient.getElementsByTagName("Signed").getLength()>0?recipient.getElementsByTagName("Signed").item(0).getChildNodes().item(0).getNodeValue():"")
+ "\"," + "\"status\":\"" + (recipient.getElementsByTagName("Status").getLength()>0?recipient.getElementsByTagName("Status").item(0).getChildNodes().item(0).getNodeValue():"")
+ "\"" + "}";
}
String documents = "{}";
String envelopeId = envelopeStatus.getElementsByTagName("EnvelopeID").item(0).getChildNodes().item(0).getNodeValue();
// iterate through the documents if the envelope is Completed
if ("Completed".equals(envelopeStatus.getElementsByTagName("Status").item(0).getChildNodes().item(0).getNodeValue())) {
// Loop through the DocumentPDFs element, noting each document.
nodeList = xml.getElementsByTagName("DocumentPDFs");
for (int i = 0; i < nodeList.getLength(); i++) {
Element pdf = (Element) nodeList.item(i);
String docFilename = docPrefix + (pdf.getElementsByTagName("DocumentID").getLength()>0?pdf.getElementsByTagName("DocumentID").item(0).getChildNodes().item(0).getNodeValue():"")
+ ".pdf";
documents = "{" + "\"document_ID\":\""
+ (pdf.getElementsByTagName("DocumentID").getLength()>0?pdf.getElementsByTagName("DocumentID").item(0).getChildNodes().item(0).getNodeValue():"") + "\","
+ "\"document_type\":\"" + pdf.getElementsByTagName("DocumentType").item(0).getChildNodes().item(0).getNodeValue()
+ "\"," + "\"name\":\"" + pdf.getElementsByTagName("Name").item(0).getChildNodes().item(0).getNodeValue() + "\","
+ "\"url\":\"" + filesDirUrl + "E" + envelopeId + "/" + docFilename + "\"" + "}";
}
}
result = "{" + "\"envelopeId\":\"" + envelopeId + "\"," + "\"xml_url\":\"" + filesDirUrl + "E" + envelopeId
+ "/" + filename + "\"," + "\"time_generated\":\""
+ envelopeStatus.getElementsByTagName("TimeGenerated").item(0).getChildNodes().item(0).getNodeValue() + "\","
+ "\"subject\":\"" + envelopeStatus.getElementsByTagName("Subject").item(0).getChildNodes().item(0).getNodeValue() + "\","
+ "\"sender_user_name\":\"" + envelopeStatus.getElementsByTagName("UserName").item(0).getChildNodes().item(0).getNodeValue()
+ "\"," + "\"sender_email\":\""
+ envelopeStatus.getElementsByTagName("Email").item(0).getChildNodes().item(0).getNodeValue() + "\","
+ "\"envelope_status\":\"" + envelopeStatus.getElementsByTagName("Status").item(0).getChildNodes().item(0).getNodeValue()
+ "\"," + "\"envelope_sent_timestamp\":\""
+ (envelopeStatus.getElementsByTagName("Sent").getLength()>0?envelopeStatus.getElementsByTagName("Sent").item(0).getChildNodes().item(0).getNodeValue():"") + "\","
+ "\"envelope_created_timestamp\":\""
+ (envelopeStatus.getElementsByTagName("Cretaed").getLength()>0?envelopeStatus.getElementsByTagName("Cretaed").item(0).getChildNodes().item(0).getNodeValue():"") + "\","
+ "\"envelope_delivered_timestamp\":\""
+ (envelopeStatus.getElementsByTagName("Delivered").getLength()>0?envelopeStatus.getElementsByTagName("Delivered").item(0).getChildNodes().item(0).getNodeValue():"") + "\","
+ "\"envelope_signed_timestamp\":\""
+ (envelopeStatus.getElementsByTagName("Signed").getLength()>0?envelopeStatus.getElementsByTagName("Signed").item(0).getChildNodes().item(0).getNodeValue():"") + "\","
+ "\"envelope_completed_timestamp\":\""
+ (envelopeStatus.getElementsByTagName("Completed").getLength()>0?envelopeStatus.getElementsByTagName("Completed").item(0).getChildNodes().item(0).getNodeValue():"") + "\","
+ "\"timezone\":\"" + xml.getElementsByTagName("TimeZone").item(0).getChildNodes().item(0).getNodeValue() + "\","
+ "\"timezone_offset\":\"" + xml.getElementsByTagName("TimeZoneOffset").item(0).getChildNodes().item(0).getNodeValue()
+ "\"," + "\"recipients\":" + recipients + "," + "\"documents\":" + documents + "}";
} catch (Exception e) {
logger.error("!!!!!! PROBLEM DocuSign Webhook: Couldn't parse the XML stored from DocuSign Connect: " + e.getMessage());
}
logger.info("result=" + result);
return result;
}
public String statusInfo(Map<String, String> map) {
// Info about the envelope
// Calls /accounts/{accountId}/envelopes/{envelopeId}
Map<String, String> result = login();
if ("false".equals(result.get("ok"))) {
return "{\"ok\": false, \"html\": \"<h3>Problem</h3><p>Couldn't login to DocuSign: " + result.get("errMsg")
+ "</p>\"}";
}
EnvelopesApi envelopesApi = new EnvelopesApi();
Envelope envelope;
try {
envelope = envelopesApi.getEnvelope(dsAccountId, map.get("envelope_id"));
if (envelope == null || envelope.getEnvelopeId() == null) {
return "{\"ok\": false, \"html\": \"<h3>Problem</h3><p>Error calling DocuSign</p>\"}";
}
return new JSON().serialize(envelope);
} catch (ApiException e) {
e.printStackTrace();
}
return "{\"ok\": false, \"html\": \"<h3>Problem</h3><p>Couldn't get envelope.</p>\"}";
}
} |
package jfdi.ui;
import com.google.common.eventbus.EventBus;
import jfdi.logic.ControlCenter;
import jfdi.ui.Constants.ListStatus;
import jfdi.ui.Constants.MsgType;
import jfdi.ui.commandhandlers.CommandHandler;
public class UI implements IUserInterface {
private static final EventBus eventBus = new EventBus();
private static UI ourInstance = new UI();
public CommandHandler cmdHandler = new CommandHandler();
private MainController controller;
private ControlCenter logic;
private UI() {
}
public static UI getInstance() {
return ourInstance;
}
@Override
public void init() {
// showToUser(UI_MESSAGE_INIT);
// Initialize Logic
logic = ControlCenter.getInstance();
this.prepareListener();
// showToUser(UI_MESSAGE_INITED);
}
@Override
public void displayWelcome() {
controller.clearFb();
showToUser(Constants.UI_MESSAGE_GREETING);
showToUser(Constants.UI_MESSAGE_WELCOME);
}
@Override
public void processInput(String input) {
if (controller.displayStatus.equals(ListStatus.HELP)) {
controller.hideOverlays();
controller.displayStatus = controller.beforeHelp;
controller.switchTabSkin();
}
// Clear controller first
controller.clearCmdArea();
controller.clearFb();
// Show user what the command recognized in the feedback area
// controller.displayFb(String.format(Constants.UI_MESSAGE_USERCMD,
// input));
// Relay user input to logic and wait for reply
relayToLogic(input);
}
@Override
public void displayFeedback(String fb, MsgType type) {
controller.clearFb();
appendFeedback(fb, type);
}
@Override
public void appendFeedback(String fb, MsgType type) {
switch (type) {
case SUCCESS:
showToUser(String.format(Constants.UI_MESSAGE_RESPONSE, fb));
break;
case WARNING:
showToUser(String.format(Constants.UI_MESSAGE_WARNING, fb));
break;
case ERROR:
showToUser(String.format(Constants.UI_MESSAGE_ERROR, fb));
break;
case EXIT:
showToUser(Constants.UI_MESSAGE_QUIT);
break;
default:
showToUser(fb);
break;
}
}
@Override
public int getTaskId(int onScreenId) {
return controller.getIdFromIndex(onScreenId - 1);
}
@Override
public void setController(MainController controller) {
this.controller = controller;
}
private void showToUser(String string) {
controller.displayFb(string);
System.out.println(string);
}
private void prepareListener() {
cmdHandler.setController(controller);
eventBus.register(cmdHandler);
}
@Override
public void relayToLogic(String input) {
// Relay user input to logic and wait for reply
logic.handleInput(input);
}
public static EventBus getEventBus() {
return eventBus;
}
public void triggerEnter() {
controller.enterRoutine();
}
} |
package siren;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
/**
* Represent navigational transitions.
* @author jonfreer
* @since 8/13/17
*/
public class Link {
/**
* Constructs instances of {@link Link}.
*/
public static class Builder implements siren.Builder<Link>{
private List<String> klass;
private String title;
private String type;
private List<String> rel;
private URI href;
/**
* Constructs an instance of {@link Link.Builder}.
*/
public Builder(){}
public Builder rel(String rel){
if(this.rel == null){
this.rel = new ArrayList<String>();
}
this.rel.add(rel);
return this;
}
/**
* Sets the current state of the builder to have the href provided.
* @param href The URI of the linked resource.
* @return The builder this method is called on.
*/
public Builder href(URI href){
this.href = href;
return this;
}
/**
* Adds the class provided to the current state of the builder.
* @param klass Describes aspects of the link based on the current
* representation. Possible values are implementation-dependent
* and should be documented.
* @return The builder this method is called on.
*/
public Builder klass(String klass){
if(this.klass == null){
this.klass = new ArrayList<String>();
}
this.klass.add(klass);
return this;
}
/**
* Sets current state of the builder to have the title provided.
* @param title Text describing the nature of a link.
* @return The builder this method is called on.
*/
public Builder title(String title){
this.title = title;
return this;
}
public Builder type(String type){
// TODO 2017-08-15 - FREER - Instead of String, utilize MediaType.
this.type = type;
return this;
}
/**
* Clears the state of the builder.
*/
@Override
public void clear() {
this.klass = null;
this.title = null;
this.type = null;
this.rel = null;
this.href = null;
}
/**
* Constructs a {@link Link} instance with the current state of the builder.
*
* @return Instance of {@link Link} with the current state of the builder.
*/
@Override
public Link build() {
// TODO 2017-08-15 - FREER - Do some checking that required state has been set.
return new Link(this.rel, this.href);
}
}
private List<String> rel;
/**
* The URI of the linked resource. Required.
*/
private String href;
/**
* Describes aspects of the link based on the current
* representation. Possible values are implementation-dependent
* and should be documented.
*/
private List<String> klass;
/**
* Text describing the nature of a link.
*/
private String title;
private String type;
/**
* Constructs an instance of {@link Link}.
* @param rel Defines the relationship of the link to its entity,
* per Web Linking (RFC5988) and Link Relations.
* @param href The URI of the linked resource.
*/
private Link(List<String> rel, URI href){
if(rel == null){
throw new IllegalArgumentException("'rel' cannot be null as it is required.");
}
if(href == null){
throw new IllegalArgumentException("'href' cannot be null as it is required.");
}
this.rel = rel;
this.href = href.toString();
}
public List<String> getRel(){
if(this.rel == null) return this.rel;
List<String> relCopy = new ArrayList<String>();
relCopy.addAll(this.rel);
return relCopy;
}
/**
* Retrieves the class for the link.
* @return List of strings describing aspects of the link based
* on the current representation. Possible values are
* implementation-dependent and should be documented.
*/
public List<String> getKlass(){
if(this.klass == null) return this.klass;
List<String> classesCopy = new ArrayList<String>();
classesCopy.addAll(this.klass);
return classesCopy;
}
/**
* Retrieves the title of the link.
* @return String describing the nature of a link.
*/
public String getTitle(){
return this.title;
}
public String getType(){
return this.type;
}
/**
* Retrieves the URI of the linked resource.
* @return The URI of the linked resource.
*/
public String getHref(){
return this.href;
}
} |
package zmq;
import java.io.IOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Poller extends PollerBase implements Runnable
{
private static class PollSet
{
protected IPollEvents handler;
protected SelectionKey key;
protected int ops;
protected boolean cancelled;
protected PollSet(IPollEvents handler)
{
this.handler = handler;
key = null;
cancelled = false;
ops = 0;
}
}
// This table stores data for registered descriptors.
private final Map<SelectableChannel, PollSet> fdTable;
// If true, there's at least one retired event source.
private boolean retired;
// If true, thread is in the process of shutting down.
private volatile boolean stopping;
private volatile boolean stopped;
private Thread worker;
private Selector selector;
private final String name;
public Poller()
{
this("poller");
}
public Poller(String name)
{
this.name = name;
retired = false;
stopping = false;
stopped = false;
fdTable = new HashMap<SelectableChannel, PollSet>();
try {
selector = Selector.open();
}
catch (IOException e) {
throw new ZError.IOException(e);
}
}
public void destroy()
{
if (!stopped) {
try {
worker.join();
}
catch (InterruptedException e) {
}
}
try {
selector.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public final void addHandle(SelectableChannel fd, IPollEvents events)
{
fdTable.put(fd, new PollSet(events));
adjustLoad(1);
}
public final void removeHandle(SelectableChannel handle)
{
fdTable.get(handle).cancelled = true;
retired = true;
// Decrease the load metric of the thread.
adjustLoad(-1);
}
public final void setPollIn(SelectableChannel handle)
{
register(handle, SelectionKey.OP_READ, false);
}
public final void resetPollOn(SelectableChannel handle)
{
register(handle, SelectionKey.OP_READ, true);
}
public final void setPollOut(SelectableChannel handle)
{
register(handle, SelectionKey.OP_WRITE, false);
}
public final void resetPollOut(SelectableChannel handle)
{
register(handle, SelectionKey.OP_WRITE, true);
}
public final void setPollConnect(SelectableChannel handle)
{
register(handle, SelectionKey.OP_CONNECT, false);
}
public final void setPollAccept(SelectableChannel handle)
{
register(handle, SelectionKey.OP_ACCEPT, false);
}
private final void register(SelectableChannel handle, int ops, boolean negate)
{
PollSet pollset = fdTable.get(handle);
if (negate) {
pollset.ops = pollset.ops & ~ops;
}
else {
pollset.ops = pollset.ops | ops;
}
if (pollset.key != null) {
pollset.key.interestOps(pollset.ops);
}
else {
retired = true;
}
}
public void start()
{
worker = new Thread(this, name);
worker.setDaemon(true);
worker.start();
}
public void stop()
{
stopping = true;
selector.wakeup();
}
@Override
public void run()
{
int returnsImmediately = 0;
while (!stopping) {
// Execute any due timers.
long timeout = executeTimers();
if (retired) {
Iterator<Map.Entry<SelectableChannel, PollSet>> it = fdTable.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<SelectableChannel, PollSet> entry = it.next();
SelectableChannel ch = entry.getKey();
PollSet pollset = entry.getValue();
if (pollset.key == null) {
try {
pollset.key = ch.register(selector, pollset.ops, pollset.handler);
}
catch (ClosedChannelException e) {
}
}
if (pollset.cancelled || !ch.isOpen()) {
if (pollset.key != null) {
pollset.key.cancel();
}
it.remove();
}
}
retired = false;
}
// Wait for events.
int rc;
long start = System.currentTimeMillis();
try {
rc = selector.select(timeout);
}
catch (IOException e) {
throw new ZError.IOException(e);
}
if (rc == 0) {
// Guess JDK epoll bug
if (timeout == 0 ||
System.currentTimeMillis() - start < timeout / 2) {
returnsImmediately++;
}
else {
returnsImmediately = 0;
}
if (returnsImmediately > 10) {
rebuildSelector();
returnsImmediately = 0;
}
continue;
}
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
IPollEvents evt = (IPollEvents) key.attachment();
it.remove();
try {
if (key.isReadable()) {
evt.inEvent();
}
else if (key.isAcceptable()) {
evt.acceptEvent();
}
else if (key.isConnectable()) {
evt.connectEvent();
}
if (key.isWritable()) {
evt.outEvent();
}
}
catch (CancelledKeyException e) {
// channel might have been closed
}
}
}
stopped = true;
}
private void rebuildSelector()
{
Selector newSelector;
try {
newSelector = Selector.open();
}
catch (IOException e) {
throw new ZError.IOException(e);
}
try {
selector.close();
}
catch (IOException e) {
}
selector = newSelector;
for (PollSet pollSet : fdTable.values()) {
pollSet.key = null;
}
retired = true;
}
} |
package com.yahoo.vespa.hosted.controller.restapi;
import com.yahoo.application.container.JDisc;
import com.yahoo.application.container.handler.Request;
import com.yahoo.application.container.handler.Response;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.container.http.filter.FilterChainRepository;
import com.yahoo.jdisc.http.filter.SecurityRequestFilter;
import com.yahoo.jdisc.http.filter.SecurityRequestFilterChain;
import com.yahoo.vespa.athenz.api.AthenzDomain;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.api.identifiers.ScrewdriverId;
import com.yahoo.vespa.hosted.controller.api.integration.athenz.ApplicationAction;
import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFactoryMock;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.athenz.HostedAthenzIdentities;
import com.yahoo.vespa.hosted.controller.integration.ConfigServerMock;
import com.yahoo.vespa.hosted.controller.integration.ServiceRegistryMock;
import com.yahoo.vespa.hosted.controller.versions.ControllerVersion;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import org.junit.ComparisonFailure;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
/**
* Provides testing of JSON container responses
*
* @author bratseth
*/
public class ContainerTester {
private final JDisc container;
private final String responseFilePath;
public ContainerTester(JDisc container, String responseFilePath) {
this.container = container;
this.responseFilePath = responseFilePath;
}
public JDisc container() { return container; }
public Controller controller() {
return (Controller) container.components().getComponent(Controller.class.getName());
}
public ConfigServerMock configServer() {
return serviceRegistry().configServerMock();
}
public AthenzClientFactoryMock athenzClientFactory() {
return (AthenzClientFactoryMock) container.components().getComponent(AthenzClientFactoryMock.class.getName());
}
public ServiceRegistryMock serviceRegistry() {
return (ServiceRegistryMock) container.components().getComponent(ServiceRegistryMock.class.getName());
}
public void computeVersionStatus() {
controller().updateVersionStatus(VersionStatus.compute(controller()));
}
public void upgradeSystem(Version version) {
var controllerVersion = new ControllerVersion(version, "badc0ffee", Instant.EPOCH);
controller().curator().writeControllerVersion(controller().hostname(), controllerVersion);
for (ZoneApi zone : controller().zoneRegistry().zones().all().zones()) {
for (SystemApplication application : SystemApplication.all()) {
configServer().setVersion(application.id(), zone.getId(), controllerVersion.version());
configServer().convergeServices(application.id(), zone.getId());
}
}
computeVersionStatus();
}
public void authorize(AthenzDomain tenantDomain, AthenzIdentity identity, ApplicationAction action, ApplicationName application) {
athenzClientFactory().getSetup()
.domains.get(tenantDomain)
.applications.get(new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(application.value()))
.addRoleMember(action, identity);
}
public void assertResponse(Supplier<Request> request, File responseFile) {
assertResponse(request.get(), responseFile);
}
public void assertResponse(Request request, File responseFile) {
assertResponse(request, responseFile, 200);
}
public void assertResponse(Supplier<Request> request, File responseFile, int expectedStatusCode) {
assertResponse(request.get(), responseFile, expectedStatusCode);
}
public void assertResponse(Request request, File responseFile, int expectedStatusCode) {
String expectedResponse = readTestFile(responseFile.toString());
expectedResponse = include(expectedResponse);
expectedResponse = expectedResponse.replaceAll("(\"[^\"]*\")|\\s*", "$1"); // Remove whitespace
FilterResult filterResult = invokeSecurityFilters(request);
request = filterResult.request;
Response response = filterResult.response != null ? filterResult.response : container.handleRequest(request);
String responseString;
try {
responseString = response.getBodyAsString();
} catch (CharacterCodingException e) {
throw new UncheckedIOException(e);
}
if (expectedResponse.contains("(ignore)")) {
// Convert expected response to a literal pattern and replace any ignored field with a pattern that matches
// until the first stop character
String stopCharacters = "[^,:\\\\[\\\\]{}]";
String expectedResponsePattern = Pattern.quote(expectedResponse)
.replaceAll("\"?\\(ignore\\)\"?", "\\\\E" +
stopCharacters + "*\\\\Q");
if (!Pattern.matches(expectedResponsePattern, responseString)) {
throw new ComparisonFailure(responseFile.toString() + " (with ignored fields)",
expectedResponsePattern, responseString);
}
} else {
assertEquals(responseFile.toString(), expectedResponse, responseString);
}
assertEquals("Status code", expectedStatusCode, response.getStatus());
}
public void assertResponse(Supplier<Request> request, String expectedResponse) {
assertResponse(request, expectedResponse, 200);
}
public void assertResponse(Request request, String expectedResponse) {
assertResponse(() -> request, expectedResponse, 200);
}
public void assertResponse(Supplier<Request> request, String expectedResponse, int expectedStatusCode) {
assertResponse(request,
(response) -> assertEquals(expectedResponse, new String(response.getBody(), StandardCharsets.UTF_8)),
expectedStatusCode);
}
public void assertResponse(Supplier<Request> requestSupplier, Consumer<Response> responseAssertion, int expectedStatusCode) {
var request = requestSupplier.get();
FilterResult filterResult = invokeSecurityFilters(request);
request = filterResult.request;
Response response = filterResult.response != null ? filterResult.response : container.handleRequest(request);
responseAssertion.accept(response);
assertEquals("Status code", expectedStatusCode, response.getStatus());
}
// Hack to run request filters as part of the request processing chain.
// Limitation: Bindings ignored, disc filter request wrapper only support limited set of methods.
private FilterResult invokeSecurityFilters(Request request) {
FilterChainRepository filterChainRepository = (FilterChainRepository) container.components().getComponent(FilterChainRepository.class.getName());
SecurityRequestFilterChain chain = (SecurityRequestFilterChain) filterChainRepository.getFilter(ComponentSpecification.fromString("default"));
for (SecurityRequestFilter securityRequestFilter : chain.getFilters()) {
ApplicationRequestToDiscFilterRequestWrapper discFilterRequest = new ApplicationRequestToDiscFilterRequestWrapper(request);
ResponseHandlerToApplicationResponseWrapper responseHandlerWrapper = new ResponseHandlerToApplicationResponseWrapper();
securityRequestFilter.filter(discFilterRequest, responseHandlerWrapper);
request = discFilterRequest.getUpdatedRequest();
Optional<Response> filterResponse = responseHandlerWrapper.toResponse();
if (filterResponse.isPresent()) {
return new FilterResult(request, filterResponse.get());
}
}
return new FilterResult(request, null);
}
/** Replaces @include(localFile) with the content of the file */
private String include(String response) {
// Please don't look at this code
int includeIndex = response.indexOf("@include(");
if (includeIndex < 0) return response;
String prefix = response.substring(0, includeIndex);
String rest = response.substring(includeIndex + "@include(".length());
int filenameEnd = rest.indexOf(")");
String includeFileName = rest.substring(0, filenameEnd);
String includedContent = readTestFile(includeFileName);
includedContent = include(includedContent);
String postFix = rest.substring(filenameEnd + 1);
postFix = include(postFix);
return prefix + includedContent + postFix;
}
private String readTestFile(String name) {
try {
return new String(Files.readAllBytes(Paths.get(responseFilePath, name)));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static class FilterResult {
final Request request;
final Response response;
FilterResult(Request request, Response response) {
this.request = request;
this.response = response;
}
}
} |
package org.apereo.cas.services;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.support.events.service.CasRegisteredServiceDeletedEvent;
import org.apereo.cas.support.events.service.CasRegisteredServiceSavedEvent;
import org.apereo.cas.util.RegexUtils;
import org.apereo.inspektr.audit.annotation.Audit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Implementation of the {@link ServicesManager} interface that organizes services by domain into
* a hash for quicker lookup.
*
* @author Travis Schmidt
* @since 5.2.0
*/
public class DomainServicesManager implements ServicesManager, Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultServicesManager.class);
private static final long serialVersionUID = -8581398063126547772L;
private final ServiceRegistryDao serviceRegistryDao;
@Autowired
private transient ApplicationEventPublisher eventPublisher;
private Map<Long, RegisteredService> services = new ConcurrentHashMap<>();
private Map<String, TreeSet<RegisteredService>> domains = new ConcurrentHashMap<>();
/**
* This regular expression is used to strip the domain form the serviceId that is set in
* the Service and also passed as the service parameter to the login endpoint.
*/
private final Pattern domainPattern = RegexUtils.createPattern("^(https?|imaps?):
/**
* Instantiates a new default services manager impl.
*
* @param serviceRegistryDao the service registry dao
*/
public DomainServicesManager(final ServiceRegistryDao serviceRegistryDao) {
this.serviceRegistryDao = serviceRegistryDao;
}
@Audit(action = "DELETE_SERVICE",
actionResolverName = "DELETE_SERVICE_ACTION_RESOLVER",
resourceResolverName = "DELETE_SERVICE_RESOURCE_RESOLVER")
@Override
public synchronized RegisteredService delete(final long id) {
final RegisteredService service = findServiceBy(id);
if (service != null) {
this.serviceRegistryDao.delete(service);
this.services.remove(id);
this.domains.get(getDomain(service.getServiceId())).remove(service);
publishEvent(new CasRegisteredServiceDeletedEvent(this, service));
}
return service;
}
@Override
public RegisteredService findServiceBy(final Service service) {
return service != null ? findServiceBy(service.getId()) : null;
}
@Override
public Collection<RegisteredService> findServiceBy(final Predicate<RegisteredService> predicate) {
return services.values().stream()
.filter(predicate)
.sorted()
.collect(Collectors.toSet());
}
@Override
public <T extends RegisteredService> T findServiceBy(final Service serviceId, final Class<T> clazz) {
return findServiceBy(serviceId.getId(), clazz);
}
@Override
public <T extends RegisteredService> T findServiceBy(final String serviceId, final Class<T> clazz) {
return getServicesForDomain(getDomain(serviceId)).stream()
.filter(s -> s.getClass().isAssignableFrom(clazz) && s.matches(serviceId))
.map(clazz::cast)
.findFirst()
.orElse(null);
}
@Override
public RegisteredService findServiceBy(final long id) {
final RegisteredService r = this.services.get(id);
try {
return r == null ? null : r.clone();
} catch (final CloneNotSupportedException e) {
return r;
}
}
@Override
public RegisteredService findServiceBy(final String serviceId) {
String domain = serviceId != null ? getDomain(serviceId) : StringUtils.EMPTY;
domain = domains.containsKey(domain) ? domain : "default";
return domains.get(domain)
.stream()
.filter(s -> s.matches(serviceId))
.findFirst().orElse(null);
}
@Override
public Collection<RegisteredService> getAllServices() {
return services.values()
.stream()
.sorted()
.collect(Collectors.toList());
}
@Override
public boolean matchesExistingService(final Service service) {
return matchesExistingService(service.getId());
}
@Override
public boolean matchesExistingService(final String service) {
return findServiceBy(service) != null;
}
@Audit(action = "SAVE_SERVICE",
actionResolverName = "SAVE_SERVICE_ACTION_RESOLVER",
resourceResolverName = "SAVE_SERVICE_RESOURCE_RESOLVER")
@Override
public synchronized RegisteredService save(final RegisteredService registeredService) {
final RegisteredService r = this.serviceRegistryDao.save(registeredService);
this.services.put(r.getId(), r);
addToDomain(r, this.domains);
publishEvent(new CasRegisteredServiceSavedEvent(this, r));
return r;
}
/**
* Load services that are provided by the DAO.
*/
@Scheduled(initialDelayString = "${cas.serviceRegistry.startDelay:20000}",
fixedDelayString = "${cas.serviceRegistry.repeatInterval:60000}")
@Override
@PostConstruct
public void load() {
LOGGER.debug("Loading services from [{}]", this.serviceRegistryDao);
this.services = this.serviceRegistryDao.load().stream()
.collect(Collectors.toConcurrentMap(r -> {
LOGGER.debug("Adding registered service [{}]", r.getServiceId());
return r.getId();
}, r -> r, (r, s) -> s == null ? r : s));
final Map<String, TreeSet<RegisteredService>> localDomains = new ConcurrentHashMap<>();
this.services.values().stream().forEach(r -> addToDomain(r, localDomains));
this.domains = localDomains;
LOGGER.info("Loaded [{}] services from [{}].", this.services.size(), this.serviceRegistryDao);
}
@Override
public int count() {
return services.size();
}
@Override
public List<String> getDomains() {
return domains.keySet().stream().sorted().collect(Collectors.toList());
}
@Override
public Collection<RegisteredService> getServicesForDomain(final String domain) {
return domains.containsKey(domain) ? domains.get(domain) : Collections.EMPTY_LIST;
}
private void publishEvent(final ApplicationEvent event) {
if (this.eventPublisher != null) {
this.eventPublisher.publishEvent(event);
}
}
private String getDomain(final String service) {
final Matcher match = domainPattern.matcher(service.toLowerCase());
return match.lookingAt() && !match.group(1).contains("*") ? match.group(1) : "default";
}
private void addToDomain(final RegisteredService r, final Map<String, TreeSet<RegisteredService>> map) {
final String domain = getDomain(r.getServiceId());
final TreeSet<RegisteredService> services;
if (map.containsKey(domain)) {
services = map.get(domain);
} else {
services = new TreeSet<>();
}
services.add(r);
map.put(domain, services);
}
} |
package org.epics.pvmanager.jca;
import gov.aps.jca.CAException;
import gov.aps.jca.CAStatus;
import gov.aps.jca.Channel;
import gov.aps.jca.Context;
import gov.aps.jca.Monitor;
import gov.aps.jca.dbr.DBR;
import gov.aps.jca.event.ConnectionEvent;
import gov.aps.jca.event.ConnectionListener;
import gov.aps.jca.event.MonitorEvent;
import gov.aps.jca.event.MonitorListener;
import gov.aps.jca.event.PutEvent;
import gov.aps.jca.event.PutListener;
import org.epics.pvmanager.Collector;
import org.epics.pvmanager.ChannelWriteCallback;
import org.epics.pvmanager.ChannelHandler;
import org.epics.pvmanager.ExceptionHandler;
import org.epics.pvmanager.ValueCache;
/**
*
* @author carcassi
*/
public class JCAChannelHandler extends ChannelHandler<MonitorEvent> {
private final Context context;
private final int monitorMask;
private Channel channel;
public JCAChannelHandler(String channelName, Context context, int monitorMask) {
super(channelName);
this.context = context;
this.monitorMask = monitorMask;
}
@Override
public synchronized void addMonitor(Collector<?> collector, ValueCache<?> cache, ExceptionHandler handler) {
if (cacheType == null) {
cacheType = cache.getType();
}
super.addMonitor(collector, cache, handler);
}
@Override
public void connect(ExceptionHandler handler) {
try {
channel = context.createChannel(getChannelName());
connectionListener = createConnectionListener(channel, handler);
// Need to wait for the connection to be established
// before reading the metadata
channel.addConnectionListener(connectionListener);
// If the channel was already connected, then the monitor may
// be never called. Set it up.
if (channel.getConnectionState() == Channel.CONNECTED) {
setup(channel);
}
} catch (CAException ex) {
handler.handleException(ex);
}
}
synchronized void setup(Channel channel) throws CAException {
// This method may be called twice, if the connection happens
// after the ConnectionListener is setup but before
// the connection state is polled.
// The synchronization makes sure that, if that happens, the
// two calls are serial. Checking the monitor for null to
// make sure the second call does not create another monitor.
if (monitor == null) {
vTypeFactory = VTypeFactory.matchFor(cacheType, channel.getFieldType(), channel.getElementCount());
if (vTypeFactory.getEpicsMetaType() != null) {
metadata = channel.get(vTypeFactory.getEpicsMetaType(), 1);
}
if (vTypeFactory.isArray()) {
monitor = channel.addMonitor(vTypeFactory.getEpicsValueType(), channel.getElementCount(), monitorMask, monitorListener);
} else {
monitor = channel.addMonitor(vTypeFactory.getEpicsValueType(), 1, monitorMask, monitorListener);
}
channel.getContext().flushIO();
}
}
private Class<?> cacheType;
private volatile VTypeFactory vTypeFactory;
private ConnectionListener connectionListener;
private volatile Monitor monitor;
private volatile DBR metadata;
private volatile MonitorEvent event;
private final MonitorListener monitorListener = new MonitorListener() {
@Override
public void monitorChanged(MonitorEvent event) {
JCAChannelHandler.this.event = event;
processValue(event);
}
};
private ConnectionListener createConnectionListener(final Channel channel,
final ExceptionHandler handler) {
return new ConnectionListener() {
@Override
public void connectionChanged(ConnectionEvent ev) {
try {
// Setup monitors on connection
if (ev.isConnected()) {
setup(channel);
if (event != null)
processValue(event);
} else {
if (event != null)
processValue(event);
}
} catch (Exception ex) {
handler.handleException(ex);
}
}
};
}
@Override
public void disconnect(ExceptionHandler handler) {
// Close the monitor
try {
monitor.removeMonitorListener(monitorListener);
monitor.clear();
} catch (Exception ex) {
handler.handleException(ex);
}
// Remove connection listener
try {
channel.removeConnectionListener(connectionListener);
} catch (CAException ex) {
handler.handleException(ex);
}
// Close the channel
try {
channel.destroy();
channel = null;
} catch (CAException ex) {
handler.handleException(ex);
}
}
@Override
public void write(Object newValue, final ChannelWriteCallback callback) {
try {
PutListener listener = new PutListener() {
@Override
public void putCompleted(PutEvent ev) {
if (ev.getStatus().isSuccessful()) {
callback.channelWritten(null);
} else {
callback.channelWritten(new Exception(ev.toString()));
}
}
};
if (newValue instanceof String) {
channel.put(newValue.toString(), listener);
} else if (newValue instanceof byte[]) {
channel.put((byte[]) newValue, listener);
} else if (newValue instanceof short[]) {
channel.put((short[]) newValue, listener);
} else if (newValue instanceof int[]) {
channel.put((int[]) newValue, listener);
} else if (newValue instanceof float[]) {
channel.put((float[]) newValue, listener);
} else if (newValue instanceof double[]) {
channel.put((double[]) newValue, listener);
} else if (newValue instanceof Byte || newValue instanceof Short
|| newValue instanceof Integer || newValue instanceof Long) {
channel.put(((Number) newValue).longValue(), listener);
} else if (newValue instanceof Float || newValue instanceof Double) {
channel.put(((Number) newValue).doubleValue(), listener);
} else {
throw new RuntimeException("Unsupported type for CA: " + newValue.getClass());
}
context.flushIO();
} catch (CAException ex) {
callback.channelWritten(ex);
}
}
@Override
public boolean updateCache(MonitorEvent event, ValueCache<?> cache) {
DBR rawvalue = event.getDBR();
@SuppressWarnings("unchecked")
Object newValue = cacheType.cast(vTypeFactory.createValue(rawvalue, metadata, !isConnected()));
cache.setValue(newValue);
return true;
}
@Override
public boolean isConnected() {
return channel != null && channel.getConnectionState() == Channel.ConnectionState.CONNECTED;
}
} |
package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.common.util.OPair;
import com.orientechnologies.orient.core.command.OBasicCommandContext;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseInternal;
import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexAbstract;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.metadata.OMetadataInternal;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.metadata.schema.OView;
import com.orientechnologies.orient.core.metadata.security.OSecurityInternal;
import com.orientechnologies.orient.core.sql.OCommandExecutorSQLAbstract;
import com.orientechnologies.orient.core.sql.parser.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/** @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com) */
public class OSelectExecutionPlanner {
private QueryPlanningInfo info;
private OSelectStatement statement;
public OSelectExecutionPlanner(OSelectStatement oSelectStatement) {
this.statement = oSelectStatement;
}
private void init(OCommandContext ctx) {
// copying the content, so that it can be manipulated and optimized
info = new QueryPlanningInfo();
info.projection =
this.statement.getProjection() == null ? null : this.statement.getProjection().copy();
info.projection = translateDistinct(info.projection);
info.distinct = info.projection != null && info.projection.isDistinct();
if (info.projection != null) {
info.projection.setDistinct(false);
}
info.target = this.statement.getTarget();
info.whereClause =
this.statement.getWhereClause() == null ? null : this.statement.getWhereClause().copy();
info.whereClause = translateLucene(info.whereClause);
info.perRecordLetClause =
this.statement.getLetClause() == null ? null : this.statement.getLetClause().copy();
info.groupBy = this.statement.getGroupBy() == null ? null : this.statement.getGroupBy().copy();
info.orderBy = this.statement.getOrderBy() == null ? null : this.statement.getOrderBy().copy();
info.unwind = this.statement.getUnwind() == null ? null : this.statement.getUnwind().copy();
info.skip = this.statement.getSkip();
info.limit = this.statement.getLimit();
info.lockRecord = this.statement.getLockRecord();
info.timeout = this.statement.getTimeout() == null ? null : this.statement.getTimeout().copy();
if (info.timeout == null
&& ctx.getDatabase().getConfiguration().getValueAsLong(OGlobalConfiguration.COMMAND_TIMEOUT)
> 0) {
info.timeout = new OTimeout(-1);
info.timeout.setVal(
ctx.getDatabase()
.getConfiguration()
.getValueAsLong(OGlobalConfiguration.COMMAND_TIMEOUT));
}
}
public OInternalExecutionPlan createExecutionPlan(
OCommandContext ctx, boolean enableProfiling, boolean useCache) {
ODatabaseDocumentInternal db = (ODatabaseDocumentInternal) ctx.getDatabase();
if (useCache && !enableProfiling && statement.executinPlanCanBeCached()) {
OExecutionPlan plan = OExecutionPlanCache.get(statement.getOriginalStatement(), ctx, db);
if (plan != null) {
return (OInternalExecutionPlan) plan;
}
}
long planningStart = System.currentTimeMillis();
init(ctx);
OSelectExecutionPlan result = new OSelectExecutionPlan(ctx);
if (info.expand && info.distinct) {
throw new OCommandExecutionException(
"Cannot execute a statement with DISTINCT expand(), please use a subquery");
}
optimizeQuery(info, ctx);
if (handleHardwiredOptimizations(result, ctx, enableProfiling)) {
return result;
}
handleGlobalLet(result, info, ctx, enableProfiling);
calculateShardingStrategy(info, ctx);
handleFetchFromTarger(result, info, ctx, enableProfiling);
if (info.globalLetPresent) {
// do the raw fetch remotely, then do the rest on the coordinator
buildDistributedExecutionPlan(result, info, ctx, enableProfiling);
}
handleLet(result, info, ctx, enableProfiling);
handleWhere(result, info, ctx, enableProfiling);
// TODO optimization: in most cases the projections can be calculated on remote nodes
buildDistributedExecutionPlan(result, info, ctx, enableProfiling);
handleLockRecord(result, info, ctx, enableProfiling);
handleProjectionsBlock(result, info, ctx, enableProfiling);
if (info.timeout != null) {
result.chain(new AccumulatingTimeoutStep(info.timeout, ctx, enableProfiling));
}
if (useCache
&& !enableProfiling
&& statement.executinPlanCanBeCached()
&& result.canBeCached()
&& OExecutionPlanCache.getLastInvalidation(db) < planningStart) {
OExecutionPlanCache.put(
statement.getOriginalStatement(), result, (ODatabaseDocumentInternal) ctx.getDatabase());
}
return result;
}
private void handleLockRecord(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean enableProfiling) {
if (info.lockRecord != null) {
result.chain(new LockRecordStep(info.lockRecord, ctx, enableProfiling));
}
}
public static void handleProjectionsBlock(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean enableProfiling) {
handleProjectionsBeforeOrderBy(result, info, ctx, enableProfiling);
if (info.expand || info.unwind != null || info.groupBy != null) {
handleProjections(result, info, ctx, enableProfiling);
handleExpand(result, info, ctx, enableProfiling);
handleUnwind(result, info, ctx, enableProfiling);
handleOrderBy(result, info, ctx, enableProfiling);
if (info.skip != null) {
result.chain(new SkipExecutionStep(info.skip, ctx, enableProfiling));
}
if (info.limit != null) {
result.chain(new LimitExecutionStep(info.limit, ctx, enableProfiling));
}
} else {
handleOrderBy(result, info, ctx, enableProfiling);
if (info.distinct || info.groupBy != null || info.aggregateProjection != null) {
handleProjections(result, info, ctx, enableProfiling);
handleDistinct(result, info, ctx, enableProfiling);
if (info.skip != null) {
result.chain(new SkipExecutionStep(info.skip, ctx, enableProfiling));
}
if (info.limit != null) {
result.chain(new LimitExecutionStep(info.limit, ctx, enableProfiling));
}
} else {
if (info.skip != null) {
result.chain(new SkipExecutionStep(info.skip, ctx, enableProfiling));
}
if (info.limit != null) {
result.chain(new LimitExecutionStep(info.limit, ctx, enableProfiling));
}
handleProjections(result, info, ctx, enableProfiling);
}
}
}
private void buildDistributedExecutionPlan(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean enableProfiling) {
if (info.distributedFetchExecutionPlans == null) {
return;
}
String currentNode = ((ODatabaseDocumentInternal) ctx.getDatabase()).getLocalNodeName();
if (info.distributedFetchExecutionPlans.size() == 1) {
if (info.distributedFetchExecutionPlans.get(currentNode) != null) {
// everything is executed on local server
OSelectExecutionPlan localSteps = info.distributedFetchExecutionPlans.get(currentNode);
for (OExecutionStep step : localSteps.getSteps()) {
result.chain((OExecutionStepInternal) step);
}
} else {
// everything is executed on a single remote node
String node = info.distributedFetchExecutionPlans.keySet().iterator().next();
OSelectExecutionPlan subPlan = info.distributedFetchExecutionPlans.get(node);
DistributedExecutionStep step =
new DistributedExecutionStep(subPlan, node, ctx, enableProfiling);
result.chain(step);
}
info.distributedFetchExecutionPlans = null;
} else {
// sharded fetching
List<OExecutionPlan> subPlans = new ArrayList<>();
for (Map.Entry<String, OSelectExecutionPlan> entry :
info.distributedFetchExecutionPlans.entrySet()) {
if (entry.getKey().equals(currentNode)) {
subPlans.add(entry.getValue());
} else {
DistributedExecutionStep step =
new DistributedExecutionStep(entry.getValue(), entry.getKey(), ctx, enableProfiling);
OSelectExecutionPlan subPlan = new OSelectExecutionPlan(ctx);
subPlan.chain(step);
subPlans.add(subPlan);
}
}
result.chain(new ParallelExecStep((List) subPlans, ctx, enableProfiling));
}
info.distributedPlanCreated = true;
}
/**
* based on the cluster/server map and the query target, this method tries to find an optimal
* strategy to execute the query on the cluster.
*
* @param info
* @param ctx
*/
private void calculateShardingStrategy(QueryPlanningInfo info, OCommandContext ctx) {
ODatabaseDocumentInternal db = (ODatabaseDocumentInternal) ctx.getDatabase();
info.distributedFetchExecutionPlans = new LinkedHashMap<>();
Map<String, Set<String>> clusterMap = db.getActiveClusterMap();
Set<String> queryClusters = calculateTargetClusters(info, ctx);
if (queryClusters == null || queryClusters.size() == 0) { // no target
String localNode = db.getLocalNodeName();
info.serverToClusters = new LinkedHashMap<>();
info.serverToClusters.put(localNode, clusterMap.get(localNode));
info.distributedFetchExecutionPlans.put(localNode, new OSelectExecutionPlan(ctx));
return;
}
// Set<String> serversWithAllTheClusers = getServersThatHasAllClusters(clusterMap,
// queryClusters);
// if (serversWithAllTheClusers.isEmpty()) {
// sharded query
Map<String, Set<String>> minimalSetOfNodes =
getMinimalSetOfNodesForShardedQuery(db.getLocalNodeName(), clusterMap, queryClusters);
if (minimalSetOfNodes == null) {
throw new OCommandExecutionException("Cannot execute sharded query");
}
info.serverToClusters = minimalSetOfNodes;
for (String node : info.serverToClusters.keySet()) {
info.distributedFetchExecutionPlans.put(node, new OSelectExecutionPlan(ctx));
}
// } else {
// // all on a node
// String targetNode = serversWithAllTheClusers.contains(db.getLocalNodeName()) ?
// db.getLocalNodeName() :
// serversWithAllTheClusers.iterator().next();
// info.serverToClusters = new HashMap<>();
// info.serverToClusters.put(targetNode, queryClusters);
}
/**
* given a cluster map and a set of clusters involved in a query, tries to calculate the minimum
* number of nodes that will have to be involved in the query execution, with clusters involved
* for each node.
*
* @param clusterMap
* @param queryClusters
* @return a map that has node names as a key and clusters (data files) for each node as a value
*/
private Map<String, Set<String>> getMinimalSetOfNodesForShardedQuery(
String localNode, Map<String, Set<String>> clusterMap, Set<String> queryClusters) {
// approximate algorithm, the problem is NP-complete
Map<String, Set<String>> result = new LinkedHashMap<>();
Set<String> uncovered = new HashSet<>();
uncovered.addAll(queryClusters);
uncovered =
uncovered.stream()
.filter(x -> x != null)
.map(x -> x.toLowerCase(Locale.ENGLISH))
.collect(Collectors.toSet());
// try local node first
Set<String> nextNodeClusters = new HashSet<>();
Set<String> clustersForNode = clusterMap.get(localNode);
if (clustersForNode != null) {
nextNodeClusters.addAll(clustersForNode);
}
nextNodeClusters.retainAll(uncovered);
if (nextNodeClusters.size() > 0) {
result.put(localNode, nextNodeClusters);
uncovered.removeAll(nextNodeClusters);
}
while (uncovered.size() > 0) {
String nextNode = findItemThatCoversMore(uncovered, clusterMap);
nextNodeClusters = new HashSet<>();
nextNodeClusters.addAll(clusterMap.get(nextNode));
nextNodeClusters.retainAll(uncovered);
if (nextNodeClusters.size() == 0) {
throw new OCommandExecutionException(
"Cannot execute a sharded query: clusters ["
+ uncovered.stream().collect(Collectors.joining(", "))
+ "] are not present on any node"
+ "\n ["
+ clusterMap.entrySet().stream()
.map(
x ->
""
+ x.getKey()
+ ":("
+ x.getValue().stream().collect(Collectors.joining(","))
+ ")")
.collect(Collectors.joining(", "))
+ "]");
}
result.put(nextNode, nextNodeClusters);
uncovered.removeAll(nextNodeClusters);
}
return result;
}
private String findItemThatCoversMore(
Set<String> uncovered, Map<String, Set<String>> clusterMap) {
String lastFound = null;
int lastSize = -1;
for (Map.Entry<String, Set<String>> nodeConfig : clusterMap.entrySet()) {
Set<String> current = new HashSet<>();
current.addAll(nodeConfig.getValue());
current.retainAll(uncovered);
int thisSize = current.size();
if (lastFound == null || thisSize > lastSize) {
lastFound = nodeConfig.getKey();
lastSize = thisSize;
}
}
return lastFound;
}
/**
* @param clusterMap the cluster map for current sharding configuration
* @param queryClusters the clusters that are target of the query
* @return
*/
private Set<String> getServersThatHasAllClusters(
Map<String, Set<String>> clusterMap, Set<String> queryClusters) {
Set<String> remainingServers = clusterMap.keySet();
for (String cluster : queryClusters) {
for (Map.Entry<String, Set<String>> serverConfig : clusterMap.entrySet()) {
if (!serverConfig.getValue().contains(cluster)) {
remainingServers.remove(serverConfig.getKey());
}
}
}
return remainingServers;
}
/**
* tries to calculate which clusters will be impacted by this query
*
* @param info
* @param ctx
* @return a set of cluster names this query will fetch from
*/
private Set<String> calculateTargetClusters(QueryPlanningInfo info, OCommandContext ctx) {
if (info.target == null) {
return Collections.EMPTY_SET;
}
Set<String> result = new HashSet<>();
ODatabaseDocumentInternal db = (ODatabaseDocumentInternal) ctx.getDatabase();
OFromItem item = info.target.getItem();
if (item.getRids() != null && item.getRids().size() > 0) {
if (item.getRids().size() == 1) {
OInteger cluster = item.getRids().get(0).getCluster();
if (cluster.getValue().longValue() > ORID.CLUSTER_MAX) {
throw new OCommandExecutionException(
"Invalid cluster Id:" + cluster + ". Max allowed value = " + ORID.CLUSTER_MAX);
}
result.add(db.getClusterNameById(cluster.getValue().intValue()));
} else {
for (ORid rid : item.getRids()) {
OInteger cluster = rid.getCluster();
result.add(db.getClusterNameById(cluster.getValue().intValue()));
}
}
return result;
} else if (item.getInputParams() != null && item.getInputParams().size() > 0) {
if (((ODatabaseInternal) ctx.getDatabase()).isSharded()) {
throw new UnsupportedOperationException(
"Sharded query with input parameter as a target is not supported yet");
}
return null;
} else if (item.getCluster() != null) {
String name = item.getCluster().getClusterName();
if (name == null) {
name = db.getClusterNameById(item.getCluster().getClusterNumber());
}
if (name != null) {
result.add(name);
return result;
} else {
return null;
}
} else if (item.getClusterList() != null) {
for (OCluster cluster : item.getClusterList().toListOfClusters()) {
String name = cluster.getClusterName();
if (name == null) {
name = db.getClusterNameById(cluster.getClusterNumber());
}
if (name != null) {
result.add(name);
}
}
return result;
} else if (item.getIndex() != null) {
String indexName = item.getIndex().getIndexName();
OIndex idx = db.getMetadata().getIndexManagerInternal().getIndex(db, indexName);
if (idx == null) {
throw new OCommandExecutionException("Index " + indexName + " does not exist");
}
result.addAll(idx.getClusters());
if (result.isEmpty()) {
return null;
}
return result;
} else if (item.getInputParam() != null) {
if (((ODatabaseInternal) ctx.getDatabase()).isSharded()) {
throw new UnsupportedOperationException(
"Sharded query with input parameter as a target is not supported yet");
}
return null;
} else if (item.getIdentifier() != null) {
String className = item.getIdentifier().getStringValue();
OClass clazz = getSchemaFromContext(ctx).getClass(className);
if (clazz == null) {
clazz = getSchemaFromContext(ctx).getView(className);
}
if (clazz == null) {
return null;
}
int[] clusterIds = clazz.getPolymorphicClusterIds();
for (int clusterId : clusterIds) {
String clusterName = db.getClusterNameById(clusterId);
if (clusterName != null) {
result.add(clusterName);
}
}
return result;
}
return null;
}
private OWhereClause translateLucene(OWhereClause whereClause) {
if (whereClause == null) {
return null;
}
if (whereClause.getBaseExpression() != null) {
whereClause.getBaseExpression().translateLuceneOperator();
}
return whereClause;
}
/**
* for backward compatibility, translate "distinct(foo)" to "DISTINCT foo". This method modifies
* the projection itself.
*
* @param projection the projection
*/
protected static OProjection translateDistinct(OProjection projection) {
if (projection != null && projection.getItems().size() == 1) {
if (isDistinct(projection.getItems().get(0))) {
projection = projection.copy();
OProjectionItem item = projection.getItems().get(0);
OFunctionCall function =
((OBaseExpression) item.getExpression().getMathExpression())
.getIdentifier()
.getLevelZero()
.getFunctionCall();
OExpression exp = function.getParams().get(0);
OProjectionItem resultItem = new OProjectionItem(-1);
resultItem.setAlias(item.getAlias());
resultItem.setExpression(exp.copy());
OProjection result = new OProjection(-1);
result.setItems(new ArrayList<>());
result.setDistinct(true);
result.getItems().add(resultItem);
return result;
}
}
return projection;
}
/**
* checks if a projection is a distinct(expr). In new executor the distinct() function is not
* supported, so "distinct(expr)" is translated to "DISTINCT expr"
*
* @param item the projection
* @return
*/
private static boolean isDistinct(OProjectionItem item) {
if (item.getExpression() == null) {
return false;
}
if (item.getExpression().getMathExpression() == null) {
return false;
}
if (!(item.getExpression().getMathExpression() instanceof OBaseExpression)) {
return false;
}
OBaseExpression base = (OBaseExpression) item.getExpression().getMathExpression();
if (base.getIdentifier() == null) {
return false;
}
if (base.getModifier() != null) {
return false;
}
if (base.getIdentifier().getLevelZero() == null) {
return false;
}
OFunctionCall function = base.getIdentifier().getLevelZero().getFunctionCall();
if (function == null) {
return false;
}
return function.getName().getStringValue().equalsIgnoreCase("distinct");
}
private boolean handleHardwiredOptimizations(
OSelectExecutionPlan result, OCommandContext ctx, boolean profilingEnabled) {
if (handleHardwiredCountOnIndex(result, info, ctx, profilingEnabled)) {
return true;
}
if (handleHardwiredCountOnClass(result, info, ctx, profilingEnabled)) {
return true;
}
return handleHardwiredCountOnClassUsingIndex(result, info, ctx, profilingEnabled);
}
private boolean handleHardwiredCountOnClass(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
OIdentifier targetClass = info.target == null ? null : info.target.getItem().getIdentifier();
if (targetClass == null) {
return false;
}
if (info.distinct || info.expand) {
return false;
}
if (info.preAggregateProjection != null) {
return false;
}
if (!isCountStar(info)) {
return false;
}
if (!isMinimalQuery(info)) {
return false;
}
if (securityPoliciesExistForClass(targetClass, ctx)) {
return false;
}
result.chain(
new CountFromClassStep(
targetClass, info.projection.getAllAliases().iterator().next(), ctx, profilingEnabled));
return true;
}
private boolean securityPoliciesExistForClass(OIdentifier targetClass, OCommandContext ctx) {
ODatabaseInternal db = (ODatabaseInternal) ctx.getDatabase();
OSecurityInternal security = db.getSharedContext().getSecurity();
OClass clazz = db.getClass(targetClass.getStringValue()); // normalize class name case
if (clazz == null) {
return false;
}
return security.isReadRestrictedBySecurityPolicy(
(ODatabaseSession) db, "database.class." + clazz.getName());
}
private boolean handleHardwiredCountOnClassUsingIndex(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
OIdentifier targetClass = info.target == null ? null : info.target.getItem().getIdentifier();
if (targetClass == null) {
return false;
}
if (info.distinct || info.expand) {
return false;
}
if (info.preAggregateProjection != null) {
return false;
}
if (!isCountStar(info)) {
return false;
}
if (info.projectionAfterOrderBy != null
|| info.globalLetClause != null
|| info.perRecordLetClause != null
|| info.groupBy != null
|| info.orderBy != null
|| info.unwind != null
|| info.skip != null) {
return false;
}
OClass clazz = ctx.getDatabase().getClass(targetClass.getStringValue());
if (clazz == null) {
return false;
}
if (info.flattenedWhereClause == null
|| info.flattenedWhereClause.size() > 1
|| info.flattenedWhereClause.get(0).getSubBlocks().size() > 1) {
// for now it only handles a single equality condition, it can be extended
return false;
}
OBooleanExpression condition = info.flattenedWhereClause.get(0).getSubBlocks().get(0);
if (!(condition instanceof OBinaryCondition)) {
return false;
}
OBinaryCondition binaryCondition = (OBinaryCondition) condition;
if (!binaryCondition.getLeft().isBaseIdentifier()) {
return false;
}
if (!(binaryCondition.getOperator() instanceof OEqualsCompareOperator)) {
// this can be extended to use range operators too
return false;
}
if (securityPoliciesExistForClass(targetClass, ctx)) {
return false;
}
for (OIndex classIndex : clazz.getClassIndexes()) {
List<String> fields = classIndex.getDefinition().getFields();
if (fields.size() == 1
&& fields.get(0).equals(binaryCondition.getLeft().getDefaultAlias().getStringValue())) {
OExpression expr = ((OBinaryCondition) condition).getRight();
result.chain(
new CountFromIndexWithKeyStep(
new OIndexIdentifier(classIndex.getName(), OIndexIdentifier.Type.INDEX),
expr,
info.projection.getAllAliases().iterator().next(),
ctx,
profilingEnabled));
return true;
}
}
return false;
}
private boolean handleHardwiredCountOnIndex(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
OIndexIdentifier targetIndex = info.target == null ? null : info.target.getItem().getIndex();
if (targetIndex == null) {
return false;
}
if (info.distinct || info.expand) {
return false;
}
if (info.preAggregateProjection != null) {
return false;
}
if (!isCountStar(info)) {
return false;
}
if (!isMinimalQuery(info)) {
return false;
}
result.chain(
new CountFromIndexStep(
targetIndex, info.projection.getAllAliases().iterator().next(), ctx, profilingEnabled));
return true;
}
/**
* returns true if the query is minimal, ie. no WHERE condition, no SKIP/LIMIT, no UNWIND, no
* GROUP/ORDER BY, no LET
*
* @return
*/
private boolean isMinimalQuery(QueryPlanningInfo info) {
return info.projectionAfterOrderBy == null
&& info.globalLetClause == null
&& info.perRecordLetClause == null
&& info.whereClause == null
&& info.flattenedWhereClause == null
&& info.groupBy == null
&& info.orderBy == null
&& info.unwind == null
&& info.skip == null;
}
private static boolean isCountStar(QueryPlanningInfo info) {
if (info.aggregateProjection == null
|| info.projection == null
|| info.aggregateProjection.getItems().size() != 1
|| info.projection.getItems().size() != 1) {
return false;
}
OProjectionItem item = info.aggregateProjection.getItems().get(0);
return item.getExpression().toString().equalsIgnoreCase("count(*)");
}
private static boolean isCountOnly(QueryPlanningInfo info) {
if (info.aggregateProjection == null
|| info.projection == null
|| info.aggregateProjection.getItems().size() != 1
|| info.projection.getItems().stream()
.filter(x -> !x.getProjectionAliasAsString().startsWith("_$$$ORDER_BY_ALIAS$$$_"))
.count()
!= 1) {
return false;
}
OProjectionItem item = info.aggregateProjection.getItems().get(0);
OExpression exp = item.getExpression();
if (exp.getMathExpression() != null && exp.getMathExpression() instanceof OBaseExpression) {
OBaseExpression base = (OBaseExpression) exp.getMathExpression();
return base.isCount() && base.getModifier() == null;
}
return false;
}
public static void handleUnwind(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (info.unwind != null) {
result.chain(new UnwindStep(info.unwind, ctx, profilingEnabled));
}
}
private static void handleDistinct(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (info.distinct) {
result.chain(new DistinctExecutionStep(ctx, profilingEnabled));
}
}
private static void handleProjectionsBeforeOrderBy(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (info.orderBy != null) {
handleProjections(result, info, ctx, profilingEnabled);
}
}
private static void handleProjections(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (!info.projectionsCalculated && info.projection != null) {
if (info.preAggregateProjection != null) {
result.chain(
new ProjectionCalculationStep(info.preAggregateProjection, ctx, profilingEnabled));
}
if (info.aggregateProjection != null) {
long aggregationLimit = -1;
if (info.orderBy == null && info.limit != null) {
aggregationLimit = info.limit.getValue(ctx);
if (info.skip != null && info.skip.getValue(ctx) > 0) {
aggregationLimit += info.skip.getValue(ctx);
}
}
result.chain(
new AggregateProjectionCalculationStep(
info.aggregateProjection,
info.groupBy,
aggregationLimit,
ctx,
info.timeout != null ? info.timeout.getVal().longValue() : -1,
profilingEnabled));
if (isCountOnly(info) && info.groupBy == null) {
result.chain(
new GuaranteeEmptyCountStep(
info.aggregateProjection.getItems().get(0), ctx, profilingEnabled));
}
}
result.chain(new ProjectionCalculationStep(info.projection, ctx, profilingEnabled));
info.projectionsCalculated = true;
}
}
protected static void optimizeQuery(QueryPlanningInfo info, OCommandContext ctx) {
splitLet(info, ctx);
rewriteIndexChainsAsSubqueries(info, ctx);
extractSubQueries(info);
if (info.projection != null && info.projection.isExpand()) {
info.expand = true;
info.projection = info.projection.getExpandContent();
}
if (info.whereClause != null) {
info.flattenedWhereClause = info.whereClause.flatten();
// this helps index optimization
info.flattenedWhereClause = moveFlattededEqualitiesLeft(info.flattenedWhereClause);
}
splitProjectionsForGroupBy(info, ctx);
addOrderByProjections(info);
}
private static void rewriteIndexChainsAsSubqueries(QueryPlanningInfo info, OCommandContext ctx) {
if (ctx == null || ctx.getDatabase() == null) {
return;
}
if (info.whereClause != null
&& info.target != null
&& info.target.getItem().getIdentifier() != null) {
String className = info.target.getItem().getIdentifier().getStringValue();
OSchema schema = getSchemaFromContext(ctx);
OClass clazz = schema.getClass(className);
if (clazz == null) {
clazz = schema.getView(className);
}
if (clazz != null) {
info.whereClause.getBaseExpression().rewriteIndexChainsAsSubqueries(ctx, clazz);
}
}
}
/** splits LET clauses in global (executed once) and local (executed once per record) */
private static void splitLet(QueryPlanningInfo info, OCommandContext ctx) {
if (info.perRecordLetClause != null && info.perRecordLetClause.getItems() != null) {
Iterator<OLetItem> iterator = info.perRecordLetClause.getItems().iterator();
while (iterator.hasNext()) {
OLetItem item = iterator.next();
if (item.getExpression() != null
&& (item.getExpression().isEarlyCalculated(ctx)
|| isUnionAllOfQueries(info, item.getVarName(), item.getExpression()))) {
iterator.remove();
addGlobalLet(info, item.getVarName(), item.getExpression());
} else if (item.getQuery() != null && !item.getQuery().refersToParent()) {
iterator.remove();
addGlobalLet(info, item.getVarName(), item.getQuery());
}
}
}
}
private static boolean isUnionAllOfQueries(
QueryPlanningInfo info, OIdentifier varName, OExpression expression) {
if (expression.getMathExpression() instanceof OBaseExpression) {
OBaseExpression exp = (OBaseExpression) expression.getMathExpression();
if (exp.getIdentifier() != null
&& exp.getModifier() == null
&& exp.getIdentifier().getLevelZero() != null
&& exp.getIdentifier().getLevelZero().getFunctionCall() != null) {
OFunctionCall fc = exp.getIdentifier().getLevelZero().getFunctionCall();
if (fc.getName().getStringValue().equalsIgnoreCase("unionall")) {
for (OExpression param : fc.getParams()) {
if (param.toString().startsWith("$")) {
return true;
}
}
return true;
}
}
}
return false;
}
/**
* re-writes a list of flat AND conditions, moving left all the equality operations
*
* @param flattenedWhereClause
* @return
*/
private static List<OAndBlock> moveFlattededEqualitiesLeft(List<OAndBlock> flattenedWhereClause) {
if (flattenedWhereClause == null) {
return null;
}
List<OAndBlock> result = new ArrayList<>();
for (OAndBlock block : flattenedWhereClause) {
List<OBooleanExpression> equalityExpressions = new ArrayList<>();
List<OBooleanExpression> nonEqualityExpressions = new ArrayList<>();
OAndBlock newBlock = block.copy();
for (OBooleanExpression exp : newBlock.getSubBlocks()) {
if (exp instanceof OBinaryCondition) {
if (((OBinaryCondition) exp).getOperator() instanceof OEqualsCompareOperator) {
equalityExpressions.add(exp);
} else {
nonEqualityExpressions.add(exp);
}
} else {
nonEqualityExpressions.add(exp);
}
}
OAndBlock newAnd = new OAndBlock(-1);
newAnd.getSubBlocks().addAll(equalityExpressions);
newAnd.getSubBlocks().addAll(nonEqualityExpressions);
result.add(newAnd);
}
return result;
}
/** creates additional projections for ORDER BY */
private static void addOrderByProjections(QueryPlanningInfo info) {
if (info.orderApplied
|| info.expand
|| info.unwind != null
|| info.orderBy == null
|| info.orderBy.getItems().size() == 0
|| info.projection == null
|| info.projection.getItems() == null
|| (info.projection.getItems().size() == 1 && info.projection.getItems().get(0).isAll())) {
return;
}
OOrderBy newOrderBy = info.orderBy == null ? null : info.orderBy.copy();
List<OProjectionItem> additionalOrderByProjections =
calculateAdditionalOrderByProjections(info.projection.getAllAliases(), newOrderBy);
if (additionalOrderByProjections.size() > 0) {
info.orderBy = newOrderBy; // the ORDER BY has changed
}
if (additionalOrderByProjections.size() > 0) {
info.projectionAfterOrderBy = new OProjection(-1);
info.projectionAfterOrderBy.setItems(new ArrayList<>());
for (String alias : info.projection.getAllAliases()) {
info.projectionAfterOrderBy.getItems().add(projectionFromAlias(new OIdentifier(alias)));
}
for (OProjectionItem item : additionalOrderByProjections) {
if (info.preAggregateProjection != null) {
info.preAggregateProjection.getItems().add(item);
info.aggregateProjection.getItems().add(projectionFromAlias(item.getAlias()));
info.projection.getItems().add(projectionFromAlias(item.getAlias()));
} else {
info.projection.getItems().add(item);
}
}
}
}
/**
* given a list of aliases (present in the existing projections) calculates a list of additional
* projections to add to the existing projections to allow ORDER BY calculation. The sorting
* clause will be modified with new replaced aliases
*
* @param allAliases existing aliases in the projection
* @param orderBy sorting clause
* @return a list of additional projections to add to the existing projections to allow ORDER BY
* calculation (empty if nothing has to be added).
*/
private static List<OProjectionItem> calculateAdditionalOrderByProjections(
Set<String> allAliases, OOrderBy orderBy) {
List<OProjectionItem> result = new ArrayList<>();
int nextAliasCount = 0;
if (orderBy != null && orderBy.getItems() != null || !orderBy.getItems().isEmpty()) {
for (OOrderByItem item : orderBy.getItems()) {
if (!allAliases.contains(item.getAlias())) {
OProjectionItem newProj = new OProjectionItem(-1);
if (item.getAlias() != null) {
newProj.setExpression(
new OExpression(new OIdentifier(item.getAlias()), item.getModifier()));
} else if (item.getRecordAttr() != null) {
ORecordAttribute attr = new ORecordAttribute(-1);
attr.setName(item.getRecordAttr());
newProj.setExpression(new OExpression(attr, item.getModifier()));
} else if (item.getRid() != null) {
OExpression exp = new OExpression(-1);
exp.setRid(item.getRid().copy());
newProj.setExpression(exp);
}
OIdentifier newAlias = new OIdentifier("_$$$ORDER_BY_ALIAS$$$_" + (nextAliasCount++));
newProj.setAlias(newAlias);
item.setAlias(newAlias.getStringValue());
item.setModifier(null);
result.add(newProj);
}
}
}
return result;
}
/**
* splits projections in three parts (pre-aggregate, aggregate and final) to efficiently manage
* aggregations
*/
private static void splitProjectionsForGroupBy(QueryPlanningInfo info, OCommandContext ctx) {
if (info.projection == null) {
return;
}
OProjection preAggregate = new OProjection(-1);
preAggregate.setItems(new ArrayList<>());
OProjection aggregate = new OProjection(-1);
aggregate.setItems(new ArrayList<>());
OProjection postAggregate = new OProjection(-1);
postAggregate.setItems(new ArrayList<>());
boolean isSplitted = false;
// split for aggregate projections
AggregateProjectionSplit result = new AggregateProjectionSplit();
for (OProjectionItem item : info.projection.getItems()) {
result.reset();
if (isAggregate(item)) {
isSplitted = true;
OProjectionItem post = item.splitForAggregation(result, ctx);
OIdentifier postAlias = item.getProjectionAlias();
postAlias = new OIdentifier(postAlias, true);
post.setAlias(postAlias);
postAggregate.getItems().add(post);
aggregate.getItems().addAll(result.getAggregate());
preAggregate.getItems().addAll(result.getPreAggregate());
} else {
preAggregate.getItems().add(item);
// also push the alias forward in the chain
OProjectionItem aggItem = new OProjectionItem(-1);
aggItem.setExpression(new OExpression(item.getProjectionAlias()));
aggregate.getItems().add(aggItem);
postAggregate.getItems().add(aggItem);
}
}
// bind split projections to the execution planner
if (isSplitted) {
info.preAggregateProjection = preAggregate;
if (info.preAggregateProjection.getItems() == null
|| info.preAggregateProjection.getItems().size() == 0) {
info.preAggregateProjection = null;
}
info.aggregateProjection = aggregate;
if (info.aggregateProjection.getItems() == null
|| info.aggregateProjection.getItems().size() == 0) {
info.aggregateProjection = null;
}
info.projection = postAggregate;
addGroupByExpressionsToProjections(info);
}
}
private static boolean isAggregate(OProjectionItem item) {
return item.isAggregate();
}
private static OProjectionItem projectionFromAlias(OIdentifier oIdentifier) {
OProjectionItem result = new OProjectionItem(-1);
result.setExpression(new OExpression(oIdentifier));
return result;
}
/**
* if GROUP BY is performed on an expression that is not explicitly in the pre-aggregate
* projections, then that expression has to be put in the pre-aggregate (only here, in subsequent
* steps it's removed)
*/
private static void addGroupByExpressionsToProjections(QueryPlanningInfo info) {
if (info.groupBy == null
|| info.groupBy.getItems() == null
|| info.groupBy.getItems().size() == 0) {
return;
}
OGroupBy newGroupBy = new OGroupBy(-1);
int i = 0;
for (OExpression exp : info.groupBy.getItems()) {
if (exp.isAggregate()) {
throw new OCommandExecutionException("Cannot group by an aggregate function");
}
boolean found = false;
if (info.preAggregateProjection != null) {
for (String alias : info.preAggregateProjection.getAllAliases()) {
// if it's a simple identifier and it's the same as one of the projections in the query,
// then the projection itself is used for GROUP BY without recalculating; in all the other
// cases, it is evaluated separately
if (alias.equals(exp.getDefaultAlias().getStringValue()) && exp.isBaseIdentifier()) {
found = true;
newGroupBy.getItems().add(exp);
break;
}
}
}
if (!found) {
OProjectionItem newItem = new OProjectionItem(-1);
newItem.setExpression(exp);
OIdentifier groupByAlias = new OIdentifier("_$$$GROUP_BY_ALIAS$$$_" + (i++));
newItem.setAlias(groupByAlias);
if (info.preAggregateProjection == null) {
info.preAggregateProjection = new OProjection(-1);
}
if (info.preAggregateProjection.getItems() == null) {
info.preAggregateProjection.setItems(new ArrayList<>());
}
info.preAggregateProjection.getItems().add(newItem);
newGroupBy.getItems().add(new OExpression(groupByAlias));
}
info.groupBy = newGroupBy;
}
}
/** translates subqueries to LET statements */
private static void extractSubQueries(QueryPlanningInfo info) {
SubQueryCollector collector = new SubQueryCollector();
if (info.perRecordLetClause != null) {
info.perRecordLetClause.extractSubQueries(collector);
}
int i = 0;
int j = 0;
for (Map.Entry<OIdentifier, OStatement> entry : collector.getSubQueries().entrySet()) {
OIdentifier alias = entry.getKey();
OStatement query = entry.getValue();
if (query.refersToParent()) {
addRecordLevelLet(info, alias, query, j++);
} else {
addGlobalLet(info, alias, query, i++);
}
}
collector.reset();
if (info.whereClause != null) {
info.whereClause.extractSubQueries(collector);
}
if (info.projection != null) {
info.projection.extractSubQueries(collector);
}
if (info.orderBy != null) {
info.orderBy.extractSubQueries(collector);
}
if (info.groupBy != null) {
info.groupBy.extractSubQueries(collector);
}
for (Map.Entry<OIdentifier, OStatement> entry : collector.getSubQueries().entrySet()) {
OIdentifier alias = entry.getKey();
OStatement query = entry.getValue();
if (query.refersToParent()) {
addRecordLevelLet(info, alias, query);
} else {
addGlobalLet(info, alias, query);
}
}
}
private static void addGlobalLet(QueryPlanningInfo info, OIdentifier alias, OExpression exp) {
if (info.globalLetClause == null) {
info.globalLetClause = new OLetClause(-1);
}
OLetItem item = new OLetItem(-1);
item.setVarName(alias);
item.setExpression(exp);
info.globalLetClause.addItem(item);
}
private static void addGlobalLet(QueryPlanningInfo info, OIdentifier alias, OStatement stm) {
if (info.globalLetClause == null) {
info.globalLetClause = new OLetClause(-1);
}
OLetItem item = new OLetItem(-1);
item.setVarName(alias);
item.setQuery(stm);
info.globalLetClause.addItem(item);
}
private static void addGlobalLet(
QueryPlanningInfo info, OIdentifier alias, OStatement stm, int pos) {
if (info.globalLetClause == null) {
info.globalLetClause = new OLetClause(-1);
}
OLetItem item = new OLetItem(-1);
item.setVarName(alias);
item.setQuery(stm);
info.globalLetClause.getItems().add(pos, item);
}
private static void addRecordLevelLet(QueryPlanningInfo info, OIdentifier alias, OStatement stm) {
if (info.perRecordLetClause == null) {
info.perRecordLetClause = new OLetClause(-1);
}
OLetItem item = new OLetItem(-1);
item.setVarName(alias);
item.setQuery(stm);
info.perRecordLetClause.addItem(item);
}
private static void addRecordLevelLet(
QueryPlanningInfo info, OIdentifier alias, OStatement stm, int pos) {
if (info.perRecordLetClause == null) {
info.perRecordLetClause = new OLetClause(-1);
}
OLetItem item = new OLetItem(-1);
item.setVarName(alias);
item.setQuery(stm);
info.perRecordLetClause.getItems().add(pos, item);
}
private void handleFetchFromTarger(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
OFromItem target = info.target == null ? null : info.target.getItem();
for (Map.Entry<String, OSelectExecutionPlan> shardedPlan :
info.distributedFetchExecutionPlans.entrySet()) {
if (target == null) {
handleNoTarget(shardedPlan.getValue(), ctx, profilingEnabled);
} else if (target.getIdentifier() != null) {
String className = target.getIdentifier().getStringValue();
if (className.startsWith("$")
&& !ctx.getDatabase().getMetadata().getSchema().existsClass(className)) {
handleVariableAsTarget(shardedPlan.getValue(), info, ctx, profilingEnabled);
} else {
Set<String> filterClusters = info.serverToClusters.get(shardedPlan.getKey());
OAndBlock ridRangeConditions = extractRidRanges(info.flattenedWhereClause, ctx);
if (ridRangeConditions != null && !ridRangeConditions.isEmpty()) {
info.ridRangeConditions = ridRangeConditions;
filterClusters =
filterClusters.stream()
.filter(
x -> clusterMatchesRidRange(x, ridRangeConditions, ctx.getDatabase(), ctx))
.collect(Collectors.toSet());
}
handleClassAsTarget(shardedPlan.getValue(), filterClusters, info, ctx, profilingEnabled);
}
} else if (target.getCluster() != null) {
handleClustersAsTarget(
shardedPlan.getValue(),
info,
Collections.singletonList(target.getCluster()),
ctx,
profilingEnabled);
} else if (target.getClusterList() != null) {
List<OCluster> allClusters = target.getClusterList().toListOfClusters();
List<OCluster> clustersForShard = new ArrayList<>();
for (OCluster cluster : allClusters) {
String name = cluster.getClusterName();
if (name == null) {
name = ctx.getDatabase().getClusterNameById(cluster.getClusterNumber());
}
if (name != null && info.serverToClusters.get(shardedPlan.getKey()).contains(name)) {
clustersForShard.add(cluster);
}
}
handleClustersAsTarget(
shardedPlan.getValue(), info, clustersForShard, ctx, profilingEnabled);
} else if (target.getStatement() != null) {
handleSubqueryAsTarget(
shardedPlan.getValue(), target.getStatement(), ctx, profilingEnabled);
} else if (target.getFunctionCall() != null) {
// handleFunctionCallAsTarget(result, target.getFunctionCall(), ctx);//TODO
throw new OCommandExecutionException("function call as target is not supported yet");
} else if (target.getInputParam() != null) {
handleInputParamAsTarget(
shardedPlan.getValue(),
info.serverToClusters.get(shardedPlan.getKey()),
info,
target.getInputParam(),
ctx,
profilingEnabled);
} else if (target.getInputParams() != null && target.getInputParams().size() > 0) {
List<OInternalExecutionPlan> plans = new ArrayList<>();
for (OInputParameter param : target.getInputParams()) {
OSelectExecutionPlan subPlan = new OSelectExecutionPlan(ctx);
handleInputParamAsTarget(
subPlan,
info.serverToClusters.get(shardedPlan.getKey()),
info,
param,
ctx,
profilingEnabled);
plans.add(subPlan);
}
shardedPlan.getValue().chain(new ParallelExecStep(plans, ctx, profilingEnabled));
} else if (target.getIndex() != null) {
handleIndexAsTarget(
shardedPlan.getValue(), info, target.getIndex(), null, ctx, profilingEnabled);
if (info.serverToClusters.size() > 1) {
shardedPlan
.getValue()
.chain(
new FilterByClustersStep(
info.serverToClusters.get(shardedPlan.getKey()), ctx, profilingEnabled));
}
} else if (target.getMetadata() != null) {
handleMetadataAsTarget(shardedPlan.getValue(), target.getMetadata(), ctx, profilingEnabled);
} else if (target.getRids() != null && target.getRids().size() > 0) {
Set<String> filterClusters = info.serverToClusters.get(shardedPlan.getKey());
List<ORid> rids = new ArrayList<>();
for (ORid rid : target.getRids()) {
if (filterClusters == null || isFromClusters(rid, filterClusters, ctx.getDatabase())) {
rids.add(rid);
}
}
if (rids.size() > 0) {
handleRidsAsTarget(shardedPlan.getValue(), rids, ctx, profilingEnabled);
} else {
result.chain(new EmptyStep(ctx, profilingEnabled)); // nothing to return
}
} else {
throw new UnsupportedOperationException();
}
}
}
private void handleVariableAsTarget(
OSelectExecutionPlan plan,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
plan.chain(
new FetchFromVariableStep(
info.target.getItem().getIdentifier().getStringValue(), ctx, profilingEnabled));
}
private boolean clusterMatchesRidRange(
String clusterName, OAndBlock ridRangeConditions, ODatabase database, OCommandContext ctx) {
int thisClusterId = database.getClusterIdByName(clusterName);
for (OBooleanExpression ridRangeCondition : ridRangeConditions.getSubBlocks()) {
if (ridRangeCondition instanceof OBinaryCondition) {
OBinaryCompareOperator operator = ((OBinaryCondition) ridRangeCondition).getOperator();
ORID conditionRid;
Object obj;
if (((OBinaryCondition) ridRangeCondition).getRight().getRid() != null) {
obj =
((OBinaryCondition) ridRangeCondition)
.getRight()
.getRid()
.toRecordId((OResult) null, ctx);
} else {
obj = ((OBinaryCondition) ridRangeCondition).getRight().execute((OResult) null, ctx);
}
conditionRid = ((OIdentifiable) obj).getIdentity();
if (conditionRid != null) {
int conditionClusterId = conditionRid.getClusterId();
if (operator instanceof OGtOperator || operator instanceof OGeOperator) {
if (thisClusterId < conditionClusterId) {
return false;
}
} else if (operator instanceof OLtOperator || operator instanceof OLeOperator) {
if (thisClusterId > conditionClusterId) {
return false;
}
}
}
}
}
return true;
}
private OAndBlock extractRidRanges(List<OAndBlock> flattenedWhereClause, OCommandContext ctx) {
OAndBlock result = new OAndBlock(-1);
if (flattenedWhereClause == null || flattenedWhereClause.size() != 1) {
return result;
}
// TODO optimization: merge multiple conditions
for (OBooleanExpression booleanExpression : flattenedWhereClause.get(0).getSubBlocks()) {
if (isRidRange(booleanExpression, ctx)) {
result.getSubBlocks().add(booleanExpression.copy());
}
}
return result;
}
private boolean isRidRange(OBooleanExpression booleanExpression, OCommandContext ctx) {
if (booleanExpression instanceof OBinaryCondition) {
OBinaryCondition cond = ((OBinaryCondition) booleanExpression);
OBinaryCompareOperator operator = cond.getOperator();
if (isRangeOperator(operator) && cond.getLeft().toString().equalsIgnoreCase("@rid")) {
Object obj;
if (cond.getRight().getRid() != null) {
obj = cond.getRight().getRid().toRecordId((OResult) null, ctx);
} else {
obj = cond.getRight().execute((OResult) null, ctx);
}
return obj instanceof OIdentifiable;
}
}
return false;
}
private boolean isRangeOperator(OBinaryCompareOperator operator) {
return operator instanceof OLtOperator
|| operator instanceof OLeOperator
|| operator instanceof OGtOperator
|| operator instanceof OGeOperator;
}
private void handleInputParamAsTarget(
OSelectExecutionPlan result,
Set<String> filterClusters,
QueryPlanningInfo info,
OInputParameter inputParam,
OCommandContext ctx,
boolean profilingEnabled) {
Object paramValue = inputParam.getValue(ctx.getInputParameters());
if (paramValue == null) {
result.chain(new EmptyStep(ctx, profilingEnabled)); // nothing to return
} else if (paramValue instanceof OClass) {
OFromClause from = new OFromClause(-1);
OFromItem item = new OFromItem(-1);
from.setItem(item);
item.setIdentifier(new OIdentifier(((OClass) paramValue).getName()));
handleClassAsTarget(result, filterClusters, from, info, ctx, profilingEnabled);
} else if (paramValue instanceof String) {
// strings are treated as classes
OFromClause from = new OFromClause(-1);
OFromItem item = new OFromItem(-1);
from.setItem(item);
item.setIdentifier(new OIdentifier((String) paramValue));
handleClassAsTarget(result, filterClusters, from, info, ctx, profilingEnabled);
} else if (paramValue instanceof OIdentifiable) {
ORID orid = ((OIdentifiable) paramValue).getIdentity();
ORid rid = new ORid(-1);
OInteger cluster = new OInteger(-1);
cluster.setValue(orid.getClusterId());
OInteger position = new OInteger(-1);
position.setValue(orid.getClusterPosition());
rid.setLegacy(true);
rid.setCluster(cluster);
rid.setPosition(position);
if (filterClusters == null || isFromClusters(rid, filterClusters, ctx.getDatabase())) {
handleRidsAsTarget(result, Collections.singletonList(rid), ctx, profilingEnabled);
} else {
result.chain(new EmptyStep(ctx, profilingEnabled)); // nothing to return
}
} else if (paramValue instanceof Iterable) {
// try list of RIDs
List<ORid> rids = new ArrayList<>();
for (Object x : (Iterable) paramValue) {
if (!(x instanceof OIdentifiable)) {
throw new OCommandExecutionException("Cannot use colleciton as target: " + paramValue);
}
ORID orid = ((OIdentifiable) x).getIdentity();
ORid rid = new ORid(-1);
OInteger cluster = new OInteger(-1);
cluster.setValue(orid.getClusterId());
OInteger position = new OInteger(-1);
position.setValue(orid.getClusterPosition());
rid.setCluster(cluster);
rid.setPosition(position);
if (filterClusters == null || isFromClusters(rid, filterClusters, ctx.getDatabase())) {
rids.add(rid);
}
}
if (rids.size() > 0) {
handleRidsAsTarget(result, rids, ctx, profilingEnabled);
} else {
result.chain(new EmptyStep(ctx, profilingEnabled)); // nothing to return
}
} else {
throw new OCommandExecutionException("Invalid target: " + paramValue);
}
}
/**
* checks if this RID is from one of these clusters
*
* @param rid
* @param filterClusters
* @param database
* @return
*/
private boolean isFromClusters(ORid rid, Set<String> filterClusters, ODatabase database) {
if (filterClusters == null) {
throw new IllegalArgumentException();
}
String clusterName = database.getClusterNameById(rid.getCluster().getValue().intValue());
return filterClusters.contains(clusterName);
}
private void handleNoTarget(
OSelectExecutionPlan result, OCommandContext ctx, boolean profilingEnabled) {
result.chain(new EmptyDataGeneratorStep(1, ctx, profilingEnabled));
}
private void handleIndexAsTarget(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OIndexIdentifier indexIdentifier,
Set<String> filterClusters,
OCommandContext ctx,
boolean profilingEnabled) {
OIndexAbstract.manualIndexesWarning();
String indexName = indexIdentifier.getIndexName();
final ODatabaseDocumentInternal database = (ODatabaseDocumentInternal) ctx.getDatabase();
OIndex index = database.getMetadata().getIndexManagerInternal().getIndex(database, indexName);
if (index == null) {
throw new OCommandExecutionException("Index not found: " + indexName);
}
int[] filterClusterIds = null;
if (filterClusters != null) {
filterClusterIds =
filterClusters.stream().map(database::getClusterIdByName).mapToInt(i -> i).toArray();
}
switch (indexIdentifier.getType()) {
case INDEX:
OBooleanExpression keyCondition = null;
OBooleanExpression ridCondition = null;
if (info.flattenedWhereClause == null || info.flattenedWhereClause.size() == 0) {
if (!index.supportsOrderedIterations()) {
throw new OCommandExecutionException(
"Index " + indexName + " does not allow iteration without a condition");
}
} else if (info.flattenedWhereClause.size() > 1) {
throw new OCommandExecutionException(
"Index queries with this kind of condition are not supported yet: "
+ info.whereClause);
} else {
OAndBlock andBlock = info.flattenedWhereClause.get(0);
if (andBlock.getSubBlocks().size() == 1) {
info.whereClause =
null; // The WHERE clause won't be used anymore, the index does all the filtering
info.flattenedWhereClause = null;
keyCondition = getKeyCondition(andBlock);
if (keyCondition == null) {
throw new OCommandExecutionException(
"Index queries with this kind of condition are not supported yet: "
+ info.whereClause);
}
} else if (andBlock.getSubBlocks().size() == 2) {
info.whereClause =
null; // The WHERE clause won't be used anymore, the index does all the filtering
info.flattenedWhereClause = null;
keyCondition = getKeyCondition(andBlock);
ridCondition = getRidCondition(andBlock);
if (keyCondition == null || ridCondition == null) {
throw new OCommandExecutionException(
"Index queries with this kind of condition are not supported yet: "
+ info.whereClause);
}
} else {
throw new OCommandExecutionException(
"Index queries with this kind of condition are not supported yet: "
+ info.whereClause);
}
}
result.chain(new FetchFromIndexStep(index, keyCondition, null, ctx, profilingEnabled));
if (ridCondition != null) {
OWhereClause where = new OWhereClause(-1);
where.setBaseExpression(ridCondition);
result.chain(
new FilterStep(
where,
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
}
break;
case VALUES:
case VALUESASC:
if (!index.supportsOrderedIterations()) {
throw new OCommandExecutionException(
"Index " + indexName + " does not allow iteration on values");
}
result.chain(new FetchFromIndexValuesStep(index, true, ctx, profilingEnabled));
result.chain(new GetValueFromIndexEntryStep(ctx, filterClusterIds, profilingEnabled));
break;
case VALUESDESC:
if (!index.supportsOrderedIterations()) {
throw new OCommandExecutionException(
"Index " + indexName + " does not allow iteration on values");
}
result.chain(new FetchFromIndexValuesStep(index, false, ctx, profilingEnabled));
result.chain(new GetValueFromIndexEntryStep(ctx, filterClusterIds, profilingEnabled));
break;
}
}
private OBooleanExpression getKeyCondition(OAndBlock andBlock) {
for (OBooleanExpression exp : andBlock.getSubBlocks()) {
String str = exp.toString();
if (str.length() < 5) {
continue;
}
if (str.substring(0, 4).equalsIgnoreCase("key ")) {
return exp;
}
}
return null;
}
private OBooleanExpression getRidCondition(OAndBlock andBlock) {
for (OBooleanExpression exp : andBlock.getSubBlocks()) {
String str = exp.toString();
if (str.length() < 5) {
continue;
}
if (str.substring(0, 4).equalsIgnoreCase("rid ")) {
return exp;
}
}
return null;
}
private void handleMetadataAsTarget(
OSelectExecutionPlan plan,
OMetadataIdentifier metadata,
OCommandContext ctx,
boolean profilingEnabled) {
ODatabaseInternal db = (ODatabaseInternal) ctx.getDatabase();
String schemaRecordIdAsString = null;
if (metadata.getName().equalsIgnoreCase(OCommandExecutorSQLAbstract.METADATA_SCHEMA)) {
schemaRecordIdAsString = db.getStorage().getConfiguration().getSchemaRecordId();
ORecordId schemaRid = new ORecordId(schemaRecordIdAsString);
plan.chain(new FetchFromRidsStep(Collections.singleton(schemaRid), ctx, profilingEnabled));
} else if (metadata.getName().equalsIgnoreCase(OCommandExecutorSQLAbstract.METADATA_INDEXMGR)) {
schemaRecordIdAsString = db.getStorage().getConfiguration().getIndexMgrRecordId();
ORecordId schemaRid = new ORecordId(schemaRecordIdAsString);
plan.chain(new FetchFromRidsStep(Collections.singleton(schemaRid), ctx, profilingEnabled));
} else if (metadata.getName().equalsIgnoreCase(OCommandExecutorSQLAbstract.METADATA_STORAGE)) {
plan.chain(new FetchFromStorageMetadataStep(ctx, profilingEnabled));
} else if (metadata.getName().equalsIgnoreCase(OCommandExecutorSQLAbstract.METADATA_DATABASE)) {
plan.chain(new FetchFromDatabaseMetadataStep(ctx, profilingEnabled));
} else {
throw new UnsupportedOperationException("Invalid metadata: " + metadata.getName());
}
}
private void handleRidsAsTarget(
OSelectExecutionPlan plan, List<ORid> rids, OCommandContext ctx, boolean profilingEnabled) {
List<ORecordId> actualRids = new ArrayList<>();
for (ORid rid : rids) {
actualRids.add(rid.toRecordId((OResult) null, ctx));
}
plan.chain(new FetchFromRidsStep(actualRids, ctx, profilingEnabled));
}
private static void handleExpand(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (info.expand) {
result.chain(new ExpandStep(ctx, profilingEnabled));
}
}
private void handleGlobalLet(
OSelectExecutionPlan result,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (info.globalLetClause != null) {
List<OLetItem> items = info.globalLetClause.getItems();
items = sortLet(items, this.statement.getLetClause());
List<String> scriptVars = new ArrayList<>();
for (OLetItem item : items) {
if (item.getExpression() != null) {
result.chain(
new GlobalLetExpressionStep(
item.getVarName(), item.getExpression(), ctx, profilingEnabled));
} else {
result.chain(
new GlobalLetQueryStep(
item.getVarName(), item.getQuery(), ctx, profilingEnabled, scriptVars));
}
scriptVars.add(item.getVarName().getStringValue());
info.globalLetPresent = true;
}
}
}
private void handleLet(
OSelectExecutionPlan plan,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
// this could be invoked multiple times
// so it can be optimized
// checking whether the execution plan already contains some LET steps
// and in case skip
if (info.perRecordLetClause != null) {
List<OLetItem> items = info.perRecordLetClause.getItems();
items = sortLet(items, this.statement.getLetClause());
if (plan.steps.size() > 0 || info.distributedPlanCreated) {
for (OLetItem item : items) {
if (item.getExpression() != null) {
plan.chain(
new LetExpressionStep(
item.getVarName(), item.getExpression(), ctx, profilingEnabled));
} else {
plan.chain(new LetQueryStep(item.getVarName(), item.getQuery(), ctx, profilingEnabled));
}
}
} else {
for (OSelectExecutionPlan shardedPlan : info.distributedFetchExecutionPlans.values()) {
for (OLetItem item : items) {
if (item.getExpression() != null) {
shardedPlan.chain(
new LetExpressionStep(
item.getVarName().copy(),
item.getExpression().copy(),
ctx,
profilingEnabled));
} else {
shardedPlan.chain(
new LetQueryStep(
item.getVarName().copy(), item.getQuery().copy(), ctx, profilingEnabled));
}
}
}
}
}
}
private List<OLetItem> sortLet(List<OLetItem> items, OLetClause letClause) {
if (letClause == null) {
return items;
}
List<OLetItem> i = new ArrayList<>();
i.addAll(items);
ArrayList<OLetItem> result = new ArrayList<>();
for (OLetItem item : letClause.getItems()) {
String var = item.getVarName().getStringValue();
Iterator<OLetItem> iterator = i.iterator();
while (iterator.hasNext()) {
OLetItem x = iterator.next();
if (x.getVarName().getStringValue().equals(var)) {
iterator.remove();
result.add(x);
break;
}
}
}
for (OLetItem item : i) {
result.add(item);
}
return result;
}
private void handleWhere(
OSelectExecutionPlan plan,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (info.whereClause != null) {
if (info.distributedPlanCreated) {
plan.chain(
new FilterStep(
info.whereClause,
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
} else {
for (OSelectExecutionPlan shardedPlan : info.distributedFetchExecutionPlans.values()) {
shardedPlan.chain(
new FilterStep(
info.whereClause.copy(),
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
}
}
}
}
public static void handleOrderBy(
OSelectExecutionPlan plan,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
int skipSize = info.skip == null ? 0 : info.skip.getValue(ctx);
if (skipSize < 0) {
throw new OCommandExecutionException("Cannot execute a query with a negative SKIP");
}
int limitSize = info.limit == null ? -1 : info.limit.getValue(ctx);
Integer maxResults = null;
if (limitSize >= 0) {
maxResults = skipSize + limitSize;
}
if (info.expand || info.unwind != null) {
maxResults = null;
}
if (!info.orderApplied
&& info.orderBy != null
&& info.orderBy.getItems() != null
&& info.orderBy.getItems().size() > 0) {
plan.chain(
new OrderByStep(
info.orderBy,
maxResults,
ctx,
info.timeout != null ? info.timeout.getVal().longValue() : -1,
profilingEnabled));
if (info.projectionAfterOrderBy != null) {
plan.chain(
new ProjectionCalculationStep(info.projectionAfterOrderBy, ctx, profilingEnabled));
}
}
}
/**
* @param plan the execution plan where to add the fetch step
* @param filterClusters clusters of interest (all the others have to be excluded from the result)
* @param info
* @param ctx
* @param profilingEnabled
*/
private void handleClassAsTarget(
OSelectExecutionPlan plan,
Set<String> filterClusters,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
handleClassAsTarget(plan, filterClusters, info.target, info, ctx, profilingEnabled);
}
private void handleClassAsTarget(
OSelectExecutionPlan plan,
Set<String> filterClusters,
OFromClause from,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
OIdentifier identifier = from.getItem().getIdentifier();
if (handleClassAsTargetWithIndexedFunction(
plan, filterClusters, identifier, info, ctx, profilingEnabled)) {
plan.chain(new FilterByClassStep(identifier, ctx, profilingEnabled));
return;
}
if (handleClassAsTargetWithIndex(
plan, identifier, filterClusters, info, ctx, profilingEnabled)) {
plan.chain(new FilterByClassStep(identifier, ctx, profilingEnabled));
return;
}
if (info.orderBy != null
&& handleClassWithIndexForSortOnly(
plan, identifier, filterClusters, info, ctx, profilingEnabled)) {
plan.chain(new FilterByClassStep(identifier, ctx, profilingEnabled));
return;
}
Boolean orderByRidAsc = null; // null: no order. true: asc, false:desc
if (isOrderByRidAsc(info)) {
orderByRidAsc = true;
} else if (isOrderByRidDesc(info)) {
orderByRidAsc = false;
}
String className = identifier.getStringValue();
OSchema schema = getSchemaFromContext(ctx);
AbstractExecutionStep fetcher;
if (schema.getClass(className) != null) {
fetcher =
new FetchFromClassExecutionStep(
className, filterClusters, info, ctx, orderByRidAsc, profilingEnabled);
} else if (schema.getView(className) != null) {
fetcher =
new FetchFromViewExecutionStep(
className, filterClusters, info, ctx, orderByRidAsc, profilingEnabled);
} else {
throw new OCommandExecutionException("Class or View not present in the schema: " + className);
}
if (orderByRidAsc != null && info.serverToClusters.size() == 1) {
info.orderApplied = true;
}
plan.chain(fetcher);
}
private boolean handleClassAsTargetWithIndexedFunction(
OSelectExecutionPlan plan,
Set<String> filterClusters,
OIdentifier queryTarget,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (queryTarget == null) {
return false;
}
OSchema schema = getSchemaFromContext(ctx);
OClass clazz = schema.getClass(queryTarget.getStringValue());
if (clazz == null) {
clazz = schema.getView(queryTarget.getStringValue());
if (clazz == null) {
throw new OCommandExecutionException("Class not found: " + queryTarget);
}
}
if (info.flattenedWhereClause == null || info.flattenedWhereClause.size() == 0) {
return false;
}
List<OInternalExecutionPlan> resultSubPlans = new ArrayList<>();
boolean indexedFunctionsFound = false;
for (OAndBlock block : info.flattenedWhereClause) {
List<OBinaryCondition> indexedFunctionConditions =
block.getIndexedFunctionConditions(clazz, (ODatabaseDocumentInternal) ctx.getDatabase());
indexedFunctionConditions =
filterIndexedFunctionsWithoutIndex(indexedFunctionConditions, info.target, ctx);
if (indexedFunctionConditions == null || indexedFunctionConditions.size() == 0) {
IndexSearchDescriptor bestIndex = findBestIndexFor(ctx, clazz.getIndexes(), block, clazz);
if (bestIndex != null) {
FetchFromIndexStep step =
new FetchFromIndexStep(
bestIndex.idx,
bestIndex.keyCondition,
bestIndex.additionalRangeCondition,
true,
ctx,
profilingEnabled);
OSelectExecutionPlan subPlan = new OSelectExecutionPlan(ctx);
subPlan.chain(step);
int[] filterClusterIds = null;
if (filterClusters != null) {
filterClusterIds =
filterClusters.stream()
.map(name -> ctx.getDatabase().getClusterIdByName(name))
.mapToInt(i -> i)
.toArray();
}
subPlan.chain(new GetValueFromIndexEntryStep(ctx, filterClusterIds, profilingEnabled));
if (requiresMultipleIndexLookups(bestIndex.keyCondition)) {
subPlan.chain(new DistinctExecutionStep(ctx, profilingEnabled));
}
if (!block.getSubBlocks().isEmpty()) {
if ((info.perRecordLetClause != null && refersToLet(block.getSubBlocks()))) {
handleLet(subPlan, info, ctx, profilingEnabled);
}
subPlan.chain(
new FilterStep(
createWhereFrom(block),
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
}
resultSubPlans.add(subPlan);
} else {
FetchFromClassExecutionStep step;
if (clazz instanceof OView) {
step =
new FetchFromViewExecutionStep(
clazz.getName(), filterClusters, info, ctx, true, profilingEnabled);
} else {
step =
new FetchFromClassExecutionStep(
clazz.getName(), filterClusters, ctx, true, profilingEnabled);
}
OSelectExecutionPlan subPlan = new OSelectExecutionPlan(ctx);
subPlan.chain(step);
if (!block.getSubBlocks().isEmpty()) {
if ((info.perRecordLetClause != null && refersToLet(block.getSubBlocks()))) {
handleLet(subPlan, info, ctx, profilingEnabled);
}
subPlan.chain(
new FilterStep(
createWhereFrom(block),
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
}
resultSubPlans.add(subPlan);
}
} else {
OBinaryCondition blockCandidateFunction = null;
for (OBinaryCondition cond : indexedFunctionConditions) {
if (!cond.allowsIndexedFunctionExecutionOnTarget(info.target, ctx)) {
if (!cond.canExecuteIndexedFunctionWithoutIndex(info.target, ctx)) {
throw new OCommandExecutionException(
"Cannot execute " + block + " on " + queryTarget);
}
}
if (blockCandidateFunction == null) {
blockCandidateFunction = cond;
} else {
boolean thisAllowsNoIndex =
cond.canExecuteIndexedFunctionWithoutIndex(info.target, ctx);
boolean prevAllowsNoIndex =
blockCandidateFunction.canExecuteIndexedFunctionWithoutIndex(info.target, ctx);
if (!thisAllowsNoIndex && !prevAllowsNoIndex) {
// none of the functions allow execution without index, so cannot choose one
throw new OCommandExecutionException(
"Cannot choose indexed function between "
+ cond
+ " and "
+ blockCandidateFunction
+ ". Both require indexed execution");
} else if (thisAllowsNoIndex && prevAllowsNoIndex) {
// both can be calculated without index, choose the best one for index execution
long thisEstimate = cond.estimateIndexed(info.target, ctx);
long lastEstimate = blockCandidateFunction.estimateIndexed(info.target, ctx);
if (thisEstimate > -1 && thisEstimate < lastEstimate) {
blockCandidateFunction = cond;
}
} else if (prevAllowsNoIndex) {
// choose current condition, because the other one can be calculated without index
blockCandidateFunction = cond;
}
}
}
FetchFromIndexedFunctionStep step =
new FetchFromIndexedFunctionStep(
blockCandidateFunction, info.target, ctx, profilingEnabled);
if (!blockCandidateFunction.executeIndexedFunctionAfterIndexSearch(info.target, ctx)) {
block = block.copy();
block.getSubBlocks().remove(blockCandidateFunction);
}
if (info.flattenedWhereClause.size() == 1) {
plan.chain(step);
plan.chain(new FilterByClustersStep(filterClusters, ctx, profilingEnabled));
if (!block.getSubBlocks().isEmpty()) {
if ((info.perRecordLetClause != null && refersToLet(block.getSubBlocks()))) {
handleLet(plan, info, ctx, profilingEnabled);
}
plan.chain(
new FilterStep(
createWhereFrom(block),
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
}
} else {
OSelectExecutionPlan subPlan = new OSelectExecutionPlan(ctx);
subPlan.chain(step);
if (!block.getSubBlocks().isEmpty()) {
subPlan.chain(
new FilterStep(
createWhereFrom(block),
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
}
resultSubPlans.add(subPlan);
}
indexedFunctionsFound = true;
}
}
if (indexedFunctionsFound) {
if (resultSubPlans.size()
> 1) { // if resultSubPlans.size() == 1 the step was already chained (see above)
plan.chain(new ParallelExecStep(resultSubPlans, ctx, profilingEnabled));
plan.chain(new FilterByClustersStep(filterClusters, ctx, profilingEnabled));
plan.chain(new DistinctExecutionStep(ctx, profilingEnabled));
}
// WHERE condition already applied
info.whereClause = null;
info.flattenedWhereClause = null;
return true;
} else {
return false;
}
}
private boolean refersToLet(List<OBooleanExpression> subBlocks) {
if (subBlocks == null) {
return false;
}
for (OBooleanExpression exp : subBlocks) {
if (exp.toString().startsWith("$")) {
return true;
}
}
return false;
}
private List<OBinaryCondition> filterIndexedFunctionsWithoutIndex(
List<OBinaryCondition> indexedFunctionConditions,
OFromClause fromClause,
OCommandContext ctx) {
if (indexedFunctionConditions == null) {
return null;
}
List<OBinaryCondition> result = new ArrayList<>();
for (OBinaryCondition cond : indexedFunctionConditions) {
if (cond.allowsIndexedFunctionExecutionOnTarget(fromClause, ctx)) {
result.add(cond);
} else if (!cond.canExecuteIndexedFunctionWithoutIndex(fromClause, ctx)) {
throw new OCommandExecutionException("Cannot evaluate " + cond + ": no index defined");
}
}
return result;
}
/**
* tries to use an index for sorting only. Also adds the fetch step to the execution plan
*
* @param plan current execution plan
* @param info the query planning information
* @param ctx the current context
* @return true if it succeeded to use an index to sort, false otherwise.
*/
private boolean handleClassWithIndexForSortOnly(
OSelectExecutionPlan plan,
OIdentifier queryTarget,
Set<String> filterClusters,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
OSchema schema = getSchemaFromContext(ctx);
OClass clazz = schema.getClass(queryTarget.getStringValue());
if (clazz == null) {
clazz = schema.getView(queryTarget.getStringValue());
if (clazz == null) {
throw new OCommandExecutionException("Class not found: " + queryTarget);
}
}
for (OIndex idx :
clazz.getIndexes().stream()
.filter(i -> i.supportsOrderedIterations())
.filter(i -> i.getDefinition() != null)
.collect(Collectors.toList())) {
List<String> indexFields = idx.getDefinition().getFields();
if (indexFields.size() < info.orderBy.getItems().size()) {
continue;
}
boolean indexFound = true;
String orderType = null;
for (int i = 0; i < info.orderBy.getItems().size(); i++) {
OOrderByItem orderItem = info.orderBy.getItems().get(i);
if (orderItem.getCollate() != null) {
return false;
}
String indexField = indexFields.get(i);
if (i == 0) {
orderType = orderItem.getType();
} else {
if (orderType == null || !orderType.equals(orderItem.getType())) {
indexFound = false;
break; // ASC/DESC interleaved, cannot be used with index.
}
}
if (!(indexField.equals(orderItem.getAlias())
|| isInOriginalProjection(indexField, orderItem.getAlias()))) {
indexFound = false;
break;
}
}
if (indexFound && orderType != null) {
plan.chain(
new FetchFromIndexValuesStep(
idx, orderType.equals(OOrderByItem.ASC), ctx, profilingEnabled));
int[] filterClusterIds = null;
if (filterClusters != null) {
filterClusterIds =
filterClusters.stream()
.map(name -> ctx.getDatabase().getClusterIdByName(name))
.mapToInt(i -> i)
.toArray();
}
plan.chain(new GetValueFromIndexEntryStep(ctx, filterClusterIds, profilingEnabled));
if (info.serverToClusters.size() == 1) {
info.orderApplied = true;
}
return true;
}
}
return false;
}
private boolean isInOriginalProjection(String indexField, String alias) {
if (info.projection == null) {
return false;
}
if (info.projection.getItems() == null) {
return false;
}
return info.projection.getItems().stream()
.filter(proj -> proj.getExpression().toString().equals(indexField))
.filter(proj -> proj.getAlias() != null)
.anyMatch(proj -> proj.getAlias().getStringValue().equals(alias));
}
private boolean handleClassAsTargetWithIndex(
OSelectExecutionPlan plan,
OIdentifier targetClass,
Set<String> filterClusters,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
List<OExecutionStepInternal> result =
handleClassAsTargetWithIndex(
targetClass.getStringValue(), filterClusters, info, ctx, profilingEnabled);
if (result != null) {
result.stream().forEach(x -> plan.chain(x));
info.whereClause = null;
info.flattenedWhereClause = null;
return true;
}
OSchema schema = getSchemaFromContext(ctx);
OClass clazz = schema.getClass(targetClass.getStringValue());
if (clazz == null) {
clazz = schema.getView(targetClass.getStringValue());
if (clazz == null) {
throw new OCommandExecutionException("Class not found: " + targetClass);
}
}
if (clazz.count(false) != 0 || clazz.getSubclasses().size() == 0 || isDiamondHierarchy(clazz)) {
return false;
}
// try subclasses
Collection<OClass> subclasses = clazz.getSubclasses();
List<OInternalExecutionPlan> subclassPlans = new ArrayList<>();
for (OClass subClass : subclasses) {
List<OExecutionStepInternal> subSteps =
handleClassAsTargetWithIndexRecursive(
subClass.getName(), filterClusters, info, ctx, profilingEnabled);
if (subSteps == null || subSteps.size() == 0) {
return false;
}
OSelectExecutionPlan subPlan = new OSelectExecutionPlan(ctx);
subSteps.stream().forEach(x -> subPlan.chain(x));
subclassPlans.add(subPlan);
}
if (subclassPlans.size() > 0) {
plan.chain(new ParallelExecStep(subclassPlans, ctx, profilingEnabled));
return true;
}
return false;
}
/**
* checks if a class is the top of a diamond hierarchy
*
* @param clazz
* @return
*/
private boolean isDiamondHierarchy(OClass clazz) {
Set<OClass> traversed = new HashSet<>();
List<OClass> stack = new ArrayList<>();
stack.add(clazz);
while (!stack.isEmpty()) {
OClass current = stack.remove(0);
traversed.add(current);
for (OClass sub : current.getSubclasses()) {
if (traversed.contains(sub)) {
return true;
}
stack.add(sub);
traversed.add(sub);
}
}
return false;
}
private List<OExecutionStepInternal> handleClassAsTargetWithIndexRecursive(
String targetClass,
Set<String> filterClusters,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
List<OExecutionStepInternal> result =
handleClassAsTargetWithIndex(targetClass, filterClusters, info, ctx, profilingEnabled);
if (result == null) {
result = new ArrayList<>();
OClass clazz = getSchemaFromContext(ctx).getClass(targetClass);
if (clazz == null) {
clazz = getSchemaFromContext(ctx).getView(targetClass);
}
if (clazz == null) {
throw new OCommandExecutionException("Cannot find class " + targetClass);
}
if (clazz.count(false) != 0
|| clazz.getSubclasses().size() == 0
|| isDiamondHierarchy(clazz)) {
return null;
}
Collection<OClass> subclasses = clazz.getSubclasses();
List<OInternalExecutionPlan> subclassPlans = new ArrayList<>();
for (OClass subClass : subclasses) {
List<OExecutionStepInternal> subSteps =
handleClassAsTargetWithIndexRecursive(
subClass.getName(), filterClusters, info, ctx, profilingEnabled);
if (subSteps == null || subSteps.size() == 0) {
return null;
}
OSelectExecutionPlan subPlan = new OSelectExecutionPlan(ctx);
subSteps.stream().forEach(x -> subPlan.chain(x));
subclassPlans.add(subPlan);
}
if (subclassPlans.size() > 0) {
result.add(new ParallelExecStep(subclassPlans, ctx, profilingEnabled));
}
}
return result.size() == 0 ? null : result;
}
private List<OExecutionStepInternal> handleClassAsTargetWithIndex(
String targetClass,
Set<String> filterClusters,
QueryPlanningInfo info,
OCommandContext ctx,
boolean profilingEnabled) {
if (info.flattenedWhereClause == null || info.flattenedWhereClause.size() == 0) {
return null;
}
OClass clazz = getSchemaFromContext(ctx).getClass(targetClass);
if (clazz == null) {
clazz = getSchemaFromContext(ctx).getView(targetClass);
}
if (clazz == null) {
throw new OCommandExecutionException("Cannot find class " + targetClass);
}
Set<OIndex> indexes = clazz.getIndexes();
final OClass c = clazz;
List<IndexSearchDescriptor> indexSearchDescriptors =
info.flattenedWhereClause.stream()
.map(x -> findBestIndexFor(ctx, indexes, x, c))
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (indexSearchDescriptors.size() != info.flattenedWhereClause.size()) {
return null; // some blocks could not be managed with an index
}
List<OExecutionStepInternal> result = null;
List<IndexSearchDescriptor> optimumIndexSearchDescriptors =
commonFactor(indexSearchDescriptors);
if (indexSearchDescriptors.size() == 1) {
IndexSearchDescriptor desc = indexSearchDescriptors.get(0);
result = new ArrayList<>();
Boolean orderAsc = getOrderDirection(info);
result.add(
new FetchFromIndexStep(
desc.idx,
desc.keyCondition,
desc.additionalRangeCondition,
!Boolean.FALSE.equals(orderAsc),
ctx,
profilingEnabled));
int[] filterClusterIds = null;
if (filterClusters != null) {
filterClusterIds =
filterClusters.stream()
.map(name -> ctx.getDatabase().getClusterIdByName(name))
.mapToInt(i -> i)
.toArray();
}
result.add(new GetValueFromIndexEntryStep(ctx, filterClusterIds, profilingEnabled));
if (requiresMultipleIndexLookups(desc.keyCondition)) {
result.add(new DistinctExecutionStep(ctx, profilingEnabled));
}
if (orderAsc != null
&& info.orderBy != null
&& fullySorted(info.orderBy, desc.keyCondition, desc.idx)
&& info.serverToClusters.size() == 1) {
info.orderApplied = true;
}
if (desc.remainingCondition != null && !desc.remainingCondition.isEmpty()) {
if ((info.perRecordLetClause != null
&& refersToLet(Collections.singletonList(desc.remainingCondition)))) {
OSelectExecutionPlan stubPlan = new OSelectExecutionPlan(ctx);
boolean prevCreatedDist = info.distributedPlanCreated;
info.distributedPlanCreated = true; // little hack, check this!!!
handleLet(stubPlan, info, ctx, profilingEnabled);
for (OExecutionStep step : stubPlan.getSteps()) {
result.add((OExecutionStepInternal) step);
}
info.distributedPlanCreated = prevCreatedDist;
}
result.add(
new FilterStep(
createWhereFrom(desc.remainingCondition),
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
}
} else {
result = new ArrayList<>();
result.add(
createParallelIndexFetch(
optimumIndexSearchDescriptors, filterClusters, ctx, profilingEnabled));
if (optimumIndexSearchDescriptors.size() > 1) {
result.add(new DistinctExecutionStep(ctx, profilingEnabled));
}
}
return result;
}
private static OSchema getSchemaFromContext(OCommandContext ctx) {
return ((OMetadataInternal) ctx.getDatabase().getMetadata()).getImmutableSchemaSnapshot();
}
private boolean fullySorted(OOrderBy orderBy, OAndBlock conditions, OIndex idx) {
if (orderBy.getItems().stream().anyMatch(x -> x.getCollate() != null)) {
return false;
}
if (!idx.supportsOrderedIterations()) return false;
List<String> orderItems = new ArrayList<>();
String order = null;
for (OOrderByItem item : orderBy.getItems()) {
if (order == null) {
order = item.getType();
} else if (!order.equals(item.getType())) {
return false;
}
orderItems.add(item.getAlias() != null ? item.getAlias() : item.getRecordAttr());
}
List<String> conditionItems = new ArrayList<>();
for (int i = 0; i < conditions.getSubBlocks().size(); i++) {
OBooleanExpression item = conditions.getSubBlocks().get(i);
if (item instanceof OBinaryCondition) {
if (((OBinaryCondition) item).getOperator() instanceof OEqualsCompareOperator) {
conditionItems.add(((OBinaryCondition) item).getLeft().toString());
} else if (i != conditions.getSubBlocks().size() - 1) {
return false;
}
} else if (i != conditions.getSubBlocks().size() - 1) {
return false;
}
}
List<String> orderedFields = new ArrayList<>();
boolean overlapping = false;
for (String s : conditionItems) {
if (orderItems.isEmpty()) {
return true; // nothing to sort, the conditions completely overlap the ORDER BY
}
if (s.equals(orderItems.get(0))) {
orderItems.remove(0);
overlapping = true; // start overlapping
} else if (overlapping) {
return false; // overlapping, but next order item does not match...
}
orderedFields.add(s);
}
orderedFields.addAll(orderItems);
final OIndexDefinition definition = idx.getDefinition();
final List<String> fields = definition.getFields();
if (fields.size() < orderedFields.size()) {
return false;
}
for (int i = 0; i < orderedFields.size(); i++) {
final String orderFieldName = orderedFields.get(i);
final String indexFieldName = fields.get(i);
if (!orderFieldName.equals(indexFieldName)) {
return false;
}
}
return true;
}
/**
* returns TRUE if all the order clauses are ASC, FALSE if all are DESC, null otherwise
*
* @return TRUE if all the order clauses are ASC, FALSE if all are DESC, null otherwise
*/
private Boolean getOrderDirection(QueryPlanningInfo info) {
if (info.orderBy == null) {
return null;
}
String result = null;
for (OOrderByItem item : info.orderBy.getItems()) {
if (result == null) {
result = item.getType() == null ? OOrderByItem.ASC : item.getType();
} else {
String newType = item.getType() == null ? OOrderByItem.ASC : item.getType();
if (!newType.equals(result)) {
return null;
}
}
}
return result == null || result.equals(OOrderByItem.ASC);
}
private OExecutionStepInternal createParallelIndexFetch(
List<IndexSearchDescriptor> indexSearchDescriptors,
Set<String> filterClusters,
OCommandContext ctx,
boolean profilingEnabled) {
List<OInternalExecutionPlan> subPlans = new ArrayList<>();
for (IndexSearchDescriptor desc : indexSearchDescriptors) {
OSelectExecutionPlan subPlan = new OSelectExecutionPlan(ctx);
subPlan.chain(
new FetchFromIndexStep(
desc.idx, desc.keyCondition, desc.additionalRangeCondition, ctx, profilingEnabled));
int[] filterClusterIds = null;
if (filterClusters != null) {
filterClusterIds =
filterClusters.stream()
.map(name -> ctx.getDatabase().getClusterIdByName(name))
.mapToInt(i -> i)
.toArray();
}
subPlan.chain(new GetValueFromIndexEntryStep(ctx, filterClusterIds, profilingEnabled));
if (requiresMultipleIndexLookups(desc.keyCondition)) {
subPlan.chain(new DistinctExecutionStep(ctx, profilingEnabled));
}
if (desc.remainingCondition != null && !desc.remainingCondition.isEmpty()) {
subPlan.chain(
new FilterStep(
createWhereFrom(desc.remainingCondition),
ctx,
this.info.timeout != null ? this.info.timeout.getVal().longValue() : -1,
profilingEnabled));
}
subPlans.add(subPlan);
}
return new ParallelExecStep(subPlans, ctx, profilingEnabled);
}
/**
* checks whether the condition has CONTAINSANY or similar expressions, that require multiple
* index evaluations
*
* @param keyCondition
* @return
*/
private boolean requiresMultipleIndexLookups(OAndBlock keyCondition) {
for (OBooleanExpression oBooleanExpression : keyCondition.getSubBlocks()) {
if (!(oBooleanExpression instanceof OBinaryCondition)) {
return true;
}
}
return false;
}
private OWhereClause createWhereFrom(OBooleanExpression remainingCondition) {
OWhereClause result = new OWhereClause(-1);
result.setBaseExpression(remainingCondition);
return result;
}
/**
* given a flat AND block and a set of indexes, returns the best index to be used to process it,
* with the complete description on how to use it
*
* @param ctx
* @param indexes
* @param block
* @return
*/
private IndexSearchDescriptor findBestIndexFor(
OCommandContext ctx, Set<OIndex> indexes, OAndBlock block, OClass clazz) {
// get all valid index descriptors
List<IndexSearchDescriptor> descriptors =
indexes.stream()
.filter(x -> x.getInternal().canBeUsedInEqualityOperators())
.map(index -> buildIndexSearchDescriptor(ctx, index, block, clazz))
.filter(Objects::nonNull)
.filter(x -> x.keyCondition != null)
.filter(x -> x.keyCondition.getSubBlocks().size() > 0)
.collect(Collectors.toList());
List<IndexSearchDescriptor> fullTextIndexDescriptors =
indexes.stream()
.filter(idx -> idx.getType().equalsIgnoreCase("FULLTEXT"))
.filter(idx -> !idx.getAlgorithm().equalsIgnoreCase("LUCENE"))
.map(idx -> buildIndexSearchDescriptorForFulltext(ctx, idx, block, clazz))
.filter(Objects::nonNull)
.filter(x -> x.keyCondition != null)
.filter(x -> x.keyCondition.getSubBlocks().size() > 0)
.collect(Collectors.toList());
descriptors.addAll(fullTextIndexDescriptors);
// remove the redundant descriptors (eg. if I have one on [a] and one on [a, b], the first one
// is redundant, just discard it)
descriptors = removePrefixIndexes(descriptors);
// sort by cost
List<OPair<Integer, IndexSearchDescriptor>> sortedDescriptors =
descriptors.stream()
.map(x -> (OPair<Integer, IndexSearchDescriptor>) new OPair(x.cost(ctx), x))
.sorted()
.collect(Collectors.toList());
// get only the descriptors with the lowest cost
if (sortedDescriptors.isEmpty()) {
descriptors = Collections.emptyList();
} else {
descriptors =
sortedDescriptors.stream()
.filter(x -> x.key.equals(sortedDescriptors.get(0).key))
.map(x -> x.value)
.collect(Collectors.toList());
}
// sort remaining by the number of indexed fields
descriptors =
descriptors.stream()
.sorted(Comparator.comparingInt(x -> x.keyCondition.getSubBlocks().size()))
.collect(Collectors.toList());
// get the one that has more indexed fields
return descriptors.isEmpty() ? null : descriptors.get(descriptors.size() - 1);
}
private List<IndexSearchDescriptor> removePrefixIndexes(List<IndexSearchDescriptor> descriptors) {
List<IndexSearchDescriptor> result = new ArrayList<>();
for (IndexSearchDescriptor desc : descriptors) {
if (result.isEmpty()) {
result.add(desc);
} else {
List<IndexSearchDescriptor> prefixes = findPrefixes(desc, result);
if (prefixes.isEmpty()) {
if (!isPrefixOfAny(desc, result)) {
result.add(desc);
}
} else {
result.removeAll(prefixes);
result.add(desc);
}
}
}
return result;
}
private boolean isPrefixOfAny(IndexSearchDescriptor desc, List<IndexSearchDescriptor> result) {
for (IndexSearchDescriptor item : result) {
if (isPrefixOf(desc, item)) {
return true;
}
}
return false;
}
/**
* finds prefix conditions for a given condition, eg. if the condition is on [a,b] and in the list
* there is another condition on [a] or on [a,b], then that condition is returned.
*
* @param desc
* @param descriptors
* @return
*/
private List<IndexSearchDescriptor> findPrefixes(
IndexSearchDescriptor desc, List<IndexSearchDescriptor> descriptors) {
List<IndexSearchDescriptor> result = new ArrayList<>();
for (IndexSearchDescriptor item : descriptors) {
if (isPrefixOf(item, desc)) {
result.add(item);
}
}
return result;
}
/**
* returns true if the first argument is a prefix for the second argument, eg. if the first
* argument is [a] and the second argument is [a, b]
*
* @param item
* @param desc
* @return
*/
private boolean isPrefixOf(IndexSearchDescriptor item, IndexSearchDescriptor desc) {
List<OBooleanExpression> left = item.keyCondition.getSubBlocks();
List<OBooleanExpression> right = desc.keyCondition.getSubBlocks();
if (left.size() > right.size()) {
return false;
}
for (int i = 0; i < left.size(); i++) {
if (!left.get(i).equals(right.get(i))) {
return false;
}
}
return true;
}
/**
* given an index and a flat AND block, returns a descriptor on how to process it with an index
* (index, index key and additional filters to apply after index fetch
*
* @param ctx
* @param index
* @param block
* @param clazz
* @return
*/
private IndexSearchDescriptor buildIndexSearchDescriptor(
OCommandContext ctx, OIndex index, OAndBlock block, OClass clazz) {
List<String> indexFields = index.getDefinition().getFields();
OBinaryCondition keyCondition = new OBinaryCondition(-1);
OIdentifier key = new OIdentifier("key");
keyCondition.setLeft(new OExpression(key));
boolean allowsRange = allowsRangeQueries(index);
boolean found = false;
OAndBlock blockCopy = block.copy();
Iterator<OBooleanExpression> blockIterator;
OAndBlock indexKeyValue = new OAndBlock(-1);
IndexSearchDescriptor result = new IndexSearchDescriptor();
result.idx = index;
result.keyCondition = indexKeyValue;
for (String indexField : indexFields) {
blockIterator = blockCopy.getSubBlocks().iterator();
boolean breakHere = false;
boolean indexFieldFound = false;
while (blockIterator.hasNext()) {
OBooleanExpression singleExp = blockIterator.next();
if (singleExp instanceof OBinaryCondition) {
OExpression left = ((OBinaryCondition) singleExp).getLeft();
if (left.isBaseIdentifier()) {
String fieldName = left.getDefaultAlias().getStringValue();
if (indexField.equals(fieldName)) {
OBinaryCompareOperator operator = ((OBinaryCondition) singleExp).getOperator();
if (!((OBinaryCondition) singleExp).getRight().isEarlyCalculated(ctx)) {
continue; // this cannot be used because the value depends on single record
}
if (operator instanceof OEqualsCompareOperator) {
found = true;
indexFieldFound = true;
OBinaryCondition condition = new OBinaryCondition(-1);
condition.setLeft(left);
condition.setOperator(operator);
condition.setRight(((OBinaryCondition) singleExp).getRight().copy());
indexKeyValue.getSubBlocks().add(condition);
blockIterator.remove();
break;
} else if (operator instanceof OContainsKeyOperator
&& isMap(clazz, indexField)
&& isIndexByKey(index, indexField)) {
found = true;
indexFieldFound = true;
OBinaryCondition condition = new OBinaryCondition(-1);
condition.setLeft(left);
condition.setOperator(operator);
condition.setRight(((OBinaryCondition) singleExp).getRight().copy());
indexKeyValue.getSubBlocks().add(condition);
blockIterator.remove();
break;
} else if (allowsRange && operator.isRangeOperator()) {
found = true;
indexFieldFound = true;
breakHere =
true; // this is last element, no other fields can be added to the key because
// this is a range condition
OBinaryCondition condition = new OBinaryCondition(-1);
condition.setLeft(left);
condition.setOperator(operator);
condition.setRight(((OBinaryCondition) singleExp).getRight().copy());
indexKeyValue.getSubBlocks().add(condition);
blockIterator.remove();
// look for the opposite condition, on the same field, for range queries (the other
// side of the range)
while (blockIterator.hasNext()) {
OBooleanExpression next = blockIterator.next();
if (createsRangeWith((OBinaryCondition) singleExp, next)) {
result.additionalRangeCondition = (OBinaryCondition) next;
blockIterator.remove();
break;
}
}
break;
}
}
}
} else if (singleExp instanceof OContainsValueCondition
&& ((OContainsValueCondition) singleExp).getExpression() != null
&& isMap(clazz, indexField)
&& isIndexByValue(index, indexField)) {
OExpression left = ((OContainsValueCondition) singleExp).getLeft();
if (left.isBaseIdentifier()) {
String fieldName = left.getDefaultAlias().getStringValue();
if (indexField.equals(fieldName)) {
found = true;
indexFieldFound = true;
OBinaryCondition condition = new OBinaryCondition(-1);
condition.setLeft(left);
condition.setOperator(new OContainsValueOperator(-1));
condition.setRight(((OContainsValueCondition) singleExp).getExpression().copy());
indexKeyValue.getSubBlocks().add(condition);
blockIterator.remove();
break;
}
}
} else if (singleExp instanceof OContainsAnyCondition) {
OExpression left = ((OContainsAnyCondition) singleExp).getLeft();
if (left.isBaseIdentifier()) {
String fieldName = left.getDefaultAlias().getStringValue();
if (indexField.equals(fieldName)) {
if (!((OContainsAnyCondition) singleExp).getRight().isEarlyCalculated(ctx)) {
continue; // this cannot be used because the value depends on single record
}
found = true;
indexFieldFound = true;
OContainsAnyCondition condition = new OContainsAnyCondition(-1);
condition.setLeft(left);
condition.setRight(((OContainsAnyCondition) singleExp).getRight().copy());
indexKeyValue.getSubBlocks().add(condition);
blockIterator.remove();
break;
}
}
} else if (singleExp instanceof OInCondition) {
OExpression left = ((OInCondition) singleExp).getLeft();
if (left.isBaseIdentifier()) {
String fieldName = left.getDefaultAlias().getStringValue();
if (indexField.equals(fieldName)) {
if (((OInCondition) singleExp).getRightMathExpression() != null) {
if (!((OInCondition) singleExp).getRightMathExpression().isEarlyCalculated(ctx)) {
continue; // this cannot be used because the value depends on single record
}
found = true;
indexFieldFound = true;
OInCondition condition = new OInCondition(-1);
condition.setLeft(left);
condition.setRightMathExpression(
((OInCondition) singleExp).getRightMathExpression().copy());
indexKeyValue.getSubBlocks().add(condition);
blockIterator.remove();
break;
} else if (((OInCondition) singleExp).getRightParam() != null) {
found = true;
indexFieldFound = true;
OInCondition condition = new OInCondition(-1);
condition.setLeft(left);
condition.setRightParam(((OInCondition) singleExp).getRightParam().copy());
indexKeyValue.getSubBlocks().add(condition);
blockIterator.remove();
break;
}
}
}
}
}
if (breakHere || !indexFieldFound) {
break;
}
}
if (result.keyCondition.getSubBlocks().size() < index.getDefinition().getFields().size()
&& !index.supportsOrderedIterations()) {
// hash indexes do not support partial key match
return null;
}
if (found) {
result.remainingCondition = blockCopy;
return result;
}
return null;
}
/**
* given a full text index and a flat AND block, returns a descriptor on how to process it with an
* index (index, index key and additional filters to apply after index fetch
*
* @param ctx
* @param index
* @param block
* @param clazz
* @return
*/
private IndexSearchDescriptor buildIndexSearchDescriptorForFulltext(
OCommandContext ctx, OIndex index, OAndBlock block, OClass clazz) {
List<String> indexFields = index.getDefinition().getFields();
OBinaryCondition keyCondition = new OBinaryCondition(-1);
OIdentifier key = new OIdentifier("key");
keyCondition.setLeft(new OExpression(key));
boolean found = false;
OAndBlock blockCopy = block.copy();
Iterator<OBooleanExpression> blockIterator;
OAndBlock indexKeyValue = new OAndBlock(-1);
IndexSearchDescriptor result = new IndexSearchDescriptor();
result.idx = index;
result.keyCondition = indexKeyValue;
for (String indexField : indexFields) {
blockIterator = blockCopy.getSubBlocks().iterator();
boolean breakHere = false;
boolean indexFieldFound = false;
while (blockIterator.hasNext()) {
OBooleanExpression singleExp = blockIterator.next();
if (singleExp instanceof OContainsTextCondition) {
OExpression left = ((OContainsTextCondition) singleExp).getLeft();
if (left.isBaseIdentifier()) {
String fieldName = left.getDefaultAlias().getStringValue();
if (indexField.equals(fieldName)) {
found = true;
indexFieldFound = true;
OContainsTextCondition condition = new OContainsTextCondition(-1);
condition.setLeft(left);
condition.setRight(((OContainsTextCondition) singleExp).getRight().copy());
indexKeyValue.getSubBlocks().add(condition);
blockIterator.remove();
break;
}
}
}
}
if (breakHere || !indexFieldFound) {
break;
}
}
if (result.keyCondition.getSubBlocks().size() < index.getDefinition().getFields().size()
&& !index.supportsOrderedIterations()) {
// hash indexes do not support partial key match
return null;
}
if (found) {
result.remainingCondition = blockCopy;
return result;
}
return null;
}
private boolean isIndexByKey(OIndex index, String field) {
OIndexDefinition def = index.getDefinition();
for (String o : def.getFieldsToIndex()) {
if (o.equalsIgnoreCase(field + " by key")) {
return true;
}
}
return false;
}
private boolean isIndexByValue(OIndex index, String field) {
OIndexDefinition def = index.getDefinition();
for (String o : def.getFieldsToIndex()) {
if (o.equalsIgnoreCase(field + " by value")) {
return true;
}
}
return false;
}
private boolean isMap(OClass clazz, String indexField) {
OProperty prop = clazz.getProperty(indexField);
if (prop == null) {
return false;
}
return prop.getType() == OType.EMBEDDEDMAP;
}
private boolean createsRangeWith(OBinaryCondition left, OBooleanExpression next) {
if (!(next instanceof OBinaryCondition)) {
return false;
}
OBinaryCondition right = (OBinaryCondition) next;
if (!left.getLeft().equals(right.getLeft())) {
return false;
}
OBinaryCompareOperator leftOperator = left.getOperator();
OBinaryCompareOperator rightOperator = right.getOperator();
if (leftOperator instanceof OGeOperator || leftOperator instanceof OGtOperator) {
return rightOperator instanceof OLeOperator || rightOperator instanceof OLtOperator;
}
if (leftOperator instanceof OLeOperator || leftOperator instanceof OLtOperator) {
return rightOperator instanceof OGeOperator || rightOperator instanceof OGtOperator;
}
return false;
}
private boolean allowsRangeQueries(OIndex index) {
return index.supportsOrderedIterations();
}
/**
* aggregates multiple index conditions that refer to the same key search
*
* @param indexSearchDescriptors
* @return
*/
private List<IndexSearchDescriptor> commonFactor(
List<IndexSearchDescriptor> indexSearchDescriptors) {
// index, key condition, additional filter (to aggregate in OR)
Map<OIndex, Map<IndexCondPair, OOrBlock>> aggregation = new HashMap<>();
for (IndexSearchDescriptor item : indexSearchDescriptors) {
Map<IndexCondPair, OOrBlock> filtersForIndex = aggregation.get(item.idx);
if (filtersForIndex == null) {
filtersForIndex = new HashMap<>();
aggregation.put(item.idx, filtersForIndex);
}
IndexCondPair extendedCond =
new IndexCondPair(item.keyCondition, item.additionalRangeCondition);
OOrBlock existingAdditionalConditions = filtersForIndex.get(extendedCond);
if (existingAdditionalConditions == null) {
existingAdditionalConditions = new OOrBlock(-1);
filtersForIndex.put(extendedCond, existingAdditionalConditions);
}
existingAdditionalConditions.getSubBlocks().add(item.remainingCondition);
}
List<IndexSearchDescriptor> result = new ArrayList<>();
for (Map.Entry<OIndex, Map<IndexCondPair, OOrBlock>> item : aggregation.entrySet()) {
for (Map.Entry<IndexCondPair, OOrBlock> filters : item.getValue().entrySet()) {
result.add(
new IndexSearchDescriptor(
item.getKey(),
filters.getKey().mainCondition,
filters.getKey().additionalRange,
filters.getValue()));
}
}
return result;
}
private void handleClustersAsTarget(
OSelectExecutionPlan plan,
QueryPlanningInfo info,
List<OCluster> clusters,
OCommandContext ctx,
boolean profilingEnabled) {
ODatabase db = ctx.getDatabase();
OClass candidateClass = null;
boolean tryByIndex = true;
Set<String> clusterNames = new HashSet<>();
for (OCluster cluster : clusters) {
String name = cluster.getClusterName();
Integer clusterId = cluster.getClusterNumber();
if (name == null) {
name = db.getClusterNameById(clusterId);
}
if (clusterId == null) {
clusterId = db.getClusterIdByName(name);
}
if (name != null) {
clusterNames.add(name);
OClass clazz = db.getMetadata().getSchema().getClassByClusterId(clusterId);
if (clazz == null) {
tryByIndex = false;
break;
}
if (candidateClass == null) {
candidateClass = clazz;
} else if (!candidateClass.equals(clazz)) {
candidateClass = null;
tryByIndex = false;
break;
}
} else {
tryByIndex = false;
break;
}
}
if (tryByIndex) {
OIdentifier clazz = new OIdentifier(candidateClass.getName());
if (handleClassAsTargetWithIndexedFunction(
plan, clusterNames, clazz, info, ctx, profilingEnabled)) {
return;
}
if (handleClassAsTargetWithIndex(plan, clazz, clusterNames, info, ctx, profilingEnabled)) {
return;
}
if (info.orderBy != null
&& handleClassWithIndexForSortOnly(
plan, clazz, clusterNames, info, ctx, profilingEnabled)) {
return;
}
}
Boolean orderByRidAsc = null; // null: no order. true: asc, false:desc
if (isOrderByRidAsc(info)) {
orderByRidAsc = true;
} else if (isOrderByRidDesc(info)) {
orderByRidAsc = false;
}
if (orderByRidAsc != null && info.serverToClusters.size() == 1) {
info.orderApplied = true;
}
if (clusters.size() == 1) {
OCluster cluster = clusters.get(0);
Integer clusterId = cluster.getClusterNumber();
if (clusterId == null) {
clusterId = db.getClusterIdByName(cluster.getClusterName());
}
if (clusterId == null) {
throw new OCommandExecutionException("Cluster " + cluster + " does not exist");
}
FetchFromClusterExecutionStep step =
new FetchFromClusterExecutionStep(clusterId, ctx, profilingEnabled);
if (Boolean.TRUE.equals(orderByRidAsc)) {
step.setOrder(FetchFromClusterExecutionStep.ORDER_ASC);
} else if (Boolean.FALSE.equals(orderByRidAsc)) {
step.setOrder(FetchFromClusterExecutionStep.ORDER_DESC);
}
plan.chain(step);
} else {
int[] clusterIds = new int[clusters.size()];
for (int i = 0; i < clusters.size(); i++) {
OCluster cluster = clusters.get(i);
Integer clusterId = cluster.getClusterNumber();
if (clusterId == null) {
clusterId = db.getClusterIdByName(cluster.getClusterName());
}
if (clusterId == null) {
throw new OCommandExecutionException("Cluster " + cluster + " does not exist");
}
clusterIds[i] = clusterId;
}
FetchFromClustersExecutionStep step =
new FetchFromClustersExecutionStep(clusterIds, ctx, orderByRidAsc, profilingEnabled);
plan.chain(step);
}
}
private void handleSubqueryAsTarget(
OSelectExecutionPlan plan,
OStatement subQuery,
OCommandContext ctx,
boolean profilingEnabled) {
OBasicCommandContext subCtx = new OBasicCommandContext();
subCtx.setDatabase(ctx.getDatabase());
subCtx.setParent(ctx);
OInternalExecutionPlan subExecutionPlan =
subQuery.createExecutionPlan(subCtx, profilingEnabled);
plan.chain(new SubQueryStep(subExecutionPlan, ctx, subCtx, profilingEnabled));
}
private boolean isOrderByRidDesc(QueryPlanningInfo info) {
if (!hasTargetWithSortedRids(info)) {
return false;
}
if (info.orderBy == null) {
return false;
}
if (info.orderBy.getItems().size() == 1) {
OOrderByItem item = info.orderBy.getItems().get(0);
String recordAttr = item.getRecordAttr();
return recordAttr != null
&& recordAttr.equalsIgnoreCase("@rid")
&& OOrderByItem.DESC.equals(item.getType());
}
return false;
}
private boolean isOrderByRidAsc(QueryPlanningInfo info) {
if (!hasTargetWithSortedRids(info)) {
return false;
}
if (info.orderBy == null) {
return false;
}
if (info.orderBy.getItems().size() == 1) {
OOrderByItem item = info.orderBy.getItems().get(0);
String recordAttr = item.getRecordAttr();
return recordAttr != null
&& recordAttr.equalsIgnoreCase("@rid")
&& (item.getType() == null || OOrderByItem.ASC.equals(item.getType()));
}
return false;
}
private boolean hasTargetWithSortedRids(QueryPlanningInfo info) {
if (info.target == null) {
return false;
}
if (info.target.getItem() == null) {
return false;
}
if (info.target.getItem().getIdentifier() != null) {
return true;
} else if (info.target.getItem().getCluster() != null) {
return true;
} else return info.target.getItem().getClusterList() != null;
}
} |
// S h a p e //
// This software is released under the terms of the GNU General Public //
// to report bugs & suggestions. //
package omr.glyph;
import omr.constant.Constant;
import omr.ui.icon.IconManager;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.util.*;
import javax.swing.*;
/**
* Class <code>Shape</code> defines the comprehensive list of glyph shapes, as
* well as pre-defined ranges (see nested class {@link Range}) of the shapes
* list (such as rests, heads, etc...) to ease user interactions. It is
* organized according to the Unicode Standard 4.0, with a few addition for
* convenience only.
*
* <p>As far as possible, an Icon should be generated for every shape.
*
* @author Hervé Bitteur
* @version $Id$
*/
public enum Shape
implements java.io.Serializable
{
// Physical shapes, whose physical characteristics can be stored for
// evaluator training.
// Garbage
NOISE("Too small stuff"),
STRUCTURE("Structure of items"),
// Pure physical stuff
CLUTTER("Pure clutter"),
DOT("General dot shape"),
DASH("General dash shape"),
// Bars
/*1D109*/ DAL_SEGNO("Repeat from the sign"),
/*1D10A*/ DA_CAPO("Repeat from the beginning"),
/*1D10B*/ SEGNO("Sign"),
/*1D10C*/ CODA("Closing section"),
/*1D10D*/ // REPEATED_FIGURE_1,
/*1D10E*/ // REPEATED_FIGURE_2,
/*1D10F*/ // REPEATED_FIGURE_3,
/*1D110*/ FERMATA("Fermata"),
/*1D111*/ FERMATA_BELOW("Fermata Below"),
/*1D112*/ BREATH_MARK("Breath Mark"),
/*1D113*/ CAESURA("Caesura"),
/*1D114*/ BRACE("Brace"),
/*1D115*/ BRACKET("Bracket"),
// Staves
/*1D116*/ // ONE_LINE_STAFF,
/*1D117*/ // TWO_LINE_STAFF,
/*1D118*/ // THREE_LINE_STAFF,
/*1D119*/ // FOUR_LINE_STAFF,
/*1D11A*/ // FIVE_LINE_STAFF,
/*1D11B*/ // SIX_LINE_STAFF,
// Tablature
/*1D11C*/ // SIX_STRING_FRETBOARD,
/*1D11D*/ // FOUR_STRING_FRETBOARD,
// Clefs
/*1D11E*/ G_CLEF("Treble Clef"),
/*1D11F*/ G_CLEF_OTTAVA_ALTA("Ottava Alta"),
/*1D120*/ G_CLEF_OTTAVA_BASSA("Ottava Bassa"),
/*1D121*/ C_CLEF("Ut Clef"),
/*1D122*/ F_CLEF("Bass Clef"),
/*1D123*/ F_CLEF_OTTAVA_ALTA("Bass Clef Ottava Alta"),
/*1D124*/ F_CLEF_OTTAVA_BASSA("Bass Clef Ottava Bassa"),
/*1D125*/ // DRUM_CLEF_1,
/*1D126*/ // DRUM_CLEF_2,
// Accidentals
/*1D127*/ FLAT("Minus one half step"),
/*1D128*/ NATURAL("Natural value"),
/*1D129*/ SHARP("Plus one half step"),
/*1D12A*/ DOUBLE_SHARP("Double Sharp"),
/*1D12B*/ DOUBLE_FLAT("Double Flat"),
/*1D12C*/ // FLAT_UP,
/*1D12D*/ // FLAT_DOWN,
/*1D12E*/ // NATURAL_UP,
/*1D12F*/ // NATURAL_DOWN,
/*1D130*/ // SHARP_UP,
/*1D131*/ // SHARP_DOWN,
/*1D132*/ // QUARTER_TONE_SHARP,
/*1D133*/ // QUARTER_TONE_FLAT,
// Time signatures
TIME_ZERO("Digit 0"),
TIME_ONE("Digit 1"),
TIME_TWO("Digit 2"),
TIME_THREE("Digit 3"),
TIME_FOUR("Digit 4"),
TIME_FIVE("Digit 5"),
TIME_SIX("Digit 6"),
TIME_SEVEN("Digit 7"),
TIME_EIGHT("Digit 8"),
TIME_NINE("Digit 9"),
TIME_TWELVE("Number 12"),
TIME_SIXTEEN("Number 16"),
TIME_FOUR_FOUR("Rational 4/4"),
TIME_TWO_TWO("Rational 2/2"),
TIME_TWO_FOUR("Rational 2/4"),
TIME_THREE_FOUR("Rational 3/4"),
TIME_SIX_EIGHT("Rational 6/8"),
/*1D134*/ COMMON_TIME("Alpha = 4/4"),
/*1D135*/ CUT_TIME("Semi-Alpha = 2/4"),
// Octaves
/*1D136*/ OTTAVA_ALTA("8 va"),
/*1D137*/ OTTAVA_BASSA("8 vb"),
/*1D138*/ // QUINDICESIMA_ALTA,
/*1D139*/ // QUINDICESIMA_BASSA,
// Rests
/*1D13A*/ MULTI_REST("Rest for multiple measures"),
/*1D13B*/ WHOLE_OR_HALF_REST("Same shape for whole or half Rest"),
// /*1D13B*/ WHOLE_REST("Rest for whole measure"),
// /*1D13C*/ HALF_REST("Rest for a 1/2"),
/*1D13D*/ QUARTER_REST("Rest for a 1/4"),
/*1D13E*/ EIGHTH_REST("Rest for a 1/8"),
/*1D13F*/ SIXTEENTH_REST("Rest for a 1/16"),
/*1D140*/ THIRTY_SECOND_REST("Rest for a 1/32"),
/*1D141*/ SIXTY_FOURTH_REST("Rest for a 1/64"),
/*1D142*/ ONE_HUNDRED_TWENTY_EIGHTH_REST("Rest for a 1/128"),
// Noteheads
/*1D143*/ // X_NOTEHEAD,
/*1D144*/ // PLUS_NOTEHEAD,
/*1D145*/ // CIRCLE_X_NOTEHEAD,
/*1D146*/ // SQUARE_NOTEHEAD_WHITE,
/*1D147*/ // SQUARE_NOTEHEAD_BLACK,
/*1D148*/ // TRIANGLE_NOTEHEAD_UP_WHITE,
/*1D149*/ // TRIANGLE_NOTEHEAD_UP_BLACK,
/*1D14A*/ // TRIANGLE_NOTEHEAD_LEFT_WHITE,
/*1D14B*/ // TRIANGLE_NOTEHEAD_LEFT_BLACK,
/*1D14C*/ // TRIANGLE_NOTEHEAD_RIGHT_WHITE,
/*1D14D*/ // TRIANGLE_NOTEHEAD_RIGHT_BLACK,
/*1D14E*/ // TRIANGLE_NOTEHEAD_DOWN_WHITE,
/*1D14F*/ // TRIANGLE_NOTEHEAD_DOWN_BLACK,
/*1D150*/ // TRIANGLE_NOTEHEAD_UP_RIGHT_WHITE,
/*1D151*/ // TRIANGLE_NOTEHEAD_UP_RIGHT_BLACK,
/*1D152*/ // MOON_NOTEHEAD_WHITE,
/*1D153*/ // MOON_NOTEHEAD_BLACK,
/*1D154*/ // TRIANGLEROUND_NOTEHEAD_DOWN_WHITE,
/*1D155*/ // TRIANGLEROUND_NOTEHEAD_DOWN_BLACK,
/*1D156*/ // PARENTHESIS_NOTEHEAD,
/*1D157*/ VOID_NOTEHEAD("Hollow node head for halves"),
VOID_NOTEHEAD_2("Pack of two hollow node heads for halves"),
VOID_NOTEHEAD_3("Pack of three hollow node heads for halves"),
/*1D158*/ NOTEHEAD_BLACK("Filled node head for quarters and less"),
NOTEHEAD_BLACK_2("Pack of two filled node heads for quarters and less"),
NOTEHEAD_BLACK_3("Pack of three filled node heads for quarters and less"),
/*1D159*/ // NULL_NOTEHEAD,
/*1D15A*/ // CLUSTER_NOTEHEAD_WHITE,
/*1D15B*/ // CLUSTER_NOTEHEAD_BLACK,
// Notes
/*1D15C*/ BREVE("Double Whole"), // ||O||
/*1D15D*/ WHOLE_NOTE("Hollow node head for wholes"),
WHOLE_NOTE_2("Pack of two hollow node heads for wholes"),
WHOLE_NOTE_3("Pack of three hollow node heads for wholes"),
/*1D15E*/ // HALF_NOTE, //= 1D157 + 1D165
/*1D15F*/ // QUARTER_NOTE, //= 1D158 +1D165
/*1D160*/ // EIGHTH_NOTE, //= 1D15F + 1D16E
/*1D161*/ // SIXTEENTH_NOTE, //= 1D15F + 1D16F
/*1D162*/ // THIRTY_SECOND_NOTE, //= 1D15F + 1D170
/*1D163*/ // SIXTY_FOURTH_NOTE, //= 1D15F + 1D171
/*1D164*/ // ONE_HUNDRED_TWENTY_EIGHTH_NOTE, //= 1D15F + 1D172
// Tremolos
/*1D167*/ // COMBINING_TREMOLO_1,
/*1D168*/ // COMBINING_TREMOLO_2,
/*1D169*/ // COMBINING_TREMOLO_3,
/*1D16A*/ // FINGERED_TREMOLO_1,
/*1D16B*/ // FINGERED_TREMOLO_2,
/*1D16C*/ // FINGERED_TREMOLO_3,
// Flags
/*1D16E*/ COMBINING_FLAG_1("Single flag down"),
/*1D16F*/ COMBINING_FLAG_2("Double flag down"),
/*1D170*/ COMBINING_FLAG_3("Triple flag down"),
/*1D171*/ COMBINING_FLAG_4("Quadruple flag down"),
/*1D172*/ COMBINING_FLAG_5("Quintuple flag down"),
COMBINING_FLAG_1_UP("Single flag up"),
COMBINING_FLAG_2_UP("Double flag up"),
COMBINING_FLAG_3_UP("Triple flag up"),
COMBINING_FLAG_4_UP("Quadruple flag up"),
COMBINING_FLAG_5_UP("Quintuple flag up"),
// Connected head and flags
HEAD_AND_FLAG_1("Black notehead with single flag down"),
HEAD_AND_FLAG_2("Black notehead with double flag down"),
HEAD_AND_FLAG_3("Black notehead with triple flag down"),
HEAD_AND_FLAG_4("Black notehead with quadruple flag down"),
HEAD_AND_FLAG_5("Black notehead with quintuple flag down"),
HEAD_AND_FLAG_1_UP("Black notehead with single flag up"),
HEAD_AND_FLAG_2_UP("Black notehead with double flag up"),
HEAD_AND_FLAG_3_UP("Black notehead with triple flag up"),
HEAD_AND_FLAG_4_UP("Black notehead with quadruple flag up"),
HEAD_AND_FLAG_5_UP("Black notehead with quintuple flag up"),
// Beams and slurs
BEAM("Beam between two stems"),
BEAM_HOOK("Hook of a beam attached on one stem"),
SLUR("Slur tying notes"),
/*1D173*/ // BEGIN_BEAM,
/*1D174*/ // END_BEAM,
/*1D175*/ // BEGIN_TIE,
/*1D176*/ // END_TIE,
/*1D177*/ // BEGIN_SLUR,
/*1D178*/ // END_SLUR,
/*1D179*/ // BEGIN_PHRASE,
/*1D17A*/ // END_PHRASE,
// Articulation
/*1D17B*/ // COMBINING_ACCENT,
/*1D17C*/ // COMBINING_STACCATO,
/*1D17D*/ // COMBINING_TENUTO,
/*1D17E*/ // COMBINING_STACCATISSIMO,
/*1D17F*/ // COMBINING_MARCATO,
/*1D180*/ // COMBINING_MARCATO_STACCATO,
/*1D181*/ // COMBINING_ACCENT_STACCATO,
/*1D182*/ // COMBINING_LOURE,
/*1D183*/ ARPEGGIATO_UP,
/*1D184*/ ARPEGGIATO_DOWN,
/*1D185*/ // COMBINING_DOIT,
/*1D186*/ // COMBINING_RIP,
/*1D187*/ // COMBINING_FLIP,
/*1D188*/ // COMBINING_SMEAR,
/*1D189*/ // COMBINING_BEND,
/*1D18A*/ // COMBINING_DOUBLE_TONGUE,
/*1D18B*/ // COMBINING_TRIPLE_TONGUE,
/*1D18C*/ // RINFORZANDO,
/*1D18D*/ // SUBITO,
/*1D18E*/ // Z,
// Dynamics
PIANISSISSIMO, // PPP
PIANISSIMO, // PP
/*1D18F*/ PIANO, // P
MEZZO_PIANO, // MP
/*1D190*/ MEZZO, // M
MEZZO_FORTE, // MF
/*1D191*/ FORTE, // F
FORTISSIMO, // FF
FORTISSISSIMO, // FFF
/*1D192*/ CRESCENDO, // <
/*1D193*/ DECRESCENDO, // >
// Ornaments
/*1D194*/ GRACE_NOTE_SLASH("Grace Note with a Slash"),
/*1D195*/ GRACE_NOTE_NO_SLASH("Grace Note with no Slash"),
/*1D196*/ TR,
/*1D197*/ TURN,
/*1D198*/ INVERTED_TURN,
/*1D199*/ TURN_SLASH,
/*1D19A*/ TURN_UP,
MORDENT, // Lower
INVERTED_MORDENT, // Upper
/*1D19B*/ // ORNAMENT_STROKE_1,
/*1D19C*/ // ORNAMENT_STROKE_2,
/*1D19D*/ // ORNAMENT_STROKE_3,
/*1D19E*/ // ORNAMENT_STROKE_4,
/*1D19F*/ // ORNAMENT_STROKE_5,
/*1D1A0*/ // ORNAMENT_STROKE_6,
/*1D1A1*/ // ORNAMENT_STROKE_7,
/*1D1A2*/ // ORNAMENT_STROKE_8,
/*1D1A3*/ // ORNAMENT_STROKE_9,
/*1D1A4*/ // ORNAMENT_STROKE_10,
/*1D1A5*/ // ORNAMENT_STROKE_11,
// Analytics
/*1D1A6*/ // HAUPTSTIMME,
/*1D1A7*/ // NEBENSTIMME,
/*1D1A8*/ // END_OF_STIMME,
/*1D1A9*/ // DEGREE_SLASH,
// Instrumentation
/*1D1AA*/ // COMBINING_DOWN_BOW,
/*1D1AB*/ // COMBINING_UP_BOW,
/*1D1AC*/ // COMBINING_HARMONIC,
/*1D1AD*/ // COMBINING_SNAP_PIZZICATO,
// Pedals
/*1D1AE*/ PEDAL_MARK, // Ped
/*1D1AF*/ PEDAL_UP_MARK, // *
/*1D1B0*/ // HALF_PEDAL_MARK,
// Pure Logical shapes, that cannot be inferred only from their
// physical characteristics.
// Bars
/*1D100*/ SINGLE_BARLINE("Single thin bar line"),
/*1D101*/ DOUBLE_BARLINE("Double thin bar line"),
/*1D102*/ FINAL_BARLINE("Thin / Thick bar line"),
/*1D103*/ REVERSE_FINAL_BARLINE("Thick / Thin bar line"),
/*1D104*/ // DASHED_BARLINE,
/*1D105*/ // SHORT_BARLINE,
/*1D106*/ LEFT_REPEAT_SIGN("Thick / Thin bar line + REPEAT_DOTS"),
/*1D107*/ RIGHT_REPEAT_SIGN("REPEAT_DOTS + Thin / Thick bar line"),
BACK_TO_BACK_REPEAT_SIGN("REPEAT_DOTS + Thin / Thick / Thin + REPEAT_DOTS"),
THICK_BAR_LINE("Thick bar line"),
THIN_BAR_LINE("Thin bar line"),
/*1D108*/ REPEAT_DOTS("Vertical dots"),
// Augmentation dot
/*1D16D*/ COMBINING_AUGMENTATION_DOT("Augmentation Dot"),
// Alternate ending indication
ENDING("Alternate ending"),
// Miscellaneous
LEDGER("Ledger"),
STAFF_LINE("Staff Line"),
ENDING_HORIZONTAL("Horizontal part of ending"),
ENDING_VERTICAL("Vertical part of ending"),
// Stems
/*1D165*/ COMBINING_STEM,
/*1D166*/ // COMBINING_SPRECHGESANG_STEM,
// Key signatures
KEY_FLAT_7("Seven Flats"), // -7
KEY_FLAT_6("Six Flats"), // -6
KEY_FLAT_5("Five Flats"), // -5
KEY_FLAT_4("Four Flats"), // -4
KEY_FLAT_3("Three Flats"), // -3
KEY_FLAT_2("Two Flats"), // -2
KEY_FLAT_1("One Flat"), // -1
KEY_SHARP_1("One Sharp"), // +1
KEY_SHARP_2("Two Sharps"), // +2
KEY_SHARP_3("Three Sharps"), // +3
KEY_SHARP_4("Four Sharps"), // +4
KEY_SHARP_5("Five Sharps"), // +5
KEY_SHARP_6("Six Sharps"), // +6
KEY_SHARP_7("Seven Sharps"), // +7
CHARACTER("A letter"),
/*1D13B*/ WHOLE_REST("Rest for whole measure", WHOLE_OR_HALF_REST),
/*1D13C*/ HALF_REST("Rest for a 1/2", WHOLE_OR_HALF_REST),
/** The following shape is a kludge to get proper icon */
MULTI_REST_DISPLAY,
FORWARD,
NO_LEGAL_SHAPE("No Legal Shape");
/**
* First physical shape an evaluator should be able to recognize based on
* their physical characteristics. For example a DOT is a DOT. Also, a DOT
* plus a FERMATA_BEND together can compose a FERMATA.
*/
public static final Shape FirstPhysicalShape = NOISE;
/**
* Last physical shape.
*/
public static final Shape LastPhysicalShape = PEDAL_UP_MARK;
/**
* First logical shape, that are more precisely assigned.
*/
public static final Shape FirstLogicalShape = SINGLE_BARLINE;
/** Color for unknown shape */
public static final Color missedColor = Color.red;
/** Color for glyphs tested as OK (color used temporarily) */
public static final Color okColor = Color.green;
/** Explanation of the glyph shape */
private final String description;
/** Related temporary display color */
private Color color;
/** Related permanent display color */
private Constant.Color constantColor;
/** Potential related icon */
private Icon icon;
/** Potential related shape to be used for training */
private Shape trainingShape;
/** Remember the fact that this shape has no related icon */
private boolean hasNoIcon;
// Shape //
Shape ()
{
this("", null); // No param
}
// Shape //
Shape (String description)
{
this(description, null);
}
// Shape //
Shape (String description,
Shape trainingShape)
{
this.description = description;
this.trainingShape = trainingShape;
}
// isWellKnown //
/**
* Report whether this shape is well known, that is a symbol not part of the
* Garbage range
*
* @return true if not part of garbage range, false otherwise
*/
public boolean isWellKnown ()
{
return (this != NO_LEGAL_SHAPE) && !Garbage.getShapes()
.contains(this);
}
// getDescription //
/**
* Report a user-friendly description of this shape
*
* @return the shape description
*/
public String getDescription ()
{
if (description == null) {
return toString(); // Could be improved
} else {
return description;
}
}
// getColor //
/**
* Report the color currently assigned to the shape, if any
*
* @return the related color, or null
*/
public java.awt.Color getColor ()
{
return color;
}
// setColor //
/**
* Assign a color for current display. This is the specific shape color if
* any, otherwise it is the default color of the containing range.
*
* @param color the display color
*/
public void setColor (java.awt.Color color)
{
this.color = color;
}
// createShapeColor //
private void createShapeColor (Color color)
{
// Create the underlying constant
constantColor = new Constant.Color(
getClass().getName(), // Unit
name() + ".color", // Name
null, // DefaultValue
"Color code for shape " + name());
// Assign the shape display color
if (constantColor.getValue() != null) {
// Use the shape specific color
setColor(constantColor.getValue());
} else {
// Use the provided default color
setColor(color);
}
}
// getConstantColor //
/**
* Report the color that is specifically assigned to this shape, if any
*
* @return the specific color if any, null otherwise
*/
public Color getConstantColor ()
{
return constantColor.getValue();
}
// setConstantColor //
/**
* Assign a specific color to the shape
*
* @param color the color to be assigned
*/
public void setConstantColor (java.awt.Color color)
{
constantColor.setValue(color);
setColor(color);
}
// resetConstantColor //
/**
* Remove the shape specific color, and reset the shape color using the
* provided color (typically the range default color)
*
* @param color the default color
*/
public void resetConstantColor (Color color)
{
constantColor.remove();
createShapeColor(color); // Use range color !!!
}
// getIcon //
/**
* Report the icon related to the shape, if any
*
* @return the related icon, or null
*/
public Icon getIcon ()
{
if (hasNoIcon) {
return null;
}
if (icon == null) {
setIcon(IconManager.getInstance().loadSymbolIcon(toString()));
if (icon == null) {
hasNoIcon = true;
}
}
return icon;
}
// setIcon //
/**
* Assign a font to this shape
*
* @param icon the assigned icon, which may be null
*/
public void setIcon (Icon icon)
{
this.icon = icon;
}
// getTrainingShape //
public Shape getTrainingShape()
{
if (trainingShape != null) {
return trainingShape;
} else {
return this;
}
}
// addRangeShapeItems //
/**
* Populate the given menu with a list of all shapes that belong to the
* given range
*
* @param range the range for which shape menu items must be buit
* @param top the JComponent to populate (typically a JMenu or a JPopupMenu)
* @param listener the listener for notification of user selection
*/
public static void addRangeShapeItems (Range range,
JComponent top,
ActionListener listener)
{
// All shapes in the given range
for (Shape shape : range.shapes) {
JMenuItem menuItem = new JMenuItem(
shape.toString(),
shape.getIcon());
addColoredItem(top, menuItem, shape.getColor());
menuItem.setToolTipText(shape.description);
menuItem.addActionListener(listener);
}
}
// addShapeItems //
/**
* Populate the given menu with a hierarchy of all shapes
*
* @param top the JComponent to populate (typically a JMenu or a JPopupMenu)
* @param listener the listener for notification of user selection
*/
public static void addShapeItems (JComponent top,
ActionListener listener)
{
// All ranges of glyph shapes
for (Field field : Shape.class.getDeclaredFields()) {
if (field.getType() == Range.class) {
JMenu menu = new JMenu(field.getName());
Range range = Range.valueOf(field.getName());
addColoredItem(top, menu, Color.black);
// Add menu items for this range
addRangeShapeItems(range, menu, listener);
}
}
}
// addColoredItem //
private static void addColoredItem (JComponent top,
JMenuItem item,
Color color)
{
if (color != null) {
item.setForeground(color);
} else {
item.setForeground(Color.black);
}
top.add(item);
}
// Range //
/**
* Class <code>Range</code> defines a range of related shapes, for example
* the "Rests" range gathers all rest shapes from MULTI_REST down to
* ONE_HUNDRED_TWENTY_EIGHTH_REST. It handles additional properties over a
* simple EnumSet, especially assigned colors and its automatic insertion in
* shape menu hierarchy.
*/
public static class Range
{
// Map for all defined ranges
private static Map<String, Range> rangeMap;
private String name; // Name of the range
private final EnumSet<Shape> shapes; // Contained shapes
private Color color; // For current color
private Constant.Color constantColor; // For specific color
// Range //
/**
* Create a Range from an EnumSet of Shapes
*
* @param shapes the contained shapes
*/
public Range (EnumSet<Shape> shapes)
{
this.shapes = shapes;
}
// getShapes //
/**
* Exports the set of shapes in the range
*
* @return the proper enum set
*/
public EnumSet<Shape> getShapes ()
{
return shapes;
}
// contains //
/**
* Convenient method to check if encapsulated shapes set does contain
* the provided object
*
* @return true if contained, false otherwise
*/
public boolean contains (Object obj)
{
return shapes.contains(obj);
}
// getColor //
/**
* Report the color currently assigned to the range, if any
*
* @return the related color, or null
*/
public java.awt.Color getColor ()
{
return color;
}
// setColor //
/**
* Assign a display color to the shape range
*
* @param color the display color
*/
public void setColor (java.awt.Color color)
{
this.color = color;
}
// setConstantColor //
/**
* Define a specific color for the range
*
* @param color the specified color
*/
public void setConstantColor (java.awt.Color color)
{
constantColor.setValue(color);
setColor(color);
}
// valueOf //
/**
* Retrieve a range knowing its name (just like an enumeration)
*
* @param str the provided range name
* @return the range found, or null otherwise
*/
public static Range valueOf (String str)
{
// Build the range map in a lazy way
if (rangeMap == null) {
rangeMap = new HashMap<String, Range>();
for (Field field : Shape.class.getDeclaredFields()) {
if (field.getType() == Range.class) {
try {
Range range = (Range) field.get(null);
rangeMap.put(field.getName(), range);
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
}
}
return rangeMap.get(str);
}
// addRangeItems //
/**
* Populate the given menu with a hierarchy of all ranges
*
* @param top the JComponent to populate (typically a JMenu or a
* JPopupMenu)
* @param listener the listener for notification of user selection
*/
public static void addRangeItems (JComponent top,
ActionListener listener)
{
// All ranges of glyph shapes
for (Field field : Shape.class.getDeclaredFields()) {
if (field.getType() == Range.class) {
JMenuItem menuItem = new JMenuItem(field.getName());
Range range = valueOf(field.getName());
addColoredItem(top, menuItem, range.getColor());
menuItem.addActionListener(listener);
}
}
}
// getName //
/**
* Report the name of the range
*
* @return the range name
*/
public String getName ()
{
return name;
}
// setName //
private void setName (String name)
{
this.name = name;
constantColor = new Constant.Color(
getClass().getName(), // Unit
name + ".color", // Name
null, // DefaultValue
"Color code for range " + name);
// Assign the range display color
if (constantColor.getValue() != null) {
// Use the range specific color
setColor(constantColor.getValue());
} else {
// Use the default color
setColor(Color.black);
}
}
}
// Predefined shape ranges
public static final Range Garbage = new Range(EnumSet.range(NOISE, STRUCTURE));
public static final Range Physicals = new Range(EnumSet.range(CLUTTER, DASH));
public static final Range Bars = new Range(EnumSet.range(DAL_SEGNO, BRACKET));
public static final Range Clefs = new Range(EnumSet.range(G_CLEF, F_CLEF_OTTAVA_BASSA));
public static final Range Accidentals = new Range(EnumSet.range(FLAT, DOUBLE_FLAT));
public static final Range Times = new Range(EnumSet.range(TIME_ZERO, CUT_TIME));
public static final Range Octaves = new Range(EnumSet.range(OTTAVA_ALTA, OTTAVA_BASSA));
public static final Range Rests = new Range(EnumSet.of(MULTI_REST,
WHOLE_REST,
HALF_REST,
QUARTER_REST,
EIGHTH_REST,
SIXTEENTH_REST,
THIRTY_SECOND_REST,
SIXTY_FOURTH_REST,
ONE_HUNDRED_TWENTY_EIGHTH_REST));
public static final Range NoteHeads = new Range(EnumSet.range(VOID_NOTEHEAD, NOTEHEAD_BLACK_3));
public static final Range Notes = new Range(EnumSet.range(BREVE, WHOLE_NOTE_3));
public static final Range Stems = new Range(EnumSet.range(COMBINING_STEM, COMBINING_STEM));
public static final Range Flags = new Range(EnumSet.range(COMBINING_FLAG_1, COMBINING_FLAG_5_UP));
public static final Range HeadAndFlags = new Range(EnumSet.range(HEAD_AND_FLAG_1, HEAD_AND_FLAG_5_UP));
public static final Range Beams = new Range(EnumSet.range(BEAM, SLUR));
public static final Range Articulations = new Range(EnumSet.range(ARPEGGIATO_UP, ARPEGGIATO_DOWN));
public static final Range Dynamics = new Range(EnumSet.range(PIANISSISSIMO, DECRESCENDO));
public static final Range Ornaments = new Range(EnumSet.range(GRACE_NOTE_SLASH, INVERTED_MORDENT));
public static final Range Pedals = new Range(EnumSet.range(PEDAL_MARK, PEDAL_UP_MARK));
public static final Range Barlines = new Range(EnumSet.range(SINGLE_BARLINE, THIN_BAR_LINE));
public static final Range Logicals = new Range(EnumSet.range(REPEAT_DOTS, ENDING));
// Assign proper name to all ranges and proper color to their contained
// shapes
static {
for (Field field : Shape.class.getDeclaredFields()) {
if (field.getType() == Range.class) {
try {
Range range = (Range) field.get(null);
range.setName(field.getName());
// Create shape color for all contained shapes
for (Shape shape : range.shapes) {
shape.createShapeColor(range.getColor());
}
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
}
}
/** Symbols that can be attached to a stem */
public static final EnumSet<Shape> StemSymbols = EnumSet.noneOf(
Shape.class);
static {
StemSymbols.add(Shape.BEAM);
StemSymbols.add(Shape.BEAM_HOOK);
StemSymbols.addAll(NoteHeads.getShapes());
StemSymbols.addAll(Flags.getShapes());
StemSymbols.addAll(HeadAndFlags.getShapes());
}
/** Specific single symbol for part of time signature (such as 4) */
public static final EnumSet<Shape> SingleTimes = EnumSet.range(
TIME_ZERO,
TIME_SIXTEEN);
/** Specific multi-symbol for entiretime signature (such as 4/4 */
public static final EnumSet<Shape> MultiTimes = EnumSet.range(
TIME_FOUR_FOUR,
CUT_TIME);
} |
package org.jdesktop.swingx;
import java.awt.AlphaComposite;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
import org.jdesktop.beans.JavaBean;
import org.jdesktop.swingx.painter.AbstractPainter;
import org.jdesktop.swingx.painter.Painter;
import org.jdesktop.swingx.util.Contract;
import org.jdesktop.swingx.util.GraphicsUtilities;
import org.jdesktop.swingx.util.JVM;
/**
* <p>
* An extended {@code JPanel} that provides additional features. First, the
* component is {@code Scrollable}, using reasonable defaults. Second, the
* component is alpha-channel enabled. This means that the {@code JXPanel} can
* be made fully or partially transparent. Finally, {@code JXPanel} has support
* for {@linkplain Painter painters}.
* </p>
* <p>
* A transparency example, this following code will show the black background of
* the parent:
*
* <pre>
* JXPanel panel = new JXPanel();
* panel.add(new JButton("Push Me"));
* panel.setAlpha(.5f);
*
* container.setBackground(Color.BLACK);
* container.add(panel);
* </pre>
*
* </p>
* <p>
* A painter example, this following code will show how to add a simple painter:
*
* <pre>
* JXPanel panel = new JXPanel();
* panel.setBackgroundPainter(new PinstripePainter());
* </pre>
*
* </p>
*
* @author rbair
* @see Scrollable
* @see Painter
*/
@JavaBean
@SuppressWarnings("nls")
public class JXPanel extends JPanel implements AlphaPaintable, BackgroundPaintable, Scrollable {
// private boolean scrollableTracksViewportHeight = true;
// private boolean scrollableTracksViewportWidth = true;
private ScrollableSizeHint scrollableWidthHint = ScrollableSizeHint.FIT;
private ScrollableSizeHint scrollableHeightHint = ScrollableSizeHint.FIT;
/**
* The alpha level for this component.
*/
private float alpha = 1.0f;
/**
* If the old alpha value was 1.0, I keep track of the opaque setting because
* a translucent component is not opaque, but I want to be able to restore
* opacity to its default setting if the alpha is 1.0. Honestly, I don't know
* if this is necessary or not, but it sounded good on paper :)
* <p>TODO: Check whether this variable is necessary or not</p>
*/
private boolean oldOpaque;
/**
* Indicates whether this component should inherit its parent alpha value
*/
private boolean inheritAlpha = true;
/**
* Specifies the Painter to use for painting the background of this panel.
* If no painter is specified, the normal painting routine for JPanel
* is called. Old behavior is also honored for the time being if no
* backgroundPainter is specified
*/
@SuppressWarnings("rawtypes")
private Painter backgroundPainter;
private boolean paintBorderInsets = true;
/**
* The listener installed on the current backgroundPainter, if any.
*/
private PropertyChangeListener painterChangeListener;
/**
* Creates a new <code>JXPanel</code> with a double buffer
* and a flow layout.
*/
public JXPanel() {
}
/**
* Creates a new <code>JXPanel</code> with <code>FlowLayout</code>
* and the specified buffering strategy.
* If <code>isDoubleBuffered</code> is true, the <code>JXPanel</code>
* will use a double buffer.
*
* @param isDoubleBuffered a boolean, true for double-buffering, which
* uses additional memory space to achieve fast, flicker-free
* updates
*/
public JXPanel(boolean isDoubleBuffered) {
super(isDoubleBuffered);
}
/**
* Create a new buffered JXPanel with the specified layout manager
*
* @param layout the LayoutManager to use
*/
public JXPanel(LayoutManager layout) {
super(layout);
}
/**
* Creates a new JXPanel with the specified layout manager and buffering
* strategy.
*
* @param layout the LayoutManager to use
* @param isDoubleBuffered a boolean, true for double-buffering, which
* uses additional memory space to achieve fast, flicker-free
* updates
*/
public JXPanel(LayoutManager layout, boolean isDoubleBuffered) {
super(layout, isDoubleBuffered);
}
/**
* {@inheritDoc}
*/
@Override
public float getAlpha() {
return alpha;
}
/**
* {@inheritDoc}
*/
@Override
public void setAlpha(float alpha) {
if (alpha < 0f || alpha > 1f) {
throw new IllegalArgumentException("invalid alpha value " + alpha);
}
float oldValue = getAlpha();
this.alpha = alpha;
if (getAlpha() < 1f) {
if (oldValue == 1) {
//it used to be 1, but now is not. Save the oldOpaque
oldOpaque = isOpaque();
setOpaque(false);
}
installRepaintManager();
} else {
uninstallRepaintManager();
//restore the oldOpaque if it was true (since opaque is false now)
if (oldOpaque) {
setOpaque(true);
}
}
firePropertyChange("alpha", oldValue, getAlpha());
repaint();
}
void installRepaintManager() {
if (!JVM.current().isOrLater(JVM.JDK1_7)) {
RepaintManager manager = RepaintManager.currentManager(this);
RepaintManager trm = SwingXUtilities.getTranslucentRepaintManager(manager);
RepaintManager.setCurrentManager(trm);
}
}
void uninstallRepaintManager() {
//TODO uninstall TranslucentRepaintManager when no more non-opaque JXPanel's exist
}
/**
* {@inheritDoc}
*/
@Override
public float getEffectiveAlpha() {
float a = getAlpha();
if (isInheritAlpha()) {
for (Component c = getParent(); c != null; c = c.getParent()) {
if (c instanceof AlphaPaintable) {
a = Math.min(((AlphaPaintable) c).getEffectiveAlpha(), a);
break;
}
}
}
return a;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isInheritAlpha() {
return inheritAlpha;
}
/**
* {@inheritDoc}
*/
@Override
public void setInheritAlpha(boolean val) {
boolean oldValue = isInheritAlpha();
inheritAlpha = val;
firePropertyChange("inheritAlpha", oldValue, isInheritAlpha());
}
/**
* Sets the horizontal sizing hint. The hint is used by the Scrollable implementation
* to service the getScrollableTracksWidth.
*
* @param hint the horizontal sizing hint, must not be null
* and must be vertical.
*
* @throws NullPointerException if null
*
* @see #setScrollableHeightHint(ScrollableSizeHint)
* @see ScrollableSizeHint
*/
public final void setScrollableWidthHint(ScrollableSizeHint hint) {
Contract.asNotNull(hint, "hint cannot be null");
ScrollableSizeHint oldValue = getScrollableWidthHint();
if (oldValue == hint) return;
this.scrollableWidthHint = hint;
revalidate();
firePropertyChange("scrollableWidthHint", oldValue, getScrollableWidthHint());
}
/**
* Sets the vertical sizing hint. The hint is used by the Scrollable implementation
* to service the getScrollableTracksHeight.
*
* @param hint the vertical sizing hint, must not be null
* and must be vertical.
*
* @throws NullPointerException if null
*
* @see #setScrollableWidthHint(ScrollableSizeHint)
* @see ScrollableSizeHint
*/
public final void setScrollableHeightHint(ScrollableSizeHint hint) {
Contract.asNotNull(hint, "hint cannot be null");
ScrollableSizeHint oldValue = getScrollableHeightHint();
if (oldValue == hint) return;
this.scrollableHeightHint = hint;
revalidate();
firePropertyChange("scrollableHeightHint", oldValue, getScrollableHeightHint());
}
protected ScrollableSizeHint getScrollableWidthHint() {
return scrollableWidthHint;
}
protected ScrollableSizeHint getScrollableHeightHint() {
return scrollableHeightHint;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getScrollableTracksViewportHeight() {
return scrollableHeightHint.getTracksParentSize(this, SwingConstants.VERTICAL);
}
/**
* {@inheritDoc}
*/
@Override
public boolean getScrollableTracksViewportWidth() {
return scrollableWidthHint.getTracksParentSize(this, SwingConstants.HORIZONTAL);
}
/**
* {@inheritDoc}
*/
@Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
/**
* {@inheritDoc}
*/
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
if (orientation == SwingConstants.VERTICAL) {
return visibleRect.height;
} else if (orientation == SwingConstants.HORIZONTAL) {
return visibleRect.width;
} else {
throw new IllegalArgumentException("invalid orientation"); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return getScrollableBlockIncrement(visibleRect, orientation, direction) / 10;
}
/**
*
* Sets the vertical size tracking to either ScrollableSizeTrack.FIT or NONE, if the
* boolean parameter is true or false, respectively.<p>
*
* <b>NOTE</b>: this method is kept for backward compatibility only, for full
* control use setScrollableHeightHint.
*
* @param scrollableTracksViewportHeight The scrollableTracksViewportHeight to set.
*
* @see #setScrollableHeightHint(ScrollableSizeHint)
*/
public void setScrollableTracksViewportHeight(boolean scrollableTracksViewportHeight) {
setScrollableHeightHint(scrollableTracksViewportHeight ?
ScrollableSizeHint.FIT : ScrollableSizeHint.NONE);
}
/**
* Sets the horizontal size tracking to either ScrollableSizeTrack.FIT or NONE, if the
* boolean parameter is true or false, respectively.<p>
*
* <b>NOTE</b>: this method is kept for backward compatibility only, for full
* control use setScrollableWidthHint.
*
*
* @param scrollableTracksViewportWidth The scrollableTracksViewportWidth to set.
*
* @see #setScrollableWidthHint(ScrollableSizeHint)
*/
public void setScrollableTracksViewportWidth(boolean scrollableTracksViewportWidth) {
setScrollableWidthHint(scrollableTracksViewportWidth ?
ScrollableSizeHint.FIT : ScrollableSizeHint.NONE);
}
/**
* Sets a Painter to use to paint the background of this JXPanel.
*
* @param p the new painter
* @see #getBackgroundPainter()
*/
@Override
public void setBackgroundPainter(Painter p) {
Painter old = getBackgroundPainter();
if (old instanceof AbstractPainter) {
((AbstractPainter<?>) old).removePropertyChangeListener(painterChangeListener);
}
backgroundPainter = p;
if (backgroundPainter instanceof AbstractPainter) {
((AbstractPainter<?>) backgroundPainter).addPropertyChangeListener(getPainterChangeListener());
}
firePropertyChange("backgroundPainter", old, getBackgroundPainter());
repaint();
}
/**
* @return a listener for painter change events
*/
protected PropertyChangeListener getPainterChangeListener() {
if (painterChangeListener == null) {
painterChangeListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
repaint();
}
};
}
return painterChangeListener;
}
/**
* Returns the current background painter. The default value of this property
* is a painter which draws the normal JPanel background according to the current look and feel.
* @return the current painter
* @see #setBackgroundPainter(Painter)
* @see #isPaintBorderInsets()
*/
@Override
public Painter getBackgroundPainter() {
return backgroundPainter;
}
/**
* Returns true if the background painter should paint where the border is
* or false if it should only paint inside the border. This property is
* true by default. This property affects the width, height,
* and initial transform passed to the background painter.
*/
@Override
public boolean isPaintBorderInsets() {
return paintBorderInsets;
}
/**
* Sets the paintBorderInsets property.
* Set to true if the background painter should paint where the border is
* or false if it should only paint inside the border. This property is true by default.
* This property affects the width, height,
* and initial transform passed to the background painter.
*
* This is a bound property.
*/
@Override
public void setPaintBorderInsets(boolean paintBorderInsets) {
boolean old = this.isPaintBorderInsets();
this.paintBorderInsets = paintBorderInsets;
firePropertyChange("paintBorderInsets", old, isPaintBorderInsets());
}
//support for Java 7 painting improvements
protected boolean isPaintingOrigin() {
if (getAlpha() < 1f) {
Container c = getParent();
while (c != null) {
if (c instanceof AlphaPaintable && ((AlphaPaintable) c).getAlpha() < 1f) {
return false;
}
}
return true;
}
return false;
}
/**
* Overridden paint method to take into account the alpha setting.
*
* @param g
* the <code>Graphics</code> context in which to paint
*/
@Override
public void paint(Graphics g) {
//short circuit painting if no transparency
if (getAlpha() == 1f) {
super.paint(g);
} else {
//the component is translucent, so we need to render to
//an intermediate image before painting
// TODO should we cache this image? repaint to same image unless size changes?
BufferedImage img = GraphicsUtilities.createCompatibleTranslucentImage(getWidth(), getHeight());
Graphics2D gfx = img.createGraphics();
try {
super.paint(gfx);
} finally {
gfx.dispose();
}
Graphics2D g2d = (Graphics2D) g;
Composite oldComp = g2d.getComposite();
try {
Composite alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getEffectiveAlpha());
g2d.setComposite(alphaComp);
//TODO should we cache the image?
g2d.drawImage(img, null, 0, 0);
} finally {
g2d.setComposite(oldComp);
}
}
}
/**
* Overridden to provide Painter support. It will call backgroundPainter.paint()
* if it is not null, else it will call super.paintComponent().
*
* @param g
* the <code>Graphics</code> context in which to paint
*/
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
try {
SwingXUtilities.paintBackground(this, g2);
} finally {
g2.dispose();
}
getUI().paint(g, this);
}
} |
package com.continuuity.data2.transaction.persist;
import com.continuuity.api.common.Bytes;
import com.continuuity.common.io.BinaryDecoder;
import com.continuuity.common.io.BinaryEncoder;
import com.continuuity.common.io.Decoder;
import com.continuuity.common.io.Encoder;
import com.continuuity.data2.transaction.inmemory.ChangeId;
import com.continuuity.data2.transaction.inmemory.InMemoryTransactionManager;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.io.InputStream;
import java.io.OutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
/**
* Handles serialization/deserialization of a {@link com.continuuity.data2.transaction.persist.TransactionSnapshot} and
* its elements to {@code byte[]}.
*/
public abstract class AbstractSnapshotCodec {
private static final Logger LOG = LoggerFactory.getLogger(AbstractSnapshotCodec.class);
protected abstract int getVersion();
protected abstract NavigableMap<Long, InMemoryTransactionManager.InProgressTx> decodeInProgress(Decoder decoder)
throws IOException;
protected abstract void encodeInProgress(Encoder encoder,
Map<Long, InMemoryTransactionManager.InProgressTx> inProgress)
throws IOException;
/**
* Encodes a given {@code TransactionSnapshot} instance into a byte array. Can be reversed by calling
* {@link #decodeState(byte[])}.
* @param snapshot snapshot state to be serialized.
* @return a byte array representing the serialized {@code TransactionSnapshot} state.
*/
public byte[] encodeState(TransactionSnapshot snapshot) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
encodeState(bos, snapshot);
return bos.toByteArray();
} finally {
try {
bos.close();
} catch (IOException e) {
LOG.error("Unable to close output stream properly: ", e);
throw Throwables.propagate(e);
}
}
}
/**
* Encodes a given {@code TransactionSnapshot} instance into a byte array output stream.
* Can be reversed by calling {@link #decodeState(java.io.InputStream)}.
* @param snapshot snapshot state to be serialized.
* @return a byte array output stream containing the serialized {@code TransactionSnapshot} state.
*/
public void encodeState(OutputStream out, TransactionSnapshot snapshot) {
Encoder encoder = new BinaryEncoder(out);
try {
encoder.writeInt(getVersion());
encoder.writeLong(snapshot.getTimestamp());
encoder.writeLong(snapshot.getReadPointer());
encoder.writeLong(snapshot.getWritePointer());
// supporting old versions of codecs
writeAbsoleteAttributes(encoder);
encodeInvalid(encoder, snapshot.getInvalid());
encodeInProgress(encoder, snapshot.getInProgress());
encodeChangeSets(encoder, snapshot.getCommittingChangeSets());
encodeChangeSets(encoder, snapshot.getCommittedChangeSets());
} catch (IOException e) {
LOG.error("Unable to serialize transaction state: ", e);
throw Throwables.propagate(e);
}
}
/**
* Deserializes an encoded {@code TransactionSnapshot} back into its object representation. Reverses serialization
* performed by {@link #encodeState(com.continuuity.data2.transaction.persist.TransactionSnapshot)}.
* @param bytes the serialized {@code TransactionSnapshot} representation as a byte array.
* @return a {@code TransactionSnapshot} instance populated with the serialized values.
*/
public TransactionSnapshot decodeState(byte[] bytes) {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
try {
return decodeState(bis);
} finally {
try {
bis.close();
} catch (IOException e) {
LOG.error("Unable to close input stream properly: ", e);
throw Throwables.propagate(e);
}
}
}
/**
* Deserializes an encoded {@code TransactionSnapshot} back into its object representation. Reverses serialization
* performed by {@link #encodeState(OutputStream, com.continuuity.data2.transaction.persist.TransactionSnapshot)}.
* @param is the serialized {@code TransactionSnapshot} representation as an input stream.
* @return a {@code TransactionSnapshot} instance populated with the serialized values.
*/
public TransactionSnapshot decodeState(InputStream is) {
Decoder decoder = new BinaryDecoder(is);
try {
int persistedVersion = decoder.readInt();
if (persistedVersion != getVersion()) {
throw new RuntimeException("Can't decode state persisted with version " + persistedVersion + ". Expected " +
"version is " + getVersion());
}
} catch (IOException e) {
LOG.error("Unable to deserialize transaction state: ", e);
throw Throwables.propagate(e);
}
return decodePartialState(is);
}
/**
* Deserializes an encoded {@code TransactionSnapshot} from which the version is missing, back into its object
* representation. Reverses serialization performed by
* {@link #encodeState(OutputStream, com.continuuity.data2.transaction.persist.TransactionSnapshot)}.
* @param is the serialized {@code TransactionSnapshot} representation as an input stream.
* @return a {@code TransactionSnapshot} instance populated with the serialized values.
*/
public TransactionSnapshot decodePartialState(InputStream is) {
Decoder decoder = new BinaryDecoder(is);
try {
long timestamp = decoder.readLong();
long readPointer = decoder.readLong();
long writePointer = decoder.readLong();
// some attributes where removed during format change, luckily those stored at the end, so we just give a chance
// to skip them
readAbsoleteAttributes(decoder);
Collection<Long> invalid = decodeInvalid(decoder);
NavigableMap<Long, InMemoryTransactionManager.InProgressTx> inProgress = decodeInProgress(decoder);
NavigableMap<Long, Set<ChangeId>> committing = decodeChangeSets(decoder);
NavigableMap<Long, Set<ChangeId>> committed = decodeChangeSets(decoder);
return new TransactionSnapshot(timestamp, readPointer, writePointer, invalid, inProgress,
committing, committed);
} catch (IOException e) {
LOG.error("Unable to deserialize transaction state: ", e);
throw Throwables.propagate(e);
}
}
// todo: remove in next version that breaks compatibility of tx log
@Deprecated
protected void readAbsoleteAttributes(Decoder decoder) throws IOException {
// NOTHING by default
}
// todo: remove in next version that breaks compatibility of tx log
@Deprecated
protected void writeAbsoleteAttributes(Encoder encoder) throws IOException {
// NOTHING by default
}
private void encodeInvalid(Encoder encoder, Collection<Long> invalid) throws IOException {
if (!invalid.isEmpty()) {
encoder.writeInt(invalid.size());
for (long invalidTx : invalid) {
encoder.writeLong(invalidTx);
}
}
encoder.writeInt(0); // zero denotes end of list as per AVRO spec
}
private Collection<Long> decodeInvalid(Decoder decoder) throws IOException {
int size = decoder.readInt();
Collection<Long> invalid = Lists.newArrayListWithCapacity(size);
while (size != 0) { // zero denotes end of list as per AVRO spec
for (int remaining = size; remaining > 0; --remaining) {
invalid.add(decoder.readLong());
}
size = decoder.readInt();
}
return invalid;
}
private void encodeChangeSets(Encoder encoder, Map<Long, Set<ChangeId>> changes) throws IOException {
if (!changes.isEmpty()) {
encoder.writeInt(changes.size());
for (Map.Entry<Long, Set<ChangeId>> entry : changes.entrySet()) {
encoder.writeLong(entry.getKey());
encodeChanges(encoder, entry.getValue());
}
}
encoder.writeInt(0); // zero denotes end of list as per AVRO spec
}
private NavigableMap<Long, Set<ChangeId>> decodeChangeSets(Decoder decoder) throws IOException {
int size = decoder.readInt();
NavigableMap<Long, Set<ChangeId>> changeSets = new TreeMap<Long, Set<ChangeId>>();
while (size != 0) { // zero denotes end of list as per AVRO spec
for (int remaining = size; remaining > 0; --remaining) {
changeSets.put(decoder.readLong(), decodeChanges(decoder));
}
size = decoder.readInt();
}
return changeSets;
}
private void encodeChanges(Encoder encoder, Set<ChangeId> changes) throws IOException {
if (!changes.isEmpty()) {
encoder.writeInt(changes.size());
for (ChangeId change : changes) {
encoder.writeBytes(change.getKey());
}
}
encoder.writeInt(0); // zero denotes end of list as per AVRO spec
}
private Set<ChangeId> decodeChanges(Decoder decoder) throws IOException {
int size = decoder.readInt();
HashSet<ChangeId> changes = Sets.newHashSetWithExpectedSize(size);
while (size != 0) { // zero denotes end of list as per AVRO spec
for (int remaining = size; remaining > 0; --remaining) {
changes.add(new ChangeId(Bytes.toBytes(decoder.readBytes())));
}
size = decoder.readInt();
}
// todo is there an immutable hash set?
return changes;
}
} |
//$HeadURL$
package org.deegree.feature.xpath.node;
import javax.xml.namespace.QName;
import org.deegree.commons.tom.TypedObjectNode;
import org.deegree.commons.tom.gml.GMLObject;
import org.deegree.feature.Feature;
import org.deegree.geometry.Geometry;
public class GMLObjectNode<V extends GMLObject, P extends TypedObjectNode> extends ElementNode<V> {
private XPathNode<P> parentNode;
private V object;
public GMLObjectNode( XPathNode<P> parentNode, V object ) {
super( getName( object ) );
this.parentNode = parentNode;
this.object = object;
}
private static QName getName( GMLObject object ) {
if ( object.getType() != null ) {
return object.getType().getName();
}
if ( object instanceof Feature ) {
return ( (Feature) object ).getName();
} else if ( object instanceof Geometry ) {
// TODO should be covered by the type
return new QName ("GEOMETRY");
}
throw new IllegalArgumentException( "Creating GMLObjectNode from " + object.getClass()
+ " needs implementation." );
}
@Override
public XPathNode<P> getParent() {
return parentNode;
}
@Override
public V getValue() {
return object;
}
} |
package org.owasp.dependencycheck.data.update;
import org.owasp.dependencycheck.data.nvdcve.NvdCve12Handler;
import org.owasp.dependencycheck.data.nvdcve.NvdCve20Handler;
import org.owasp.dependencycheck.data.nvdcve.InvalidDataException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.owasp.dependencycheck.data.CachedWebDataSource;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.owasp.dependencycheck.data.UpdateException;
import org.owasp.dependencycheck.data.cpe.CpeIndexWriter;
import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.owasp.dependencycheck.utils.DownloadFailedException;
import org.owasp.dependencycheck.utils.Downloader;
import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.utils.InvalidSettingException;
import static org.owasp.dependencycheck.data.update.DataStoreMetaInfo.BATCH;
import static org.owasp.dependencycheck.data.update.DataStoreMetaInfo.MODIFIED;
/**
*
* @author Jeremy Long (jeremy.long@owasp.org)
*/
public class DatabaseUpdater implements CachedWebDataSource {
/**
* Utility to read and write meta-data about the data.
*/
private DataStoreMetaInfo properties = null;
/**
* Reference to the Cve Database.
*/
private CveDB cveDB = null;
/**
* Reference to the Cpe Index.
*/
private CpeIndexWriter cpeIndex = null;
/**
* A flag indicating whether or not the batch update should be performed.
*/
protected boolean doBatchUpdate;
/**
* Get the value of doBatchUpdate
*
* @return the value of doBatchUpdate
*/
protected boolean isDoBatchUpdate() {
return doBatchUpdate;
}
/**
* Set the value of doBatchUpdate
*
* @param doBatchUpdate new value of doBatchUpdate
*/
protected void setDoBatchUpdate(boolean doBatchUpdate) {
this.doBatchUpdate = doBatchUpdate;
}
/**
* <p>Downloads the latest NVD CVE XML file from the web and imports it into
* the current CVE Database.</p>
*
* @throws UpdateException is thrown if there is an error updating the
* database
*/
@Override
public void update() throws UpdateException {
doBatchUpdate = false;
properties = new DataStoreMetaInfo();
try {
final Map<String, NvdCveInfo> update = updateNeeded();
int maxUpdates = 0;
for (NvdCveInfo cve : update.values()) {
if (cve.getNeedsUpdate()) {
maxUpdates += 1;
}
}
if (maxUpdates > 3 && !properties.isBatchUpdateMode()) {
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
"NVD CVE requires several updates; this could take a couple of minutes.");
}
if (maxUpdates > 0 && !isDoBatchUpdate()) {
openDataStores();
}
if (properties.isBatchUpdateMode() && isDoBatchUpdate()) {
try {
performBatchUpdate();
openDataStores();
} catch (IOException ex) {
throw new UpdateException("Unable to perform batch update", ex);
}
}
int count = 0;
for (NvdCveInfo cve : update.values()) {
if (cve.getNeedsUpdate()) {
count += 1;
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
"Updating NVD CVE ({0} of {1})", new Object[]{count, maxUpdates});
URL url = new URL(cve.getUrl());
File outputPath = null;
File outputPath12 = null;
try {
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
"Downloading {0}", cve.getUrl());
outputPath = File.createTempFile("cve" + cve.getId() + "_", ".xml");
Downloader.fetchFile(url, outputPath);
url = new URL(cve.getOldSchemaVersionUrl());
outputPath12 = File.createTempFile("cve_1_2_" + cve.getId() + "_", ".xml");
Downloader.fetchFile(url, outputPath12);
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
"Processing {0}", cve.getUrl());
importXML(outputPath, outputPath12);
cveDB.commit();
cpeIndex.commit();
properties.save(cve);
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.INFO,
"Completed update {0} of {1}", new Object[]{count, maxUpdates});
} catch (FileNotFoundException ex) {
throw new UpdateException(ex);
} catch (ParserConfigurationException ex) {
throw new UpdateException(ex);
} catch (SAXException ex) {
throw new UpdateException(ex);
} catch (IOException ex) {
throw new UpdateException(ex);
} catch (SQLException ex) {
throw new UpdateException(ex);
} catch (DatabaseException ex) {
throw new UpdateException(ex);
} catch (ClassNotFoundException ex) {
throw new UpdateException(ex);
} finally {
boolean deleted = false;
try {
if (outputPath != null && outputPath.exists()) {
deleted = outputPath.delete();
}
} finally {
if (outputPath != null && (outputPath.exists() || !deleted)) {
outputPath.deleteOnExit();
}
}
try {
deleted = false;
if (outputPath12 != null && outputPath12.exists()) {
deleted = outputPath12.delete();
}
} finally {
if (outputPath12 != null && (outputPath12.exists() || !deleted)) {
outputPath12.deleteOnExit();
}
}
}
}
}
if (maxUpdates >= 1) { //ensure the modified file date gets written
properties.save(update.get(MODIFIED));
cveDB.cleanupDatabase();
}
if (update.get(BATCH) != null) {
properties.save(update.get(BATCH));
}
} catch (MalformedURLException ex) {
throw new UpdateException(ex);
} catch (DownloadFailedException ex) {
throw new UpdateException(ex);
} finally {
closeDataStores();
}
}
/**
* Imports the NVD CVE XML File into the Lucene Index.
*
* @param file the file containing the NVD CVE XML
* @param oldVersion contains the file containing the NVD CVE XML 1.2
* @throws ParserConfigurationException is thrown if there is a parser
* configuration exception
* @throws SAXException is thrown if there is a SAXException
* @throws IOException is thrown if there is a IO Exception
* @throws SQLException is thrown if there is a SQL exception
* @throws DatabaseException is thrown if there is a database exception
* @throws ClassNotFoundException thrown if the h2 database driver cannot be
* loaded
*/
private void importXML(File file, File oldVersion)
throws ParserConfigurationException, SAXException, IOException, SQLException, DatabaseException, ClassNotFoundException {
final SAXParserFactory factory = SAXParserFactory.newInstance();
final SAXParser saxParser = factory.newSAXParser();
final NvdCve12Handler cve12Handler = new NvdCve12Handler();
saxParser.parse(oldVersion, cve12Handler);
final Map<String, List<VulnerableSoftware>> prevVersionVulnMap = cve12Handler.getVulnerabilities();
final NvdCve20Handler cve20Handler = new NvdCve20Handler();
cve20Handler.setCveDB(cveDB);
cve20Handler.setPrevVersionVulnMap(prevVersionVulnMap);
cve20Handler.setCpeIndex(cpeIndex);
saxParser.parse(file, cve20Handler);
}
/**
* Deletes the existing data directories.
*
* @throws IOException thrown if the directory cannot be deleted
*/
protected void deleteExistingData() throws IOException {
File data = Settings.getFile(Settings.KEYS.CVE_DATA_DIRECTORY);
if (data.exists()) {
FileUtils.delete(data);
}
data = Settings.getFile(Settings.KEYS.CPE_DATA_DIRECTORY);
if (data.exists()) {
FileUtils.delete(data);
}
data = properties.getPropertiesFile();
if (data.exists()) {
FileUtils.delete(data);
}
}
private void performBatchUpdate() throws UpdateException {
if (properties.isBatchUpdateMode() && doBatchUpdate) {
final String batchSrc = Settings.getString(Settings.KEYS.BATCH_UPDATE_URL);
File tmp = null;
try {
deleteExistingData();
final File dataDirectory = CveDB.getDataDirectory().getParentFile();
final URL batchUrl = new URL(batchSrc);
if ("file".equals(batchUrl.getProtocol())) {
try {
tmp = new File(batchUrl.toURI());
} catch (URISyntaxException ex) {
final String msg = String.format("Invalid batch update URI: %s", batchSrc);
throw new UpdateException(msg, ex);
}
} else if ("http".equals(batchUrl.getProtocol())
|| "https".equals(batchUrl.getProtocol())) {
tmp = File.createTempFile("batch_", ".zip");
Downloader.fetchFile(batchUrl, tmp);
}
//TODO add FTP?
FileUtils.extractFiles(tmp, dataDirectory);
} catch (IOException ex) {
final String msg = String.format("IO Exception Occured performing batch update using: %s", batchSrc);
throw new UpdateException(msg, ex);
} finally {
if (tmp != null && !tmp.delete()) {
tmp.deleteOnExit();
}
}
}
}
/**
* Closes the CVE and CPE data stores.
*/
private void closeDataStores() {
if (cveDB != null) {
try {
cveDB.close();
} catch (Exception ignore) {
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINEST, "Error closing the cveDB", ignore);
}
}
if (cpeIndex != null) {
try {
cpeIndex.close();
} catch (Exception ignore) {
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINEST, "Error closing the cpeIndex", ignore);
}
}
}
/**
* Opens the CVE and CPE data stores.
*
* @throws UpdateException thrown if a data store cannot be opened
*/
private void openDataStores() throws UpdateException {
//open the cve and cpe data stores
try {
cveDB = new CveDB();
cveDB.open();
cpeIndex = new CpeIndexWriter();
cpeIndex.open();
} catch (IOException ex) {
closeDataStores();
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, "IO Error opening databases", ex);
throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
} catch (SQLException ex) {
closeDataStores();
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, "SQL Exception opening databases", ex);
throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
} catch (DatabaseException ex) {
closeDataStores();
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, "Database Exception opening databases", ex);
throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
} catch (ClassNotFoundException ex) {
closeDataStores();
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, "Class not found exception opening databases", ex);
throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
}
}
/**
* Determines if the index needs to be updated. This is done by fetching the
* NVD CVE meta data and checking the last update date. If the data needs to
* be refreshed this method will return the NvdCveUrl for the files that
* need to be updated.
*
* @return the NvdCveUrl of the files that need to be updated.
* @throws MalformedURLException is thrown if the URL for the NVD CVE Meta
* data is incorrect.
* @throws DownloadFailedException is thrown if there is an error.
* downloading the NVD CVE download data file.
* @throws UpdateException Is thrown if there is an issue with the last
* updated properties file.
*/
private Map<String, NvdCveInfo> updateNeeded() throws MalformedURLException, DownloadFailedException, UpdateException {
Map<String, NvdCveInfo> currentlyPublished;
try {
currentlyPublished = retrieveCurrentTimestampsFromWeb();
} catch (InvalidDataException ex) {
final String msg = "Unable to retrieve valid timestamp from nvd cve downloads page";
Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.FINE, msg, ex);
throw new DownloadFailedException(msg, ex);
} catch (InvalidSettingException ex) {
Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.FINE, "Invalid setting found when retrieving timestamps", ex);
throw new DownloadFailedException("Invalid settings", ex);
}
if (currentlyPublished == null) {
throw new DownloadFailedException("Unable to retrieve the timestamps of the currently published NVD CVE data");
}
// final File cpeDataDirectory;
// try {
// cpeDataDirectory = CveDB.getDataDirectory();
// } catch (IOException ex) {
// String msg;
// try {
// msg = String.format("Unable to create the CVE Data Directory '%s'",
// Settings.getFile(Settings.KEYS.CVE_DATA_DIRECTORY).getCanonicalPath());
// } catch (IOException ex1) {
// msg = String.format("Unable to create the CVE Data Directory, this is likely a configuration issue: '%s%s%s'",
// Settings.getString(Settings.KEYS.DATA_DIRECTORY, ""),
// File.separator,
// Settings.getString(Settings.KEYS.CVE_DATA_DIRECTORY, ""));
// throw new UpdateException(msg, ex);
if (!properties.isEmpty()) {
try {
boolean deleteAndRecreate = false;
float version;
if (properties.getProperty("version") == null) {
deleteAndRecreate = true;
} else {
try {
version = Float.parseFloat(properties.getProperty("version"));
final float currentVersion = Float.parseFloat(CveDB.DB_SCHEMA_VERSION);
if (currentVersion > version) {
deleteAndRecreate = true;
}
} catch (NumberFormatException ex) {
deleteAndRecreate = true;
}
}
NvdCveInfo batchInfo = currentlyPublished.get(BATCH);
if (properties.isBatchUpdateMode() && batchInfo != null) {
final long lastUpdated = Long.parseLong(properties.getProperty(DataStoreMetaInfo.BATCH, "0"));
if (lastUpdated != batchInfo.getTimestamp()) {
deleteAndRecreate = true;
}
}
if (deleteAndRecreate) {
setDoBatchUpdate(properties.isBatchUpdateMode());
try {
deleteExistingData();
} catch (IOException ex) {
final String msg = "Unable to delete existing data";
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.WARNING, msg);
Logger.getLogger(DatabaseUpdater.class.getName()).log(Level.FINE, null, ex);
}
return currentlyPublished;
}
final long lastUpdated = Long.parseLong(properties.getProperty(DataStoreMetaInfo.LAST_UPDATED, "0"));
final Date now = new Date();
final int days = Settings.getInt(Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS, 7);
final int start = Settings.getInt(Settings.KEYS.CVE_START_YEAR, 2002);
final int end = Calendar.getInstance().get(Calendar.YEAR);
if (lastUpdated == currentlyPublished.get(MODIFIED).getTimestamp()) {
currentlyPublished.clear(); //we don't need to update anything.
setDoBatchUpdate(properties.isBatchUpdateMode());
} else if (withinRange(lastUpdated, now.getTime(), days)) {
currentlyPublished.get(MODIFIED).setNeedsUpdate(true);
if (properties.isBatchUpdateMode()) {
setDoBatchUpdate(false);
} else {
for (int i = start; i <= end; i++) {
currentlyPublished.get(String.valueOf(i)).setNeedsUpdate(false);
}
}
} else if (properties.isBatchUpdateMode()) {
currentlyPublished.get(MODIFIED).setNeedsUpdate(true);
setDoBatchUpdate(true);
} else { //we figure out which of the several XML files need to be downloaded.
currentlyPublished.get(MODIFIED).setNeedsUpdate(false);
for (int i = start; i <= end; i++) {
final NvdCveInfo cve = currentlyPublished.get(String.valueOf(i));
long currentTimestamp = 0;
try {
currentTimestamp = Long.parseLong(properties.getProperty(DataStoreMetaInfo.LAST_UPDATED_BASE + String.valueOf(i), "0"));
} catch (NumberFormatException ex) {
final String msg = String.format("Error parsing '%s' '%s' from nvdcve.lastupdated",
DataStoreMetaInfo.LAST_UPDATED_BASE, String.valueOf(i));
Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.FINE, msg, ex);
}
if (currentTimestamp == cve.getTimestamp()) {
cve.setNeedsUpdate(false); //they default to true.
}
}
}
} catch (NumberFormatException ex) {
Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.WARNING, "An invalid schema version or timestamp exists in the data.properties file.");
Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.FINE, null, ex);
setDoBatchUpdate(properties.isBatchUpdateMode());
}
} else {
setDoBatchUpdate(properties.isBatchUpdateMode());
}
return currentlyPublished;
}
/**
* Determines if the epoch date is within the range specified of the
* compareTo epoch time. This takes the (compareTo-date)/1000/60/60/24 to
* get the number of days. If the calculated days is less then the range the
* date is considered valid.
*
* @param date the date to be checked.
* @param compareTo the date to compare to.
* @param range the range in days to be considered valid.
* @return whether or not the date is within the range.
*/
private boolean withinRange(long date, long compareTo, int range) {
final double differenceInDays = (compareTo - date) / 1000.0 / 60.0 / 60.0 / 24.0;
return differenceInDays < range;
}
/**
* Retrieves the timestamps from the NVD CVE meta data file.
*
* @return the timestamp from the currently published nvdcve downloads page
* @throws MalformedURLException thrown if the URL for the NVD CCE Meta data
* is incorrect.
* @throws DownloadFailedException thrown if there is an error downloading
* the nvd cve meta data file
* @throws InvalidDataException thrown if there is an exception parsing the
* timestamps
* @throws InvalidSettingException thrown if the settings are invalid
*/
private Map<String, NvdCveInfo> retrieveCurrentTimestampsFromWeb()
throws MalformedURLException, DownloadFailedException, InvalidDataException, InvalidSettingException {
final Map<String, NvdCveInfo> map = new TreeMap<String, NvdCveInfo>();
String retrieveUrl = Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL);
if (retrieveUrl == null && properties.isBatchUpdateMode()) {
NvdCveInfo item = new NvdCveInfo();
retrieveUrl = Settings.getString(Settings.KEYS.BATCH_UPDATE_URL);
if (retrieveUrl == null) {
final String msg = "Invalid configuration - neither the modified or batch update URLs are specified in the configuration.";
Logger.getLogger(DataStoreMetaInfo.class.getName()).log(Level.SEVERE, msg);
throw new InvalidSettingException(msg);
}
item.setTimestamp(Downloader.getLastModified(new URL(retrieveUrl)));
item.setId(BATCH);
item.setNeedsUpdate(false);
map.put(BATCH, item);
} else {
NvdCveInfo item = new NvdCveInfo();
item.setNeedsUpdate(false); //the others default to true, to make life easier later this should default to false.
item.setId(MODIFIED);
item.setUrl(retrieveUrl);
item.setOldSchemaVersionUrl(Settings.getString(Settings.KEYS.CVE_MODIFIED_12_URL));
item.setTimestamp(Downloader.getLastModified(new URL(retrieveUrl)));
map.put(MODIFIED, item);
//only add these urls if we are not in batch mode
if (!properties.isBatchUpdateMode()) {
final int start = Settings.getInt(Settings.KEYS.CVE_START_YEAR);
final int end = Calendar.getInstance().get(Calendar.YEAR);
final String baseUrl20 = Settings.getString(Settings.KEYS.CVE_SCHEMA_2_0);
final String baseUrl12 = Settings.getString(Settings.KEYS.CVE_SCHEMA_1_2);
for (int i = start; i <= end; i++) {
retrieveUrl = String.format(baseUrl20, i);
item = new NvdCveInfo();
item.setId(Integer.toString(i));
item.setUrl(retrieveUrl);
item.setOldSchemaVersionUrl(String.format(baseUrl12, i));
item.setTimestamp(Downloader.getLastModified(new URL(retrieveUrl)));
map.put(item.getId(), item);
}
}
}
return map;
}
} |
package dev.jeka.core.api.tooling.eclipse;
import dev.jeka.core.api.depmanagement.*;
import dev.jeka.core.api.file.JkPathTree;
import dev.jeka.core.api.java.JkJavaVersion;
import dev.jeka.core.api.java.project.JkJavaProjectIde;
import dev.jeka.core.api.java.project.JkProjectSourceLayout;
import dev.jeka.core.api.system.JkLocator;
import dev.jeka.core.api.utils.JkUtilsIterable;
import dev.jeka.core.api.utils.JkUtilsString;
import dev.jeka.core.api.utils.JkUtilsThrowable;
import dev.jeka.core.tool.JkConstants;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
/**
* Provides method to generate Eclipse .classpath metadata files.
*/
public final class JkEclipseClasspathGenerator {
private static final String ENCODING = "UTF-8";
private final JkProjectSourceLayout sourceLayout;
private final JkDependencyResolver dependencyResolver;
private final JkDependencySet dependencies;
// content for build class only
private JkDependencyResolver runDependencyResolver;
private JkDependencySet runDependencies;
// content for build class only
private List<Path> importedProjects = new LinkedList<>();
private Map<JkDependency, Properties> attributes = new HashMap<>();
private Map<JkDependency, Properties> accessRules = new HashMap<>();
private boolean includeJavadoc = true;
private final JkJavaVersion sourceVersion;
private String jreContainer;
/**
* Use JEKA_REPO and JEKA_HOME variable instead of absolute path
*/
private boolean usePathVariables;
/**
* Constructs a {@link JkEclipseClasspathGenerator}.
*/
private JkEclipseClasspathGenerator(JkProjectSourceLayout sourceLayout, JkDependencySet dependencies,
JkDependencyResolver resolver, JkJavaVersion sourceVersion) {
this.sourceLayout = sourceLayout;
this.dependencies = dependencies;
this.dependencyResolver = resolver;
this.sourceVersion = sourceVersion;
}
/**
* Constructs a {@link JkEclipseClasspathGenerator}.
*/
public static JkEclipseClasspathGenerator of(JkProjectSourceLayout sourceLayout, JkDependencySet dependencies,
JkDependencyResolver resolver, JkJavaVersion sourceVersion) {
return new JkEclipseClasspathGenerator(sourceLayout, dependencies, resolver, sourceVersion);
}
/**
* Constructs a {@link JkEclipseClasspathGenerator}.
*/
public static JkEclipseClasspathGenerator of(JkJavaProjectIde projectDef) {
return new JkEclipseClasspathGenerator(projectDef.getSourceLayout(), projectDef.getDependencies(),
projectDef.getDependencyResolver(), projectDef.getSourceVersion());
}
private boolean hasBuildDef() {
return new File(this.sourceLayout.getBaseDir().toFile(), JkConstants.DEF_DIR).exists();
}
/**
* Set whether or not generated .classpath file should contains javadoc link for libraries.
*/
public JkEclipseClasspathGenerator setIncludeJavadoc(boolean includeJavadoc) {
this.includeJavadoc = includeJavadoc;
return this;
}
/**
* Specifies the exact string to use as jre container.
*/
public JkEclipseClasspathGenerator setJreContainer(String jreContainer) {
this.jreContainer = jreContainer;
return this;
}
/**
* If <code>true</code> dependencies path will use JEKA_HOME and JEKA_REPO classpath variable instead of absolute paths.
*/
public JkEclipseClasspathGenerator setUsePathVariables(boolean usePathVariables) {
this.usePathVariables = usePathVariables;
return this;
}
/**
* If the build script depends on build script located in another projects, you must add those projects here.
*/
public JkEclipseClasspathGenerator setImportedProjects(List<Path> importedBuildProjects) {
this.importedProjects = importedBuildProjects;
return this;
}
/**
* If the build script depends on external libraries, you must set the resolver of this dependencies here.
*/
public JkEclipseClasspathGenerator setRunDependencies(JkDependencyResolver buildDependencyResolver,
JkDependencySet buildDependencies) {
this.runDependencyResolver = buildDependencyResolver;
this.runDependencies = buildDependencies;
return this;
}
/**
* For the specified dependency, specify a child attribute tag to add to the mapping classpathentry tag.
* @param dependency The dependency paired to the classpathentry we want generate `<attributes></attributes>` children
* for. It can be a {@link dev.jeka.core.api.depmanagement.JkModuleDependency} or a
* {@link dev.jeka.core.api.depmanagement.JkFileSystemDependency}.
* If it is a module dependency, it can be a direct or transitive dependency and only group:name
* is relevant.
*/
public JkEclipseClasspathGenerator addAttribute(JkDependency dependency, String name, String value) {
this.attributes.putIfAbsent(dependency, new Properties());
this.attributes.get(dependency).put(name, value);
return this;
}
/**
* @See #addAttribute.
*/
public JkEclipseClasspathGenerator addAttributes(JkDependency dependency, Properties attributes) {
this.attributes.putIfAbsent(dependency, new Properties());
this.attributes.get(dependency).putAll(attributes);
return this;
}
/**
* For the specified dependency, specify a child accessrule tag to add to the mapping classpathentry tag.
* @param dependency The dependency paired to the classpathentry we want generate `<attributes></attributes>` children
* for. It can be a {@link dev.jeka.core.api.depmanagement.JkModuleDependency} or a
* {@link dev.jeka.core.api.depmanagement.JkFileSystemDependency}.
* If it is a module dependency, it can be a direct or transitive dependency and only group:name
* is relevant.
*/
public JkEclipseClasspathGenerator addAccessRule(JkDependency dependency, String kind, String pattern) {
this.accessRules.putIfAbsent(dependency, new Properties());
this.accessRules.get(dependency).put(kind, pattern);
return this;
}
/**
* @see #addAccessRule(JkDependency, String, String)
*/
public JkEclipseClasspathGenerator addAccessRules(JkDependency dependency, Properties rules) {
this.accessRules.putIfAbsent(dependency, new Properties());
this.accessRules.get(dependency).putAll(rules);
return this;
}
/**
* Generate the .classpath file
*/
public String generate() {
try {
return _generate();
} catch (final Exception e) {
throw JkUtilsThrowable.unchecked(e);
}
}
private String _generate() throws IOException, XMLStreamException, FactoryConfigurationError {
final ByteArrayOutputStream fos = new ByteArrayOutputStream();
final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fos, ENCODING);
writer.writeStartDocument(ENCODING, "1.0");
writer.writeCharacters("\n");
writer.writeStartElement("classpath");
writer.writeCharacters("\n");
final Set<String> paths = new HashSet<>();
// Write sources for build classes
if (hasBuildDef() && new File(sourceLayout.getBaseDir().toFile(), JkConstants.DEF_DIR).exists()) {
writer.writeCharacters("\t");
writeClasspathEl(writer, "kind", "src",
"including", "**/*",
"path", JkConstants.DEF_DIR);
}
generateSrcAndTestSrc(writer);
// write entries for project importedRuns
for (final Path projectFile : this.importedProjects) {
if (!paths.add(projectFile.toAbsolutePath().toString())) {
continue;
}
writer.writeCharacters("\t");
writeClasspathEl(writer, "combineaccessrules", "false", "kind", "src", "exported", "true",
"path", "/" + projectFile.getFileName().toString());
}
if (this.dependencyResolver != null) {
writeDependenciesEntries(writer, this.dependencies, this.dependencyResolver, paths);
}
writeJre(writer);
// add build dependencies
if (hasBuildDef() && runDependencyResolver != null) {
writeDependenciesEntries(writer, runDependencies, runDependencyResolver, paths);
}
// Write output
writer.writeCharacters("\t");
writeClasspathEl(writer, "kind", "output", "path", "bin");
// Writer doc footer
writer.writeEndDocument();
writer.flush();
writer.close();
return fos.toString(ENCODING);
}
/** convenient method to write classpath element shorter */
private static void writeClasspathEl(XMLStreamWriter writer, String... items) throws XMLStreamException {
final Map<String, String> map = JkUtilsIterable.mapOfAny((Object[]) items);
writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY);
for (final Map.Entry<String, String> entry : map.entrySet()) {
writer.writeAttribute(entry.getKey(), entry.getValue());
}
writer.writeCharacters("\n");
}
private static String eclipseJavaVersion(JkJavaVersion compilerVersion) {
if (JkJavaVersion.V1_3.equals(compilerVersion)) {
return "J2SE-1.3";
}
if (JkJavaVersion.V1_4.equals(compilerVersion)) {
return "J2SE-1.4";
}
if (JkJavaVersion.V5.equals(compilerVersion)) {
return "J2SE-1.5";
}
if (JkJavaVersion.V6.equals(compilerVersion)) {
return "JavaSE-1.6";
}
if (JkJavaVersion.V7.equals(compilerVersion)) {
return "JavaSE-1.7";
}
if (JkJavaVersion.V8.equals(compilerVersion)) {
return "JavaSE-1.8";
}
return "JavaSE-" + compilerVersion.get();
}
private void writeProjectEntryIfNeeded(Path projectDir, XMLStreamWriter writer, Set<String> paths) throws XMLStreamException {
if (paths.add(projectDir.toAbsolutePath().toString())) {
writer.writeCharacters("\t");
writeClasspathEl(writer, "kind", "src", "exported", "true",
"path", "/" + projectDir.getFileName().toString());
}
}
private void writeFileDepsEntries(XMLStreamWriter writer, Iterable<Path> fileDeps, Set<String> paths,
Properties attributeProps, Properties accessRuleProps) throws XMLStreamException {
for (final Path file : fileDeps) {
writeFileEntry(file, writer, paths, attributeProps, accessRuleProps);
}
}
private void writeJre(XMLStreamWriter writer) throws XMLStreamException {
writer.writeCharacters("\t");
writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY);
writer.writeAttribute("kind", "con");
final String container;
if (jreContainer != null) {
container = jreContainer;
} else {
if (sourceVersion != null) {
container = "org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/"
+ eclipseJavaVersion(sourceVersion);
} else {
container = "org.eclipse.jdt.launching.JRE_CONTAINER";
}
}
writer.writeAttribute("path", container);
writer.writeCharacters("\n");
}
private void writeFileEntry(Path file, XMLStreamWriter writer, Set<String> paths, Properties attributeProps,
Properties accessRuleProps)
throws XMLStreamException {
final String name = JkUtilsString.substringBeforeLast(file.getFileName().toString(), ".jar");
Path source = file.resolveSibling(name + "-sources.jar");
if (!Files.exists(source)) {
source = file.resolveSibling("../../libs-sources/" + name + "-sources.jar");
}
if (!Files.exists(source)) {
source = file.resolveSibling("libs-sources/" + name + "-sources.jar");
}
Path javadoc = file.resolveSibling(name + "-javadoc.jar");
if (!Files.exists(javadoc)) {
javadoc = file.resolveSibling("../../libs-javadoc/" + name + "-javadoc.jar");
}
if (!Files.exists(javadoc)) {
javadoc = file.resolveSibling("libs-javadoc/" + name + "-javadoc.jar");
}
if (Files.exists(javadoc) && includeJavadoc) {
attributeProps.put("javadoc_location", javadocAttributeValue(javadoc));
}
writeClasspathEl(writer, file, source, attributeProps, accessRuleProps, paths);
}
private void generateSrcAndTestSrc(XMLStreamWriter writer) throws XMLStreamException {
final Set<String> sourcePaths = new HashSet<>();
// Test Sources
for (final JkPathTree fileTree : sourceLayout.getTests().and(sourceLayout.getTestResources()).getPathTrees()) {
if (!fileTree.exists()) {
continue;
}
final String path = sourceLayout.getBaseDir().relativize(fileTree.getRoot()).toString().replace(File.separator, "/");
if (sourcePaths.contains(path)) {
continue;
}
sourcePaths.add(path);
writer.writeCharacters("\t");
writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY);
writer.writeAttribute("kind", "src");
writeIncludingExcluding(writer, fileTree);
writer.writeAttribute("path", path);
writer.writeCharacters("\n");
}
// Sources
for (final JkPathTree fileTree : sourceLayout.getSources().and(sourceLayout.getResources()).getPathTrees()) {
if (!fileTree.exists()) {
continue;
}
final String path = relativePathIfPossible(sourceLayout.getBaseDir(), fileTree.getRoot()).toString().replace(File.separator, "/");
if (sourcePaths.contains(path)) {
continue;
}
sourcePaths.add(path);
writer.writeCharacters("\t");
writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY);
writer.writeAttribute("kind", "src");
writeIncludingExcluding(writer, fileTree);
writer.writeAttribute("path", path);
writer.writeCharacters("\n");
}
}
private static Path relativePathIfPossible(Path base, Path candidate) {
if (!candidate.startsWith(base)) {
return candidate.toAbsolutePath().normalize();
}
return base.relativize(candidate);
}
private void writeIncludingExcluding(XMLStreamWriter writer, JkPathTree fileTree) throws XMLStreamException {
final String including = "";
if (!JkUtilsString.isBlank(including)) {
writer.writeAttribute("including", including);
}
final String excluding = "";
if (!JkUtilsString.isBlank(excluding)) {
writer.writeAttribute("excluding", excluding);
}
}
private void writeDependenciesEntries(XMLStreamWriter writer, JkDependencySet dependencies,
JkDependencyResolver resolver, Set<String> allPaths) throws XMLStreamException {
final JkResolveResult resolveResult = resolver.resolve(dependencies);
final JkRepoSet repos = resolver.getRepos();
for (final JkDependencyNode node : resolveResult.getDependencyTree().toFlattenList()) {
// Maven dependency
if (node.isModuleNode()) {
final JkDependencyNode.JkModuleNodeInfo moduleNodeInfo = node.getModuleInfo();
JkDependency dependency = JkModuleDependency.of(moduleNodeInfo.getModuleId().getGroupAndName());
Properties attributeProps = copyOfPropsOf(dependency, this.attributes);
Properties accessruleProps = copyOfPropsOf(dependency, this.accessRules);
writeModuleEntry(writer,
moduleNodeInfo.getResolvedVersionedModule(),
moduleNodeInfo.getFiles(), repos, allPaths, attributeProps, accessruleProps);
// File dependencies (file system + computed)
} else {
final JkDependencyNode.JkFileNodeInfo fileNodeInfo = (JkDependencyNode.JkFileNodeInfo) node.getNodeInfo();
if (fileNodeInfo.isComputed()) {
final JkComputedDependency computedDependency = fileNodeInfo.computationOrigin();
final Path ideProjectBaseDir = computedDependency.getIdeProjectBaseDir();
if (ideProjectBaseDir != null) {
if (!allPaths.contains(ideProjectBaseDir.toAbsolutePath().toString())) {
writeProjectEntryIfNeeded(ideProjectBaseDir, writer, allPaths);
}
} else {
writeFileDepsEntries(writer, node.getResolvedFiles(), allPaths, new Properties(), new Properties());
}
} else {
JkDependency fileDep = JkFileSystemDependency.of(fileNodeInfo.getFiles());
Properties attributeProps = copyOfPropsOf(fileDep, this.attributes);
Properties accessRuleProps = copyOfPropsOf(fileDep, this.accessRules);
writeFileDepsEntries(writer, node.getResolvedFiles(), allPaths, attributeProps, accessRuleProps);
}
}
}
}
private void writeModuleEntry(XMLStreamWriter writer, JkVersionedModule versionedModule, Iterable<Path> files,
JkRepoSet repos, Set<String> paths, Properties attributeProps,
Properties accessRuleProps) throws XMLStreamException {
final Path source = repos.get(JkModuleDependency.of(versionedModule).withClassifier("sources"));
Path javadoc = null;
if (source == null || !Files.exists(source) || this.includeJavadoc) {
javadoc = repos.get(JkModuleDependency.of(versionedModule).withClassifier("javadoc"));
}
if (javadoc != null) {
attributeProps.put("javadoc_location", javadocAttributeValue(javadoc));
}
for (final Path file : files) {
writeClasspathEl(writer, file, source, attributeProps, accessRuleProps, paths);
}
}
private void writeClasspathEl(XMLStreamWriter writer, Path bin, Path source, Properties attributeProps,
Properties accesRuleProps, Set<String> paths)
throws XMLStreamException {
String binPath = bin.toAbsolutePath().toString();
if (!paths.add(binPath)) {
return;
}
boolean usePathVariable = usePathVariables && bin.startsWith(JkLocator.getJekaUserHomeDir());
boolean isVar = true;
if (usePathVariable) {
binPath = DotClasspathModel.JEKA_USER_HOME + "/" + JkLocator.getJekaUserHomeDir().relativize(bin).toString();
} else if (usePathVariables && bin.startsWith(JkLocator.getJekaHomeDir())) {
binPath = DotClasspathModel.JEKA_HOME + "/" + JkLocator.getJekaHomeDir().relativize(bin).toString();
} else {
isVar = false;
binPath = relativePathIfPossible(sourceLayout.getBaseDir(), bin).toString();
}
binPath = binPath.replace(File.separator, "/");
writer.writeCharacters("\t");
boolean emptyTag = attributeProps.isEmpty() && accesRuleProps.isEmpty();
if (emptyTag) {
writer.writeEmptyElement(DotClasspathModel.CLASSPATHENTRY);
} else {
writer.writeStartElement(DotClasspathModel.CLASSPATHENTRY);
}
writer.writeAttribute("kind", isVar ? "var" : "lib");
writer.writeAttribute("path", binPath);
writer.writeAttribute("exported", "true");
if (source != null && Files.exists(source)) {
String srcPath;
if (usePathVariables && source.startsWith(JkLocator.getJekaUserHomeDir())) {
srcPath = DotClasspathModel.JEKA_USER_HOME + "/" + JkLocator.getJekaUserHomeDir().relativize(source).toString();
} else if (usePathVariables && source.startsWith(JkLocator.getJekaHomeDir())) {
srcPath = DotClasspathModel.JEKA_HOME + "/" + JkLocator.getJekaHomeDir().relativize(source).toString();
} else {
srcPath = relativePathIfPossible(sourceLayout.getBaseDir(), source).toString();
}
srcPath = srcPath.replace(File.separator, "/");
writer.writeAttribute("sourcepath", srcPath);
}
writeClasspathentryChildAttributes(writer, attributeProps);
writeClasspathentryChildAccessRules(writer, accesRuleProps);
if (!emptyTag) {
writer.writeCharacters("\n\t");
writer.writeEndElement();
}
writer.writeCharacters("\n");
}
private static String javadocAttributeValue(Path javadocPath) {
return "jar:file:/" + javadocPath.toAbsolutePath().normalize().toString()
.replace(File.separator, "/") + "!/";
}
private void writeClasspathentryChildAttributes(XMLStreamWriter writer, Properties props) throws XMLStreamException {
if (props == null || props.isEmpty()) {
return;
}
writer.writeCharacters("\n\t\t");
writer.writeStartElement("attributes");
for (String key : props.stringPropertyNames()) {
writer.writeCharacters("\n\t\t\t");
String value = props.getProperty(key);
writer.writeEmptyElement("attribute");
writer.writeAttribute("name", key);
writer.writeAttribute("value", value);
}
writer.writeCharacters("\n\t\t");
writer.writeEndElement();
}
private void writeClasspathentryChildAccessRules(XMLStreamWriter writer, Properties props) throws XMLStreamException {
if (props == null || props.isEmpty()) {
return;
}
writer.writeCharacters("\n\t\t");
writer.writeStartElement("accessrules");
for (String key : props.stringPropertyNames()) {
writer.writeCharacters("\n\t\t\t");
String value = props.getProperty(key);
writer.writeEmptyElement("accessrule");
writer.writeAttribute("kind", key);
writer.writeAttribute("pattern", value);
}
writer.writeCharacters("\n\t\t");
writer.writeEndElement();
}
private static Properties copyOfPropsOf(JkDependency dependency, Map<JkDependency, Properties> propMap) {
JkDependency key = findMatchingKey(dependency, propMap.keySet());
if (key == null) {
return new Properties();
}
Properties props = propMap.get(key);
Properties result = new Properties();
result.putAll(props);
return result;
}
private static JkDependency findMatchingKey(JkDependency dep1, Collection<JkDependency> deps) {
return deps.stream().filter(dep -> depsMatchForExtraAttributes(dep1, dep)).findFirst().orElse(null);
}
private static boolean depsMatchForExtraAttributes(JkDependency dep1, JkDependency dep2) {
if (dep1 instanceof JkModuleDependency) {
if (dep2 instanceof JkModuleDependency) {
JkModuleDependency modDep1 = (JkModuleDependency) dep1;
JkModuleDependency modDep2 = (JkModuleDependency) dep2;
return modDep1.getModuleId().equals(modDep2.getModuleId());
}
return false;
}
if (dep1 instanceof JkFileDependency) {
if (dep2 instanceof JkFileSystemDependency) {
return dep1.equals(dep2);
}
}
return false;
}
} |
package com.orientechnologies.distribution.integration;
import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
public class OGitHubIssuesIT extends OIntegrationTestTemplate {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
String database = this.getClass().getName();
if (!orientDB.exists(database)) {
orientDB.create(database, ODatabaseType.PLOCAL);
}
db = orientDB.open(database, "admin", "admin");
}
@Test
public void Issue7249() throws Exception {
db.command("CREATE CLASS t7249Profiles EXTENDS V;");
db.command("CREATE CLASS t7249HasFriend EXTENDS E;");
db.command("INSERT INTO t7249Profiles SET Name = 'Santo';");
db.command("INSERT INTO t7249Profiles SET Name = 'Luca';");
db.command("INSERT INTO t7249Profiles SET Name = 'Luigi';");
db.command("INSERT INTO t7249Profiles SET Name = 'Colin';");
db.command("INSERT INTO t7249Profiles SET Name = 'Enrico';");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Luca');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Luigi');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Colin');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Enrico') TO (SELECT FROM t7249Profiles WHERE Name='Santo');");
List<OResult> results = db.query("SELECT in('t7249HasFriend').size() as InFriendsNumber FROM t7249Profiles WHERE Name='Santo'")
.stream().collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 1, results.get(0).getProperty("InFriendsNumber"));
results = db.query("SELECT out('t7249HasFriend').size() as OutFriendsNumber FROM t7249Profiles WHERE Name='Santo'").stream()
.collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 3, results.get(0).getProperty("OutFriendsNumber"));
results = db.query("SELECT both('t7249HasFriend').size() as TotalFriendsNumber FROM t7249Profiles WHERE Name='Santo'").stream()
.collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 4, results.get(0).getProperty("TotalFriendsNumber"));
}
@Test
public void Issue7256() throws Exception {
db.command("CREATE CLASS t7265Customers EXTENDS V;");
db.command("CREATE CLASS t7265Services EXTENDS V;");
db.command("CREATE CLASS t7265Hotels EXTENDS V, t7265Services;");
db.command("CREATE CLASS t7265Restaurants EXTENDS V, t7265Services;");
db.command("CREATE CLASS t7265Countries EXTENDS V;");
db.command("CREATE CLASS t7265IsFromCountry EXTENDS E;");
db.command("CREATE CLASS t7265HasUsedService EXTENDS E;");
db.command("CREATE CLASS t7265HasStayed EXTENDS E, t7265HasUsedService;");
db.command("CREATE CLASS t7265HasEaten EXTENDS E, t7265HasUsedService;");
db.command("INSERT INTO t7265Customers SET OrderedId = 1, Phone = '+1400844724';");
db.command("INSERT INTO t7265Hotels SET Id = 1, Name = 'Best Western Ascott', Type = 'hotel';");
db.command("INSERT INTO t7265Restaurants SET Id = 1, Name = 'La Brasserie de Milan', Type = 'restaurant';");
db.command("INSERT INTO t7265Countries SET Id = 1, Code = 'AD', Name = 'Andorra';");
db.command(
"CREATE EDGE t7265HasEaten FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Restaurants WHERE Id=1);");
db.command(
"CREATE EDGE t7265HasStayed FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Hotels WHERE Id=1);");
db.command(
"CREATE EDGE t7265IsFromCountry FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Countries WHERE Id=1);");
OResultSet results = db.query(
"MATCH {class: t7265Customers, as: customer, where: (OrderedId=1)}--{Class: t7265Services, as: service} RETURN service.Name");
assertThat(results).hasSize(2);
}
} |
package com.liferay.lms.learningactivity.questiontype;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.portlet.ActionRequest;
import com.liferay.lms.model.TestAnswer;
import com.liferay.lms.model.TestQuestion;
import com.liferay.lms.service.LearningActivityLocalServiceUtil;
import com.liferay.lms.service.LearningActivityTryLocalServiceUtil;
import com.liferay.lms.service.TestAnswerLocalService;
import com.liferay.lms.service.TestAnswerLocalServiceUtil;
import com.liferay.lms.service.TestQuestionLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.SAXReaderUtil;
import com.liferay.portal.theme.ThemeDisplay;
public class DraganddropQuestionType extends BaseQuestionType {
private static final long serialVersionUID = 1L;
public long getTypeId(){
return 4;
}
public String getName() {
return "draganddrop";
}
public String getTitle(Locale locale) {
return LanguageUtil.get(locale, "draganddrop.title");
}
public String getDescription(Locale locale) {
return LanguageUtil.get(locale, "draganddrop.description");
}
public String getURLEdit(){
return "/html/execactivity/test/admin/editAnswerOptions.jsp";
}
public String getURLNew(){
return "/html/execactivity/test/admin/popups/options.jsp";
}
public long correct(ActionRequest actionRequest, long questionId){
List<TestAnswer> testAnswers = new ArrayList<TestAnswer>();
try {
testAnswers.addAll(TestAnswerLocalServiceUtil.getTestAnswersByQuestionId(questionId));
} catch (SystemException e) {
e.printStackTrace();
}
//me quedo solo con un array con la solucion
for(java.util.ListIterator<TestAnswer> itr = testAnswers.listIterator(); itr.hasNext();){
TestAnswer tanswer = itr.next();
if(!tanswer.isIsCorrect()) itr.remove();
}
List<Long> answersId = new ArrayList<Long>();
for(int i=0;i<testAnswers.size();i++){
answersId.add(ParamUtil.getLong(actionRequest, "question_"+questionId+"_"+i+"hidden"));
}
if(!isCorrect(answersId, testAnswers)){
return INCORRECT;
}else{
return CORRECT;
}
}
protected boolean isCorrect(List<Long> answersId, List<TestAnswer> testAnswers){
boolean result = Boolean.TRUE;
if (testAnswers.size() == answersId.size()) {
// El numero de respuestas ha de coincidir
for(TestAnswer testAnswer : testAnswers) {
if (!answersId.contains(testAnswer.getAnswerId())) {
result = Boolean.FALSE;
}
}
} else {
return Boolean.FALSE;
}
return result;
}
public String getHtmlView(long questionId, ThemeDisplay themeDisplay, Document document){
return getHtml(document, questionId, false, themeDisplay);
}
public Element getResults(ActionRequest actionRequest, long questionId){
List<TestAnswer> testAnswers = new ArrayList<TestAnswer>();
try {
testAnswers.addAll(TestAnswerLocalServiceUtil.getTestAnswersByQuestionId(questionId));
} catch (SystemException e) {
e.printStackTrace();
}
//me quedo solo con un array con la solucion
for(java.util.ListIterator<TestAnswer> itr = testAnswers.listIterator(); itr.hasNext();){
TestAnswer tanswer = itr.next();
if(!tanswer.isIsCorrect()) itr.remove();
}
List<Long> answersId = new ArrayList<Long>();
for(int i=0;i<testAnswers.size();i++){
answersId.add(ParamUtil.getLong(actionRequest, "question_"+questionId+"_"+i+"hidden"));
}
Element questionXML=SAXReaderUtil.createElement("question");
questionXML.addAttribute("id", Long.toString(questionId));
long currentQuestionId = ParamUtil.getLong(actionRequest, "currentQuestionId");
if (currentQuestionId == questionId) {
questionXML.addAttribute("current", "true");
}
for(long answer:answersId){
Element answerXML=SAXReaderUtil.createElement("answer");
answerXML.addAttribute("id", Long.toString(answer));
questionXML.add(answerXML);
}
return questionXML;
}
private String getHtml(Document document, long questionId, boolean feedback, ThemeDisplay themeDisplay){
String html = "", leftCol="", rightCol = "", feedMessage="", feedsol="", showCorrectAnswer="false";
String namespace = themeDisplay != null ? themeDisplay.getPortletDisplay().getNamespace() : "";
try {
TestQuestion question = TestQuestionLocalServiceUtil.fetchTestQuestion(questionId);
//String feedMessage = LanguageUtil.get(themeDisplay.getLocale(),"answer-in-blank") ;
List<TestAnswer> answersSelected=getAnswersSelected(document, questionId);
List<TestAnswer> tA= TestAnswerLocalServiceUtil.getTestAnswersByQuestionId(question.getQuestionId());
List<Long>answersSelectedIds = new ArrayList<Long>();
List<TestAnswer> sols = new ArrayList<TestAnswer>();
//array con todas las respuestas posibles desordenadas
ArrayList<TestAnswer> testAnswers = new ArrayList<TestAnswer>();
testAnswers.addAll(tA);
Collections.shuffle(testAnswers);
//la lista tA la reutilizo como lista con la solucion
for(TestAnswer an:tA){
if(an.isIsCorrect()) sols.add(an);
}
//Si el alumno ha pasado por la pregunta alguna vez, eliminamos de testAnswers las que el alumno puso en answersSelected
if(answersSelected != null && answersSelected.size() == sols.size()){
for(int k=0; k<answersSelected.size(); k++){
if(answersSelected.get(k) != null){
testAnswers.remove(answersSelected.get(k));
answersSelectedIds.add(answersSelected.get(k).getAnswerId());
}else
answersSelectedIds.add(new Long(-1));
}
//sino, creamos el array de respuestas con el tamano que tiene q tener para pintar las cajas grises vacias.
}else{
for(int k=0; k<sols.size(); k++) answersSelectedIds.add(new Long(-1));
}
String correctionClass = "";
if(feedback){
feedMessage = LanguageUtil.get(locale,"answer-in-blank");
showCorrectAnswer = LearningActivityLocalServiceUtil.getExtraContentValue(question.getActId(), "showCorrectAnswer");
String showCorrectAnswerOnlyOnFinalTryString = LearningActivityLocalServiceUtil.getExtraContentValue(question.getActId(), "showCorrectAnswerOnlyOnFinalTry");
try {
if ("true".equals(showCorrectAnswerOnlyOnFinalTryString)) {
if(LearningActivityTryLocalServiceUtil.canUserDoANewTry(question.getActId(), themeDisplay.getUserId())){
showCorrectAnswer = "false";
}else{
showCorrectAnswer = "true";
}
}
} catch (Exception e) {}
if(isCorrect(answersSelectedIds, sols)) correctionClass = " correct";
else correctionClass = " incorrect";
}
html += "<div id=\"id"+questionId+"\" class=\"question draganddrop"+correctionClass + " questiontype_" + getName() + " questiontype_" + getTypeId() +"\">"+
"<input type=\"hidden\" name=\""+namespace+"question\" value=\"" + question.getQuestionId() + "\"/>"+
"<div class=\"questiontext\">" + question.getText() + "</div>";
//en la columna de la izq el contenido de testAnswers, con las que el estudiante dejo sin arrastrar
leftCol += "<div class=\"items\" style=\"border:1px solid #fff; min-height:"+20*testAnswers.size()+"px; min-width=300px;\">";
for(TestAnswer answer:testAnswers){
leftCol += "<div id=\""+answer.getAnswerId()+"\" class=\"ui-corner-all\">"+answer.getAnswer()+"</div>";
}
leftCol += "</div>";
//en la columna de la derecha el contenido de answersSelected, con las respuestas que dio el estudiante
rightCol += "<div class=\"drop\">";
for(int i=0;i<answersSelectedIds.size();i++){
int aux = i+1;
long value = -1;
String text = LanguageUtil.format(locale, "drop", aux);
if(answersSelectedIds.get(i)!= -1 && answersSelected.get(i) != null){
value = answersSelected.get(i).getAnswerId();
text = answersSelected.get(i).getAnswer();
}
if(feedback){
if(answersSelectedIds.get(i) == sols.get(i).getAnswerId()) {
//feedMessage = (!LanguageUtil.get(themeDisplay.getLocale(),"answer-in-blank").equals(feedMessage))?feedMessage+"<div class=\"questionFeedback\">"+sols.get(i).getFeedbackCorrect()+"</div>":"<div class=\"questionFeedback\">"+sols.get(i).getFeedbackCorrect()+"</div>";
feedMessage = "<div class=\"questionFeedback\">"+sols.get(i).getFeedbackCorrect()+"</div>";
}
else {
//feedMessage = (!LanguageUtil.get(themeDisplay.getLocale(),"answer-in-blank").equals(feedMessage))?feedMessage+"<div class=\"questionFeedback\">"+sols.get(i).getFeedbacknocorrect()+"</div>":"<div class=\"questionFeedback\">"+sols.get(i).getFeedbacknocorrect()+"</div>";
String feedAux = new String();
Iterator<TestAnswer> it = tA.iterator();
TestAnswer answerAux = null;
while (it.hasNext()){
answerAux = it.next();
if(answersSelectedIds.get(i) == answerAux.getAnswerId()){
feedAux = answerAux.getFeedbacknocorrect();
break;
}
}
feedMessage = "<div class=\"questionFeedback\">"+feedAux+"</div>";
}
if("true".equals(showCorrectAnswer)) {
feedsol = "<div class=\" font_14 color_cuarto negrita\">" + sols.get(i).getAnswer() + "</div>";
}
if (!"<div class=\"questionFeedback\"></div>".equals(feedMessage)) {
feedsol += feedMessage;
}
}
rightCol += "<input type=\"hidden\" name=\""+namespace+"question_" + question.getQuestionId() + "_" + i +"hidden\" value=\""+value+"\"/>" +
"<div name=\""+namespace+"question_" + question.getQuestionId() + "_" + i +"\" id=\"Drop"+aux +"\" class=\"drop-containers ui-corner-all background "+(value == -1 ? "base" : "occupied")+"\">"+
(value == -1 ? "" : "<div id=\""+value+"\" class=\"ui-corner-all ui-draggable\">") +
text +
(value == -1 ? "" : "</div>") +
"</div>"
+ feedsol;
}
rightCol += "</div>";
if(feedback) {
html += "<div class=\"content_answer\">" + leftCol + rightCol + "</div>";
// if (!"".equals(feedMessage)) {
// //html += "<div class=\"questionFeedback\">" + feedMessage + "</div>";
// html += feedMessage;
}
else html += leftCol + rightCol;
html+= "</div>";
} catch (SystemException e) {
e.printStackTrace();
}
return html;
}
public String getHtmlFeedback(Document document,long questionId, ThemeDisplay themeDisplay){
return getHtml(document, questionId, true, themeDisplay);
}
protected List<TestAnswer> getAnswersSelected(Document document,long questionId){
List<TestAnswer> answerSelected = new ArrayList<TestAnswer>();
if(document != null){
Iterator<Element> nodeItr = document.getRootElement().elementIterator();
while(nodeItr.hasNext()) {
Element element = nodeItr.next();
if("question".equals(element.getName()) && questionId == Long.valueOf(element.attributeValue("id"))){
Iterator<Element> elementItr = element.elementIterator();
while(elementItr.hasNext()) {
Element elementElement = elementItr.next();
if("answer".equals(elementElement.getName())) {
try {
long id = Long.valueOf(elementElement.attributeValue("id"));
if(id != -1)
answerSelected.add(TestAnswerLocalServiceUtil.getTestAnswer(id));
else answerSelected.add(null);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (PortalException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
}
}
}
}
}
}
return answerSelected;
}
public Element exportXML(long questionId) {
XMLType = "draganddrop";
Element questionXML = super.exportXML(questionId);
try {
List<TestAnswer> answers = TestAnswerLocalServiceUtil.getTestAnswersByQuestionId(questionId);
for(TestAnswer answer:answers){
Element answerE = SAXReaderUtil.createElement("answer");
answerE.addAttribute("fraction", (answer.isIsCorrect())?"100":"0");
Element text = SAXReaderUtil.createElement("text");
text.addText(answer.getAnswer());
answerE.add(text);
Element feedback = SAXReaderUtil.createElement("feedback");
Element feedText = SAXReaderUtil.createElement("text");
feedText.addText(answer.getFeedbackCorrect());
feedback.add(feedText);
answerE.add(feedback);
questionXML.add(answerE);
}
} catch (SystemException e) {
e.printStackTrace();
}
return questionXML;
}
public void importXML(long actId, Element question, TestAnswerLocalService testAnswerLocalService)throws SystemException, PortalException {
Element questiontext=question.element("questiontext");
String description=questiontext.elementText("text");
TestQuestion theQuestion=TestQuestionLocalServiceUtil.addQuestion(actId,description,getTypeId());
for(Element answerElement:question.elements("answer")){
boolean correct=(!"0".equals(answerElement.attributeValue("fraction")))? true:false;
String answer=answerElement.elementText("text");
String feedback="";
if(answerElement.element("feedback")!=null && answerElement.element("feedback").element("text")!=null)
feedback=answerElement.element("feedback").element("text").getText();
testAnswerLocalService.addTestAnswer(theQuestion.getQuestionId(), answer, feedback, feedback, correct);
}
}
public int getMaxAnswers(){
return GetterUtil.getInteger(PropsUtil.get("lms.maxAnswers.dragAndDrop"), 100);
}
public int getDefaultAnswersNo(){
return GetterUtil.getInteger(PropsUtil.get("lms.defaultAnswersNo.dragAndDrop"), 2);
}
} |
package edu.cuny.citytech.refactoring.common;
import java.util.Map;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
/**
* @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi
* Khatchadourian</a>
*
*/
public abstract class Refactoring extends
org.eclipse.ltk.core.refactoring.Refactoring {
public RefactoringStatus initialize(Map arguments) {
return new RefactoringStatus();
}
} |
package org.opendaylight.netvirt.elanmanager.tests;
import static java.util.Arrays.asList;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
import com.google.common.base.Optional;
import java.util.List;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.mockito.Mockito;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
import org.opendaylight.genius.datastoreutils.testutils.JobCoordinatorTestModule;
import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
import org.opendaylight.genius.mdsalutil.MDSALUtil;
import org.opendaylight.genius.mdsalutil.NwConstants;
import org.opendaylight.genius.mdsalutil.cache.InstanceIdDataObjectCache;
import org.opendaylight.genius.testutils.interfacemanager.TunnelInterfaceDetails;
import org.opendaylight.genius.utils.batching.ResourceBatchingManager;
import org.opendaylight.infrautils.caches.CacheProvider;
import org.opendaylight.infrautils.caches.testutils.CacheModule;
import org.opendaylight.infrautils.inject.guice.testutils.GuiceRule;
import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
import org.opendaylight.infrautils.jobcoordinator.internal.JobCoordinatorImpl;
import org.opendaylight.infrautils.metrics.MetricProvider;
import org.opendaylight.infrautils.metrics.testimpl.TestMetricProviderImpl;
import org.opendaylight.infrautils.testutils.LogRule;
import org.opendaylight.mdsal.binding.testutils.AssertDataObjects;
import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
import org.opendaylight.netvirt.bgpmanager.api.IBgpManager;
import org.opendaylight.netvirt.elan.cache.ElanInstanceDpnsCache;
import org.opendaylight.netvirt.elan.evpn.listeners.ElanMacEntryListener;
import org.opendaylight.netvirt.elan.evpn.listeners.EvpnElanInstanceListener;
import org.opendaylight.netvirt.elan.evpn.listeners.MacVrfEntryListener;
import org.opendaylight.netvirt.elan.evpn.utils.EvpnUtils;
import org.opendaylight.netvirt.elan.internal.ElanDpnInterfaceClusteredListener;
import org.opendaylight.netvirt.elan.internal.ElanExtnTepConfigListener;
import org.opendaylight.netvirt.elan.internal.ElanExtnTepListener;
import org.opendaylight.netvirt.elan.internal.ElanInterfaceManager;
import org.opendaylight.netvirt.elan.l2gw.listeners.HwvtepPhysicalSwitchListener;
import org.opendaylight.netvirt.elan.l2gw.listeners.L2GatewayConnectionListener;
import org.opendaylight.netvirt.elan.l2gw.listeners.LocalUcastMacListener;
import org.opendaylight.netvirt.elan.l2gw.nodehandlertest.DataProvider;
import org.opendaylight.netvirt.elan.l2gw.nodehandlertest.PhysicalSwitchHelper;
import org.opendaylight.netvirt.elan.l2gw.utils.ElanL2GatewayUtils;
import org.opendaylight.netvirt.elan.utils.ElanUtils;
import org.opendaylight.netvirt.elanmanager.api.IElanService;
import org.opendaylight.netvirt.elanmanager.api.IL2gwService;
import org.opendaylight.netvirt.elanmanager.tests.utils.EvpnTestHelper;
import org.opendaylight.netvirt.elanmanager.utils.ElanL2GwCacheUtils;
import org.opendaylight.netvirt.neutronvpn.api.l2gw.L2GatewayCache;
import org.opendaylight.netvirt.neutronvpn.l2gw.L2GatewayListener;
import org.opendaylight.netvirt.vpnmanager.api.IVpnManager;
import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.ebgp.rev150901.Bgp;
import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.ebgp.rev150901.bgp.Networks;
import org.opendaylight.yang.gen.v1.urn.ericsson.params.xml.ns.yang.ebgp.rev150901.bgp.NetworksKey;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LocalUcastMacs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LogicalSwitches;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* End-to-end test of IElanService.
*
* @author Michael Vorburger
* @author Riyazahmed Talikoti
*/
public class ElanServiceTest extends ElanServiceTestBase {
private static final Logger LOG = LoggerFactory.getLogger(ElanServiceTest.class);
// TODO as-is, this test is flaky; as uncommenting will show
// Uncomment this to keep running this test indefinitely
// public static @ClassRule RunUntilFailureClassRule classRepeater = new RunUntilFailureClassRule();
// public @Rule RunUntilFailureRule repeater = new RunUntilFailureRule(classRepeater);
public @Rule LogRule logRule = new LogRule();
public @Rule MethodRule guice = new GuiceRule(ElanServiceTestModule.class, JobCoordinatorTestModule.class,
CacheModule.class);
// TODO re-enable after we can await completion of listeners and DJC:
// Otherwise this too frequently causes spurious test failures, e.g. due to error
// logs Caused by: java.lang.RuntimeException: java.util.concurrent.ExecutionException: Operation was interrupted
// public @Rule LogCaptureRule logCaptureRule = new LogCaptureRule();
private @Inject IElanService elanService;
private @Inject IdManagerService idManager;
private @Inject EvpnElanInstanceListener evpnElanInstanceListener;
private @Inject ElanMacEntryListener elanMacEntryListener;
private @Inject MacVrfEntryListener macVrfEntryListener;
private @Inject EvpnUtils evpnUtils;
private @Inject IBgpManager bgpManager;
private @Inject IVpnManager vpnManager;
private @Inject EvpnTestHelper evpnTestHelper;
private @Inject OdlInterfaceRpcService odlInterfaceRpcService;
private @Inject ElanL2GatewayUtils elanL2GatewayUtils;
private @Inject ElanInterfaceManager elanInterfaceManager;
private @Inject HwvtepPhysicalSwitchListener hwvtepPhysicalSwitchListener;
private @Inject L2GatewayConnectionListener l2GatewayConnectionListener;
private @Inject LocalUcastMacListener localUcastMacListener;
private @Inject ElanDpnInterfaceClusteredListener elanDpnInterfaceClusteredListener;
private @Inject EntityOwnershipService mockedEntityOwnershipService;
private @Inject L2GatewayCache l2GatewayCache;
private @Inject ElanUtils elanUtils;
private @Inject ElanInstanceDpnsCache elanInstanceDpnsCache;
private @Inject ElanExtnTepConfigListener elanExtnTepConfigListener;
private @Inject ElanExtnTepListener elanExtnTepListener;
private @Inject CacheProvider cacheProvider;
private L2GatewayListener l2gwListener;
private MetricProvider metricProvider = new TestMetricProviderImpl();
private Verifications verifications;
private L2gwBuilders l2gwBuilders;
private SingleTransactionDataBroker singleTxdataBroker;
private InstanceIdDataObjectCache<LogicalSwitches> logicalSwitchCache;
@Before public void before() throws Exception {
singleTxdataBroker = new SingleTransactionDataBroker(dataBroker);
logicalSwitchCache = new InstanceIdDataObjectCache<LogicalSwitches>(
LogicalSwitches.class, dataBroker, CONFIGURATION,
InstanceIdentifier.builder(NetworkTopology.class)
.child(Topology.class, new TopologyKey(new TopologyId(new Uri("hwvtep:1"))))
.child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
.network.topology.rev131021.network.topology.topology.Node.class)
.augmentation(HwvtepGlobalAugmentation.class)
.child(LogicalSwitches.class).build(), cacheProvider) {
@Override
protected void added(InstanceIdentifier<LogicalSwitches> path, LogicalSwitches dataObject) {
new Thread(() -> {
try {
singleTxdataBroker.syncWrite(OPERATIONAL, path, dataObject);
} catch (TransactionCommitFailedException e) {
LOG.error("Failed to write to oper ds");
}
}).start();
}
};
verifications = new Verifications(singleTxdataBroker, odlInterfaceRpcService, EXTN_INTFS, getAwaiter());
l2gwBuilders = new L2gwBuilders(singleTxdataBroker);
JobCoordinator jobCoordinator = new JobCoordinatorImpl(metricProvider);
l2gwListener = new L2GatewayListener(dataBroker, mockedEntityOwnershipService,
Mockito.mock(ItmRpcService.class), Mockito.mock(IL2gwService.class), jobCoordinator, l2GatewayCache);
l2gwListener.init();
setupItm();
l2gwBuilders.buildTorNode(TOR2_NODE_ID, PS2, TOR2_TEPIP);
l2gwBuilders.buildTorNode(TOR1_NODE_ID, PS1, TOR1_TEPIP);
}
@After public void after() throws Exception {
for (ResourceBatchingManager.ShardResource i : ResourceBatchingManager.ShardResource.values()) {
ResourceBatchingManager.getInstance().deregisterBatchableResource(i.name());
}
ElanL2GwCacheUtils.removeL2GatewayDeviceFromAllElanCache(TOR1_NODE_ID);
ElanL2GwCacheUtils.removeL2GatewayDeviceFromAllElanCache(TOR2_NODE_ID);
ElanL2GwCacheUtils.removeL2GatewayDeviceFromCache(ExpectedObjects.ELAN1, TOR1_NODE_ID);
ElanL2GwCacheUtils.removeL2GatewayDeviceFromCache(ExpectedObjects.ELAN1, TOR2_NODE_ID);
}
@Test public void elanServiceTestModule() {
// Intentionally empty; the goal is just to first test the ElanServiceTestModule
}
void createL2gwAndConnection(InstanceIdentifier<Node> nodePath,
String l2gwName,
String deviceName,
List<String> ports,
String connectionName)
throws InterruptedException, TransactionCommitFailedException {
//Create l2gw
singleTxdataBroker.syncWrite(LogicalDatastoreType.CONFIGURATION,
l2gwBuilders.buildL2gwIid(l2gwName), l2gwBuilders.buildL2gw(l2gwName, deviceName, ports));
awaitForData(LogicalDatastoreType.CONFIGURATION, l2gwBuilders.buildL2gwIid(l2gwName));
//Create l2gwconn
singleTxdataBroker.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION,
l2gwBuilders.buildConnectionIid(connectionName), l2gwBuilders.buildConnection(connectionName,
l2gwName, ExpectedObjects.ELAN1, 100));
awaitForData(LogicalDatastoreType.CONFIGURATION, l2gwBuilders.buildConnectionIid(connectionName));
}
@Test public void checkSMAC() throws Exception {
// Create Elan instance
createElanInstance(ExpectedObjects.ELAN1, ExpectedObjects.ELAN1_SEGMENT_ID);
awaitForElanTag(ExpectedObjects.ELAN1);
// Add Elan interface
InterfaceInfo interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC1).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN1IP1);
// Read Elan instance
InstanceIdentifier<ElanInstance> elanInstanceIid = InstanceIdentifier.builder(ElanInstances.class)
.child(ElanInstance.class, new ElanInstanceKey(ExpectedObjects.ELAN1)).build();
ElanInstance actualElanInstances = singleTxdataBroker.syncRead(CONFIGURATION, elanInstanceIid);
// Read and Compare SMAC flow
String flowId = new StringBuffer()
.append(NwConstants.ELAN_SMAC_TABLE)
.append(actualElanInstances.getElanTag())
.append(DPN1_ID)
.append(interfaceInfo.getInterfaceTag())
.append(interfaceInfo.getMacAddress())
.toString();
InstanceIdentifier<Flow> flowInstanceIidSrc = getFlowIid(NwConstants.ELAN_SMAC_TABLE,
new FlowId(flowId), DPN1_ID);
awaitForData(LogicalDatastoreType.CONFIGURATION, flowInstanceIidSrc);
Flow flowSrc = singleTxdataBroker.syncRead(CONFIGURATION, flowInstanceIidSrc);
flowSrc = getFlowWithoutCookie(flowSrc);
Flow expected = ExpectedObjects.checkSmac(flowId, interfaceInfo, actualElanInstances);
AssertDataObjects.assertEqualBeans(expected, flowSrc);
}
@Test public void checkDmacSameDPN() throws Exception {
// Create Elan instance
createElanInstance(ExpectedObjects.ELAN1, ExpectedObjects.ELAN1_SEGMENT_ID);
awaitForElanTag(ExpectedObjects.ELAN1);
// Add Elan interface in DPN1
InterfaceInfo interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC1).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN1IP1);
// Read Elan instance
InstanceIdentifier<ElanInstance> elanInstanceIid = InstanceIdentifier.builder(ElanInstances.class)
.child(ElanInstance.class, new ElanInstanceKey(ExpectedObjects.ELAN1)).build();
ElanInstance actualElanInstances = singleTxdataBroker.syncRead(CONFIGURATION, elanInstanceIid);
// Read DMAC Flow in DPN1
String flowId = new StringBuffer()
.append(NwConstants.ELAN_DMAC_TABLE)
.append(actualElanInstances.getElanTag())
.append(DPN1_ID)
.append(interfaceInfo.getInterfaceTag())
.append(interfaceInfo.getMacAddress())
.toString();
InstanceIdentifier<Flow> flowInstanceIidDst = getFlowIid(NwConstants.ELAN_DMAC_TABLE,
new FlowId(flowId), DPN1_ID);
awaitForData(LogicalDatastoreType.CONFIGURATION, flowInstanceIidDst);
Flow flowDst = singleTxdataBroker.syncRead(CONFIGURATION, flowInstanceIidDst);
flowDst = getFlowWithoutCookie(flowDst);
Flow expected = ExpectedObjects.checkDmacOfSameDpn(flowId, interfaceInfo, actualElanInstances);
AssertDataObjects.assertEqualBeans(getSortedActions(expected), getSortedActions(flowDst));
}
@Test public void checkDmacOfOtherDPN() throws Exception {
// Create Elan instance
createElanInstance(ExpectedObjects.ELAN1, ExpectedObjects.ELAN1_SEGMENT_ID);
awaitForElanTag(ExpectedObjects.ELAN1);
InterfaceInfo interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC1).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN1IP1);
// Read Elan instance
InstanceIdentifier<ElanInstance> elanInstanceIid = InstanceIdentifier.builder(ElanInstances.class)
.child(ElanInstance.class, new ElanInstanceKey(ExpectedObjects.ELAN1)).build();
ElanInstance actualElanInstances = singleTxdataBroker.syncRead(CONFIGURATION, elanInstanceIid);
interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN2MAC1).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN2IP1);
// Read and Compare DMAC flow in DPN1 for MAC1 of DPN2
String flowId = ElanUtils.getKnownDynamicmacFlowRef((short)51,
DPN1_ID,
DPN2_ID,
interfaceInfo.getMacAddress().toString(),
actualElanInstances.getElanTag());
InstanceIdentifier<Flow> flowInstanceIidDst = getFlowIid(NwConstants.ELAN_DMAC_TABLE,
new FlowId(flowId), DPN1_ID);
awaitForData(LogicalDatastoreType.CONFIGURATION, flowInstanceIidDst);
Flow flowDst = singleTxdataBroker.syncRead(CONFIGURATION, flowInstanceIidDst);
flowDst = getFlowWithoutCookie(flowDst);
TunnelInterfaceDetails tepDetails = EXTN_INTFS.get(DPN1_ID_STR + ":" + DPN2_ID_STR);
Flow expected = ExpectedObjects.checkDmacOfOtherDPN(flowId, interfaceInfo, tepDetails,
actualElanInstances);
AssertDataObjects.assertEqualBeans(getSortedActions(expected), getSortedActions(flowDst));
}
@Test public void checkEvpnAdvRT2() throws Exception {
createElanInstanceAndInterfaceAndAttachEvpn();
AssertDataObjects.assertEqualBeans(
ExpectedObjects.checkEvpnAdvertiseRoute(ELAN1_SEGMENT_ID, DPN1MAC1, DPN1_TEPIP, DPN1IP1, RD),
readBgpNetworkFromDS(DPN1IP1));
}
@Test public void checkEvpnAdvRT2NewInterface() throws Exception {
createElanInstanceAndInterfaceAndAttachEvpn();
// Add Elan interface
addElanInterface(ExpectedObjects.ELAN1, ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC2).getLeft(), DPN1IP2);
AssertDataObjects.assertEqualBeans(
ExpectedObjects.checkEvpnAdvertiseRoute(ELAN1_SEGMENT_ID, DPN1MAC2, DPN1_TEPIP, DPN1IP2, RD),
readBgpNetworkFromDS(DPN1IP2));
}
@Test public void checkEvpnWithdrawRT2DelIntf() throws Exception {
createElanInstanceAndInterfaceAndAttachEvpn();
InstanceIdentifier<Networks> iid = evpnTestHelper.buildBgpNetworkIid(DPN1IP1);
awaitForData(LogicalDatastoreType.CONFIGURATION, iid);
evpnTestHelper.deleteRdtoNetworks();
deleteElanInterface(ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC1).getLeft());
awaitForDataDelete(LogicalDatastoreType.CONFIGURATION, iid);
}
@Test public void checkEvpnWithdrawRouteDetachEvpn() throws Exception {
createElanInstanceAndInterfaceAndAttachEvpn();
addElanInterface(ExpectedObjects.ELAN1, ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC2).getLeft(), DPN1IP2);
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildBgpNetworkIid(DPN1IP1));
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildBgpNetworkIid(DPN1IP2));
evpnTestHelper.detachEvpnToNetwork(ExpectedObjects.ELAN1);
awaitForDataDelete(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildBgpNetworkIid(DPN1IP1));
awaitForDataDelete(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildBgpNetworkIid(DPN1IP2));
}
@Test public void checkEvpnInstalDmacFlow() throws Exception {
createElanInstanceAndInterfaceAndAttachEvpn();
addElanInterface(ExpectedObjects.ELAN1, ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC2).getLeft(), DPN1IP2);
// Verify advertise RT2 route success for both MAC's
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildBgpNetworkIid(DPN1IP1));
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildBgpNetworkIid(DPN1IP2));
// RT2 received from Peer
evpnTestHelper.handleEvpnRt2Recvd(EVPNRECVMAC1, EVPNRECVIP1);
evpnTestHelper.handleEvpnRt2Recvd(EVPNRECVMAC2, EVPNRECVIP2);
// verify successful installation of DMAC flow for recvd rt2
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildMacVrfEntryIid(EVPNRECVMAC1));
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildMacVrfEntryIid(EVPNRECVMAC2));
}
@Test public void checkEvpnUnInstalDmacFlow() throws Exception {
createElanInstanceAndInterfaceAndAttachEvpn();
addElanInterface(ExpectedObjects.ELAN1, ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC2).getLeft(), DPN1IP2);
// Verify advertise RT2 route success for both MAC's
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildBgpNetworkIid(DPN1IP1));
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildBgpNetworkIid(DPN1IP2));
// RT2 received from Peer
evpnTestHelper.handleEvpnRt2Recvd(EVPNRECVMAC1, EVPNRECVIP1);
evpnTestHelper.handleEvpnRt2Recvd(EVPNRECVMAC2, EVPNRECVIP2);
// verify successful installation of DMAC flow for recvd rt2
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildMacVrfEntryIid(EVPNRECVMAC1));
awaitForData(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildMacVrfEntryIid(EVPNRECVMAC2));
// withdraw RT2 received from Peer
evpnTestHelper.deleteMacVrfEntryToDS(RD, EVPNRECVMAC1);
evpnTestHelper.deleteMacVrfEntryToDS(RD, EVPNRECVMAC2);
// verify successful un-installation of DMAC flow for recvd rt2
awaitForDataDelete(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildMacVrfEntryIid(EVPNRECVMAC1));
awaitForDataDelete(LogicalDatastoreType.CONFIGURATION, evpnTestHelper.buildMacVrfEntryIid(EVPNRECVMAC2));
}
public void createElanInstanceAndInterfaceAndAttachEvpn() throws ReadFailedException,
TransactionCommitFailedException {
// Create Elan instance
createElanInstance(ExpectedObjects.ELAN1, ExpectedObjects.ELAN1_SEGMENT_ID);
awaitForElanTag(ExpectedObjects.ELAN1);
// Read Elan Instance
InstanceIdentifier<ElanInstance> elanInstanceIid = InstanceIdentifier.builder(ElanInstances.class)
.child(ElanInstance.class, new ElanInstanceKey(ExpectedObjects.ELAN1)).build();
ElanInstance elanInstance = singleTxdataBroker.syncRead(CONFIGURATION, elanInstanceIid);
// Add Elan interface
addElanInterface(ExpectedObjects.ELAN1, ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC1).getLeft(), DPN1IP1);
// Attach EVPN to networks
evpnTestHelper.attachEvpnToNetwork(elanInstance);
}
public Networks readBgpNetworkFromDS(String prefix) throws ReadFailedException {
InstanceIdentifier<Networks> iid = InstanceIdentifier.builder(Bgp.class)
.child(Networks.class, new NetworksKey(prefix, RD))
.build();
awaitForData(LogicalDatastoreType.CONFIGURATION, iid);
return singleTxdataBroker.syncRead(CONFIGURATION, iid);
}
private void awaitForElanTag(String elanName) {
InstanceIdentifier<ElanInstance> elanInstanceIid = InstanceIdentifier.builder(ElanInstances.class)
.child(ElanInstance.class, new ElanInstanceKey(elanName)).build();
getAwaiter().until(() -> {
Optional<ElanInstance> elanInstance = MDSALUtil.read(dataBroker, CONFIGURATION, elanInstanceIid);
return elanInstance.isPresent() && elanInstance.get().getElanTag() != null;
});
}
public void verifyL2gw1Connection() throws Exception {
//Create ELAN
createElanInstance(ExpectedObjects.ELAN1, ExpectedObjects.ELAN1_SEGMENT_ID);
awaitForElanTag(ExpectedObjects.ELAN1);
//Add Elan MAC1, MAC2 in DPN1
InterfaceInfo interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC1).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN1IP1);
interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC2).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN1IP2);
//Add Elan MAC1, MAC2 in DPN2
interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN2MAC1).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN2IP1);
verifications.verifyLocalBcGroup(DPN2_ID, 1);
interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN2MAC2).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN2IP2);
verifications.verifyLocalBcGroup(DPN2_ID, 2);
createL2gwAndConnection(TOR1_NODE_IID, L2GW1, PS1, DataProvider.getPortNameListD1(), L2GW_CONN1);
verifications.verifyThatMcastMacTepsCreated(TOR1_NODE_IID, asList(DPN1_TEPIP, DPN2_TEPIP));
verifications.verifyThatUcastCreated(TOR1_NODE_IID, asList(DPN1MAC1, DPN1MAC2, DPN2MAC1, DPN2MAC2));
verifications.verifyThatDpnGroupUpdated(DPN1_ID, asList(DPN2_ID), asList(TOR1_TEPIP));
verifications.verifyThatDpnGroupUpdated(DPN2_ID, asList(DPN1_ID), asList(TOR1_TEPIP));
}
@Test
public void verifyL2gwPreProvisioning() throws Exception {
createElanInstance(ExpectedObjects.ELAN1, ExpectedObjects.ELAN1_SEGMENT_ID);
awaitForElanTag(ExpectedObjects.ELAN1);
addElanInterface(ExpectedObjects.ELAN1, ELAN_INTERFACES.get(ELAN1 + ":" + DPN1MAC1).getLeft(), DPN1IP1);
singleTxdataBroker.syncDelete(OPERATIONAL, TOR1_NODE_IID);
singleTxdataBroker.syncDelete(OPERATIONAL,
PhysicalSwitchHelper.getPhysicalSwitchInstanceIdentifier(TOR1_NODE_IID, PS1));
createL2gwAndConnection(TOR1_NODE_IID, L2GW1, PS1, DataProvider.getPortNameListD1(), L2GW_CONN1);
l2gwBuilders.buildTorNode(TOR1_NODE_ID, PS1, TOR1_TEPIP);
verifications.verifyThatMcastMacTepsCreated(TOR1_NODE_IID, asList(DPN1_TEPIP));
verifications.verifyThatUcastCreated(TOR1_NODE_IID, asList(DPN1MAC1));
}
public void verifyL2gwMac1InDpns() throws Exception {
verifyL2gw1Connection();
l2gwBuilders.createLocalUcastMac(TOR1_NODE_IID, TOR1_MAC1, TOR1_IP1, TOR1_TEPIP);
verifications.verifyThatDmacFlowOfTORCreated(asList(DPN1_ID, DPN2_ID), TOR1_NODE_IID, asList(TOR1_MAC1));
}
public void verifyL2gw2Connection() throws Exception {
verifyL2gwMac1InDpns();
// TOR Node 2 creation
createL2gwAndConnection(TOR2_NODE_IID, L2GW2, PS2, DataProvider.getPortNameListTor2(), L2GW_CONN2);
//check for remote mcast mac in tor2 against TEPs of dpn1, dpn2 and dpn3, tor1)
verifications.verifyThatMcastMacTepsCreated(TOR2_NODE_IID, asList(DPN1_TEPIP, DPN2_TEPIP, TOR1_TEPIP));
verifications.verifyThatMcastMacTepsCreated(TOR1_NODE_IID, asList(DPN1_TEPIP, DPN2_TEPIP, TOR2_TEPIP));
verifications.verifyThatUcastCreated(TOR2_NODE_IID, asList(DPN1MAC1, DPN2MAC1, DPN2MAC1, DPN2MAC2, TOR1_MAC1));
}
@Test
public void verifyL2gwMac2InTors() throws Exception {
verifyL2gw2Connection();
l2gwBuilders.createLocalUcastMac(TOR1_NODE_IID, TOR1_MAC2, TOR1_IP2, TOR1_TEPIP);
verifications.verifyThatUcastCreated(TOR2_NODE_IID, asList(TOR1_MAC2));
}
@Test
public void verifyL2gwMacDeleteInTors() throws Exception {
verifyL2gwMac2InTors();
LocalUcastMacs localUcastMacs1 = l2gwBuilders.createLocalUcastMac(
TOR1_NODE_IID, TOR1_MAC1, TOR1_IP1, TOR1_TEPIP);
singleTxdataBroker.syncDelete(LogicalDatastoreType.OPERATIONAL,
l2gwBuilders.buildMacIid(TOR1_NODE_IID, localUcastMacs1));
verifications.verifyThatDmacFlowOfTORDeleted(asList(DPN1_ID, DPN2_ID), TOR1_NODE_IID, asList(TOR1_MAC1));
verifications.verifyThatUcastDeleted(TOR2_NODE_IID, asList(TOR1_MAC1));
}
@Test
public void verifyAddDpnAfterL2gwConnection() throws Exception {
verifyL2gwMac2InTors();
//Add Elan MAC1, MAC2 in DPN3
InterfaceInfo interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN3MAC1).getLeft();
addElanInterface(ExpectedObjects.ELAN1, interfaceInfo, DPN3IP1);
//bc group of this dpn created
verifications.verifyThatDpnGroupUpdated(DPN3_ID, asList(DPN1_ID, DPN2_ID), asList(TOR1_NODE_ID, TOR2_NODE_ID));
//other tors macs be installed in this dpn
verifications.verifyThatDmacFlowOfTORCreated(asList(DPN3_ID), TOR1_NODE_IID, asList(TOR1_MAC1));
verifications.verifyThatDmacOfOtherDpnCreated(DPN3_ID, DPN1_ID, asList(DPN1MAC1, DPN1MAC2));
verifications.verifyThatDmacOfOtherDpnCreated(DPN3_ID, DPN2_ID, asList(DPN2MAC1, DPN2MAC2));
//bc group of the other dpns be updated
verifications.verifyThatDpnGroupUpdated(DPN1_ID, asList(DPN2_ID, DPN3_ID), asList(TOR1_NODE_ID, TOR2_NODE_ID));
verifications.verifyThatDpnGroupUpdated(DPN2_ID, asList(DPN1_ID, DPN3_ID), asList(TOR1_NODE_ID, TOR2_NODE_ID));
//mcast of tor should be updated
verifications.verifyThatMcastMacTepsCreated(TOR2_NODE_IID,
asList(DPN1_TEPIP, DPN2_TEPIP, DPN3_TEPIP, TOR1_TEPIP));
verifications.verifyThatMcastMacTepsCreated(TOR1_NODE_IID,
asList(DPN1_TEPIP, DPN2_TEPIP, DPN3_TEPIP, TOR2_TEPIP));
//this dpn mac should get installed in other dpns and tors
verifications.verifyThatUcastCreated(TOR1_NODE_IID, asList(DPN3MAC1));
verifications.verifyThatUcastCreated(TOR2_NODE_IID, asList(DPN3MAC1));
verifications.verifyThatDmacOfOtherDpnCreated(DPN1_ID, DPN3_ID, asList(DPN3MAC1));
verifications.verifyThatDmacOfOtherDpnCreated(DPN2_ID, DPN3_ID, asList(DPN3MAC1));
}
@Test
@Ignore("Ignoring for Neon MRI")
public void verifyDeleteDpnAfterL2gwConnection() throws Exception {
verifyAddDpnAfterL2gwConnection();
InterfaceInfo interfaceInfo = ELAN_INTERFACES.get(ELAN1 + ":" + DPN3MAC1).getLeft();
deleteElanInterface(interfaceInfo);
//clean up of group of this dpn3
verifications.verifyThatDpnGroupDeleted(DPN3_ID);
//clean up dmacs of this dpn3
verifications.verifyThatDmacFlowOfTORDeleted(asList(DPN3_ID), TOR1_NODE_IID, asList(TOR1_MAC1));
verifications.verifyThatDmacOfOtherDPNDeleted(DPN3_ID, DPN1_ID, asList(DPN1MAC1, DPN1MAC2));
verifications.verifyThatDmacOfOtherDPNDeleted(DPN3_ID, DPN2_ID, asList(DPN2MAC1, DPN2MAC2));
//clean up of dmacs in the other dpns
verifications.verifyThatDmacOfOtherDPNDeleted(DPN1_ID, DPN3_ID, asList(DPN3MAC1));
verifications.verifyThatDmacOfOtherDPNDeleted(DPN2_ID, DPN3_ID, asList(DPN3MAC1));
//cleanup of bc group of other dpns
verifications.verifyThatDpnGroupUpdated(DPN1_ID, asList(DPN2_ID), asList(TOR1_NODE_ID, TOR2_NODE_ID));
verifications.verifyThatDpnGroupUpdated(DPN2_ID, asList(DPN1_ID), asList(TOR1_NODE_ID, TOR2_NODE_ID));
//dpn tep should be removed from tors
verifications.verifyThatMcastMacTepsDeleted(TOR2_NODE_IID, asList(DPN3_TEPIP));
verifications.verifyThatMcastMacTepsDeleted(TOR2_NODE_IID, asList(DPN3_TEPIP));
//dpn mac should be removed from tors
verifications.verifyThatUcastDeleted(TOR1_NODE_IID, asList(DPN3MAC1));
verifications.verifyThatUcastDeleted(TOR2_NODE_IID, asList(DPN3MAC1));
}
@Test
public void verifyDeleteL2gw1Connection() throws Exception {
verifyL2gw2Connection();
//delete tor1 l2gw connection
l2gwBuilders.deletel2GWConnection(L2GW_CONN1);
//deleted tors mcast & cast be cleared
verifications.verifyThatMcastMacTepsDeleted(TOR1_NODE_IID, asList(DPN1_TEPIP, DPN2_TEPIP, TOR2_TEPIP));
verifications.verifyThatUcastDeleted(TOR1_NODE_IID, asList(DPN1MAC1, DPN1MAC2, DPN2MAC1, DPN2MAC2));
//mcast of other tor be updated
verifications.verifyThatMcastMacTepsDeleted(TOR2_NODE_IID, asList(TOR1_TEPIP));
//ucast of deleted to be deleted in other tor
verifications.verifyThatUcastDeleted(TOR2_NODE_IID, asList(TOR1_MAC1));
//group of dpns be udpated
verifications.verifyThatDpnGroupUpdated(DPN1_ID, asList(DPN2_ID), asList(TOR2_NODE_ID));
verifications.verifyThatDpnGroupUpdated(DPN2_ID, asList(DPN1_ID), asList(TOR2_NODE_ID));
//ucast of deleted tor be deleted in other dpns
verifications.verifyThatDmacFlowOfTORDeleted(asList(DPN1_ID, DPN2_ID), TOR1_NODE_IID, asList(TOR1_MAC1));
}
} |
package org.vertexium.elasticsearch;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.stats.IndexStats;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.hppc.ObjectContainer;
import org.elasticsearch.common.hppc.cursors.ObjectCursor;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.vertexium.*;
import org.vertexium.id.NameSubstitutionStrategy;
import org.vertexium.property.StreamingPropertyValue;
import org.vertexium.query.*;
import org.vertexium.search.SearchIndex;
import org.vertexium.search.SearchIndexWithVertexPropertyCountByValue;
import org.vertexium.type.GeoCircle;
import org.vertexium.type.GeoPoint;
import org.vertexium.util.VertexiumLogger;
import org.vertexium.util.VertexiumLoggerFactory;
import java.io.IOException;
import java.util.*;
import static org.vertexium.util.Preconditions.checkNotNull;
public abstract class ElasticSearchSearchIndexBase implements SearchIndex, SearchIndexWithVertexPropertyCountByValue {
private static final VertexiumLogger LOGGER = VertexiumLoggerFactory.getLogger(ElasticSearchSearchIndexBase.class);
protected static final VertexiumLogger MUTATION_LOGGER = VertexiumLoggerFactory.getMutationLogger(SearchIndex.class);
public static final String ELEMENT_TYPE = "element";
public static final String ELEMENT_TYPE_FIELD_NAME = "__elementType";
public static final String VISIBILITY_FIELD_NAME = "__visibility";
public static final String EXACT_MATCH_PROPERTY_NAME_SUFFIX = "_e";
public static final String GEO_PROPERTY_NAME_SUFFIX = "_g";
public static final int MAX_BATCH_COUNT = 25000;
public static final long MAX_BATCH_SIZE = 15 * 1024 * 1024;
public static final int EXACT_MATCH_IGNORE_ABOVE_LIMIT = 10000;
private static final long IN_PROCESS_NODE_WAIT_TIME_MS = 10 * 60 * 1000;
private final Client client;
private final ElasticSearchSearchIndexConfiguration config;
private final Map<String, IndexInfo> indexInfos = new HashMap<>();
private int indexInfosLastSize = 0; // Used to prevent creating a index name array each time
private String[] indexNamesAsArray;
private NameSubstitutionStrategy nameSubstitutionStrategy;
private IndexSelectionStrategy indexSelectionStrategy;
private boolean allFieldEnabled;
private Node inProcessNode;
protected ElasticSearchSearchIndexBase(Graph graph, GraphConfiguration config) {
this.config = new ElasticSearchSearchIndexConfiguration(graph, config);
this.nameSubstitutionStrategy = this.config.getNameSubstitutionStrategy();
this.indexSelectionStrategy = this.config.getIndexSelectionStrategy();
this.allFieldEnabled = this.config.isAllFieldEnabled(getDefaultAllFieldEnabled());
this.client = createClient(this.config);
loadIndexInfos();
loadPropertyDefinitions();
}
protected Client createClient(ElasticSearchSearchIndexConfiguration config) {
if (config.isInProcessNode()) {
return createInProcessNode(config);
} else {
return createTransportClient(config);
}
}
private Client createInProcessNode(ElasticSearchSearchIndexConfiguration config) {
String dataPath = config.getInProcessNodeDataPath();
checkNotNull(dataPath, ElasticSearchSearchIndexConfiguration.IN_PROCESS_NODE_DATA_PATH + " is required for in process Elasticsearch node");
String logsPath = config.getInProcessNodeLogsPath();
checkNotNull(logsPath, ElasticSearchSearchIndexConfiguration.IN_PROCESS_NODE_LOGS_PATH + " is required for in process Elasticsearch node");
String workPath = config.getInProcessNodeWorkPath();
checkNotNull(workPath, ElasticSearchSearchIndexConfiguration.IN_PROCESS_NODE_WORK_PATH + " is required for in process Elasticsearch node");
int numberOfShards = config.getNumberOfShards();
NodeBuilder nodeBuilder = NodeBuilder
.nodeBuilder();
if (config.getClusterName() != null) {
nodeBuilder = nodeBuilder.clusterName(config.getClusterName());
}
this.inProcessNode = nodeBuilder
.local(false)
.settings(
ImmutableSettings.settingsBuilder()
.put("script.disable_dynamic", "false")
.put("gateway.type", "local")
.put("index.number_of_shards", numberOfShards)
.put("index.number_of_replicas", "0")
.put("path.data", dataPath)
.put("path.logs", logsPath)
.put("path.work", workPath)
).node();
inProcessNode.start();
Client client = inProcessNode.client();
long startTime = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() > startTime + IN_PROCESS_NODE_WAIT_TIME_MS) {
throw new VertexiumException("Status failed to exit red status after waiting " + IN_PROCESS_NODE_WAIT_TIME_MS + "ms. Giving up.");
}
ClusterHealthResponse health = client.admin().cluster().prepareHealth().get();
if (health.getStatus() != ClusterHealthStatus.RED) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new VertexiumException("Could not sleep", e);
}
LOGGER.info("Status is %s, waiting...", health.getStatus());
}
return client;
}
private static TransportClient createTransportClient(ElasticSearchSearchIndexConfiguration config) {
ImmutableSettings.Builder settingsBuilder = ImmutableSettings.settingsBuilder();
if (config.getClusterName() != null) {
settingsBuilder.put("cluster.name", config.getClusterName());
}
TransportClient transportClient = new TransportClient(settingsBuilder.build());
for (String esLocation : config.getEsLocations()) {
String[] locationSocket = esLocation.split(":");
String hostname;
int port;
if (locationSocket.length == 2) {
hostname = locationSocket[0];
port = Integer.parseInt(locationSocket[1]);
} else if (locationSocket.length == 1) {
hostname = locationSocket[0];
port = config.getPort();
} else {
throw new VertexiumException("Invalid elastic search location: " + esLocation);
}
transportClient.addTransportAddress(new InetSocketTransportAddress(hostname, port));
}
return transportClient;
}
protected boolean getDefaultAllFieldEnabled() {
return true;
}
protected boolean isStoreSourceData() {
return getConfig().isStoreSourceData();
}
protected final boolean isAllFieldEnabled() {
return allFieldEnabled;
}
protected void loadIndexInfos() {
Map<String, IndexStats> indices = getExistingIndexNames();
for (String indexName : indices.keySet()) {
if (!indexSelectionStrategy.isIncluded(this, indexName)) {
LOGGER.debug("skipping index %s, not in indicesToQuery", indexName);
continue;
}
IndexInfo indexInfo = indexInfos.get(indexName);
if (indexInfo != null) {
continue;
}
LOGGER.debug("loading index info for %s", indexName);
indexInfo = createIndexInfo(indexName);
indexInfos.put(indexName, indexInfo);
}
}
private Map<String, IndexStats> getExistingIndexNames() {
return client.admin().indices().prepareStats().execute().actionGet().getIndices();
}
protected IndexInfo ensureIndexCreatedAndInitialized(String indexName, boolean storeSourceData) {
IndexInfo indexInfo = indexInfos.get(indexName);
if (indexInfo != null && indexInfo.isElementTypeDefined()) {
return indexInfo;
}
synchronized (indexInfos) {
if (indexInfo == null) {
if (!client.admin().indices().prepareExists(indexName).execute().actionGet().isExists()) {
try {
createIndex(indexName, storeSourceData);
} catch (IOException e) {
throw new VertexiumException("Could not create index: " + indexName, e);
}
}
indexInfo = createIndexInfo(indexName);
indexInfos.put(indexName, indexInfo);
}
ensureMappingsCreated(indexInfo);
return indexInfo;
}
}
protected IndexInfo createIndexInfo(String indexName) {
return new IndexInfo(indexName);
}
protected void ensureMappingsCreated(IndexInfo indexInfo) {
if (!indexInfo.isElementTypeDefined()) {
try {
XContentBuilder mappingBuilder = XContentFactory.jsonBuilder()
.startObject()
.startObject("_source").field("enabled", isStoreSourceData()).endObject()
.startObject("_all").field("enabled", isAllFieldEnabled()).endObject()
.startObject("properties");
createIndexAddFieldsToElementType(mappingBuilder);
XContentBuilder mapping = mappingBuilder.endObject()
.endObject();
client.admin().indices().preparePutMapping(indexInfo.getIndexName())
.setType(ELEMENT_TYPE)
.setSource(mapping)
.execute()
.actionGet();
indexInfo.setElementTypeDefined(true);
} catch (Throwable e) {
throw new VertexiumException("Could not add mappings to index: " + indexInfo.getIndexName(), e);
}
}
}
@SuppressWarnings("unused")
protected void createIndex(String indexName, boolean storeSourceData) throws IOException {
int shards = getConfig().getNumberOfShards();
CreateIndexResponse createResponse = client.admin().indices().prepareCreate(indexName)
.setSettings(ImmutableSettings.settingsBuilder().put("number_of_shards", shards))
.execute().actionGet();
ClusterHealthResponse health = client.admin().cluster().prepareHealth(indexName)
.setWaitForGreenStatus()
.execute().actionGet();
LOGGER.debug("Index status: %s", health.toString());
if (health.isTimedOut()) {
LOGGER.warn("timed out waiting for green index status, for index: %s", indexName);
}
}
protected void createIndexAddFieldsToElementType(XContentBuilder builder) throws IOException {
builder
.startObject(ELEMENT_TYPE_FIELD_NAME).field("type", "string").field("store", "true").endObject()
.startObject(VISIBILITY_FIELD_NAME).field("type", "string").field("analyzer", "keyword").field("index", "not_analyzed").field("store", "true").endObject()
;
getConfig().getScoringStrategy().addFieldsToElementType(builder);
}
public synchronized void loadPropertyDefinitions() {
for (String indexName : indexInfos.keySet()) {
loadPropertyDefinitions(indexName);
}
}
private void loadPropertyDefinitions(String indexName) {
IndexInfo indexInfo = indexInfos.get(indexName);
Map<String, String> propertyTypes = getPropertyTypesFromServer(indexName);
for (Map.Entry<String, String> property : propertyTypes.entrySet()) {
PropertyDefinition propertyDefinition = createPropertyDefinition(property, propertyTypes);
indexInfo.addPropertyDefinition(deflatePropertyName(propertyDefinition), propertyDefinition);
}
}
private PropertyDefinition createPropertyDefinition(Map.Entry<String, String> property, Map<String, String> propertyTypes) {
String propertyName = deflatePropertyName(property.getKey());
Class dataType = elasticSearchTypeToClass(property.getValue());
Set<TextIndexHint> indexHints = new HashSet<>();
if (dataType == String.class) {
if (propertyTypes.containsKey(propertyName + GEO_PROPERTY_NAME_SUFFIX)) {
dataType = GeoPoint.class;
indexHints.add(TextIndexHint.FULL_TEXT);
} else if (propertyName.endsWith(EXACT_MATCH_PROPERTY_NAME_SUFFIX)) {
indexHints.add(TextIndexHint.EXACT_MATCH);
if (propertyTypes.containsKey(propertyName.substring(0, propertyName.length() - EXACT_MATCH_PROPERTY_NAME_SUFFIX.length()))) {
indexHints.add(TextIndexHint.FULL_TEXT);
}
} else {
indexHints.add(TextIndexHint.FULL_TEXT);
if (propertyTypes.containsKey(propertyName + EXACT_MATCH_PROPERTY_NAME_SUFFIX)) {
indexHints.add(TextIndexHint.EXACT_MATCH);
}
}
} else if (dataType == GeoPoint.class) {
indexHints.add(TextIndexHint.FULL_TEXT);
}
return new PropertyDefinition(propertyName, dataType, indexHints);
}
private Class elasticSearchTypeToClass(String typeName) {
if ("string".equals(typeName)) {
return String.class;
}
if ("float".equals(typeName)) {
return Float.class;
}
if ("double".equals(typeName)) {
return Double.class;
}
if ("byte".equals(typeName)) {
return Byte.class;
}
if ("short".equals(typeName)) {
return Short.class;
}
if ("integer".equals(typeName)) {
return Integer.class;
}
if ("date".equals(typeName)) {
return Date.class;
}
if ("long".equals(typeName)) {
return Long.class;
}
if ("boolean".equals(typeName)) {
return Boolean.class;
}
if ("geo_point".equals(typeName)) {
return GeoPoint.class;
}
throw new VertexiumException("Unhandled type: " + typeName);
}
private Map<String, String> getPropertyTypesFromServer(String indexName) {
Map<String, String> propertyTypes = new HashMap<>();
try {
ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> imd = client.admin().indices().prepareGetMappings(indexName).execute().actionGet().getMappings();
for (ObjectCursor<ImmutableOpenMap<String, MappingMetaData>> m : imd.values()) {
ObjectContainer<MappingMetaData> mappingMetaDatas = m.value.values();
for (ObjectCursor<MappingMetaData> mappingMetaData : mappingMetaDatas) {
Map<String, Object> sourceAsMap = mappingMetaData.value.getSourceAsMap();
Map properties = (Map) sourceAsMap.get("properties");
for (Object propertyObj : properties.entrySet()) {
Map.Entry property = (Map.Entry) propertyObj;
String propertyName = inflatePropertyName((String) property.getKey());
try {
Map propertyAttributes = (Map) property.getValue();
String propertyType = (String) propertyAttributes.get("type");
if (propertyType != null) {
propertyTypes.put(propertyName, propertyType);
continue;
}
Map subProperties = (Map) propertyAttributes.get("properties");
if (subProperties != null) {
if (subProperties.containsKey("lat") && subProperties.containsKey("lon")) {
propertyTypes.put(propertyName, "geo_point");
continue;
}
}
throw new VertexiumException("Failed to parse property type on property could not determine property type: " + propertyName);
} catch (Exception ex) {
throw new VertexiumException("Failed to parse property type on property: " + propertyName);
}
}
}
}
} catch (Exception ex) {
throw new VertexiumException("Could not get current properties from elastic search for index " + indexName, ex);
}
return propertyTypes;
}
@Override
public abstract void addElement(Graph graph, Element element, Authorizations authorizations);
@Override
public abstract void deleteElement(Graph graph, Element element, Authorizations authorizations);
@Override
public void deleteProperty(Graph graph, Element element, Property property, Authorizations authorizations) {
deleteProperty(graph, element, property.getKey(), deflatePropertyName(graph, property), property.getVisibility(), authorizations);
}
@Override
public void deleteProperty(Graph graph, Element element, String propertyKey, String propertyName, Visibility propertyVisibility, Authorizations authorizations) {
addElement(graph, element, authorizations);
}
@Override
public void addElements(Graph graph, Iterable<? extends Element> elements, Authorizations authorizations) {
int totalCount = 0;
Map<IndexInfo, BulkRequest> bulkRequests = new HashMap<>();
for (Element element : elements) {
IndexInfo indexInfo = addPropertiesToIndex(graph, element, element.getProperties());
BulkRequest bulkRequest = bulkRequests.get(indexInfo);
if (bulkRequest == null) {
bulkRequest = new BulkRequest();
bulkRequests.put(indexInfo, bulkRequest);
}
if (bulkRequest.numberOfActions() >= MAX_BATCH_COUNT || bulkRequest.estimatedSizeInBytes() > MAX_BATCH_SIZE) {
LOGGER.debug("adding elements... %d (est size %d)", bulkRequest.numberOfActions(), bulkRequest.estimatedSizeInBytes());
totalCount += bulkRequest.numberOfActions();
doBulkRequest(bulkRequest);
bulkRequest = new BulkRequest();
bulkRequests.put(indexInfo, bulkRequest);
}
addElementToBulkRequest(graph, bulkRequest, indexInfo, element, authorizations);
getConfig().getScoringStrategy().addElement(this, graph, bulkRequest, indexInfo, element, authorizations);
}
for (BulkRequest bulkRequest : bulkRequests.values()) {
if (bulkRequest.numberOfActions() > 0) {
LOGGER.debug("adding elements... %d (est size %d)", bulkRequest.numberOfActions(), bulkRequest.estimatedSizeInBytes());
totalCount += bulkRequest.numberOfActions();
doBulkRequest(bulkRequest);
}
}
LOGGER.debug("added %d elements", totalCount);
if (getConfig().isAutoFlush()) {
flush();
}
}
@Override
public abstract SearchIndexSecurityGranularity getSearchIndexSecurityGranularity();
@Override
public abstract GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations);
@Override
public MultiVertexQuery queryGraph(Graph graph, String[] vertexIds, String queryString, Authorizations authorizations) {
return new DefaultMultiVertexQuery(graph, vertexIds, queryString, getAllPropertyDefinitions(), authorizations);
}
@Override
public abstract VertexQuery queryVertex(Graph graph, Vertex vertex, String queryString, Authorizations authorizations);
@Override
public boolean isQuerySimilarToTextSupported() {
return true;
}
@Override
public abstract SimilarToGraphQuery querySimilarTo(Graph graph, String[] similarToFields, String similarToText, Authorizations authorizations);
public Map<String, PropertyDefinition> getAllPropertyDefinitions() {
Map<String, PropertyDefinition> allPropertyDefinitions = new HashMap<>();
for (IndexInfo indexInfo : this.indexInfos.values()) {
allPropertyDefinitions.putAll(indexInfo.getPropertyDefinitions());
}
return allPropertyDefinitions;
}
@Override
public void flush() {
client.admin().indices().prepareRefresh(getIndexNamesAsArray()).execute().actionGet();
}
protected String[] getIndexNamesAsArray() {
if (indexInfos.size() == indexInfosLastSize) {
return indexNamesAsArray;
}
synchronized (this) {
Set<String> keys = indexInfos.keySet();
indexNamesAsArray = keys.toArray(new String[keys.size()]);
indexInfosLastSize = indexInfos.size();
return indexNamesAsArray;
}
}
@Override
public void shutdown() {
client.close();
if (inProcessNode != null) {
inProcessNode.stop();
inProcessNode = null;
}
}
@Override
public void addPropertyDefinition(Graph graph, PropertyDefinition propertyDefinition) throws IOException {
LOGGER.debug("adding property definition: %s", propertyDefinition.toString());
String propertyName = deflatePropertyName(propertyDefinition);
for (String indexName : getIndexNames(propertyDefinition)) {
IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName, isStoreSourceData());
addPropertyDefinitionToIndex(graph, indexInfo, propertyName, propertyDefinition);
indexInfo.addPropertyDefinition(propertyName, propertyDefinition);
}
}
@Override
public boolean isPropertyDefined(String propertyName) {
for (String indexName : getIndexNamesAsArray()) {
IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName, isStoreSourceData());
if (indexInfo.isPropertyDefined(propertyName)) {
return true;
}
}
return false;
}
protected void addPropertyDefinitionToIndex(Graph graph, IndexInfo indexInfo, String propertyName, PropertyDefinition propertyDefinition) throws IOException {
if (propertyDefinition.getDataType() == String.class) {
if (propertyDefinition.getTextIndexHints().contains(TextIndexHint.EXACT_MATCH)) {
addPropertyToIndex(graph, indexInfo, propertyName + EXACT_MATCH_PROPERTY_NAME_SUFFIX, String.class, false, propertyDefinition.getBoost(), propertyDefinition.isSortable());
}
if (propertyDefinition.getTextIndexHints().contains(TextIndexHint.FULL_TEXT)) {
addPropertyToIndex(graph, indexInfo, propertyName, String.class, true, propertyDefinition.getBoost(), propertyDefinition.isSortable());
}
} else if (propertyDefinition.getDataType() == GeoPoint.class
|| propertyDefinition.getDataType() == GeoCircle.class) {
addPropertyToIndex(graph, indexInfo, propertyName + GEO_PROPERTY_NAME_SUFFIX, propertyDefinition.getDataType(), true, propertyDefinition.getBoost(), propertyDefinition.isSortable());
addPropertyToIndex(graph, indexInfo, propertyName, String.class, true, propertyDefinition.getBoost(), propertyDefinition.isSortable());
} else {
addPropertyToIndex(graph, indexInfo, propertyDefinition);
}
}
@SuppressWarnings("unused")
protected String[] getIndexNames(PropertyDefinition propertyDefinition) {
return indexSelectionStrategy.getIndexNames(this, propertyDefinition);
}
@SuppressWarnings("unused")
protected String getIndexName(Element element) {
return indexSelectionStrategy.getIndexName(this, element);
}
protected String[] getIndicesToQuery() {
return indexSelectionStrategy.getIndicesToQuery(this);
}
@Override
public boolean isFieldBoostSupported() {
return true;
}
public IndexInfo addPropertiesToIndex(Graph graph, Element element, Iterable<Property> properties) {
try {
String indexName = getIndexName(element);
IndexInfo indexInfo = ensureIndexCreatedAndInitialized(indexName, isStoreSourceData());
for (Property property : properties) {
addPropertyToIndex(graph, indexInfo, property);
}
return indexInfo;
} catch (IOException e) {
throw new VertexiumException("Could not add properties to index", e);
}
}
private void addPropertyToIndex(Graph graph, IndexInfo indexInfo, String propertyName, Class dataType, boolean analyzed, boolean sortable) throws IOException {
addPropertyToIndex(graph, indexInfo, propertyName, dataType, analyzed, null, sortable);
}
private void addPropertyToIndex(Graph graph, IndexInfo indexInfo, PropertyDefinition propertyDefinition) throws IOException {
addPropertyToIndex(graph, indexInfo, deflatePropertyName(propertyDefinition), propertyDefinition.getDataType(), true, propertyDefinition.getBoost(), propertyDefinition.isSortable());
}
public void addPropertyToIndex(Graph graph, IndexInfo indexInfo, Property property) throws IOException {
String deflatedPropertyName = deflatePropertyName(graph, property);
if (indexInfo.isPropertyDefined(deflatedPropertyName)) {
return;
}
Class dataType;
Object propertyValue = property.getValue();
if (propertyValue instanceof StreamingPropertyValue) {
StreamingPropertyValue streamingPropertyValue = (StreamingPropertyValue) propertyValue;
if (!streamingPropertyValue.isSearchIndex()) {
return;
}
dataType = streamingPropertyValue.getValueType();
addPropertyToIndex(graph, indexInfo, deflatedPropertyName, dataType, true, false);
} else if (propertyValue instanceof String) {
dataType = String.class;
addPropertyToIndex(graph, indexInfo, deflatedPropertyName + EXACT_MATCH_PROPERTY_NAME_SUFFIX, dataType, false, false);
addPropertyToIndex(graph, indexInfo, deflatedPropertyName, dataType, true, false);
} else if (propertyValue instanceof GeoPoint) {
addPropertyToIndex(graph, indexInfo, deflatedPropertyName + GEO_PROPERTY_NAME_SUFFIX, GeoPoint.class, true, false);
addPropertyToIndex(graph, indexInfo, deflatedPropertyName, String.class, true, false);
} else if (propertyValue instanceof GeoCircle) {
addPropertyToIndex(graph, indexInfo, deflatedPropertyName + GEO_PROPERTY_NAME_SUFFIX, GeoCircle.class, true, false);
addPropertyToIndex(graph, indexInfo, deflatedPropertyName, String.class, true, false);
} else {
checkNotNull(propertyValue, "property value cannot be null for property: " + deflatedPropertyName);
dataType = propertyValue.getClass();
addPropertyToIndex(graph, indexInfo, deflatedPropertyName, dataType, true, true);
}
}
protected String inflatePropertyName(String string) {
return nameSubstitutionStrategy.inflate(string);
}
protected String deflatePropertyName(Graph graph, Property property) {
return deflatePropertyName(property.getName());
}
protected String deflatePropertyName(PropertyDefinition propertyDefinition) {
return deflatePropertyName(propertyDefinition.getPropertyName());
}
protected String deflatePropertyName(String propertyName) {
return nameSubstitutionStrategy.deflate(propertyName);
}
public String[] getAllMatchingPropertyNames(Graph graph, String propertyName, Authorizations authorizations) {
return new String[]{nameSubstitutionStrategy.deflate(propertyName)};
}
protected abstract void addPropertyToIndex(Graph graph, IndexInfo indexInfo, String propertyName, Class dataType, boolean analyzed, Double boost, boolean sortable) throws IOException;
protected boolean shouldIgnoreType(Class dataType) {
return dataType == byte[].class;
}
public Client getClient() {
return client;
}
public ElasticSearchSearchIndexConfiguration getConfig() {
return config;
}
protected void addTypeToMapping(XContentBuilder mapping, String propertyName, Class dataType, boolean analyzed, Double boost) throws IOException {
if (dataType == String.class) {
LOGGER.debug("Registering string type for %s", propertyName);
mapping.field("type", "string");
if (!analyzed) {
mapping.field("index", "not_analyzed");
mapping.field("ignore_above", EXACT_MATCH_IGNORE_ABOVE_LIMIT);
}
} else if (dataType == Float.class) {
LOGGER.debug("Registering float type for %s", propertyName);
mapping.field("type", "float");
} else if (dataType == Double.class) {
LOGGER.debug("Registering double type for %s", propertyName);
mapping.field("type", "double");
} else if (dataType == Byte.class) {
LOGGER.debug("Registering byte type for %s", propertyName);
mapping.field("type", "byte");
} else if (dataType == Short.class) {
LOGGER.debug("Registering short type for %s", propertyName);
mapping.field("type", "short");
} else if (dataType == Integer.class) {
LOGGER.debug("Registering integer type for %s", propertyName);
mapping.field("type", "integer");
} else if (dataType == Date.class || dataType == DateOnly.class) {
LOGGER.debug("Registering date type for %s", propertyName);
mapping.field("type", "date");
} else if (dataType == Long.class) {
LOGGER.debug("Registering long type for %s", propertyName);
mapping.field("type", "long");
} else if (dataType == Boolean.class) {
LOGGER.debug("Registering boolean type for %s", propertyName);
mapping.field("type", "boolean");
} else if (dataType == GeoPoint.class) {
LOGGER.debug("Registering geo_point type for %s", propertyName);
mapping.field("type", "geo_point");
} else if (dataType == GeoCircle.class) {
LOGGER.debug("Registering geo_shape type for %s", propertyName);
mapping.field("type", "geo_shape");
mapping.field("tree", "quadtree");
mapping.field("precision", "100m");
} else if (Number.class.isAssignableFrom(dataType)) {
LOGGER.debug("Registering double type for %s", propertyName);
mapping.field("type", "double");
} else {
throw new VertexiumException("Unexpected value type for property \"" + propertyName + "\": " + dataType.getName());
}
if (boost != null) {
mapping.field("boost", boost.doubleValue());
}
}
protected void doBulkRequest(BulkRequest bulkRequest) {
BulkResponse response = getClient().bulk(bulkRequest).actionGet();
if (response.hasFailures()) {
for (BulkItemResponse bulkResponse : response) {
if (bulkResponse.isFailed()) {
LOGGER.error("Failed to index %s (message: %s)", bulkResponse.getId(), bulkResponse.getFailureMessage());
}
}
throw new VertexiumException("Could not add element.");
}
}
@Override
public synchronized void truncate() {
LOGGER.warn("Truncate of Elasticsearch is not possible, dropping the indices and recreating instead.");
drop();
loadPropertyDefinitions();
}
@Override
public void drop() {
Set<String> indexInfosSet = indexInfos.keySet();
for (String indexName : indexInfosSet) {
try {
DeleteIndexRequest deleteRequest = new DeleteIndexRequest(indexName);
getClient().admin().indices().delete(deleteRequest).actionGet();
indexInfos.remove(indexName);
} catch (Exception ex) {
throw new VertexiumException("Could not delete index " + indexName, ex);
}
ensureIndexCreatedAndInitialized(indexName, isStoreSourceData());
}
}
public abstract void addElementToBulkRequest(Graph graph, BulkRequest bulkRequest, IndexInfo indexInfo, Element element, Authorizations authorizations);
@SuppressWarnings("unchecked")
protected void addPropertyValueToPropertiesMap(Map<String, Object> propertiesMap, String propertyName, Object propertyValue) {
Object existingValue = propertiesMap.get(propertyName);
if (existingValue == null) {
propertiesMap.put(propertyName, propertyValue);
return;
}
if (existingValue instanceof List) {
((List) existingValue).add(propertyValue);
return;
}
List list = new ArrayList();
list.add(existingValue);
list.add(propertyValue);
propertiesMap.put(propertyName, list);
}
protected void convertGeoPoint(Graph graph, XContentBuilder jsonBuilder, Property property, GeoPoint geoPoint) throws IOException {
Map<String, Object> propertyValueMap = new HashMap<>();
propertyValueMap.put("lat", geoPoint.getLatitude());
propertyValueMap.put("lon", geoPoint.getLongitude());
jsonBuilder.field(deflatePropertyName(graph, property) + GEO_PROPERTY_NAME_SUFFIX, propertyValueMap);
if (geoPoint.getDescription() != null) {
jsonBuilder.field(deflatePropertyName(graph, property), geoPoint.getDescription());
}
}
protected void convertGeoPoint(Graph graph, Map<String, Object> propertiesMap, Property property, GeoPoint geoPoint) throws IOException {
Map<String, Object> propertyValueMap = new HashMap<>();
propertyValueMap.put("lat", geoPoint.getLatitude());
propertyValueMap.put("lon", geoPoint.getLongitude());
addPropertyValueToPropertiesMap(propertiesMap, deflatePropertyName(graph, property) + GEO_PROPERTY_NAME_SUFFIX, propertyValueMap);
if (geoPoint.getDescription() != null) {
addPropertyValueToPropertiesMap(propertiesMap, deflatePropertyName(graph, property), geoPoint.getDescription());
}
}
protected void convertGeoCircle(Graph graph, XContentBuilder jsonBuilder, Property property, GeoCircle geoCircle) throws IOException {
Map<String, Object> propertyValueMap = new HashMap<>();
propertyValueMap.put("type", "circle");
List<Double> coordinates = new ArrayList<>();
coordinates.add(geoCircle.getLongitude());
coordinates.add(geoCircle.getLatitude());
propertyValueMap.put("coordinates", coordinates);
propertyValueMap.put("radius", geoCircle.getRadius() + "km");
jsonBuilder.field(deflatePropertyName(graph, property) + GEO_PROPERTY_NAME_SUFFIX, propertyValueMap);
if (geoCircle.getDescription() != null) {
jsonBuilder.field(deflatePropertyName(graph, property), geoCircle.getDescription());
}
}
protected void convertGeoCircle(Graph graph, Map<String, Object> propertiesMap, Property property, GeoCircle geoCircle) throws IOException {
Map<String, Object> propertyValueMap = new HashMap<>();
propertyValueMap.put("type", "circle");
List<Double> coordinates = new ArrayList<>();
coordinates.add(geoCircle.getLongitude());
coordinates.add(geoCircle.getLatitude());
propertyValueMap.put("coordinates", coordinates);
propertyValueMap.put("radius", geoCircle.getRadius() + "km");
addPropertyValueToPropertiesMap(propertiesMap, deflatePropertyName(graph, property) + GEO_PROPERTY_NAME_SUFFIX, propertyValueMap);
if (geoCircle.getDescription() != null) {
addPropertyValueToPropertiesMap(propertiesMap, deflatePropertyName(graph, property), geoCircle.getDescription());
}
}
public IndexSelectionStrategy getIndexSelectionStrategy() {
return indexSelectionStrategy;
}
public String getPropertyVisibilityHashFromDeflatedPropertyName(String propertyName) {
return "";
}
public String getAggregationName(String name) {
return name;
}
public boolean isAuthorizationFilterEnabled() {
return getConfig().isAuthorizationFilterEnabled();
}
public PropertyDefinition getPropertyDefinition(Graph graph, String propertyName) {
return getAllPropertyDefinitions().get(propertyName);
}
protected boolean isReservedFieldName(String fieldName) {
return fieldName.equals(ELEMENT_TYPE_FIELD_NAME) || fieldName.equals(VISIBILITY_FIELD_NAME);
}
} |
package org.neo4j.server;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.server.logging.InMemoryAppender;
import org.neo4j.server.web.Jetty6WebServer;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
public class NeoServerStartupLoggingFunctionalTest {
private File tempDir;
private NeoServer server;
private InMemoryAppender appender;
@Before
public void setupServer() throws IOException {
tempDir = new File(ServerTestUtils.createTempDir().getAbsolutePath() + File.separator + "html");
FileUtils.moveDirectory(new File("target/classes/webadmin-html"), tempDir);
appender = new InMemoryAppender(Jetty6WebServer.log);
server = ServerBuilder.server().withRandomDatabaseDir().withPassingStartupHealthcheck().build();
server.start();
}
@After
public void stopServer() throws IOException {
server.stop();
FileUtils.moveDirectory(tempDir, new File("target/classes/webadmin-html"));
}
@Test
public void shouldLogStartup() throws IOException, ServerStartupException {
// Check the logs
assertThat(appender.toString().length(), is(greaterThan(0)));
// Check the server is alive
Client client = Client.create();
client.setFollowRedirects(false);
ClientResponse response = client.resource("http://localhost:" + server.getWebServerPort() + "/").get(ClientResponse.class);
assertThat(response.getStatus(), is(greaterThan(199)));
}
} |
package uk.ac.ebi.spot.goci.component;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONArray;
import org.json.JSONObject;
import com.mashape.unirest.http.JsonNode;
import uk.ac.ebi.spot.goci.service.EnsemblRestService;
import uk.ac.ebi.spot.goci.model.EnsemblGene;
import uk.ac.ebi.spot.goci.model.EntrezGene;
import uk.ac.ebi.spot.goci.model.Gene;
import uk.ac.ebi.spot.goci.model.GenomicContext;
import uk.ac.ebi.spot.goci.model.Location;
import uk.ac.ebi.spot.goci.model.Region;
import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EnsemblMappingPipeline {
private String rsId;
private int merged;
private Collection<String> reported_genes = new ArrayList<>();
private Collection<Location> locations = new ArrayList<>();
private Collection<GenomicContext> genomic_contexts = new ArrayList<>();
private ArrayList<String> pipeline_errors = new ArrayList<>();
// Internal variables populated within the class
private ArrayList<String> overlapping_genes = new ArrayList<>();
private Hashtable<String, String> endpoints = new Hashtable<String, String>();
// Fixed variables
private final String ensembl_source = "Ensembl";
private final String ncbi_source = "NCBI";
private final String ncbi_db_type = "otherfeatures";
private final String ncbi_logic_name = "refseq_import";
private final String mapping_method = "Ensembl pipeline";
private final int genomic_distance = 100000; // 100kb
// JPA no-args constructor
public EnsemblMappingPipeline() {
this.setEndpoints();
}
public EnsemblMappingPipeline(String rsId, Collection<String> reported_genes) {
this.rsId = rsId;
this.reported_genes = reported_genes;
this.setEndpoints();
}
// Set the different Ensembl REST API endpoints used in the pipeline
protected void setEndpoints() {
String species = "homo_sapiens";
this.endpoints.put("variation", "/variation/" + species + "/");
this.endpoints.put("lookup_symbol", "/lookup/symbol/" + species + "/");
this.endpoints.put("overlap_region", "/overlap/region/" + species + "/");
this.endpoints.put("info_assembly", "/info/assembly/" + species + "/");
}
/**
* Getter for the collection of Location instances
* @return Collection of Location instances.
*/
public Collection<Location> getLocations() {
return locations;
}
/**
* Getter for the collection of GenomicContext instances
* @return Collection of GenomicContext instances.
*/
public Collection<GenomicContext> getGenomicContexts() {
return genomic_contexts;
}
/**
* Getter for the list of pipeline error messages
* @return List of strings.
*/
public ArrayList<String> getPipelineErrors() {
return pipeline_errors;
}
// Run the pipeline for a given SNP
public void run_pipeline() {
// Variation call
JSONObject variation_result = this.getVariationData();
if (variation_result.has("error")) {
this.checkError(variation_result, "variation", "Variant " + this.rsId + " is not found in Ensembl");
}
else {
// Merged SNP
this.merged = (variation_result.getString("name") == this.rsId) ? 0 : 1;
// Mapping errors
if (variation_result.has("failed")) {
pipeline_errors.add(variation_result.getString("failed"));
}
// Mapping and genomic context calls
JSONArray mappings = variation_result.getJSONArray("mappings");
this.getMappings(mappings);
// Genomic context & Reported genes
if (locations.size() > 0) {
// Genomic context (loop over the "locations" object)
for (Location snp_location : locations) {
this.getAllGenomicContexts(snp_location);
}
// Reported genes checks
if (reported_genes.size() > 0) {
this.checkReportedGenes();
}
}
}
}
/**
* Variation REST API call
* @return JSONObject containing the output of the Ensembl REST API endpoint "variation"
* @throws UnirestException
* @throws InterruptedException
*/
private JSONObject getVariationData() {
JSONObject variation_result = this.getSimpleRestCall("variation", this.rsId);
return variation_result;
}
/**
* Get the mappings data ( chromosome, position and cytogenetic band).
* Store the location information in the class variable "locations" (list of "Location" classes)
*
* @param mappings A JSONArray object containing the list the variant locations
* @throws UnirestException
* @throws InterruptedException
*/
private void getMappings(JSONArray mappings) {
for (int i = 0; i < mappings.length(); ++i) {
JSONObject mapping = mappings.getJSONObject(i);
if (!mapping.has("seq_region_name")) {
continue;
}
String chromosome = mapping.getString("seq_region_name");
String position = String.valueOf(mapping.getInt("start"));
Region cytogenetic_band = this.getRegion(chromosome, position);
Location location = new Location(chromosome,position,cytogenetic_band);
locations.add(location);
}
}
/**
* Get the cytogenetic band from a given location
*
* @param chromosome the chromosome name
* @param position the position of the variant
* @return Region object only containing a region name
* @throws UnirestException
* @throws InterruptedException
*/
private Region getRegion(String chromosome, String position) {
String band = "NA"; // Default value
String rest_opt = "feature=band";
// REST Call
JSONArray cytogenetic_band_result = this.getOverlapRegionCalls(chromosome, position, position, rest_opt);
if (cytogenetic_band_result.length() != 0 && !cytogenetic_band_result.getJSONObject(0).has("error")) {
String cytogenetic_band = cytogenetic_band_result.getJSONObject(0).getString("id");
Matcher matcher1 = Pattern.compile("^[0-9]+|[XY]$").matcher(chromosome); // Chromosomes
Matcher matcher2 = Pattern.compile("^MT$").matcher(chromosome); // Mitochondria
if (matcher1.matches() || matcher2.matches()) {
band = chromosome + cytogenetic_band;
}
}
Region region = new Region(band);
return region;
}
/**
* Run the genomic context pipeline for both sources (Ensembl and NCBI)
*
* @param snp_location an instance of the Location class (chromosome name and position)
* @throws UnirestException
* @throws InterruptedException
*/
private void getAllGenomicContexts(Location snp_location) {
int chr_start = 1;
int chr_end = this.getChromosomeEnd(snp_location.getChromosomeName());
this.getGenomicContext(snp_location, chr_start, chr_end, this.ensembl_source);
this.getGenomicContext(snp_location, chr_start, chr_end, this.ncbi_source);
}
/**
* Get the genomic context in 3 calls: overlap, upstream and downstream genes
*
* @param snp_location an instance of the Location class (chromosome name and position)
* @param chr_start 5' start position of the chromosome
* @param chr_end 3' end position of the chromosome
* @param source the source of the data (Ensembl or NCBI)
*/
private void getGenomicContext(Location snp_location, int chr_start, int chr_end, String source) {
// By default the db_type is 'core' (i.e. Ensembl)
String rest_opt = "feature=gene";
if (source == this.ncbi_source) {
rest_opt += "&logic_name="+this.ncbi_logic_name;
rest_opt += "&db_type="+this.ncbi_db_type;
}
// Overlapping genes
this.getOverlappingGenes(snp_location, source, rest_opt);
// Upstream genes
this.getUpstreamGenes(snp_location, source, chr_start, rest_opt);
// Downstream genes
this.getDownstreamGenes(snp_location, source, chr_end, rest_opt);
}
/**
* Get the list of overlapping genes
*
* @param snp_location an instance of the Location class (chromosome name and position)
* @param source the source of the data (Ensembl or NCBI)
* @param rest_opt the extra parameters to add at the end of the REST call url
*/
private void getOverlappingGenes(Location snp_location, String source, String rest_opt) {
String chromosome = snp_location.getChromosomeName();
String position = snp_location.getChromosomePosition();
// Check if there are overlap genes
JSONArray overlap_gene_result = this.getOverlapRegionCalls(chromosome, position, position, rest_opt);
if (overlap_gene_result.length() != 0 && !overlap_gene_result.getJSONObject(0).has("error")) {
for (int i = 0; i < overlap_gene_result.length(); ++i) {
JSONObject gene_json_object = overlap_gene_result.getJSONObject(i);
String gene_name = gene_json_object.getString("external_name");
overlapping_genes.add(gene_name);
}
this.addGenomicContext(overlap_gene_result, snp_location, source, "overlap");
}
}
/**
* Get the list of upstream genes
*
* @param snp_location an instance of the Location class (chromosome name and position)
* @param source the source of the data (Ensembl or NCBI)
* @param chr_start 5' start position of the chromosome
* @param rest_opt the extra parameters to add at the end of the REST call url
*/
private void getUpstreamGenes(Location snp_location, String source, int chr_start, String rest_opt) {
String type = "upstream";
String chromosome = snp_location.getChromosomeName();
String position = snp_location.getChromosomePosition();
int position_up = Integer.parseInt(snp_location.getChromosomePosition()) - genomic_distance;
if (position_up < 0) {
position_up = chr_start;
}
String pos_up = String.valueOf(position_up);
// Check if there are overlap genes
JSONArray overlap_gene_result = this.getOverlapRegionCalls(chromosome,pos_up,position,rest_opt);
if ((overlap_gene_result.length() != 0 && !overlap_gene_result.getJSONObject(0).has("error")) || overlap_gene_result.length() == 0) {
boolean closest_found = this.addGenomicContext(overlap_gene_result, snp_location, source, type);
if (!closest_found) {
if (position_up > chr_start) {
JSONArray closest_gene = this.getNearestGene(chromosome, position, pos_up, 1, rest_opt, type);
if (closest_gene.length() > 0) {
addGenomicContext(closest_gene, snp_location, source, type);
}
}
}
}
}
/**
* Get the list of downstream genes
*
* @param snp_location an instance of the Location class (chromosome name and position)
* @param source the source of the data (Ensembl or NCBI)
* @param chr_end 3' end position of the chromosome
* @param rest_opt the extra parameters to add at the end of the REST call url
*/
private void getDownstreamGenes(Location snp_location, String source, int chr_end, String rest_opt) {
String type = "downstream";
String chromosome = snp_location.getChromosomeName();
String position = snp_location.getChromosomePosition();
int position_down = Integer.parseInt(snp_location.getChromosomePosition()) + genomic_distance;
// Check the downstream position to avoid having a position over the 3' end of the chromosome
if (chr_end != 0 && position_down > chr_end) {
position_down = chr_end;
}
String pos_down = String.valueOf(position_down);
// Check if there are overlap genes
JSONArray overlap_gene_result = this.getOverlapRegionCalls(chromosome,position,pos_down,rest_opt);
if ((overlap_gene_result.length() != 0 && !overlap_gene_result.getJSONObject(0).has("error")) || overlap_gene_result.length() == 0) {
boolean closest_found = this.addGenomicContext(overlap_gene_result, snp_location, source, type);
if (!closest_found) {
if (position_down != chr_end) {
JSONArray closest_gene =
this.getNearestGene(chromosome, position, pos_down, chr_end, rest_opt, type);
if (closest_gene.length() > 0) {
addGenomicContext(closest_gene, snp_location, source, type);
}
}
}
}
}
/**
* Create GenomicContext objects from the JSONObjects and add them to the class variable "genomic_contexts"
* (list of "GenomicContext" classes)
*
* @param json_gene_list the list of overlapping genes in JSONObject format
* @param snp_location an instance of the Location class (chromosome name and position)
* @param source the source of the data (Ensembl or NCBI)
* @param type the type of genomic context (i.e. overlap, upstream, downstream)
* @return boolean to indicate whether a closest gene has been found or not (only relevant for upstream and downstream gene)
*/
private boolean addGenomicContext(JSONArray json_gene_list, Location snp_location, String source, String type) {
String closest_gene = "";
int closest_distance = 0;
boolean intergenic = (type == "overlap") ? false : true;
boolean upstream = (type == "upstream") ? true : false;
boolean downstream = (type == "downstream") ? true: false;
String position = snp_location.getChromosomePosition();
SingleNucleotidePolymorphism snp_tmp = new SingleNucleotidePolymorphism(); // TODO Try to use the repository to find existing SNP ?
snp_tmp.setRsId(this.rsId);
// Get closest gene
if (intergenic) {
int pos = Integer.parseInt(position);
for (int i = 0; i < json_gene_list.length(); ++i) {
JSONObject json_gene = json_gene_list.getJSONObject(i);
String gene_id = json_gene.getString("id");
String gene_name = json_gene.getString("external_name");
if ((gene_name != null && overlapping_genes.contains(gene_name)) || gene_name == null) { // Skip overlapping genes which also overlap upstream and/or downstream of the variant
continue;
}
int distance = 0;
if (type == "upstream") {
distance = pos - json_gene.getInt("end");
}
else if (type == "downstream") {
distance = json_gene.getInt("start") - pos;
}
if ((distance < closest_distance && distance > 0) || closest_distance == 0) {
closest_gene = gene_id;
closest_distance = distance;
}
}
}
for (int i = 0; i < json_gene_list.length(); ++i) {
JSONObject json_gene = json_gene_list.getJSONObject(i);
String gene_id = json_gene.getString("id");
String gene_name = json_gene.getString("external_name");
String ncbi_id = (source == "NCBI") ? gene_id : null;
String ensembl_id = (source == "Ensembl") ? gene_id : null;
int distance = 0;
if (intergenic) {
if ((gene_name != null && overlapping_genes.contains(gene_name)) || gene_name ==
null) { // Skip overlapping genes which also overlap upstream and/or downstream of the variant
continue;
}
int pos = Integer.parseInt(position);
if (type == "upstream") {
distance = pos - json_gene.getInt("end");
}
else if (type == "downstream") {
distance = json_gene.getInt("start") - pos;
}
}
Long dist = new Long(distance);
// TODO: (Emma) Updated GENE model object so it can have
// TODO: collection of entrez/ensembl gene IDs
EntrezGene entrezGene = new EntrezGene();
entrezGene.setEntrezGeneId(ncbi_id);
Collection<EntrezGene> entrezGenes = new ArrayList<>();
entrezGenes.add(entrezGene);
EnsemblGene ensemblGene = new EnsemblGene();
ensemblGene.setEnsemblGeneId(ensembl_id);
Collection<EnsemblGene> ensemblGenes = new ArrayList<>();
ensemblGenes.add(ensemblGene);
Gene gene_object = new Gene(gene_name, entrezGenes, ensemblGenes);
// Check if the gene corresponds to the closest gene
boolean is_closest_gene = (closest_gene == gene_id && closest_gene != "") ? true : false;
GenomicContext gc = new GenomicContext(intergenic, upstream, downstream, dist, snp_tmp, gene_object, snp_location, source, mapping_method, is_closest_gene);
genomic_contexts.add(gc);
}
return (closest_gene != "") ? true : false;
}
/**
* Recursive method to get the closest upstream or downstream gene over the 100kb range, jumping 100kb by 100kb
* until a gene is found or the boundary of the chromosome is reached.
*
* @param chromosome the chromosome name
* @param snp_position the position of the variant
* @param position the start position for the search (at least 100kb upstream or downstream from the variant)
* @param boundary the chromosome boundary (upstream: beginning of the chromosome (position 1), downstream: end of the chromosome)
* @param rest_opt the extra parameters to add at the end of the REST call url (inherited from other methods)
* @param type the type of genomic context (i.e. overlap, upstream, downstream)
* @return A JSONArray object containing a single JSONObject corresponding to the closest gene (upstream or downstream) over the 100kb range
*/
private JSONArray getNearestGene (String chromosome,String snp_position, String position, int boundary, String rest_opt, String type) {
int position1 = Integer.parseInt(position);
int position2 = Integer.parseInt(position);
int snp_pos = Integer.parseInt(snp_position);
String new_pos = position;
JSONArray closest_gene = new JSONArray();
int closest_distance = 0;
if (type == "upstream") {
position1 = position2 - genomic_distance;
position1 = (position1 < 0) ? boundary : position1;
new_pos = String.valueOf(position1);
}
else {
if (type == "downstream") {
position2 = position1 + genomic_distance;
position2 = (position2 > boundary) ? boundary : position2;
new_pos = String.valueOf(position2);
}
}
String pos1 = String.valueOf(position1);
String pos2 = String.valueOf(position2);
JSONArray json_gene_list = this.getOverlapRegionCalls(chromosome,pos1,pos2,rest_opt);
for (int i = 0; i < json_gene_list.length(); ++i) {
JSONObject json_gene = json_gene_list.getJSONObject(i);
String gene_id = json_gene.getString("id");
String gene_name = json_gene.getString("external_name");
if ((gene_name != null && overlapping_genes.contains(gene_name)) || gene_name ==
null) { // Skip overlapping genes which also overlap upstream and/or downstream of the variant
continue;
}
int distance = 0;
if (type == "upstream") {
distance = snp_pos - json_gene.getInt("end");
}
else if (type == "downstream") {
distance = json_gene.getInt("start") - snp_pos;
}
if ((distance < closest_distance && distance > 0) || closest_distance == 0) {
closest_gene = new JSONArray("["+json_gene.toString()+"]");
closest_distance = distance;
}
}
if (closest_gene.length() == 0) {
if (position2 != boundary) {
// Recursive code to find the nearest upstream or downstream gene
closest_gene = this.getNearestGene(chromosome, snp_position, new_pos, boundary, rest_opt, type);
}
}
return closest_gene;
}
/**
* Ensembl REST API call for the overlap region endpoint
*
* @param chromosome the chromosome name
* @param position1 the 5' position of the region
* @param position2 the 3' position of the region
* @param rest_opt the extra parameters to add at the end of the REST call url (inherited from other methods)
* @return A JSONArray object containing a list of JSONObjects corresponding to the genes overlapping the region
*/
private JSONArray getOverlapRegionCalls (String chromosome, String position1, String position2, String rest_opt) {
String webservice = "overlap_region";
String endpoint = this.getEndpoint(webservice);
String data = chromosome+":"+position1+"-"+position2;
EnsemblRestService rest_overlap = new EnsemblRestService(endpoint, data, rest_opt);
JSONArray overlap_result = new JSONArray();
try {
rest_overlap.getRestCall();
JsonNode result = rest_overlap.getRestResults();
if (result.isArray())
overlap_result = result.getArray();
else {
JSONObject res_obj = result.getObject();
if (res_obj.has("error")) {
this.checkError(res_obj,webservice,"");
overlap_result.put(0,result); // Add error in the result
}
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (UnirestException e) {
e.printStackTrace();
}
return overlap_result;
}
/**
* Simple generic Ensembl REST API call method.
*
* @param endpoint_type the endpoint name
* @param data the data/id/symbol we want to query
* @return the corresponding JSONObject
*/
private JSONObject getSimpleRestCall (String endpoint_type, String data) {
String endpoint = this.getEndpoint(endpoint_type);
EnsemblRestService ens_rest_call = new EnsemblRestService(endpoint, data);
JSONObject json_result = new JSONObject();
try {
ens_rest_call.getRestCall();
json_result = ens_rest_call.getRestResults().getObject();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (UnirestException e) {
e.printStackTrace();
}
return json_result;
}
/**
* Get the end position of a given chromosome, using an Ensembl REST API call
*
* @param chromosome the chromosome name
* @return the position of the end of the chromosome
*/
private int getChromosomeEnd (String chromosome) {
int chr_end = 0;
String webservice = "info_assembly";
JSONObject info_result = this.getSimpleRestCall(webservice, chromosome);
if (info_result.has("error")) {
this.checkError(info_result, webservice, "Chromosome end not found");
}
else {
chr_end = info_result.getInt("length");
}
return chr_end;
}
/**
* Check that the reported gene symbols exist and that they are located in the same chromosome as the variant
*/
private void checkReportedGenes() {
for (String reported_gene : this.reported_genes) {
reported_gene = reported_gene.replaceAll(" ",""); // Remove extra spaces
String webservice = "lookup_symbol";
JSONObject reported_gene_result = this.getSimpleRestCall(webservice, reported_gene);
// Gene symbol not found in Ensembl
if (reported_gene_result.has("error")) {
this.checkError(reported_gene_result, webservice, "Reported gene "+reported_gene+" is not found in Ensembl");
}
// Check if the gene is in the same chromosome as the variant
else {
if (reported_gene_result.has("seq_region_name")) {
String gene_chromosome = reported_gene_result.getString("seq_region_name");
int same_chromosome = 0;
for (Location location : this.locations) {
String snp_chromosome = location.getChromosomeName();
if (gene_chromosome.equals(snp_chromosome)) {
same_chromosome = 1;
break;
}
}
if (same_chromosome == 0) {
pipeline_errors.add("Reported gene " + reported_gene + " is on a different chromosome (chr" + gene_chromosome + ")");
}
}
// No gene location found
else {
pipeline_errors.add("Can't find a location in Ensembl for the reported gene " + reported_gene);
}
}
}
}
/**
* Check the type of error returned by the REST web service JSON output
* @param result The JSONObject result
* @param webservice The name of the REST web service
* @param default_message The default error message
*/
private void checkError(JSONObject result, String webservice, String default_message) {
if (result.getString("error").contains("page not found")) {
pipeline_errors.add("Web service '"+webservice+"' not found or not working.");
}
else {
if (default_message.equals("")) {
pipeline_errors.add(result.getString("error"));
}
else {
pipeline_errors.add(default_message);
}
}
}
/**
* Return the Ensembl REST API endpoint URL corresponding the the endpoint name provided
*
* @param endpoint_name the name of the REST API endpoint
* @return the URL part specific to the queried endpoint
*/
private String getEndpoint(String endpoint_name) {
return this.endpoints.get(endpoint_name);
}
} |
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class TennisGameScoreTest {
@InjectMocks
private TennisGameScore tennisGameScore;
@Test
public void should_game_over_when_federer_wins_the_game() {
// Arrange
tennisGameScore.setFedererScore(4);
// Act
boolean tennisGameOver = tennisGameScore.isOver();
// Assert
assertThat(tennisGameOver).isTrue();
}
@Test
public void should_game_over_when_nadal_wins_the_game() {
// Arrange
tennisGameScore.setNadalScore(4);
// Act
boolean tennisGameOver = tennisGameScore.isOver();
// Assert
assertThat(tennisGameOver).isTrue();
}
@Test
public void should_not_game_over_when_no_one_wins() {
// Arrange
tennisGameScore.setFedererScore(2);
tennisGameScore.setNadalScore(2);
// Act
boolean tennisGameNotOver = tennisGameScore.isNotOver();
// Assert
assertThat(tennisGameNotOver).isTrue();
}
@Test
public void should_add_point_to_federer_when_federer_wins_point() {
// Act
tennisGameScore.addPointFederer();
// Assert
assertThat(tennisGameScore.getFedererScore()).isEqualTo(1);
assertThat(tennisGameScore.getWinner()).isEqualTo("Federer");
}
@Test
public void should_add_point_to_nadal_when_nadal_wins_point() {
// Act
tennisGameScore.addPointNadal();
// Assert
assertThat(tennisGameScore.getWinner()).isEqualTo("Nadal");
assertThat(tennisGameScore.getNadalScore()).isEqualTo(1);
}
@Test
public void should_give_0_as_tennis_score_when_score_is_0() {
// Arrange
int score = 0;
// Act
String tennisScore = tennisGameScore.toTennisScore(score);
// Assert
assertThat(tennisScore).isEqualTo("0");
}
@Test
public void should_give_15_as_tennis_score_when_score_is_1() {
// Arrange
int score = 1;
// Act
String tennisScore = tennisGameScore.toTennisScore(score);
// Assert
assertThat(tennisScore).isEqualTo("15");
}
@Test
public void should_give_30_as_tennis_score_when_score_is_2() {
// Arrange
int score = 2;
// Act
String tennisScore = tennisGameScore.toTennisScore(score);
// Assert
assertThat(tennisScore).isEqualTo("30");
}
@Test
public void should_give_40_as_tennis_score_when_score_is_3() {
// Arrange
int score = 3;
// Act
String tennisScore = tennisGameScore.toTennisScore(score);
// Assert
assertThat(tennisScore).isEqualTo("40");
}
@Test
public void should_add_game_column_to_game_score_table_when_it_has_a_game_winner() {
// Arrange
tennisGameScore.addPointFederer();
tennisGameScore.addPointFederer();
tennisGameScore.addPointFederer();
tennisGameScore.addPointFederer();
// Act
tennisGameScore.addGameOverCol();
// Assert
assertThat(tennisGameScore.getGameScoreHeader().get(2)).isEqualTo("Federer wins 1 point");
assertThat(tennisGameScore.getGameScoreFedererRow().get(2)).isEqualTo("0");
assertThat(tennisGameScore.getGameScoreNadalRow().get(2)).isEqualTo("0");
assertThat(tennisGameScore.getGameScoreWinnerRow().get(2)).isEqualTo("Federer wins the game");
}
@Test
public void should_add_game_column_to_game_score_table_when_it_has_a_point_winner() {
// Arrange
tennisGameScore.addPointFederer();
// Act
tennisGameScore.addPointCol();
// Assert
assertThat(tennisGameScore.getGameScoreHeader().get(2)).isEqualTo("Federer wins 1 point");
assertThat(tennisGameScore.getGameScoreFedererRow().get(2)).isEqualTo("15");
assertThat(tennisGameScore.getGameScoreNadalRow().get(2)).isEqualTo("0");
assertThat(tennisGameScore.getGameScoreWinnerRow().get(2)).isEqualTo("");
}
} |
package io.spine.validate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Descriptors;
import io.spine.option.OnDuplicate;
import io.spine.option.OnDuplicate.DuplicatePolicy;
import io.spine.option.OptionsProto;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* An option that can be applied to {@code repeated} Protobuf fields to specify that values
* represented by that {@code repeated} field don't contain duplicates.
*/
final class DistinctFieldOption extends FieldValidatingOption<OnDuplicate.DuplicatePolicy> {
@Override
boolean applicableTo(Descriptors.FieldDescriptor field) {
return field.isRepeated();
}
@Override
ValidationException onInapplicable(Descriptors.FieldDescriptor field) {
ConstraintViolation inapplicable = ConstraintViolation
.newBuilder()
.setMsgFormat("Error for field %s. A non-repeated field cannot be `distinct`.")
.addParam(field.getFullName())
.build();
ValidationException exception = new ValidationException(ImmutableList.of(inapplicable));
return exception;
}
@Override
List<ConstraintViolation> applyValidatingRules(FieldValue value) {
return checkForDuplicates(value);
}
@Override
boolean optionPresentFor(FieldValue value) {
return policyFor(value).getNumber() > 0;
}
@SuppressWarnings("SuspiciousMethodCalls")
private static List<ConstraintViolation> checkForDuplicates(FieldValue value) {
List<?> potentialDuplicates = new ArrayList<>(value.asList());
Set<?> duplicates = findDuplicates(potentialDuplicates);
return ImmutableList.of(duplicateFound(value, duplicates));
}
private static Set<?> findDuplicates(Iterable<?> potentialDuplicates) {
Set<Object> duplicateLess = new HashSet<>();
ImmutableSet.Builder<Object> duplicates = ImmutableSet.builder();
for (Object potentialDuplicate : potentialDuplicates) {
if (duplicateLess.contains(potentialDuplicate)) {
duplicates.add(potentialDuplicate);
} else {
duplicateLess.add(potentialDuplicate);
}
}
return duplicates.build();
}
private static <T> ConstraintViolation duplicateFound(FieldValue value, Set<T> duplicates) {
String fieldName = value.declaration()
.name()
.value();
List<String> stringValues = duplicates.stream()
.map(Object::toString)
.collect(Collectors.toList());
String formatParams = String.join(", ", stringValues);
String msgFormat =
"Found a duplicate element in a `distinct` field %s. " +
"Duplicate elements: " +
formatParams;
ConstraintViolation.Builder duplicatesBuilder = ConstraintViolation
.newBuilder()
.setMsgFormat(msgFormat)
.addParam(fieldName);
stringValues.forEach(duplicatesBuilder::addParam);
return duplicatesBuilder.build();
}
private static DuplicatePolicy policyFor(FieldValue field) {
return field.valueOf(OptionsProto.onDuplicate)
.getDuplicatePolicy();
}
@Override
public DuplicatePolicy getValueFor(FieldValue something) {
return something.valueOf(OptionsProto.onDuplicate)
.getDuplicatePolicy();
}
} |
package com.hz.pet.bexchange;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.hz.pet.bexchange.domain.Advt.AdvtStatus;
import com.hz.pet.bexchange.domain.advt.Advt;
import com.hz.pet.bexchange.domain.advt.AdvtLocation;
import com.hz.pet.bexchange.domain.advt.AdvtRepository;
import com.hz.pet.bexchange.domain.user.User;
import com.hz.pet.bexchange.domain.user.UserRepository;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.*;
import java.util.stream.Stream;
import static com.google.common.collect.Iterables.get;
import static com.google.common.collect.Sets.newHashSet;
import static com.hz.pet.bexchange.domain.Advt.AdvtType.BUY;
import static com.hz.pet.bexchange.domain.Advt.AdvtType.SELL;
import static com.hz.pet.bexchange.domain.Advt.Currency.values;
/**
* @author Herman Zamula
*/
@Component
public class DemoCreator {
private static final ImmutableSet<String> COMMENTS = ImmutableSet.of(
"Срочно",
"Б*я касса горит",
"Вася, срочно нужно нужно обменять",
"Стою в здании СБУ",
"Выручайте!",
"Гонтаревой нужно, норм курс");
static {
final HashSet<String> builder = newHashSet();
Stream.generate(() -> String.format("0%09d", new Random().nextInt(1_000_000_000)))
.filter((n) -> !builder.contains(n))
.limit(100)
.forEach(builder::add);
phoneNumbers = ImmutableSet.copyOf(builder);
}
private static final Set<String> phoneNumbers;
private static final Map<String, Set<String>> locations = ImmutableMap.of(
"Киев", ImmutableSet.of("Оболонский", "Деснянский", "Печерский", "Дарницкий", "Соломенский"),
"Харьков", ImmutableSet.of("Киевский", "Дзержинсий", "Октябрьский", "ХТЗ", "Салтовка")
);
@Inject
private UserRepository userRepository;
@Inject
private AdvtRepository advtRepository;
@PostConstruct
public void load() {
Random random = new Random();
phoneNumbers.stream()
.map(number -> userRepository.save(new User(number, "pwd")))
.forEach(user -> {
Advt advt = new Advt();
advt.setAdvtStatus(AdvtStatus.values()[2]);
advt.setAdvtType(random.nextBoolean() ? SELL : BUY);
advt.setCreationTime(new Date());
advt.setCurrency(values()[random.nextInt(4)]);
advt.setAmount((long) random.nextInt(100000));
advt.setCreator(user);
advt.setExchangeRate(random.nextBoolean() ? 25.05f : 28.9f);
AdvtLocation advtLocation = getAdvtLocation(random);
advt.setLocation(advtLocation);
advt.setComment(get(COMMENTS, random.nextInt(COMMENTS.size())));
advtRepository.save(advt);
});
}
private AdvtLocation getAdvtLocation(Random random) {
final String city = random.nextBoolean() ? "Киев" : "Харьков";
AdvtLocation advtLocation = new AdvtLocation();
advtLocation.setCity(city);
final Set<String> areas = locations.get(city);
advtLocation.setArea(get(areas, random.nextInt(areas.size())));
return advtLocation;
}
} |
package org.hyperic.sigar.win32;
import java.util.Date;
/**
* Class to represent event log records
*/
public class EventLogRecord {
long recordNumber;
long timeGenerated;
long timeWritten;
long eventId;
short eventType;
String source;
String computerName;
String user;
String message;
String logName;
EventLogRecord() {}
/**
* @return Event log name which generated the event
*/
public String getLogName() {
return this.logName;
}
void setLogName(String logName) {
this.logName = logName;
}
/* Get the record number for this event entry */
public long getRecordNumber() {
return recordNumber;
}
/**
* Get the time at which this entry was submitted. This time is
* measured in the number of seconds elapsed since 00:00:00
* January 1, 1970, Universal Coordinated Time.
*/
public long getTimeGenerated() {
return this.timeGenerated;
}
/**
* Get the time at which this entry was received by the service to be
* written to the logfile. This time is measured in the number of
* seconds elapsed since 00:00:00 January 1, 1970, Universal
* Coordinated Time.
*/
public long getTimeWritten() {
return this.timeWritten;
}
/**
* Event identifier. The value is specific to the event source
* for the event, and is used with source name to locate a
* description string in the message file for the event source.
*
* XXX: This is probably not needed
*/
public long getEventId() {
return this.eventId;
}
/**
* Return the event type.
* See the EVENTLOG_* constants in the EventLog class
*/
public short getEventType() {
return this.eventType;
}
public String getEventTypeString() {
switch (this.eventType) {
case EventLog.EVENTLOG_ERROR_TYPE:
return "Error";
case EventLog.EVENTLOG_WARNING_TYPE:
return "Warning";
case EventLog.EVENTLOG_INFORMATION_TYPE:
return "Information";
case EventLog.EVENTLOG_AUDIT_SUCCESS:
return "Success Audit";
case EventLog.EVENTLOG_AUDIT_FAILURE:
return "Failure Audit";
default:
return "Unknown";
}
}
/**
* Get the application which triggered the event
*/
public String getSource() {
return this.source;
}
/**
* Get the machine name where the event was generated
*/
public String getComputerName() {
return this.computerName;
}
/**
* Get the user who generated the event. May be null if no user is
* associated with the event.
*/
public String getUser() {
return this.user;
}
/**
* Get the message for the event.
*/
public String getMessage() {
return this.message;
}
/**
* @deprecated
*/
public String getStringData() {
return getMessage();
}
/**
* For debugging
*/
public String toString()
{
return
"[" + new Date(getTimeGenerated() * 1000) + "] " +
"[" + getEventTypeString() + "] " +
"[" + getSource() + "] " +
getMessage();
}
} |
package com.browseengine.bobo.sort;
import java.io.IOException;
import java.util.Locale;
import java.util.Set;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import com.browseengine.bobo.api.BoboCustomSortField;
import com.browseengine.bobo.api.BoboSubBrowser;
import com.browseengine.bobo.api.Browsable;
import com.browseengine.bobo.api.BrowseHit;
import com.browseengine.bobo.facets.FacetHandler;
import com.browseengine.bobo.sort.DocComparatorSource.DocIdDocComparatorSource;
import com.browseengine.bobo.sort.DocComparatorSource.RelevanceDocComparatorSource;
public abstract class SortCollector extends Collector {
protected Collector _collector = null;
protected final SortField[] _sortFields;
protected final boolean _fetchStoredFields;
protected SortCollector(SortField[] sortFields,boolean fetchStoredFields){
_sortFields = sortFields;
_fetchStoredFields = fetchStoredFields;
}
abstract public BrowseHit[] topDocs() throws IOException;
abstract public int getTotalHits();
private static DocComparatorSource getNonFacetComparatorSource(SortField sf){
String fieldname = sf.getField();
Locale locale = sf.getLocale();
if (locale != null) {
return new DocComparatorSource.StringLocaleComparatorSource(fieldname, locale);
}
int type = sf.getType();
switch (type) {
case SortField.INT:
return new DocComparatorSource.IntDocComparatorSource(fieldname);
case SortField.FLOAT:
return new DocComparatorSource.FloatDocComparatorSource(fieldname);
case SortField.LONG:
return new DocComparatorSource.LongDocComparatorSource(fieldname);
case SortField.DOUBLE:
return new DocComparatorSource.LongDocComparatorSource(fieldname);
case SortField.BYTE:
return new DocComparatorSource.ByteDocComparatorSource(fieldname);
case SortField.SHORT:
return new DocComparatorSource.ShortDocComparatorSource(fieldname);
case SortField.CUSTOM:
throw new IllegalArgumentException("lucene custom sort no longer supported");
case SortField.STRING:
return new DocComparatorSource.StringOrdComparatorSource(fieldname);
case SortField.STRING_VAL:
return new DocComparatorSource.StringValComparatorSource(fieldname);
default:
throw new IllegalStateException("Illegal sort type: " + type);
}
}
private static DocComparatorSource getComparatorSource(Browsable browser,SortField sf){
DocComparatorSource compSource = null;
if (SortField.FIELD_DOC.equals(sf)){
compSource = new DocIdDocComparatorSource();
}
else if (SortField.FIELD_SCORE.equals(sf) || sf.getType() == SortField.SCORE){
// we want to do reverse sorting regardless for relevance
compSource = new ReverseDocComparatorSource(new RelevanceDocComparatorSource());
}
else if (sf instanceof BoboCustomSortField){
BoboCustomSortField custField = (BoboCustomSortField)sf;
DocComparatorSource src = custField.getCustomComparatorSource();
assert src!=null;
compSource = src;
}
else{
Set<String> facetNames = browser.getFacetNames();
String sortName = sf.getField();
if (facetNames.contains(sortName)){
FacetHandler<?> handler = browser.getFacetHandler(sortName);
assert handler!=null;
compSource = handler.getDocComparatorSource();
}
else{ // default lucene field
compSource = getNonFacetComparatorSource(sf);
}
}
boolean reverse = sf.getReverse();
if (reverse){
compSource = new ReverseDocComparatorSource(compSource);
}
compSource.setReverse(reverse);
return compSource;
}
private static SortField convert(BoboSubBrowser browser,SortField sort){
String field =sort.getField();
FacetHandler<?> facetHandler = browser.getFacetHandler(field);
if (facetHandler!=null){
browser.getFacetHandler(field);
BoboCustomSortField sortField = new BoboCustomSortField(field, sort.getReverse(), facetHandler.getDocComparatorSource());
return sortField;
}
else{
return sort;
}
}
public static SortCollector buildSortCollector(BoboSubBrowser browser,Query q,SortField[] sort,int offset,int count,boolean forceScoring,boolean fetchStoredFields){
boolean doScoring=forceScoring;
if (sort == null || sort.length==0){
if (q!=null && !(q instanceof MatchAllDocsQuery)){
sort = new SortField[]{SortField.FIELD_SCORE};
}
}
if (sort==null || sort.length==0){
sort = new SortField[]{SortField.FIELD_DOC};
}
Set<String> facetNames = browser.getFacetNames();
for (SortField sf : sort){
if (sf.getType() == SortField.SCORE) {
doScoring= true;
break;
}
}
DocComparatorSource compSource;
if (sort.length==1){
SortField sf = convert(browser,sort[0]);
compSource = getComparatorSource(browser,sf);
}
else{
DocComparatorSource[] compSources = new DocComparatorSource[sort.length];
for (int i = 0; i<sort.length;++i){
compSources[i]=getComparatorSource(browser,convert(browser,sort[i]));
}
compSource = new MultiDocIdComparatorSource(compSources);
}
return new SortCollectorImpl(compSource, sort, browser, offset, count, doScoring, fetchStoredFields);
}
public void setCollector(Collector collector){
_collector = collector;
}
public Collector getCollector(){
return _collector;
}
} |
package org.dna.mqtt.moquette.server;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import org.dna.mqtt.moquette.messaging.spi.impl.SimpleMessaging;
//import org.dna.mqtt.moquette.server.mina.MinaAcceptor;
import org.dna.mqtt.moquette.server.netty.NettyAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Launch a configured version of the server.
* @author andrea
*/
public class Server {
private static final Logger LOG = LoggerFactory.getLogger(Server.class);
public static final String STORAGE_FILE_PATH = System.getProperty("user.home") +
File.separator + "moquette_store.hawtdb";
private ServerAcceptor m_acceptor;
SimpleMessaging messaging;
public static void main(String[] args) throws IOException {
final Server server = new Server();
server.startServer();
System.out.println("Server started, version 0.4-SNAPSHOT");
//Bind a shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.stopServer();
}
});
}
public void startServer() throws IOException {
messaging = SimpleMessaging.getInstance();
messaging.init();
m_acceptor = new NettyAcceptor();
m_acceptor.initialize(messaging);
}
/**
* It's an asynchronous method, it's only a request to stop
*/
public void stopServer() {
System.out.println("Server stopping...");
messaging.stop();
m_acceptor.close();
System.out.println("Server stopped");
try {
//sleep one second to give the disruptor
Thread.sleep(100);
} catch (InterruptedException ex) {
LOG.error(null, ex);
}
}
} |
package org.lockss.repository;
import java.io.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.net.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.lockss.test.*;
import org.lockss.app.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
import org.lockss.protocol.*;
/**
* This is the test class for org.lockss.repository.RepositoryNodeImpl
*/
public class TestRepositoryNodeImpl extends LockssTestCase {
static final String TREE_SIZE_PROPERTY =
RepositoryNodeImpl.TREE_SIZE_PROPERTY;
static final String CHILD_COUNT_PROPERTY =
RepositoryNodeImpl.CHILD_COUNT_PROPERTY;
private MockLockssDaemon theDaemon;
private MyLockssRepositoryImpl repo;
private String tempDirPath;
MockArchivalUnit mau;
private MockIdentityManager idmgr;
Properties props;
public void setUp() throws Exception {
super.setUp();
tempDirPath = getTempDir().getAbsolutePath() + File.separator;
props = new Properties();
props.setProperty(LockssRepositoryImpl.PARAM_CACHE_LOCATION, tempDirPath);
ConfigurationUtil.setCurrentConfigFromProps(props);
mau = new MockArchivalUnit();
theDaemon = getMockLockssDaemon();
// Create the identity manager...
idmgr = new MockIdentityManager();
theDaemon.setIdentityManager(idmgr);
idmgr.initService(theDaemon);
repo = (MyLockssRepositoryImpl)MyLockssRepositoryImpl.createNewLockssRepository(mau);
theDaemon.setAuManager(LockssDaemon.LOCKSS_REPOSITORY, mau, repo);
repo.initService(theDaemon);
repo.startService();
}
public void tearDown() throws Exception {
TimeBase.setReal();
repo.stopService();
theDaemon.stopDaemon();
super.tearDown();
}
// RepositoryNodeImpl relies on nonexistent dir.listFiles() returning
// null, not empty list.
public void testFileAssumptions() throws Exception {
// empty dir returns empty list
File dir1 = getTempDir();
assertNotNull(null, dir1.listFiles());
assertEquals(new File[0], dir1.listFiles());
// nonexistent dir returns null
File dir2 = new File(dir1, "bacds");
assertNull(null, dir2.listFiles());
// dir list of non-dir returns null
File file1 = File.createTempFile("xxx", ".tmp", dir1);
assertTrue(file1.exists());
assertNull(null, file1.listFiles());
}
// Ensure that our maximum filename component calculation agrees with
// reality.
File root;
int maxDirname;
int preflen;
int sufflen;
String pref;
String suff;
public void testUnicodeAssumptions() throws Exception {
assertEquals("1234", trimTo("1234", 4));
assertEquals("1234", trimTo("12345", 4));
assertEquals("1234", trimTo("123454444444", 4));
root = getTempDir();
assertTrue(canMkdir(root, "xyz" + "\u00e9"));
maxDirname = findMaxDirname(root);
log.info("Max dirname on " + root + ": " + maxDirname);
if (maxDirname < 30) {
log.critical("Skipping test because filesystem is inadequate for LOCKSS");
return;
}
preflen = (maxDirname - 10) / 2;
sufflen = maxDirname - preflen;
pref = mkstr(preflen);
suff = mkstr(sufflen);
String t1 = pref + suff;
String t2 = pref + "e" + suff;
assertTrue(byteLength(t1) == t1.length());
assertTrue(canMkdir(root, t1));
assertFalse(canMkdir(root, t2));
String uniStrs[] = {
"\u00e9",
"\u0113", // Latin Extended-A
"\u01a2", // Latin Extended-B
"\u025a", // IPA Extensions
"\u0393", // Greek
"\u0409", // Cyrillic
"\u05d2", // Hebrew
"\u062c", // Arabic
"\u0ab2", // Gujarati
"\u0E28", // Thai
"\u0EC0", // Lao
"\u0F44", // Tibetan
"\u305D", // Hiragana
"\u30AE", // Katakana
"\u2EA8", // CJK Radicals Supplement
"\u3028", // CJK Symbols and Punctuation
"\u4E05", // CJK Unified Ideographs
"\uAC07", // Hangul Syllables
};
// One unicode char
for (String s : uniStrs) {
testUni(s);
}
// Two unicode chars
for (String s1 : uniStrs) {
for (String s2 : uniStrs) {
testUni(s1 + s2);
}
}
}
void testUni(String unistr) {
String str = pref + unistr + suff;
int failat = -1;
int probelen = str.length();
while (probelen >= 1) {
String probe = trimTo(str, probelen);
int blen = byteLength(probe);
boolean should = blen <= maxDirname;
boolean does = canMkdir(root, probe);
log.debug2("probelen: " + probe.length() +
", byte: " + byteLength(probe) + ": " + does);
if (should) {
if (does) {
return;
}
fail("foo");
}
probelen
}
}
static String trimTo(String s, int len) {
return s.substring(0, len);
}
int byteLength(String s) {
return RepositoryNodeImpl.byteLength(s);
}
int findMaxDirname(File root) {
for (int len = 1; len < 1000; len++) {
if (!canMkdir(root, len)) {
return len - 1;
}
}
return -1;
}
void findMaxDirPath(File root) {
int maxName = findMaxDirname(root) - 10;
String one = mkstr("onedir", maxName) + "/";
for (int rpt = 1; rpt < 1000; rpt++) {
String path = StringUtils.repeat(one, rpt);
File dir = new File(root, path);
String dirstr = dir.getPath();
boolean res = dir.mkdirs();
if (!res) {
log.info("mkdirs failed at " + dirstr.length() + " chars");
break;
}
log.info("mkdirs ok: " + dirstr.length());
File f = new File(dir, "foobbb");
try {
OutputStream os = new FileOutputStream(f);
os.close();
log.info("file ok at " + f.getPath().length() + " chars");
} catch (FileNotFoundException fnfe) {
log.info("FNF: " + f.getPath().length(), fnfe);
} catch (IOException ioe) {
log.error("IOE: " + f.getPath().length() + ", " + ioe.getMessage());
}
}
}
void findMaxDirPathNio(File root) {
int maxName = findMaxDirname(root) - 10;
String one = mkstr("onedir", maxName) + "/";
for (int rpt = 1; rpt < 1000; rpt++) {
String path = StringUtils.repeat(one, rpt);
File dir = new File(root, path);
String dirstr = dir.getPath();
boolean res = dir.mkdirs();
if (!res) {
log.info("mkdirs failed at " + dirstr.length() + " chars");
break;
}
log.info("mkdirs ok: " + dirstr.length());
File f = new File(dir, "foobbb");
try {
Path npath = Paths.get(f.getPath());
Files.createFile(npath);
FileChannel ochan = FileChannel.open(npath, StandardOpenOption.WRITE);
OutputStream os = Channels.newOutputStream(ochan);
os.write((byte)44);
os.close();
FileChannel ichan = FileChannel.open(npath, StandardOpenOption.READ);
InputStream is = Channels.newInputStream(ichan);
int bb = is.read();
is.close();
assertEquals(44, bb);
log.info("file ok at " + npath.toString().length() + " chars");
} catch (FileNotFoundException fnfe) {
log.error("FNF: " + f.getPath().length(), fnfe);
} catch (IOException ioe) {
log.error("IOE: " + f.getPath().length() + ", " + ioe.getMessage());
}
}
}
boolean canMkdir(File root, int len) {
return canMkdir(root, mkstr(len));
}
boolean canMkdir(String root, String name) {
return canMkdir(new File(root), name);
}
boolean canMkdir(File root, String name) {
File f = new File(root, name);
boolean res = f.mkdirs();
if (!res) {
if (f.exists()) {
throw new RuntimeException("mkdirs = false but dir exists: " + f);
}
log.debug2("canMkdir("+f+"): false");
return false;
}
if (f.exists()) {
if (!f.delete()) {
throw new RuntimeException("Couldn't delete newly created dir: " + f);
}
if (f.exists()) {
throw new RuntimeException("Deleted newly created dir still exists: " + f);
}
log.debug2("canMkdir("+f+"): true");
return true;
}
throw new RuntimeException("mkdirs() == true but exists() == false: " + f);
}
public void testMkstr() {
for (int ix = 0; ix < 1000; ix++) {
assertEquals(ix, mkstr(ix).length());
}
}
String mkstr(int len) {
return mkstr("abcdefghijklmnopqrstuvwxyz0123456789", len);
}
String mkstr(String al, int len) {
StringBuilder sb = new StringBuilder(len);
for (int ix = 1; ix <= len / al.length(); ix++) {
sb.append(al);
}
sb.append(al.substring(0, len % al.length()));
if (sb.length() != len) {
throw new RuntimeException("mkstr(" + len + ") made string w/ len: "
+ sb.length());
}
return sb.toString();
}
public void testGetNodeUrl() {
RepositoryNode node = new RepositoryNodeImpl("testUrl", "testDir", null);
assertEquals("testUrl", node.getNodeUrl());
node = new RepositoryNodeImpl("testUrl/test.txt", "testUrl/test.txt", null);
assertEquals("testUrl/test.txt", node.getNodeUrl());
}
public void testFileLocation() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
File testFile = new File(tempDirPath);
assertTrue(testFile.exists());
testFile = new File(tempDirPath + "/#content/current");
assertTrue(testFile.exists());
testFile = new File(tempDirPath + "/#content/current.props");
assertTrue(testFile.exists());
testFile = new File(tempDirPath + "/#node_props");
assertFalse(testFile.exists());
testFile = new File(tempDirPath + "/#agreement");
assertFalse(testFile.exists());
}
public void testUpdateAgreementCreatesFile() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
File testFile = new File(tempDirPath, "#agreement");
assertFalse(testFile.exists());
// Agreeing IDs.
PeerIdentity[] agreeingPeers =
{ new MockPeerIdentity("TCP:[192.168.0.1]:9723"),
new MockPeerIdentity("TCP:[192.168.0.2]:9723")
};
leaf.signalAgreement(ListUtil.fromArray(agreeingPeers));
assertTrue(testFile.exists());
}
public void testUpdateAndLoadAgreement() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
PeerIdentity testid_1 = new MockPeerIdentity("TCP:[192.168.0.1]:9723");
PeerIdentity testid_2 = new MockPeerIdentity("TCP:[192.168.0.2]:9723");
PeerIdentity testid_3 = new MockPeerIdentity("TCP:[192.168.0.3]:9723");
PeerIdentity testid_4 = new MockPeerIdentity("TCP:[192.168.0.4]:9723");
idmgr.addPeerIdentity(testid_1.getIdString(), testid_1);
idmgr.addPeerIdentity(testid_2.getIdString(), testid_2);
idmgr.addPeerIdentity(testid_3.getIdString(), testid_3);
idmgr.addPeerIdentity(testid_4.getIdString(), testid_4);
leaf.signalAgreement(ListUtil.list(testid_1, testid_3));
assertEquals(2, ((RepositoryNodeImpl)leaf).loadAgreementHistory().size());
assertTrue(leaf.hasAgreement(testid_1));
assertFalse(leaf.hasAgreement(testid_2));
assertTrue(leaf.hasAgreement(testid_3));
assertFalse(leaf.hasAgreement(testid_4));
leaf.signalAgreement(ListUtil.list(testid_1, testid_2, testid_3, testid_4));
assertEquals(4, ((RepositoryNodeImpl)leaf).loadAgreementHistory().size());
assertTrue(leaf.hasAgreement(testid_1));
assertTrue(leaf.hasAgreement(testid_2));
assertTrue(leaf.hasAgreement(testid_3));
assertTrue(leaf.hasAgreement(testid_4));
}
public void testVersionFileLocation() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
File testFile = new File(tempDirPath + "/#content/1");
assertFalse(testFile.exists());
testFile = new File(tempDirPath + "/#content/1.props");
assertFalse(testFile.exists());
leaf.makeNewVersion();
OutputStream os = leaf.getNewOutputStream();
InputStream is = new StringInputStream("test stream 2");
StreamUtil.copy(is, os);
is.close();
os.close();
leaf.setNewProperties(new Properties());
leaf.sealNewVersion();
assertFalse(leaf.isIdenticalVersion());
testFile = new File(tempDirPath + "/#content/1");
assertTrue(testFile.exists());
testFile = new File(tempDirPath + "/#content/1.props");
assertTrue(testFile.exists());
}
public void testInactiveFileLocation() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
File curFile = new File(tempDirPath + "/#content/current");
File curPropsFile = new File(tempDirPath + "/#content/current.props");
File inactFile = new File(tempDirPath + "/#content/inactive");
File inactPropsFile = new File(tempDirPath + "/#content/inactive.props");
assertTrue(curFile.exists());
assertTrue(curPropsFile.exists());
assertFalse(inactFile.exists());
assertFalse(inactPropsFile.exists());
leaf.deactivateContent();
assertFalse(curFile.exists());
assertFalse(curPropsFile.exists());
assertTrue(inactFile.exists());
assertTrue(inactPropsFile.exists());
//reactivate
leaf.restoreLastVersion();
assertTrue(curFile.exists());
assertTrue(curPropsFile.exists());
assertFalse(inactFile.exists());
assertFalse(inactPropsFile.exists());
leaf.deactivateContent();
assertFalse(curFile.exists());
assertFalse(curPropsFile.exists());
assertTrue(inactFile.exists());
assertTrue(inactPropsFile.exists());
// make new version
leaf.makeNewVersion();
OutputStream os = leaf.getNewOutputStream();
InputStream is = new StringInputStream("test stream 2");
StreamUtil.copy(is, os);
is.close();
os.close();
leaf.setNewProperties(new Properties());
leaf.sealNewVersion();
assertTrue(curFile.exists());
assertTrue(curPropsFile.exists());
assertFalse(inactFile.exists());
assertFalse(inactPropsFile.exists());
assertFalse(leaf.isIdenticalVersion());
}
public void testDeleteFileLocation() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
File curFile = new File(tempDirPath + "/#content/current");
File curPropsFile = new File(tempDirPath + "/#content/current.props");
File inactFile = new File(tempDirPath + "/#content/inactive");
File inactPropsFile = new File(tempDirPath + "/#content/inactive.props");
assertTrue(curFile.exists());
assertTrue(curPropsFile.exists());
assertFalse(inactFile.exists());
assertFalse(inactPropsFile.exists());
leaf.markAsDeleted();
assertFalse(curFile.exists());
assertFalse(curPropsFile.exists());
assertTrue(inactFile.exists());
assertTrue(inactPropsFile.exists());
//reactivate
leaf.restoreLastVersion();
assertTrue(curFile.exists());
assertTrue(curPropsFile.exists());
assertFalse(inactFile.exists());
assertFalse(inactPropsFile.exists());
leaf.markAsDeleted();
assertFalse(curFile.exists());
assertFalse(curPropsFile.exists());
assertTrue(inactFile.exists());
assertTrue(inactPropsFile.exists());
// make new version
leaf.makeNewVersion();
OutputStream os = leaf.getNewOutputStream();
InputStream is = new StringInputStream("test stream 2");
StreamUtil.copy(is, os);
is.close();
os.close();
leaf.setNewProperties(new Properties());
leaf.sealNewVersion();
assertTrue(curFile.exists());
assertTrue(curPropsFile.exists());
assertFalse(inactFile.exists());
assertFalse(inactPropsFile.exists());
assertFalse(leaf.isIdenticalVersion());
}
public void testListEntriesNonexistentDir() throws Exception {
RepositoryNode node = new RepositoryNodeImpl("foo-no-url", "foo-no-dir",
null);
try {
node.listChildren(null, false);
fail("listChildren() is nonexistent dir should throw");
} catch (LockssRepository.RepositoryStateException e) {
}
}
public void testListEntries() throws Exception {
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
createLeaf("http:
// root branch
RepositoryNode dirEntry =
repo.getNode("http:
Iterator childIt = dirEntry.listChildren(null, false);
ArrayList childL = new ArrayList(3);
while (childIt.hasNext()) {
RepositoryNode node = (RepositoryNode)childIt.next();
childL.add(node.getNodeUrl());
}
String[] expectedA = new String[] {
"http:
"http:
"http:
};
assertSameElements(expectedA, childL);
// sub-branch
dirEntry = repo.getNode("http:
childL.clear();
childIt = dirEntry.listChildren(null, false);
while (childIt.hasNext()) {
RepositoryNode node = (RepositoryNode)childIt.next();
childL.add(node.getNodeUrl());
}
expectedA = new String[] {
"http:
"http:
};
assertSameElements(expectedA, childL);
// sub-branch with content
dirEntry = repo.getNode("http:
childL.clear();
childIt = dirEntry.listChildren(null, false);
while (childIt.hasNext()) {
RepositoryNode node = (RepositoryNode)childIt.next();
childL.add(node.getNodeUrl());
}
expectedA = new String[] {
"http:
};
assertSameElements(expectedA, childL);
// leaf node
dirEntry = repo.getNode("http:
childL.clear();
childIt = dirEntry.listChildren(null, false);
while (childIt.hasNext()) {
RepositoryNode node = (RepositoryNode)childIt.next();
childL.add(node.getNodeUrl());
}
expectedA = new String[] { };
assertSameElements(expectedA, childL);
}
String normalizeName(RepositoryNodeImpl node, String name) {
return node.normalize(new File(name)).getPath();
}
public void testNormalizeUrlEncodingCase() throws Exception {
if (!PlatformUtil.getInstance().isCaseSensitiveFileSystem()) {
log.debug("Skipping testNormalizeUrlEncodingCase: file system is not case sensitive.");
return;
}
RepositoryNodeImpl node = new RepositoryNodeImpl("foo", "bar", null);
// nothing to normalize
File file = new File("foo/bar/baz");
assertSame(file, node.normalize(file));
file = new File("foo/bar/ba%ABz");
assertSame(file, node.normalize(file));
// unnormalized in parent dir name is left alone
file = new File("ba%abz/bar");
assertSame(file, node.normalize(file));
file = new File("foo/ba%abz/bar");
assertSame(file, node.normalize(file));
// should be normalized
assertEquals("ba%ABz", normalizeName(node, "ba%aBz"));
assertEquals("/ba%ABz", normalizeName(node, "/ba%aBz"));
assertEquals("foo/bar/ba%ABz", normalizeName(node, "foo/bar/ba%aBz"));
assertEquals("foo/bar/ba%ABz", normalizeName(node, "foo/bar/ba%Abz"));
assertEquals("foo/bar/ba%ABz", normalizeName(node, "foo/bar/ba%abz"));
assertEquals("foo/bar/ba%abz/ba%ABz", normalizeName(node, "foo/bar/ba%abz/ba%abz"));
}
public void testNormalizeTrailingQuestion() throws Exception {
RepositoryNodeImpl node = new RepositoryNodeImpl("foo", "bar", null);
// nothing to normalize
File file = new File("foo/bar/baz");
assertSame(file, node.normalize(file));
file = new File("foo/bar/ba?z");
assertSame(file, node.normalize(file));
// unnormalized in parent dir name is left alone
file = new File("ba?/bar");
assertSame(file, node.normalize(file));
// should be normalized
assertEquals("baz", normalizeName(node, "baz?"));
assertEquals(new File("/ba").getPath(), normalizeName(node, "/ba?"));
assertEquals(new File("foo/bar/bar").getPath(), normalizeName(node, "foo/bar/bar?"));
assertEquals(new File("foo/ba?r/bar").getPath(), normalizeName(node, "foo/ba?r/bar?"));
assertEquals(new File("foo/bar?/bar").getPath(), normalizeName(node, "foo/bar?/bar?"));
// disable trailing ? normalization
ConfigurationUtil.addFromArgs(UrlUtil.PARAM_NORMALIZE_EMPTY_QUERY,
"false");
assertEquals("baz?", normalizeName(node, "baz?"));
}
List getChildNames(String nodeName) throws MalformedURLException {
RepositoryNode dirEntry = repo.getNode(nodeName);
ArrayList res = new ArrayList();
for (Iterator childIt = dirEntry.listChildren(null, false);
childIt.hasNext(); ) {
RepositoryNode node = (RepositoryNode)childIt.next();
log.debug2("node: " + node);
res.add(node.getNodeUrl());
}
return res;
}
public void testFixUnnormalized_Rename() throws Exception {
if (!PlatformUtil.getInstance().isCaseSensitiveFileSystem()) {
log.debug("Skipping testFixUnnormalized_Rename: file system is not case sensitive.");
return;
}
repo.setDontNormalize(true);
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"No");
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
createLeaf("http:
String[] expectedA = new String[] {
"http:
"http:
"http:
};
assertSameElements(expectedA,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Log");
assertSameElements(expectedA,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Fix");
String[] expectedB = new String[] {
"http:
"http:
"http:
};
assertSameElements(expectedB,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"No");
assertSameElements(expectedB,
getChildNames(("http:
String[] expectedC = new String[] {
"http:
"http:
};
assertSameElements(expectedC,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Log");
assertSameElements(expectedB,
getChildNames(("http:
assertSameElements(expectedC,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Fix");
assertSameElements(expectedB,
getChildNames(("http:
String[] expectedD = new String[] {
"http:
"http:
};
assertSameElements(expectedD,
getChildNames(("http:
}
public void testFixUnnormalizedMultiple_Delete() throws Exception {
if (!PlatformUtil.getInstance().isCaseSensitiveFileSystem()) {
log.debug("Skipping testFixUnnormalizedMultiple_Delete: file system is not case sensitive.");
return;
}
repo.setDontNormalize(true);
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"No");
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
String[] expectedA = new String[] {
"http:
"http:
"http:
};
assertSameElements(expectedA,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Log");
assertSameElements(expectedA,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Fix");
String[] expectedB = new String[] {
"http:
"http:
};
assertSameElements(expectedB,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"No");
assertSameElements(expectedB,
getChildNames(("http:
}
public void testFixUnnormalizedMultiple_DeleteMultiple() throws Exception {
if (!PlatformUtil.getInstance().isCaseSensitiveFileSystem()) {
log.debug("Skipping testFixUnnormalizedMultiple_DeleteMultiple: file system is not case sensitive.");
return;
}
repo.setDontNormalize(true);
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"No");
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
String[] expectedA = new String[] {
"http:
"http:
"http:
"http:
"http:
};
assertSameElements(expectedA,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Log");
assertSameElements(expectedA,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Fix");
String[] expectedB = new String[] {
"http:
"http:
};
assertSameElements(expectedB,
getChildNames(("http:
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"No");
assertSameElements(expectedB,
getChildNames(("http:
}
public void testFixUnnormalized_DontFixParent() throws Exception {
if (!PlatformUtil.getInstance().isCaseSensitiveFileSystem()) {
log.debug("Skipping testFixUnnormalized_DontFixParent: file system is not case sensitive.");
return;
}
repo.setDontNormalize(true);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Fix");
String[] expectedA = new String[] {
"http:
"http:
};
assertSameElements(expectedA,
getChildNames(("http:
}
public void testUnnormalizedIterate() throws Exception {
if (!PlatformUtil.getInstance().isCaseSensitiveFileSystem()) {
log.debug("Skipping testUnnormalizedIterate: file system is not case sensitive.");
return;
}
repo.setDontNormalize(true);
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"No");
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
repo.setDontNormalize(false);
// Unnormalized name in result of listChildren not included in result
// because name gets normalized when node created, thus not found
String[] expectedA = new String[] {
"http:
"http:
};
assertSameElements(expectedA,
getChildNames(("http:
// Same with checkUnnormalized = Log
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Log");
assertSameElements(expectedA,
getChildNames(("http:
// If checkUnnormalized = Fix, unnnormalized file in repo will be fixed
// and inluded in result
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_CHECK_UNNORMALIZED,
"Fix");
String[] expectedB = new String[] {
"http:
"http:
"http:
};
assertSameElements(expectedB,
getChildNames(("http:
}
public void testEntrySort() throws Exception {
createLeaf("http:
createLeaf("http:
createLeaf("http:
createLeaf("http:
RepositoryNode dirEntry =
repo.getNode("http:
Iterator childIt = dirEntry.listChildren(null, false);
ArrayList childL = new ArrayList(4);
while (childIt.hasNext()) {
RepositoryNode node = (RepositoryNode)childIt.next();
childL.add(node.getNodeUrl());
}
String[] expectedA = new String[] {
"http:
"http:
"http:
"http:
};
assertSameElements(expectedA, childL);
}
public void testIllegalOperations() throws Exception {
RepositoryNode leaf =
repo.createNewNode("http:
assertFalse(leaf.hasContent());
try {
leaf.getCurrentVersion();
fail("Cannot get current version if no content.");
} catch (UnsupportedOperationException uoe) { }
try {
leaf.getContentSize();
fail("Cannot get content size if no content.");
} catch (UnsupportedOperationException uoe) { }
try {
leaf.getNodeContents();
fail("Cannot get RepositoryNodeContents if no content.");
} catch (UnsupportedOperationException uoe) { }
try {
leaf.sealNewVersion();
fail("Cannot seal version if not open.");
} catch (UnsupportedOperationException uoe) { }
leaf.makeNewVersion();
try {
leaf.sealNewVersion();
fail("Cannot seal version if getNewOutputStream() uncalled.");
} catch (UnsupportedOperationException uoe) { }
leaf.makeNewVersion();
try {
leaf.deactivateContent();
fail("Cannot deactivate if currently open for writing.");
} catch (UnsupportedOperationException uoe) { }
writeToLeaf(leaf, "test stream");
try {
leaf.sealNewVersion();
fail("Cannot seal version if setNewProperties() uncalled.");
} catch (UnsupportedOperationException uoe) { }
leaf.makeNewVersion();
writeToLeaf(leaf, "test stream");
leaf.setNewProperties(new Properties());
leaf.sealNewVersion();
assertEquals(1, leaf.getCurrentVersion());
assertTrue(leaf.hasContent());
assertFalse(leaf.isIdenticalVersion());
}
public void testVersionTimeout() throws Exception {
TimeBase.setSimulated();
RepositoryNode leaf =
repo.createNewNode("http:
RepositoryNode leaf2 =
repo.getNode("http:
leaf.makeNewVersion();
try {
leaf2.makeNewVersion();
fail("Can't make new version while version open.");
} catch (UnsupportedOperationException e) { }
TimeBase.step(RepositoryNodeImpl.DEFAULT_VERSION_TIMEOUT/2);
try {
leaf2.makeNewVersion();
fail("Can't make new version while version not timed out.");
} catch (UnsupportedOperationException e) { }
TimeBase.step(RepositoryNodeImpl.DEFAULT_VERSION_TIMEOUT/2);
leaf2.makeNewVersion();
}
public void testMakeNewCache() throws Exception {
RepositoryNode leaf =
repo.createNewNode("http:
assertFalse(leaf.hasContent());
try {
leaf.getCurrentVersion();
fail("Cannot get current version if no content.");
} catch (UnsupportedOperationException uoe) { }
leaf.makeNewVersion();
writeToLeaf(leaf, "test stream");
leaf.setNewProperties(new Properties());
leaf.sealNewVersion();
assertTrue(leaf.hasContent());
assertEquals(1, leaf.getCurrentVersion());
}
static String LONG_1 = "http://ijs.macroeconomicsresearch.org/articles/renderlist.action/fmt=ahah&items=http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY585,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY592,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY591,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY593,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY594,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY601,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY602,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY603,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY604,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY611,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY614,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY619,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY618,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY620,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY621,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY626,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY629,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY630,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY635,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY633,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY637,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY639,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY643,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY649,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY650,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY652,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY655,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY656,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY659,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY666,http:s/sgm.metawrite.magenta.com/content/journal/ijsem/42.867-5309/ijsem.0.XXXYYY673";
static String LONG_2 = "http:
public void testLongPath(String url) throws Exception {
// findMaxDirPath(getTempDir());
// findMaxDirPathNio(getTempDir());
String longUrl = trimUrlForOs(url);
RepositoryNode leaf =
repo.createNewNode(longUrl);
assertFalse(leaf.hasContent());
try {
leaf.getCurrentVersion();
fail("Cannot get current version if no content.");
} catch (UnsupportedOperationException uoe) { }
leaf.makeNewVersion();
writeToLeaf(leaf, "test stream");
leaf.setNewProperties(new Properties());
leaf.sealNewVersion();
assertTrue(leaf.hasContent());
assertEquals(1, leaf.getCurrentVersion());
assertEquals(longUrl, leaf.getNodeUrl());
RepositoryNode.RepositoryNodeContents rnc = leaf.getNodeContents();
assertInputStreamMatchesString("test stream", rnc.getInputStream());
RepositoryNode top = repo.getNode(AuUrl.PROTOCOL_COLON);
List<String> tree = getSubTreeUrls(top);
assertEquals(ListUtil.list(longUrl), tree);
}
public void testLongPath1() throws Exception {
testLongPath(LONG_1);
}
public void testLongPath2() throws Exception {
testLongPath(LONG_2);
}
List<String> getSubTreeUrls(RepositoryNode node) throws Exception {
List<String> res = new ArrayList<String>();
addSubTreeUrls(res, node);
return res;
}
void addSubTreeUrls(List<String> res, RepositoryNode node) throws Exception {
if (node.hasContent()) {
res.add(node.getNodeUrl());
}
Iterator<RepositoryNode> iter = node.listChildren(null, false);
while (iter.hasNext()) {
addSubTreeUrls(res, iter.next());
}
}
String trimUrlForOs(String url) {
int pad = 10 + tempDirPath.length() + "/cache/xxx".length() +
RepositoryNodeImpl.CONTENT_DIR.length() +
Math.max(RepositoryNodeImpl.CURRENT_FILENAME.length(),
RepositoryNodeImpl.CURRENT_PROPS_FILENAME.length());
PlatformUtil pi = PlatformUtil.getInstance();
log.info("pi: " + pi);
int max = pi.maxPathname() - pad;
if (url.length() <= max) {
return url;
}
url = trimTo(url, max);
if (url.endsWith("/")) {
url += "a";
}
log.info("Trimmed long URL to (" + url.length() + "): " + url);
return url;
}
public void testMakeNodeLocation() throws Exception {
RepositoryNodeImpl leaf = (RepositoryNodeImpl)
repo.createNewNode("http:
String nodeLoc = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath,
mau);
nodeLoc = LockssRepositoryImpl.mapUrlToFileLocation(nodeLoc,
"http:
File testFile = new File(nodeLoc);
assertFalse(testFile.exists());
leaf.createNodeLocation();
assertTrue(testFile.exists());
assertTrue(testFile.isDirectory());
}
public void testMakeNewVersion() throws Exception {
Properties props = new Properties();
props.setProperty("test 1", "value 1");
RepositoryNode leaf =
createLeaf("http:
"test stream 1", props);
assertEquals(1, leaf.getCurrentVersion());
props = new Properties();
props.setProperty("test 1", "value 2");
leaf.makeNewVersion();
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream 2");
leaf.sealNewVersion();
assertEquals(2, leaf.getCurrentVersion());
assertFalse(leaf.isIdenticalVersion());
String resultStr = getLeafContent(leaf);
assertEquals("test stream 2", resultStr);
props = leaf.getNodeContents().getProperties();
assertEquals("value 2", props.getProperty("test 1"));
}
static final int DEL_NODE_DIR = 1;
static final int DEL_CONTENT_DIR = 2;
static final int DEL_CONTENT_FILE = 3;
static final int DEL_PROPS_FILE = 4;
public void testDisappearingFile(int whichFile, boolean tryRead)
throws Exception {
String url = "http:
RepositoryNodeImpl leaf = (RepositoryNodeImpl)repo.createNewNode(url);
String nodeLoc = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath,
mau);
nodeLoc = LockssRepositoryImpl.mapUrlToFileLocation(nodeLoc, url);
File testFile;
switch (whichFile) {
case DEL_NODE_DIR:
testFile = new File(nodeLoc);
break;
case DEL_CONTENT_DIR:
testFile = new File(nodeLoc, "#content");
break;
case DEL_CONTENT_FILE:
testFile = new File(nodeLoc, "#content/current");
break;
case DEL_PROPS_FILE:
testFile = new File(nodeLoc, "#content/current.props");
break;
default:
throw new UnsupportedOperationException();
}
assertFalse(testFile.exists());
Properties props1 = PropUtil.fromArgs("key1", "value 1");
createContentVersion(leaf, "test content 11111", props1);
assertEquals(1, leaf.getCurrentVersion());
assertTrue(testFile.exists());
switch (whichFile) {
case DEL_NODE_DIR:
case DEL_CONTENT_DIR:
assertTrue(FileUtil.delTree(testFile));
break;
case DEL_CONTENT_FILE:
case DEL_PROPS_FILE:
assertTrue(testFile.delete());
break;
}
assertFalse(testFile.exists());
Properties props2 = PropUtil.fromArgs("key2", "value 2");
RepositoryNode leaf2 = repo.createNewNode(url);
assertSame(leaf, leaf2);
assertTrue(leaf.hasContent());
if (tryRead) {
try {
getLeafContent(leaf);
} catch (LockssRepository.RepositoryStateException e) {
// expected
}
}
leaf2.makeNewVersion();
writeToLeaf(leaf, "test content 22222");
leaf.setNewProperties(props2);
leaf.sealNewVersion();
assertFalse(leaf.isIdenticalVersion());
assertTrue(testFile.exists());
int expver = 2;
// if we tried to read while node or content dir was missing, version
// number will have been reset.
if (tryRead) {
switch (whichFile) {
case DEL_NODE_DIR:
case DEL_CONTENT_DIR:
expver = 1;
}
}
assertEquals(expver, leaf.getCurrentVersion());
assertEquals("test content 22222", getLeafContent(leaf));
assertEquals("value 2", leaf.getNodeContents().getProperties().get("key2"));
}
public void testDisappearingNodeDir() throws Exception {
testDisappearingFile(DEL_NODE_DIR, false);
}
public void testDisappearingContentDir() throws Exception {
testDisappearingFile(DEL_CONTENT_DIR, false);
}
public void testDisappearingContentFile() throws Exception {
testDisappearingFile(DEL_CONTENT_FILE, false);
}
public void testDisappearingPropsFile() throws Exception {
testDisappearingFile(DEL_PROPS_FILE, false);
}
public void testDisappearingNodeDirWithRead() throws Exception {
testDisappearingFile(DEL_NODE_DIR, true);
}
public void testDisappearingContentDirWithRead() throws Exception {
testDisappearingFile(DEL_CONTENT_DIR, true);
}
public void testDisappearingContentFileWithRead() throws Exception {
testDisappearingFile(DEL_CONTENT_FILE, true);
}
public void testDisappearingPropsFileWithRead() throws Exception {
testDisappearingFile(DEL_PROPS_FILE, true);
}
public void testMakeNewVersionWithoutClosingStream() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream 1", new Properties());
leaf.makeNewVersion();
leaf.setNewProperties(new Properties());
OutputStream os = leaf.getNewOutputStream();
InputStream is = new StringInputStream("test stream 2");
StreamUtil.copy(is, os);
is.close();
// don't close outputstream
leaf.sealNewVersion();
assertEquals(2, leaf.getCurrentVersion());
String resultStr = getLeafContent(leaf);
assertEquals("test stream 2", resultStr);
assertFalse(leaf.isIdenticalVersion());
}
public void testMakeNewIdenticalVersionDefault() throws Exception {
Properties props = new Properties();
props.setProperty("test 1", "value 1");
MyMockRepositoryNode leaf = new MyMockRepositoryNode(
(RepositoryNodeImpl)createLeaf(
"http:
assertEquals(1, leaf.getCurrentVersion());
// set the file extension
leaf.dateValue = 123321;
props = new Properties();
props.setProperty("test 1", "value 2");
leaf.makeNewVersion();
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream");
leaf.sealNewVersion();
assertEquals(1, leaf.getCurrentVersion());
assertTrue(leaf.isIdenticalVersion());
String resultStr = getLeafContent(leaf);
assertEquals("test stream", resultStr);
props = leaf.getNodeContents().getProperties();
assertEquals("value 2", props.getProperty("test 1"));
// make sure proper files exist
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
File testFileDir = new File(tempDirPath + "/#content");
File[] files = testFileDir.listFiles();
assertEquals(2, files.length);
File testFile = new File(testFileDir, "current");
assertTrue(testFile.exists());
testFile = new File(testFileDir, "current.props");
assertTrue(testFile.exists());
// testFile = new File(testFileDir, "1.props-123321");
// assertFalse(testFile.exists());
// ensure non-identical version clears isIdenticalVersion()
leaf.makeNewVersion();
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream not the same");
leaf.sealNewVersion();
assertEquals(2, leaf.getCurrentVersion());
assertFalse(leaf.isIdenticalVersion());
}
public void testMakeNewIdenticalVersionOldWay() throws Exception {
props.setProperty(RepositoryNodeImpl.PARAM_KEEP_ALL_PROPS_FOR_DUP_FILE,
"true");
ConfigurationUtil.setCurrentConfigFromProps(props);
Properties props = new Properties();
props.setProperty("test 1", "value 1");
MyMockRepositoryNode leaf = new MyMockRepositoryNode(
(RepositoryNodeImpl)createLeaf(
"http:
assertEquals(1, leaf.getCurrentVersion());
// set the file extension
leaf.dateValue = 123321;
props = new Properties();
props.setProperty("test 1", "value 2");
leaf.makeNewVersion();
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream");
leaf.sealNewVersion();
assertEquals(1, leaf.getCurrentVersion());
assertTrue(leaf.isIdenticalVersion());
String resultStr = getLeafContent(leaf);
assertEquals("test stream", resultStr);
props = leaf.getNodeContents().getProperties();
assertEquals("value 2", props.getProperty("test 1"));
// make sure proper files exist
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
File testFileDir = new File(tempDirPath + "/#content");
File[] files = testFileDir.listFiles();
assertEquals(3, files.length);
File testFile = new File(testFileDir, "current");
assertTrue(testFile.exists());
testFile = new File(testFileDir, "current.props");
assertTrue(testFile.exists());
testFile = new File(testFileDir, "1.props-123321");
assertTrue(testFile.exists());
}
public void testMakeNewIdenticalVersionNewWay() throws Exception {
props.setProperty(RepositoryNodeImpl.PARAM_KEEP_ALL_PROPS_FOR_DUP_FILE,
"false");
ConfigurationUtil.setCurrentConfigFromProps(props);
Properties props = new Properties();
props.setProperty("test 1", "value 1");
MyMockRepositoryNode leaf = new MyMockRepositoryNode(
(RepositoryNodeImpl)createLeaf(
"http:
assertEquals(1, leaf.getCurrentVersion());
// set the file extension
leaf.dateValue = 123321;
props = new Properties();
props.setProperty("test 1", "value 2");
leaf.makeNewVersion();
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream");
leaf.sealNewVersion();
assertEquals(1, leaf.getCurrentVersion());
assertTrue(leaf.isIdenticalVersion());
String resultStr = getLeafContent(leaf);
assertEquals("test stream", resultStr);
props = leaf.getNodeContents().getProperties();
assertEquals("value 2", props.getProperty("test 1"));
// make sure proper files exist
tempDirPath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
tempDirPath = LockssRepositoryImpl.mapUrlToFileLocation(tempDirPath,
"http:
File testFileDir = new File(tempDirPath + "/#content");
File[] files = testFileDir.listFiles();
assertEquals(2, files.length);
File testFile = new File(testFileDir, "current");
assertTrue(testFile.exists());
testFile = new File(testFileDir, "current.props");
assertTrue(testFile.exists());
// testFile = new File(testFileDir, "1.props-123321");
// assertFalse(testFile.exists());
}
public void testIdenticalVersionFixesVersionError() throws Exception {
Properties props = new Properties();
MyMockRepositoryNode leaf = new MyMockRepositoryNode(
(RepositoryNodeImpl)createLeaf(
"http:
assertEquals(1, leaf.getCurrentVersion());
props = new Properties();
leaf.makeNewVersion();
leaf.setNewProperties(props);
// set to error state
leaf.currentVersion = 0;
writeToLeaf(leaf, "test stream");
assertEquals(0, leaf.currentVersion);
leaf.sealNewVersion();
// fixes error state, even though identical
assertEquals(1, leaf.getCurrentVersion());
assertTrue(leaf.isIdenticalVersion());
}
public void testMakeNewVersionFixesVersionError() throws Exception {
Properties props = new Properties();
MyMockRepositoryNode leaf = new MyMockRepositoryNode(
(RepositoryNodeImpl)createLeaf(
"http:
assertEquals(1, leaf.getCurrentVersion());
props = new Properties();
leaf.makeNewVersion();
// set to error state
leaf.currentVersion = -1;
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream2");
leaf.sealNewVersion();
// fixes error state
assertEquals(1, leaf.getCurrentVersion());
assertFalse(leaf.isIdenticalVersion());
}
public void testUnsealedRnc() throws Exception {
String url = "http:
String content = "test test test";
Properties props = new Properties();
props.setProperty("test 1", "value 1");
RepositoryNode leaf = repo.createNewNode(url);
try {
leaf.getUnsealedRnc();
fail("Should throw");
} catch (IllegalStateException e) {
}
leaf.makeNewVersion();
writeToLeaf(leaf, content);
RepositoryNode.RepositoryNodeContents rnc = leaf.getUnsealedRnc();
assertInputStreamMatchesString(content, rnc.getInputStream());
assertInputStreamMatchesString(content, rnc.getInputStream());
try {
rnc.getProperties();
fail("Should throw");
} catch (UnsupportedOperationException e) {
}
try {
rnc.addProperty("foo", "bar");
fail("Should throw");
} catch (UnsupportedOperationException e) {
}
rnc.release();
leaf.setNewProperties(props);
leaf.sealNewVersion();
assertFalse(leaf.isIdenticalVersion());
try {
rnc.getInputStream();
fail("Should throw");
} catch (IllegalStateException e) {
}
RepositoryNode.RepositoryNodeContents rncSealed = leaf.getNodeContents();
assertInputStreamMatchesString(content, rncSealed.getInputStream());
}
public void testGetInputStream() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
String resultStr = getLeafContent(leaf);
assertEquals("test stream", resultStr);
}
public void testGetProperties() throws Exception {
Properties props = new Properties();
props.setProperty("test 1", "value 1");
RepositoryNode leaf =
createLeaf("http:
"test stream", props);
RepositoryNode.RepositoryNodeContents contents = leaf.getNodeContents();
props = contents.getProperties();
// close stream to allow the file to be renamed later
// XXX 'getProperties()' creates an input stream, and 'release()' just
// sets it to null. The rename still fails in Windows unless the stream
// is closed first.
contents.getInputStream().close();
contents.release();
assertEquals("value 1", props.getProperty("test 1"));
leaf.makeNewVersion();
props = new Properties();
props.setProperty("test 1", "value 2");
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream 2");
leaf.sealNewVersion();
props = leaf.getNodeContents().getProperties();
assertEquals("value 2", props.getProperty("test 1"));
}
// More addProperty tests below in testGetNodeVersions()
public void testAddProperty() throws Exception {
Properties props = new Properties();
props.setProperty("test 1", "value 2");
RepositoryNode leaf =
createLeaf("http:
"test stream", props);
RepositoryNode.RepositoryNodeContents rnc0 = leaf.getNodeContents();
// get two more rncs on the same node
RepositoryNode.RepositoryNodeContents rnc1 = leaf.getNodeContents();
RepositoryNode.RepositoryNodeContents rnc2 = leaf.getNodeContents();
// and have one of them load the props
rnc2.getProperties();
assertNotSame(rnc0, rnc1);
// original props
Properties rnc0p1 = rnc0.getProperties();
assertEquals("value 2", rnc0p1.getProperty("test 1"));
// add prop to node
rnc0.addProperty(CachedUrl.PROPERTY_CHECKSUM, "checksum");
// old Properties object isn't updated.
assertFalse(rnc0p1.containsKey(CachedUrl.PROPERTY_CHECKSUM));
// rnc properties should have new prop
Properties rnc0p2 = rnc0.getProperties();
// not essential, but this is the way it works
assertNotSame(rnc0p1, rnc0p2);
assertEquals("checksum", rnc0p2.getProperty(CachedUrl.PROPERTY_CHECKSUM));
assertEquals("value 2", rnc0p2.getProperty("test 1"));
// previously obtained rnc whose properties hadn't already been loaded
// has new prop
Properties rnc1p1 = rnc1.getProperties();
assertEquals("checksum", rnc1p1.getProperty(CachedUrl.PROPERTY_CHECKSUM));
assertEquals("value 2", rnc1p1.getProperty("test 1"));
// previously obtained rnc whose properties *had* already been loaded
// doesn't have new prop
Properties rnc2p1 = rnc2.getProperties();
assertFalse(rnc2p1.containsKey(CachedUrl.PROPERTY_CHECKSUM));
assertEquals("value 2", rnc2p1.getProperty("test 1"));
RepositoryNode.RepositoryNodeContents rnc = leaf.getNodeContents();
props = rnc.getProperties();
assertNotNull(props);
assertTrue(props.containsKey(CachedUrl.PROPERTY_CHECKSUM));
assertEquals("checksum", props.getProperty(CachedUrl.PROPERTY_CHECKSUM));
}
RepositoryNode createNodeWithCorruptProps(String url) throws Exception {
Properties props = new Properties();
props.setProperty("test 1", "value 1");
RepositoryNode leaf = createLeaf(url, "test stream", props);
RepositoryNodeImpl leafImpl = (RepositoryNodeImpl)leaf;
File propsFile = new File(leafImpl.getContentDir(),
RepositoryNodeImpl.CURRENT_PROPS_FILENAME);
// Write a Malformed unicode escape that will cause Properties.load()
// to throw
OutputStream os =
new BufferedOutputStream(new FileOutputStream(propsFile, true));
os.write("\\uxxxxfoo=bar".getBytes());
os.close();
return leaf;
}
public void testCorruptProperties1() throws Exception {
RepositoryNode leaf =
createNodeWithCorruptProps("http:
assertFalse(leaf.hasContent());
assertTrue(leaf.isDeleted());
leaf.makeNewVersion();
writeToLeaf(leaf, "test stream");
leaf.setNewProperties(new Properties());
leaf.sealNewVersion();
assertTrue(leaf.hasContent());
assertFalse(leaf.isDeleted());
}
public void testCorruptProperties2() throws Exception {
String stem = "http:
RepositoryNode leaf = createNodeWithCorruptProps(stem + "/test.cache");
RepositoryNode leaf2 = createLeaf(stem + "/foo", "test stream", props);
RepositoryNode dirEntry =
repo.getNode("http:
Iterator childIt = dirEntry.listChildren(null, false);
assertEquals(ListUtil.list(leaf2), ListUtil.fromIterator(childIt));
}
static String PROP_VAL_STEM = "valstem_";
static String PROP_KEY = "key";
static String cntnt(int ix) {
return "content " + ix + "ABCDEFGHIJKLMNOPQRSTUVWXYZ".substring(0, ix);
}
static int lngth(int ix) {
return cntnt(ix).length();
}
void checkVersion(RepositoryNodeVersion nodeVer,
int exp, String addedPropVal)
throws IOException {
RepositoryNode.RepositoryNodeContents rnc = nodeVer.getNodeContents();
String verCont = getRNCContent(rnc);
Properties verProps = rnc.getProperties();
log.debug("ver: " + nodeVer.getVersion() + ", content: " + verCont);
log.debug2("ver: " + nodeVer.getVersion() + ", " +
StringUtil.shortName(props.getClass()) + ": " + verProps);
assertEquals(exp, nodeVer.getVersion());
assertEquals(cntnt(exp), verCont);
assertEquals(lngth(exp), nodeVer.getContentSize());
assertEquals(PROP_VAL_STEM+exp, verProps.getProperty(PROP_KEY));
assertEquals(addedPropVal,
verProps.getProperty(CachedUrl.PROPERTY_CHECKSUM));
// ensure can reread content from same rnc
assertEquals(verCont, getRNCContent(rnc));
}
void addPropToVersion(RepositoryNodeVersion nodeVer, String propVal) {
RepositoryNode.RepositoryNodeContents rnc = nodeVer.getNodeContents();
rnc.addProperty(CachedUrl.PROPERTY_CHECKSUM, propVal);
}
public void testGetNodeVersion() throws Exception {
int max = 5;
String url = "http:
Properties props = new Properties();
RepositoryNode leaf = repo.createNewNode(url);
// create several versions
for (int ix = 1; ix <= max; ix++) {
props.setProperty(PROP_KEY, PROP_VAL_STEM+ix);
createContentVersion(leaf, cntnt(ix), props);
}
// getNodeVersion(current) should return the main node
assertEquals(leaf, leaf.getNodeVersion(leaf.getCurrentVersion()));
// loop through other versions checking version, content, props
for (int ix = 1; ix < max; ix++) {
RepositoryNodeVersion nodeVer = leaf.getNodeVersion(ix);
checkVersion(nodeVer, ix, null);
}
}
public void testGetNodeVersions() throws Exception {
int max = 5;
String url = "http:
Properties props = new Properties();
// No existing node
RepositoryNode leaf0 = repo.createNewNode(url);
assertFalse(leaf0.hasContent());
RepositoryNodeVersion[] vers0 = leaf0.getNodeVersions();
assertEquals(1, vers0.length);
RepositoryNode leaf = repo.createNewNode(url);
// create several versions
for (int ix = 1; ix <= max; ix++) {
props.setProperty(PROP_KEY, PROP_VAL_STEM+ix);
createContentVersion(leaf, cntnt(ix), props);
}
// check expected current version number
assertEquals(max, leaf.getCurrentVersion());
assertEquals(max, leaf.getVersion());
// check version, content, props of current version
assertEquals(cntnt(max), getLeafContent(leaf));
assertEquals(lngth(max), leaf.getContentSize());
props = leaf.getNodeContents().getProperties();
assertEquals(PROP_VAL_STEM+max, props.getProperty(PROP_KEY));
// ask for all older versions
RepositoryNodeVersion[] vers = leaf.getNodeVersions();
assertEquals(max, vers.length);
RepositoryNode.RepositoryNodeContents[] rncs =
new RepositoryNode.RepositoryNodeContents[max];
// loop through them checking version, content, props
for (int ix = 0; ix < max; ix++) {
int exp = max - ix;
RepositoryNodeVersion nodeVer = vers[ix];
rncs[ix] = nodeVer.getNodeContents();
checkVersion(nodeVer, exp, null);
}
// now ask for and check a subset of the older versions
assertTrue("max must be at least 4 for this test", max >= 4);
int numver = max - 2;
RepositoryNodeVersion[] subvers = leaf.getNodeVersions(numver);
assertEquals(numver, subvers.length);
for (int ix = 0; ix < numver; ix++) {
int exp = max - ix;
RepositoryNodeVersion nodeVer = subvers[ix];
log.debug("ver: " + nodeVer.getVersion() + ", content: " +
getLeafContent(nodeVer));
assertEquals(exp, nodeVer.getVersion());
assertEquals(cntnt(exp), getLeafContent(nodeVer));
assertEquals(lngth(exp), nodeVer.getContentSize());
props = nodeVer.getNodeContents().getProperties();
assertEquals(PROP_VAL_STEM+exp, props.getProperty(PROP_KEY));
}
// Add a property to selected versions, ensure only the correct
// versions change
addPropToVersion(vers[0], "5new1");
checkVersion(vers[0], 5, "5new1");
for (int ix = 1; ix <= 4; ix++) {
checkVersion(vers[ix], max-ix, null);
}
addPropToVersion(vers[2], "3new1");
checkVersion(vers[2], 3, "3new1");
checkVersion(vers[0], 5, "5new1");
for (int ix : new int[]{1,3,4}) {
checkVersion(vers[ix], max-ix, null);
}
}
public void testIllegalVersionOperations() throws Exception {
RepositoryNode.RepositoryNodeContents rnc;
RepositoryNodeVersion nv;
RepositoryNode leaf =
repo.createNewNode("http:
try {
nv = leaf.getNodeVersion(7);
fail("No content, shouldn't be able to get versioned node: " + nv);
} catch (UnsupportedOperationException e) { }
// create first version
Properties props = new Properties();
props.setProperty("key", "val1");
createContentVersion(leaf, cntnt(1), props);
// We're allowed to get a RepositoryNodeVersion when the version
// doesn't exist ...
nv = leaf.getNodeVersion(7);
// but all operations on it should throw
try {
nv.getContentSize();
fail("No version; shouldn't get content size");
} catch (UnsupportedOperationException e) { }
try {
rnc = nv.getNodeContents();
fail("No version; shouldn't get RepositoryNodeContents");
} catch (UnsupportedOperationException e) { }
}
public void testDirContent() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
assertTrue(leaf.hasContent());
RepositoryNode dir =
repo.getNode("http:
dir.makeNewVersion();
writeToLeaf(dir, "test stream");
dir.setNewProperties(new Properties());
dir.sealNewVersion();
assertTrue(dir.hasContent());
dir = createLeaf("http:
"test stream", null);
assertTrue(dir.hasContent());
}
public void testNodeSize() throws Exception {
RepositoryNode leaf =
createLeaf("http:
"test stream", null);
assertTrue(leaf.hasContent());
assertEquals(11, (int)leaf.getContentSize());
}
public void testTreeSize() throws Exception {
createLeaf("http:
createLeaf("http:
createLeaf("http:
createLeaf("http:
"test33", null);
createLeaf("http:
"test33", null);
RepositoryNode leaf = repo.getNode("http:
assertEquals(-1, leaf.getTreeContentSize(null, false));
assertEquals(26, leaf.getTreeContentSize(null, true));
assertEquals(26, leaf.getTreeContentSize(null, false));
leaf = repo.getNode("http:
assertEquals(5, leaf.getTreeContentSize(null, true));
leaf = repo.getNode("http:
assertEquals(12, leaf.getTreeContentSize(null, true));
CachedUrlSetSpec cuss =
new RangeCachedUrlSetSpec("http:
"/branch1", "/branch1");
assertEquals(6, leaf.getTreeContentSize(cuss, true));
}
public void testDetermineParentNode() throws Exception {
repo.createNewNode("http:
repo.createNewNode("http:
assertNotNull(repo.getNode("http:
RepositoryNodeImpl node = (RepositoryNodeImpl)repo.createNewNode(
"http:
assertEquals("http:
node = node.determineParentNode();
assertEquals("http:
node = node.determineParentNode();
assertEquals("http:
node = node.determineParentNode();
assertEquals(AuUrl.PROTOCOL, node.getNodeUrl());
node = node.determineParentNode();
assertEquals(AuUrl.PROTOCOL, node.getNodeUrl());
// query args containing slash formerly caused determineParentNode() to
// return wrong result
RepositoryNodeImpl node2 = (RepositoryNodeImpl)repo.createNewNode(
"http:
node = node2.determineParentNode();
assertEquals("http:
}
public void testCacheInvalidation() throws Exception {
RepositoryNodeImpl root =
(RepositoryNodeImpl)createLeaf("http:
"test", null);
RepositoryNodeImpl branch =
(RepositoryNodeImpl)createLeaf("http:
"test", null);
RepositoryNodeImpl branch2 =
(RepositoryNodeImpl)createLeaf("http:
"test", null);
// This one has directory level with no node prop file, to check that
// cache invalidation traverses them correctly
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)createLeaf("http:
"test", null);
assertNull(branch.nodeProps.getProperty(TREE_SIZE_PROPERTY));
assertNull(leaf.nodeProps.getProperty(TREE_SIZE_PROPERTY));
// force invalidation to happen
branch.nodeProps.setProperty(TREE_SIZE_PROPERTY, "789");
branch.invalidateCachedValues(true);
// should now be explicitly marked invalid
assertEquals(RepositoryNodeImpl.INVALID,
branch.nodeProps.getProperty(TREE_SIZE_PROPERTY));
assertEquals(RepositoryNodeImpl.INVALID,
branch.nodeProps.getProperty(CHILD_COUNT_PROPERTY));
// fake prop set at root to check invalidation stops properly
root.nodeProps.setProperty(TREE_SIZE_PROPERTY, "789");
root.nodeProps.setProperty(CHILD_COUNT_PROPERTY, "3");
// don't set branch so the invalidate stops there
branch2.nodeProps.setProperty(TREE_SIZE_PROPERTY, "456");
branch2.nodeProps.setProperty(CHILD_COUNT_PROPERTY, "1");
leaf.nodeProps.setProperty(TREE_SIZE_PROPERTY, "123");
leaf.nodeProps.setProperty(CHILD_COUNT_PROPERTY, "0");
leaf.invalidateCachedValues(true);
// shoulddn't be set here anymore
assertFalse(isPropValid(leaf.nodeProps.getProperty(TREE_SIZE_PROPERTY)));
assertFalse(isPropValid(leaf.nodeProps.getProperty(CHILD_COUNT_PROPERTY)));
// or here (requires recursing up through dirs that have no node props
// file)
assertFalse(isPropValid(branch2.nodeProps.getProperty(TREE_SIZE_PROPERTY)));
assertFalse(isPropValid(branch2.nodeProps.getProperty(CHILD_COUNT_PROPERTY)));
// still invalid, recursion should have stopped here
assertFalse(isPropValid(branch.nodeProps.getProperty(TREE_SIZE_PROPERTY)));
assertFalse(isPropValid(branch.nodeProps.getProperty(CHILD_COUNT_PROPERTY)));
// so not cleared these
assertTrue(isPropValid(root.nodeProps.getProperty(TREE_SIZE_PROPERTY)));
assertTrue(isPropValid(root.nodeProps.getProperty(CHILD_COUNT_PROPERTY)));
assertEquals("789", root.nodeProps.getProperty(TREE_SIZE_PROPERTY));
assertEquals("3", root.nodeProps.getProperty(CHILD_COUNT_PROPERTY));
}
// Add a first child after #node_props have been created
public void testCacheInvalidationIncremental() throws Exception {
RepositoryNodeImpl root =
(RepositoryNodeImpl)createLeaf("http:
"test", null);
RepositoryNodeImpl branch =
(RepositoryNodeImpl)createLeaf("http:
"test", null);
assertFalse(isPropValid(branch.nodeProps.getProperty(TREE_SIZE_PROPERTY)));
assertTrue(branch.isLeaf());
assertEquals(0, branch.getChildCount());
assertEquals(4, branch.getTreeContentSize(null, true));
assertTrue(isPropValid(branch.nodeProps.getProperty(TREE_SIZE_PROPERTY)));
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)createLeaf("http:
"test", null);
assertEquals(8, branch.getTreeContentSize(null, true));
assertFalse(branch.isLeaf());
}
boolean isPropValid(String val) {
return RepositoryNodeImpl.isPropValid(val);
}
boolean isPropInvalid(String val) {
return RepositoryNodeImpl.isPropInvalid(val);
}
public void testTreeSizeCaching() throws Exception {
createLeaf("http:
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)repo.getNode("http:
assertNull(leaf.nodeProps.getProperty(TREE_SIZE_PROPERTY));
assertEquals(4, leaf.getTreeContentSize(null, true));
assertEquals("4", leaf.nodeProps.getProperty(TREE_SIZE_PROPERTY));
leaf.markAsDeleted();
assertTrue(isPropInvalid(leaf.nodeProps.getProperty(TREE_SIZE_PROPERTY)));
assertEquals(0, leaf.getTreeContentSize(null, true));
assertEquals("0", leaf.nodeProps.getProperty(TREE_SIZE_PROPERTY));
}
public void testChildCount() throws Exception {
createLeaf("http:
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)repo.getNode("http:
assertNull(leaf.nodeProps.getProperty(CHILD_COUNT_PROPERTY));
assertEquals(0, leaf.getChildCount());
assertEquals("0", leaf.nodeProps.getProperty(CHILD_COUNT_PROPERTY));
createLeaf("http:
createLeaf("http:
assertEquals(2, leaf.getChildCount());
assertEquals("2", leaf.nodeProps.getProperty(CHILD_COUNT_PROPERTY));
}
public void testDeactivate() throws Exception {
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)createLeaf("http:
"test stream", null);
assertTrue(leaf.hasContent());
assertFalse(leaf.isContentInactive());
assertEquals(1, leaf.getCurrentVersion());
assertNull(leaf.nodeProps.getProperty(RepositoryNodeImpl.INACTIVE_CONTENT_PROPERTY));
leaf.deactivateContent();
assertFalse(leaf.hasContent());
assertTrue(leaf.isContentInactive());
assertEquals(RepositoryNodeImpl.INACTIVE_VERSION, leaf.getCurrentVersion());
assertEquals("true", leaf.nodeProps.getProperty(RepositoryNodeImpl.INACTIVE_CONTENT_PROPERTY));
}
public void testDelete() throws Exception {
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)createLeaf("http:
"test stream", null);
assertTrue(leaf.hasContent());
assertFalse(leaf.isDeleted());
assertEquals(1, leaf.getCurrentVersion());
assertNull(leaf.nodeProps.getProperty(RepositoryNodeImpl.DELETION_PROPERTY));
leaf.markAsDeleted();
assertFalse(leaf.hasContent());
assertTrue(leaf.isDeleted());
assertEquals(RepositoryNodeImpl.DELETED_VERSION, leaf.getCurrentVersion());
assertEquals("true", leaf.nodeProps.getProperty(RepositoryNodeImpl.DELETION_PROPERTY));
}
public void testUnDelete() throws Exception {
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)createLeaf("http:
"test stream", null);
leaf.markAsDeleted();
assertTrue(leaf.isDeleted());
assertEquals(RepositoryNodeImpl.DELETED_VERSION, leaf.getCurrentVersion());
leaf.markAsNotDeleted();
assertFalse(leaf.isContentInactive());
assertFalse(leaf.isDeleted());
assertEquals(1, leaf.getCurrentVersion());
// make to null, not 'false'
assertNull(leaf.nodeProps.getProperty(RepositoryNodeImpl.DELETION_PROPERTY));
String resultStr = getLeafContent(leaf);
assertEquals("test stream", resultStr);
}
public void testRestoreLastVersion() throws Exception {
Properties props = new Properties();
props.setProperty("test 1", "value 1");
RepositoryNode leaf =
createLeaf("http:
assertEquals(1, leaf.getCurrentVersion());
props = new Properties();
props.setProperty("test 1", "value 2");
leaf.makeNewVersion();
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream 2");
leaf.sealNewVersion();
assertEquals(2, leaf.getCurrentVersion());
leaf.restoreLastVersion();
assertEquals(1, leaf.getCurrentVersion());
String resultStr = getLeafContent(leaf);
assertEquals("test stream 1", resultStr);
props = leaf.getNodeContents().getProperties();
assertEquals("value 1", props.getProperty("test 1"));
}
public void testReactivateViaRestore() throws Exception {
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)createLeaf("http:
"test stream", null);
leaf.deactivateContent();
assertTrue(leaf.isContentInactive());
assertEquals(RepositoryNodeImpl.INACTIVE_VERSION, leaf.getCurrentVersion());
leaf.restoreLastVersion();
assertFalse(leaf.isContentInactive());
assertEquals(1, leaf.getCurrentVersion());
// back to null, not 'false'
assertNull(leaf.nodeProps.getProperty(RepositoryNodeImpl.INACTIVE_CONTENT_PROPERTY));
String resultStr = getLeafContent(leaf);
assertEquals("test stream", resultStr);
}
public void testReactivateViaNewVersion() throws Exception {
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)createLeaf("http:
"test stream", null);
leaf.deactivateContent();
assertTrue(leaf.isContentInactive());
assertEquals(RepositoryNodeImpl.INACTIVE_VERSION, leaf.getCurrentVersion());
Properties props = new Properties();
props.setProperty("test 1", "value 2");
leaf.makeNewVersion();
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream 2");
leaf.sealNewVersion();
assertFalse(leaf.isContentInactive());
assertEquals(2, leaf.getCurrentVersion());
String resultStr = getLeafContent(leaf);
assertEquals("test stream 2", resultStr);
File lastProps = new File(leaf.contentDir, "1.props");
assertTrue(lastProps.exists());
InputStream is =
new BufferedInputStream(new FileInputStream(lastProps));
props.load(is);
is.close();
// make sure the 'was inactive' property hasn't been lost
assertEquals("true",
props.getProperty(RepositoryNodeImpl.NODE_WAS_INACTIVE_PROPERTY));
}
public void testAbandonReactivateViaNewVersion() throws Exception {
RepositoryNode leaf =
createLeaf("http:
leaf.deactivateContent();
assertTrue(leaf.isContentInactive());
assertEquals(RepositoryNodeImpl.INACTIVE_VERSION, leaf.getCurrentVersion());
Properties props = new Properties();
props.setProperty("test 1", "value 2");
leaf.makeNewVersion();
leaf.setNewProperties(props);
writeToLeaf(leaf, "test stream 2");
leaf.abandonNewVersion();
assertTrue(leaf.isContentInactive());
assertEquals(RepositoryNodeImpl.INACTIVE_VERSION, leaf.getCurrentVersion());
}
public void testIsLeaf() throws Exception {
createLeaf("http:
createLeaf("http:
createLeaf("http:
RepositoryNode leaf = repo.getNode("http:
assertTrue(leaf.isLeaf());
leaf = repo.getNode("http:
assertFalse(leaf.isLeaf());
}
public void testListInactiveNodes() throws Exception {
createLeaf("http:
createLeaf("http:
createLeaf("http:
createLeaf("http:
createLeaf("http:
createLeaf("http:
createLeaf("http:
RepositoryNode dirEntry = repo.getNode("http:
Iterator childIt = dirEntry.listChildren(null, false);
ArrayList childL = new ArrayList(3);
while (childIt.hasNext()) {
RepositoryNode node = (RepositoryNode)childIt.next();
childL.add(node.getNodeUrl());
}
String[] expectedA = new String[] {
"http:
"http:
"http:
"http:
"http:
};
assertSameElements(expectedA, childL);
RepositoryNode leaf = repo.getNode("http:
leaf.deactivateContent();
// this next shouldn't be excluded since it isn't a leaf node
leaf = repo.getNode("http:
leaf.deactivateContent();
// this next should be excluded because it's deleted
leaf = repo.getNode("http:
leaf.markAsDeleted();
childIt = dirEntry.listChildren(null, false);
childL = new ArrayList(2);
while (childIt.hasNext()) {
RepositoryNode node = (RepositoryNode)childIt.next();
childL.add(node.getNodeUrl());
}
expectedA = new String[] {
"http:
"http:
"http:
};
assertSameElements("Excluding inactive nodes failed.", expectedA, childL);
childIt = dirEntry.listChildren(null, true);
childL = new ArrayList(3);
while (childIt.hasNext()) {
RepositoryNode node = (RepositoryNode)childIt.next();
childL.add(node.getNodeUrl());
}
expectedA = new String[] {
"http:
"http:
"http:
"http:
};
assertSameElements("Including inactive nodes failed.", expectedA, childL);
}
public void testDeleteInnerNode() throws Exception {
createLeaf("http:
createLeaf("http:
RepositoryNode dirEntry = repo.getNode("http:
assertFalse(dirEntry.isDeleted());
dirEntry.markAsDeleted();
assertTrue(dirEntry.isDeleted());
dirEntry.markAsNotDeleted();
assertFalse(dirEntry.isDeleted());
}
public void testGetFileStrings() throws Exception {
RepositoryNodeImpl node = (RepositoryNodeImpl)repo.createNewNode(
"http:
node.initNodeRoot();
String contentStr = FileUtil.sysDepPath(node.nodeLocation + "/#content");
contentStr = contentStr.replaceAll("\\//", "\\\\/"); // sysDepPath mangles our backslashes
assertEquals(contentStr, node.getContentDir().toString());
contentStr = contentStr + File.separator;
String expectedStr = contentStr + "123";
assertEquals(expectedStr,
node.getVersionedCacheFile(123).getAbsolutePath());
expectedStr = contentStr + "123.props";
assertEquals(expectedStr,
node.getVersionedPropsFile(123).getAbsolutePath());
expectedStr = contentStr + "inactive";
assertEquals(expectedStr, node.getInactiveCacheFile().getAbsolutePath());
expectedStr = contentStr + "inactive.props";
assertEquals(expectedStr, node.getInactivePropsFile().getAbsolutePath());
}
public void testCheckNodeConsistency() throws Exception {
// check returns proper values for errors
MyMockRepositoryNode leaf = new MyMockRepositoryNode(
(RepositoryNodeImpl)repo.createNewNode("http:
leaf.makeNewVersion();
// should abort and return true since version open
leaf.failRootConsist = true;
assertTrue(leaf.checkNodeConsistency());
// finish write
leaf.setNewProperties(new Properties());
writeToLeaf(leaf, "test stream");
leaf.sealNewVersion();
// should return false if node root fails
assertFalse(leaf.checkNodeConsistency());
leaf.failRootConsist = false;
assertTrue(leaf.checkNodeConsistency());
// check returns false if content fails
leaf.failContentConsist = true;
assertFalse(leaf.checkNodeConsistency());
leaf.failContentConsist = false;
assertTrue(leaf.checkNodeConsistency());
// check returns false if current info load fails
leaf.failEnsureCurrentLoaded = true;
assertFalse(leaf.checkNodeConsistency());
leaf.failEnsureCurrentLoaded = false;
assertTrue(leaf.checkNodeConsistency());
}
public void testCheckNodeRootConsistency() throws Exception {
MyMockRepositoryNode leaf = new MyMockRepositoryNode(
(RepositoryNodeImpl)repo.createNewNode("http:
leaf.createNodeLocation();
assertTrue(leaf.nodeRootFile.exists());
// returns true when normal
assertTrue(leaf.checkNodeRootConsistency());
leaf.nodeRootFile.delete();
assertFalse(leaf.nodeRootFile.exists());
// creates dir, returns true when missing
assertTrue(leaf.checkNodeRootConsistency());
assertTrue(leaf.nodeRootFile.exists());
assertTrue(leaf.nodeRootFile.isDirectory());
// fail node props load
leaf.getChildCount();
assertTrue(leaf.nodePropsFile.exists());
File renameFile = new File(leaf.nodePropsFile.getAbsolutePath()+
RepositoryNodeImpl.FAULTY_FILE_EXTENSION);
assertFalse(renameFile.exists());
leaf.failPropsLoad = true;
assertTrue(leaf.checkNodeRootConsistency());
assertFalse(leaf.nodePropsFile.exists());
assertTrue(renameFile.exists());
}
public void testCheckContentConsistency() throws Exception {
MyMockRepositoryNode leaf = new MyMockRepositoryNode(
(RepositoryNodeImpl)createLeaf("http:
"test stream", null));
leaf.ensureCurrentInfoLoaded();
// should return false if content dir fails
MyMockRepositoryNode.failEnsureDirExists = true;
assertFalse(leaf.checkContentConsistency());
MyMockRepositoryNode.failEnsureDirExists = false;
assertTrue(leaf.checkContentConsistency());
// should return false if content file absent
File renameFile =
new File(leaf.currentCacheFile.getAbsolutePath()+"RENAME");
assertTrue(PlatformUtil.updateAtomically(leaf.currentCacheFile, renameFile));
assertFalse(leaf.checkContentConsistency());
PlatformUtil.updateAtomically(renameFile, leaf.currentCacheFile);
assertTrue(leaf.checkContentConsistency());
// should return false if content props absent
PlatformUtil.updateAtomically(leaf.currentPropsFile, renameFile);
assertFalse(leaf.checkContentConsistency());
PlatformUtil.updateAtomically(renameFile, leaf.currentPropsFile);
assertTrue(leaf.checkContentConsistency());
// should return false if inactive and files missing
leaf.currentVersion = RepositoryNodeImpl.INACTIVE_VERSION;
assertFalse(leaf.checkContentConsistency());
PlatformUtil.updateAtomically(leaf.currentPropsFile, leaf.getInactivePropsFile());
assertFalse(leaf.checkContentConsistency());
PlatformUtil.updateAtomically(leaf.currentCacheFile, leaf.getInactiveCacheFile());
assertTrue(leaf.checkContentConsistency());
PlatformUtil.updateAtomically(leaf.getInactivePropsFile(), leaf.currentPropsFile);
assertFalse(leaf.checkContentConsistency());
// finish restoring
PlatformUtil.updateAtomically(leaf.getInactiveCacheFile(), leaf.currentCacheFile);
leaf.currentVersion = 1;
assertTrue(leaf.checkContentConsistency());
// remove residual files
// - create files
FileOutputStream fos = new FileOutputStream(leaf.tempCacheFile);
StringInputStream sis = new StringInputStream("test stream");
StreamUtil.copy(sis, fos);
fos.close();
sis.close();
fos = new FileOutputStream(leaf.tempPropsFile);
sis = new StringInputStream("test stream");
StreamUtil.copy(sis, fos);
fos.close();
sis.close();
// should be removed
assertTrue(leaf.tempCacheFile.exists());
assertTrue(leaf.tempPropsFile.exists());
assertTrue(leaf.checkContentConsistency());
assertFalse(leaf.tempCacheFile.exists());
assertFalse(leaf.tempPropsFile.exists());
}
public void testEnsureDirExists() throws Exception {
RepositoryNodeImpl leaf =
(RepositoryNodeImpl)createLeaf("http:
File testDir = new File(tempDirPath, "testDir");
// should return true if dir exists
testDir.mkdir();
assertTrue(testDir.exists());
assertTrue(testDir.isDirectory());
assertTrue(leaf.ensureDirExists(testDir));
// should create dir, return true if not exists
testDir.delete();
assertFalse(testDir.exists());
assertTrue(leaf.ensureDirExists(testDir));
assertTrue(testDir.exists());
assertTrue(testDir.isDirectory());
// should rename file, create dir, return true if file exists
// -create file
testDir.delete();
FileOutputStream fos = new FileOutputStream(testDir);
StringInputStream sis = new StringInputStream("test stream");
StreamUtil.copy(sis, fos);
fos.close();
sis.close();
assertTrue(testDir.exists());
assertTrue(testDir.isFile());
// rename via 'ensureDirExists()'
File renameFile = new File(tempDirPath, "testDir"+
RepositoryNodeImpl.FAULTY_FILE_EXTENSION);
assertFalse(renameFile.exists());
assertTrue(leaf.ensureDirExists(testDir));
assertTrue(testDir.isDirectory());
assertEquals("test stream", StringUtil.fromFile(renameFile));
}
public void testCheckFileExists() throws Exception {
// return false if doesn't exist
File testFile = new File(tempDirPath, "testFile");
assertFalse(testFile.exists());
assertFalse(RepositoryNodeImpl.checkFileExists(testFile, "test file"));
// rename if dir (to make room for file creation), then return false
testFile.mkdir();
File renameDir = new File(tempDirPath, "testFile"+
RepositoryNodeImpl.FAULTY_FILE_EXTENSION);
assertTrue(testFile.exists());
assertTrue(testFile.isDirectory());
assertFalse(renameDir.exists());
assertFalse(RepositoryNodeImpl.checkFileExists(testFile, "test file"));
assertFalse(testFile.exists());
assertTrue(renameDir.exists());
assertTrue(renameDir.isDirectory());
// return true if exists
FileOutputStream fos = new FileOutputStream(testFile);
StringInputStream sis = new StringInputStream("test stream");
StreamUtil.copy(sis, fos);
fos.close();
sis.close();
assertTrue(testFile.exists());
assertTrue(testFile.isFile());
assertTrue(RepositoryNodeImpl.checkFileExists(testFile, "test file"));
assertEquals("test stream", StringUtil.fromFile(testFile));
}
public void testCheckChildCountCacheAccuracy() throws Exception {
createLeaf("http:
createLeaf("http:
RepositoryNodeImpl dirEntry =
(RepositoryNodeImpl)repo.getNode("http:
assertEquals(2, dirEntry.getChildCount());
assertEquals("2",
dirEntry.nodeProps.getProperty(RepositoryNodeImpl.CHILD_COUNT_PROPERTY));
// check that no change to valid count cache
dirEntry.checkChildCountCacheAccuracy();
log.debug2("child count: " +
dirEntry.nodeProps.getProperty(RepositoryNodeImpl.CHILD_COUNT_PROPERTY));
assertEquals("2",
dirEntry.nodeProps.getProperty(RepositoryNodeImpl.CHILD_COUNT_PROPERTY));
// check that invalid cache removed
dirEntry.nodeProps.setProperty(RepositoryNodeImpl.CHILD_COUNT_PROPERTY, "3");
dirEntry.checkChildCountCacheAccuracy();
assertEquals(RepositoryNodeImpl.INVALID,
dirEntry.nodeProps.getProperty(RepositoryNodeImpl.CHILD_COUNT_PROPERTY));
}
public void testEncodeUrl() {
assertEquals(null, RepositoryNodeImpl.encodeUrl(null));
assertEquals("", RepositoryNodeImpl.encodeUrl(""));
assertEquals("www.example.com",
RepositoryNodeImpl.encodeUrl("www.example.com"));
assertEquals("www.example.com/val",
RepositoryNodeImpl.encodeUrl("www.example.com/val"));
assertEquals("www.example.com%5Cval",
RepositoryNodeImpl.encodeUrl("www.example.com\\val"));
assertEquals("www.example.com/val%5Cval",
RepositoryNodeImpl.encodeUrl("www.example.com/val\\val"));
assertEquals("www.example.com/val/val",
RepositoryNodeImpl.encodeUrl("www.example.com/val/val"));
assertEquals("www.example.com/val%5C%5Cval",
RepositoryNodeImpl.encodeUrl("www.example.com/val\\\\val"));
assertEquals("www.example.com/val/val",
RepositoryNodeImpl.encodeUrl("www.example.com/val/val"));
assertEquals("www.example.com/val/val/",
RepositoryNodeImpl.encodeUrl("www.example.com/val/val/"));
assertEquals("www.example.com/val/val%5C",
RepositoryNodeImpl.encodeUrl("www.example.com/val/val\\"));
assertEquals("www.example.com%5Cval%5Cval%5C",
RepositoryNodeImpl.encodeUrl("www.example.com\\val\\val\\"));
}
public void testEncodeUrlUnicode() {
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_MAX_COMPONENT_LENGTH,
"30");
assertEquals("www.example.com/val/12345678901234567890123456789\\/0123",
RepositoryNodeImpl.encodeUrl("www.example.com/val/123456789012345678901234567890123"));
assertEquals("www.example.com/val/123\u00E7567890123456789012345678\\/90123",
RepositoryNodeImpl.encodeUrl("www.example.com/val/123\u00E756789012345678901234567890123"));
}
public void testEncodeUrlCompatibility() {
ConfigurationUtil.addFromArgs(RepositoryManager.PARAM_ENABLE_LONG_COMPONENTS_COMPATIBILITY,
"true");
assertEquals(null, RepositoryNodeImpl.encodeUrl(null));
assertEquals("", RepositoryNodeImpl.encodeUrl(""));
assertEquals("www.example.com",
RepositoryNodeImpl.encodeUrl("www.example.com"));
assertEquals("www.example.com/val",
RepositoryNodeImpl.encodeUrl("www.example.com/val"));
assertEquals("www.example.com%5cval",
RepositoryNodeImpl.encodeUrl("www.example.com\\val"));
assertEquals("www.example.com/val%5cval",
RepositoryNodeImpl.encodeUrl("www.example.com/val\\val"));
assertEquals("www.example.com/val/val",
RepositoryNodeImpl.encodeUrl("www.example.com/val/val"));
assertEquals("www.example.com/val%5c%5cval",
RepositoryNodeImpl.encodeUrl("www.example.com/val\\\\val"));
assertEquals("www.example.com/val/val",
RepositoryNodeImpl.encodeUrl("www.example.com/val/val"));
assertEquals("www.example.com/val/val/",
RepositoryNodeImpl.encodeUrl("www.example.com/val/val/"));
assertEquals("www.example.com/val/val%5c",
RepositoryNodeImpl.encodeUrl("www.example.com/val/val\\"));
assertEquals("www.example.com%5cval%5cval%5c",
RepositoryNodeImpl.encodeUrl("www.example.com\\val\\val\\"));
}
public void testShortDecodeUrl() {
assertEquals(null, RepositoryNodeImpl.decodeUrl(null));
assertEquals("", RepositoryNodeImpl.decodeUrl(""));
assertEquals("www.example.com",
RepositoryNodeImpl.decodeUrl("www.example.com"));
assertEquals("www.example.com/val",
RepositoryNodeImpl.decodeUrl("www.example.com/val"));
assertEquals("www.example.com%5Cval",
RepositoryNodeImpl.decodeUrl("www.example.com%5Cval"));
assertEquals("www.example.com/val%5Cval",
RepositoryNodeImpl.decodeUrl("www.example.com/val%5Cval"));
assertEquals("www.example.com/val/val",
RepositoryNodeImpl.decodeUrl("www.example.com/val/val"));
assertEquals("www.example.com/val%5C%5Cval",
RepositoryNodeImpl.decodeUrl("www.example.com/val%5C%5Cval"));
assertEquals("www.example.com/val/val",
RepositoryNodeImpl.decodeUrl("www.example.com/val/val"));
assertEquals("www.example.com/val/val/",
RepositoryNodeImpl.decodeUrl("www.example.com/val/val/"));
assertEquals("www.example.com/val/val%5C",
RepositoryNodeImpl.decodeUrl("www.example.com/val/val%5C"));
assertEquals("www.example.com%5cval%5Cval%5c",
RepositoryNodeImpl.decodeUrl("www.example.com%5cval%5Cval%5c"));
}
public void testLongDecodeUrl() {
StringBuilder longUrl = new StringBuilder();
longUrl.append("www.example.com/");
for(int i=0; i<218; i++) {
longUrl.append(i + ",");
}
longUrl.append(".");
String result = RepositoryNodeImpl.encodeUrl(longUrl.toString());
log.debug2(longUrl.toString());
log.debug2(result);
String result2 = RepositoryNodeImpl.decodeUrl(result);
log.debug2(result2);
assertTrue(longUrl.toString().equals(result2));
}
private RepositoryNode createLeaf(String url, String content,
Properties props) throws Exception {
return createLeaf(repo, url, content, props);
}
public static RepositoryNode createLeaf(LockssRepository repo, String url,
String content, Properties props) throws Exception {
RepositoryNode leaf = repo.createNewNode(url);
createContentVersion(leaf, content, props);
return leaf;
}
public static RepositoryNode createLeaf(LockssRepository repo, String url,
InputStream contentStream, Properties props) throws Exception {
RepositoryNode leaf = repo.createNewNode(url);
createContentVersion(leaf, contentStream, props);
return leaf;
}
public static void createContentVersion(RepositoryNode leaf,
String content, Properties props)
throws Exception {
leaf.makeNewVersion();
writeToLeaf(leaf, content);
if (props==null) {
props = new Properties();
}
leaf.setNewProperties(props);
leaf.sealNewVersion();
}
public static void createContentVersion(RepositoryNode leaf,
InputStream contentStream,
Properties props)
throws Exception {
leaf.makeNewVersion();
writeToLeaf(leaf, contentStream);
if (props==null) {
props = new Properties();
}
leaf.setNewProperties(props);
leaf.sealNewVersion();
}
public static void writeToLeaf(RepositoryNode leaf, String content)
throws Exception {
if (content==null) {
content = "";
}
OutputStream os = leaf.getNewOutputStream();
InputStream is = new StringInputStream(content);
StreamUtil.copy(is, os);
os.close();
is.close();
}
public static void writeToLeaf(RepositoryNode leaf, InputStream contentStream)
throws Exception {
OutputStream os = leaf.getNewOutputStream();
StreamUtil.copy(contentStream, os);
os.close();
contentStream.close();
}
public static String getLeafContent(RepositoryNodeVersion leaf)
throws IOException {
return getRNCContent(leaf.getNodeContents());
}
public static String getRNCContent(RepositoryNode.RepositoryNodeContents rnc)
throws IOException {
InputStream is = rnc.getInputStream();
OutputStream baos = new ByteArrayOutputStream(20);
StreamUtil.copy(is, baos);
is.close();
String resultStr = baos.toString();
baos.close();
return resultStr;
}
public static void main(String[] argv) {
String[] testCaseList = { TestRepositoryNodeImpl.class.getName()};
junit.swingui.TestRunner.main(testCaseList);
}
// this class overrides 'getDatedVersionedPropsFile()' so I can
// manipulate the file names for testing. Also allows 'loadNodeProps()
// to fail on demand
static class MyMockRepositoryNode extends RepositoryNodeImpl {
long dateValue;
boolean failPropsLoad = false;
boolean failRootConsist = false;
boolean failContentConsist = false;
boolean failEnsureCurrentLoaded = false;
static boolean failEnsureDirExists = false;
MyMockRepositoryNode(RepositoryNodeImpl nodeImpl) {
super(nodeImpl.url, nodeImpl.nodeLocation, nodeImpl.repository);
}
File getDatedVersionedPropsFile(int version, long date) {
StringBuilder buffer = new StringBuilder();
buffer.append(version);
buffer.append(PROPS_EXTENSION);
buffer.append("-");
buffer.append(dateValue);
return new File(getContentDir(), buffer.toString());
}
void loadNodeProps(boolean okIfNotThere) {
if (failPropsLoad) {
throw new LockssRepository.RepositoryStateException("Couldn't load properties file.");
} else {
super.loadNodeProps(okIfNotThere);
}
}
boolean checkNodeRootConsistency() {
if (failRootConsist) {
return false;
} else {
return super.checkNodeRootConsistency();
}
}
boolean checkContentConsistency() {
if (failContentConsist) {
return false;
} else {
return super.checkContentConsistency();
}
}
void ensureCurrentInfoLoaded() {
if (failEnsureCurrentLoaded) {
throw new LockssRepository.RepositoryStateException("Couldn't load current info.");
} else {
super.ensureCurrentInfoLoaded();
}
}
boolean ensureDirExists(File dirFile) {
if (failEnsureDirExists) {
return false;
} else {
return super.ensureDirExists(dirFile);
}
}
}
static class MyLockssRepositoryImpl extends LockssRepositoryImpl {
boolean dontNormalize = false;
void setDontNormalize(boolean val) {
dontNormalize = val;
}
MyLockssRepositoryImpl(String rootPath) {
super(rootPath);
}
public String canonicalizePath(String url)
throws MalformedURLException {
if (dontNormalize) return url;
return super.canonicalizePath(url);
}
public static LockssRepository createNewLockssRepository(ArchivalUnit au) {
String root = getRepositoryRoot(au);
if (root == null) {
throw new LockssRepository.RepositoryStateException("null root");
}
String auDir = LockssRepositoryImpl.mapAuToFileLocation(root, au);
log.debug("repo: " + auDir + ", au: " + au.getName());
// staticCacheLocation = extendCacheLocation(root);
LockssRepositoryImpl repo = new MyLockssRepositoryImpl(auDir);
Plugin plugin = au.getPlugin();
if (plugin != null) {
LockssDaemon daemon = plugin.getDaemon();
if (daemon != null) {
RepositoryManager mgr = daemon.getRepositoryManager();
if (mgr != null) {
mgr.setRepositoryForPath(auDir, repo);
}
}
}
return repo;
}
}
} |
package hudson.tasks.junit;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import static org.jvnet.hudson.test.MemoryAssert.*;
import static org.junit.Assert.*;
import org.junit.Test;
public class SuiteResultTest {
@SuppressWarnings({"DM_DEFAULT_ENCODING", "OS_OPEN_STREAM", "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE"})
@Test public void sizeSurefire() throws Exception {
File data = File.createTempFile("TEST-", ".xml");
try {
Writer w = new FileWriter(data);
try {
PrintWriter pw = new PrintWriter(w);
pw.println("<testsuites name='x'>");
pw.println("<testsuite failures='10' errors='0' tests='20' name='x'>");
// Simulating Surefire 2.12.4 with redirectTestOutputToFile=true:
for (int i = 0; i < 10; i++) { // these pass and SF omits stdio
pw.println("<testcase name='t" + i + "' classname='x'/>");
}
for (int i = 10; i < 20; i++) { // these fail and SF includes per-test stdio
pw.println("<testcase name='t" + i + "' classname='x'>");
pw.println("<failure type='java.lang.AssertionError'>some stack trace</failure>");
pw.print("<system-out>");
for (int j = 0; j < 1000; j++) {
pw.println("t" + i + " out
}
pw.println("</system-out>");
pw.print("<system-err>");
for (int j = 0; j < 1000; j++) {
pw.println("t" + i + " err
}
pw.println("</system-err>");
pw.println("</testcase>");
}
pw.println("</testsuite>");
pw.println("</testsuites>");
pw.flush();
} finally {
w.close();
}
File data2 = new File(data.getParentFile(), data.getName().replaceFirst("^TEST-(.+)[.]xml$", "$1-output.txt"));
try {
w = new FileWriter(data2);
try {
PrintWriter pw = new PrintWriter(w);
for (int i = 0; i < 20; i++) { // stdio for complete suite (incl. passing tests)
for (int j = 0; j < 1000; j++) {
pw.println("t" + i + " out
pw.println("t" + i + " err
}
}
pw.flush();
} finally {
w.close();
}
SuiteResult sr = parseOne(data);
assertHeapUsage(sr, 252 + /* Unicode overhead */2 * (int) (/*259946*/data.length() + /*495600*/data2.length() + /* SuiteResult.file */data.getAbsolutePath().length()));
// XXX serialize using TestResultAction.XSTREAM and verify that round-tripped object has same size
} finally {
data2.delete();
}
} finally {
data.delete();
}
}
private SuiteResult parseOne(File file) throws Exception {
List<SuiteResult> results = SuiteResult.parse(file, false);
assertEquals(1,results.size());
return results.get(0);
}
} |
package markehme.factionsplus.MCore;
import java.util.List;
import java.util.Map;
import org.bukkit.entity.Player;
import com.massivecraft.factions.entity.Faction;
import com.massivecraft.factions.entity.UPlayer;
import com.massivecraft.mcore.ps.PS;
import com.massivecraft.mcore.store.Entity;
public class FactionData extends Entity<FactionData> {
// META
public static FactionData get(Object oid)
{
return FactionDataColls.get().get2(oid);
}
// OVERRIDE: ENTITY
@Override
public FactionData load(FactionData that) {
this.faction = that.faction;
return this;
}
@Override
public void preDetach(String id) {
// Not sure we need to use this yet.
//String universe = this.getUniverse();
}
// METHODS
/**
* Check if a warp exists.
* @param name
* @return
*/
public boolean warpExists(String name) {
if(warpLocation.get(name.toLowerCase()) == null) {
return false;
}
return true;
}
/**
* Check if a warp has a password. Returns true if a warp has a password.
* @param name
* @return
*/
public boolean warpHasPassword(String name) {
return (warpPasswords.get(name.toLowerCase()) != null);
}
/**
* Validate the password of a warp, returns true if it is valid.
* @param name
* @param pass
* @return
*/
public boolean warpValidatePassword(String name, String pass) {
if(!warpHasPassword(name.toLowerCase())) {
return true;
}
if(warpPasswords.get(name.toLowerCase()) == pass) {
return true;
}
return false;
}
/**
* Returns the (PS) Location of a warp
* @param warp
* @return
*/
public PS getWarpLocation(String warp) {
return(warpLocation.get(warp.toLowerCase()));
}
/**
* Returns a map of the warps and their locations
* @return
*/
public Map<String, PS> getWarps() {
return null;
}
public boolean isJailed(UPlayer uPlayer) {
return(isJailed(uPlayer.getPlayer()));
}
public boolean isJailed(Player player) {
return(this.jailedPlayerIDs.containsKey(player.getUniqueId().toString()));
}
// VARIABLES
public Faction faction = null;
public Map<String, PS> warpLocation;
public Map<String, String> warpPasswords;
public String announcement = null;
public Map<String, String> bannedPlayerIDs;
public Map<String, PS> jailedPlayerIDs;
public PS jailLocation = null;
public List<String> rules;
} |
package meizhuo.org.lightmeeting.model;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.Gson;
public class Research {
/**
*
* @param json
* @return
*/
public static Research create_by_json(String json){
try {
Gson gson = new Gson();
return (Research)gson.fromJson(json, Research.class);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
/**
*
* @param jsonarray
* @return
*/
public static List<Research>create_by_jsonarray(String jsonarray){
List<Research>list = new ArrayList<Research>();
JSONObject obj = null;
JSONArray array = null;
try {
obj = new JSONObject(jsonarray);
array = obj.getJSONArray("response");
for(int i=0 ; i<array.length();i++)
{
list.add(create_by_json(array.getJSONObject(i).toString()));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
list = null;
}
return list;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMeetid() {
return meetid;
}
public void setMeetid(String meetid) {
this.meetid = meetid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getStime() {
return stime;
}
public void setStime(String stime) {
this.stime = stime;
}
public String getEtime() {
return etime;
}
public void setEtime(String etime) {
this.etime = etime;
}
private String id;
@Override
public String toString() {
return "Research [id=" + id + ", meetid=" + meetid + ", title=" + title
+ ", intro=" + intro + ", stime=" + stime + ", etime=" + etime
+ "]";
}
private String meetid;
private String title;
private String intro;
private String stime;
private String etime;
} |
package musician101.itembank.commands;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import musician101.itembank.ItemBank;
import musician101.itembank.lib.Constants;
import musician101.itembank.lib.Messages;
import musician101.itembank.util.IBUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class IBCommand implements CommandExecutor
{
ItemBank plugin;
public IBCommand(ItemBank plugin)
{
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
if (args.length > 0)
{
/** Help Command */
if (args[0].equalsIgnoreCase(Constants.HELP_CMD))
{
if (args.length > 1)
{
if (args[1].equalsIgnoreCase(Constants.ACCOUNT_CMD))
{
IBUtils.sendMessages((Player) sender, Messages.ACCOUNT_HELP_MSG);
return true;
}
else if (args[1].equalsIgnoreCase(Constants.RELOAD_CMD))
{
IBUtils.sendMessages((Player) sender, Messages.RELOAD_HELP_MSG);
return true;
}
else if (args[1].equalsIgnoreCase(Constants.PURGE_CMD))
{
IBUtils.sendMessages((Player) sender, Messages.PURGE_HELP_MSG);
return true;
}
}
sender.sendMessage(Messages.PREFIX + Messages.HELP_MSG.get(3));
return true;
}
/** Purge Command */
else if (args[0].equalsIgnoreCase(Constants.PURGE_CMD))
{
if (!sender.hasPermission(Constants.PURGE_PERM))
{
sender.sendMessage(Messages.NO_PERMISSION);
return false;
}
if (args.length > 1)
{
if (plugin.config.useMYSQL)
{
try
{
plugin.c.createStatement().execute("DROP TABLE IF EXISTS ib_" + args[0]);
}
catch (SQLException e)
{
sender.sendMessage(Messages.SQL_EX);
return false;
}
sender.sendMessage(Messages.PURGE_SINGLE);
return true;
}
File file = new File(plugin.playerData, args[1] + "." + plugin.config.format);
if (!file.exists())
{
sender.sendMessage(Messages.PURGE_NO_FILE);
return false;
}
file.delete();
IBUtils.createPlayerFile(file);
sender.sendMessage(Messages.PURGE_SINGLE);
return true;
}
if (plugin.config.useMYSQL)
{
try
{
Statement statement = plugin.c.createStatement();
ResultSet rs = plugin.c.getMetaData().getTables(null, null, null, new String[]{"TABLE"});
while (rs.next())
{
sender.sendMessage(rs.getString(3));
if (rs.getString(3).contains("ib_"))
statement.execute("DROP TABLE " + rs.getString(3));
}
}
catch (SQLException e)
{
sender.sendMessage(Messages.SQL_EX);
return false;
}
sender.sendMessage(Messages.PURGE_MULTIPLE);
return true;
}
for (File file : plugin.playerData.listFiles())
file.delete();
IBUtils.createPlayerFiles(plugin);
sender.sendMessage(Messages.PURGE_MULTIPLE);
return true;
}
/** Reload Command */
else if (args[0].equalsIgnoreCase(Constants.RELOAD_CMD))
{
if (!sender.hasPermission(Constants.RELOAD_PERM))
{
sender.sendMessage(Messages.NO_PERMISSION);
return false;
}
plugin.config.reloadConfiguration();
sender.sendMessage(Messages.RELOAD_SUCCESS);
return true;
}
}
IBUtils.sendMessages((Player) sender, Messages.HELP_MSG);
return true;
}
} |
package algorithms.imageProcessing;
import algorithms.util.ResourceFinder;
import java.util.logging.Logger;
import junit.framework.TestCase;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
/**
*
* @author nichole
*/
public class BlobScaleFindersTest extends TestCase {
private Logger log = Logger.getLogger(this.getClass().getName());
public void test0() throws Exception {
boolean useBinned = false;
String filePath1 = ResourceFinder.findFileInTestResources("brown_lowe_2003_image1.jpg");
ImageExt img1 = ImageIOHelper.readImageExt(filePath1);
String filePath2 = ResourceFinder.findFileInTestResources("brown_lowe_2003_image2.jpg");
ImageExt img2 = ImageIOHelper.readImageExt(filePath2);
BlobPerimeterHelper bph1 = new BlobPerimeterHelper(img1, "1");
bph1.applySegmentation(SegmentationType.GREYSCALE_KMPP, useBinned);
BlobCornerHelper bch1 = new BlobCornerHelper(bph1, "1");
bch1.generatePerimeterCorners(SegmentationType.GREYSCALE_KMPP,
useBinned);
BlobPerimeterHelper bph2 = new BlobPerimeterHelper(img2, "2");
bph2.applySegmentation(SegmentationType.GREYSCALE_KMPP, useBinned);
BlobCornerHelper bch2 = new BlobCornerHelper(bph2, "2");
bch2.generatePerimeterCorners(SegmentationType.GREYSCALE_KMPP,
useBinned);
BlobCornersScaleFinder bsFinder = new BlobCornersScaleFinder();
float[] outputScaleRotTransXYStDev = new float[4];
IntensityFeatures features1 = new IntensityFeatures(img1, 5, true);
IntensityFeatures features2 = new IntensityFeatures(img2, 5, true);
TransformationParameters params = bsFinder.solveForScale(
bch1, features1,
SegmentationType.GREYSCALE_KMPP, useBinned,
bch2, features2,
SegmentationType.GREYSCALE_KMPP, useBinned,
outputScaleRotTransXYStDev);
assertNotNull(params);
assertTrue(Math.abs(params.getScale() - 1) < 0.15);
}
public void test1() throws Exception {
boolean useBinned = false;
String filePath1 = ResourceFinder.findFileInTestResources("venturi_mountain_j6_0001.png");
ImageExt img1 = ImageIOHelper.readImageExt(filePath1);
String filePath2 = ResourceFinder.findFileInTestResources("venturi_mountain_j6_0010.png");
ImageExt img2 = ImageIOHelper.readImageExt(filePath2);
BlobPerimeterHelper bph1 = new BlobPerimeterHelper(img1, "1");
bph1.applyEqualization();
bph1.applySegmentation(SegmentationType.COLOR_POLARCIEXY, useBinned);
BlobCornerHelper bch1 = new BlobCornerHelper(bph1, "1");
bch1.generatePerimeterCorners(SegmentationType.COLOR_POLARCIEXY,
useBinned);
BlobPerimeterHelper bph2 = new BlobPerimeterHelper(img2, "2");
bph2.applyEqualization();
bph2.applySegmentation(SegmentationType.COLOR_POLARCIEXY, useBinned);
BlobCornerHelper bch2 = new BlobCornerHelper(bph2, "2");
bch2.generatePerimeterCorners(SegmentationType.COLOR_POLARCIEXY,
useBinned);
BlobCornersScaleFinder bsFinder = new BlobCornersScaleFinder();
float[] outputScaleRotTransXYStDev = new float[4];
IntensityFeatures features1 = new IntensityFeatures(img1, 5, true);
IntensityFeatures features2 = new IntensityFeatures(img2, 5, true);
TransformationParameters params = bsFinder.solveForScale(
bch1, features1,
SegmentationType.COLOR_POLARCIEXY, useBinned,
bch2, features2,
SegmentationType.COLOR_POLARCIEXY, useBinned,
outputScaleRotTransXYStDev);
assertNotNull(params);
assertTrue(Math.abs(params.getScale() - 1) < 0.1);
}
public void test2() throws Exception {
boolean useBinned = false;
String filePath1 = ResourceFinder.findFileInTestResources("brown_lowe_2003_image1.jpg");
ImageExt img1 = ImageIOHelper.readImageExt(filePath1);
String filePath2 = ResourceFinder.findFileInTestResources("brown_lowe_2003_image2.jpg");
ImageExt img2 = ImageIOHelper.readImageExt(filePath2);
BlobPerimeterHelper bph1 = new BlobPerimeterHelper(img1, "1");
bph1.applySegmentation(SegmentationType.GREYSCALE_KMPP, useBinned);
BlobContourHelper bch1 = new BlobContourHelper(bph1, "1");
bch1.generatePerimeterContours(SegmentationType.GREYSCALE_KMPP,
useBinned);
BlobPerimeterHelper bph2 = new BlobPerimeterHelper(img2, "2");
bph2.applySegmentation(SegmentationType.GREYSCALE_KMPP, useBinned);
BlobContourHelper bch2 = new BlobContourHelper(bph2, "2");
bch2.generatePerimeterContours(SegmentationType.GREYSCALE_KMPP,
useBinned);
BlobContoursScaleFinder bsFinder = new BlobContoursScaleFinder();
float[] outputScaleRotTransXYStDev = new float[4];
IntensityFeatures features1 = new IntensityFeatures(img1, 5, true);
IntensityFeatures features2 = new IntensityFeatures(img2, 5, true);
TransformationParameters params = bsFinder.solveForScale(
bch1, features1,
SegmentationType.GREYSCALE_KMPP, useBinned,
bch2, features2,
SegmentationType.GREYSCALE_KMPP, useBinned,
outputScaleRotTransXYStDev);
assertNotNull(params);
assertTrue(Math.abs(params.getScale() - 1) < 0.15);
}
public void test3() throws Exception {
boolean useBinned = false;
String filePath1 = ResourceFinder.findFileInTestResources("venturi_mountain_j6_0001.png");
ImageExt img1 = ImageIOHelper.readImageExt(filePath1);
String filePath2 = ResourceFinder.findFileInTestResources("venturi_mountain_j6_0010.png");
ImageExt img2 = ImageIOHelper.readImageExt(filePath2);
BlobPerimeterHelper bph1 = new BlobPerimeterHelper(img1, "1");
bph1.applyEqualization();
bph1.applySegmentation(SegmentationType.COLOR_POLARCIEXY, useBinned);
BlobContourHelper bch1 = new BlobContourHelper(bph1, "1");
bch1.generatePerimeterContours(SegmentationType.COLOR_POLARCIEXY,
useBinned);
BlobPerimeterHelper bph2 = new BlobPerimeterHelper(img2, "2");
bph2.applyEqualization();
bph2.applySegmentation(SegmentationType.COLOR_POLARCIEXY, useBinned);
BlobContourHelper bch2 = new BlobContourHelper(bph2, "2");
bch2.generatePerimeterContours(SegmentationType.COLOR_POLARCIEXY,
useBinned);
BlobContoursScaleFinder bsFinder = new BlobContoursScaleFinder();
float[] outputScaleRotTransXYStDev = new float[4];
IntensityFeatures features1 = new IntensityFeatures(img1, 5, true);
IntensityFeatures features2 = new IntensityFeatures(img2, 5, true);
TransformationParameters params = bsFinder.solveForScale(
bch1, features1,
SegmentationType.COLOR_POLARCIEXY, useBinned,
bch2, features2,
SegmentationType.COLOR_POLARCIEXY, useBinned,
outputScaleRotTransXYStDev);
assertNotNull(params);
assertTrue(Math.abs(params.getScale() - 1) < 0.1);
}
public void test4() throws Exception {
boolean useBinned = true;
String filePath1 = ResourceFinder.findFileInTestResources("venturi_mountain_j6_0001.png");
ImageExt img1 = ImageIOHelper.readImageExt(filePath1);
String filePath2 = ResourceFinder.findFileInTestResources("venturi_mountain_j6_0010.png");
ImageExt img2 = ImageIOHelper.readImageExt(filePath2);
BlobPerimeterHelper bph1 = new BlobPerimeterHelper(img1, "1");
bph1.applyEqualization();
bph1.createBinnedGreyscaleImage(300);
bph1.applySegmentation(SegmentationType.COLOR_POLARCIEXY, useBinned);
BlobContourHelper bch1 = new BlobContourHelper(bph1, "1");
bch1.generatePerimeterContours(SegmentationType.COLOR_POLARCIEXY,
useBinned);
BlobPerimeterHelper bph2 = new BlobPerimeterHelper(img2, "2");
bph2.applyEqualization();
bph2.createBinnedGreyscaleImage(300);
bph2.applySegmentation(SegmentationType.COLOR_POLARCIEXY, useBinned);
BlobContourHelper bch2 = new BlobContourHelper(bph2, "2");
bch2.generatePerimeterContours(SegmentationType.COLOR_POLARCIEXY,
useBinned);
BlobContoursScaleFinder bsFinder = new BlobContoursScaleFinder();
float[] outputScaleRotTransXYStDev = new float[4];
IntensityFeatures features1 = new IntensityFeatures(img1, 5, true);
IntensityFeatures features2 = new IntensityFeatures(img2, 5, true);
TransformationParameters params = bsFinder.solveForScale(
bch1, features1,
SegmentationType.COLOR_POLARCIEXY, useBinned,
bch2, features2,
SegmentationType.COLOR_POLARCIEXY, useBinned,
outputScaleRotTransXYStDev);
assertNotNull(params);
assertTrue(Math.abs(params.getScale() - 1) < 0.1);
}
public void test6() throws Exception {
boolean useBinned = false;
String filePath1 = ResourceFinder.findFileInTestResources("brown_lowe_2003_image1.jpg");
ImageExt img1 = ImageIOHelper.readImageExt(filePath1);
String filePath2 = ResourceFinder.findFileInTestResources("brown_lowe_2003_image2.jpg");
ImageExt img2 = ImageIOHelper.readImageExt(filePath2);
BlobPerimeterHelper bph1 = new BlobPerimeterHelper(img1, "1");
bph1.applySegmentation(SegmentationType.GREYSCALE_KMPP, useBinned);
BlobCornerHelper bch1 = new BlobCornerHelper(bph1, "1");
bch1.generatePerimeterCorners(SegmentationType.GREYSCALE_KMPP,
useBinned);
BlobPerimeterHelper bph2 = new BlobPerimeterHelper(img2, "2");
bph2.applySegmentation(SegmentationType.GREYSCALE_KMPP, useBinned);
BlobCornerHelper bch2 = new BlobCornerHelper(bph2, "2");
bch2.generatePerimeterCorners(SegmentationType.GREYSCALE_KMPP,
useBinned);
BlobCornersScaleFinder0 bsFinder = new BlobCornersScaleFinder0();
float[] outputScaleRotTransXYStDev = new float[4];
IntensityFeatures features1 = new IntensityFeatures(img1, 5, true);
IntensityFeatures features2 = new IntensityFeatures(img2, 5, true);
TransformationParameters params = bsFinder.solveForScale(
bch1, features1,
SegmentationType.GREYSCALE_KMPP, useBinned,
bch2, features2,
SegmentationType.GREYSCALE_KMPP, useBinned,
outputScaleRotTransXYStDev);
assertNotNull(params);
assertTrue(Math.abs(params.getScale() - 1) < 0.15);
}
public void test7() throws Exception {
boolean useBinned = false;
String filePath1 = ResourceFinder.findFileInTestResources("venturi_mountain_j6_0001.png");
ImageExt img1 = ImageIOHelper.readImageExt(filePath1);
String filePath2 = ResourceFinder.findFileInTestResources("venturi_mountain_j6_0010.png");
ImageExt img2 = ImageIOHelper.readImageExt(filePath2);
BlobPerimeterHelper bph1 = new BlobPerimeterHelper(img1, "venturi1");
bph1.applyEqualization();
bph1.applySegmentation(SegmentationType.COLOR_POLARCIEXY, useBinned);
BlobCornerHelper bch1 = new BlobCornerHelper(bph1, "venturi1");
bch1.generatePerimeterCorners(SegmentationType.COLOR_POLARCIEXY,
useBinned);
BlobPerimeterHelper bph2 = new BlobPerimeterHelper(img2, "venturi2");
bph2.applyEqualization();
bph2.applySegmentation(SegmentationType.COLOR_POLARCIEXY, useBinned);
BlobCornerHelper bch2 = new BlobCornerHelper(bph2, "venturi2");
bch2.generatePerimeterCorners(SegmentationType.COLOR_POLARCIEXY,
useBinned);
BlobCornersScaleFinder0 bsFinder = new BlobCornersScaleFinder0();
float[] outputScaleRotTransXYStDev = new float[4];
IntensityFeatures features1 = new IntensityFeatures(img1, 5, true);
IntensityFeatures features2 = new IntensityFeatures(img2, 5, true);
TransformationParameters params = bsFinder.solveForScale(
bch1, features1,
SegmentationType.COLOR_POLARCIEXY, useBinned,
bch2, features2,
SegmentationType.COLOR_POLARCIEXY, useBinned,
outputScaleRotTransXYStDev);
assertNotNull(params);
//log.info("params=" + params);
assertTrue(Math.abs(params.getScale() - 1) < 0.1);
}
public void test8() throws Exception {
boolean useBinned = false;
String filePath1 = ResourceFinder.findFileInTestResources("lena.jpg");
ImageExt img1 = ImageIOHelper.readImageExt(filePath1);
String filePath2 = ResourceFinder.findFileInTestResources("lena.jpg");
ImageExt img2 = ImageIOHelper.readImageExt(filePath2);
SegmentationType type = SegmentationType.COLOR_POLARCIEXY_LARGE;
BlobPerimeterHelper bph1 = new BlobPerimeterHelper(img1, "1");
bph1.applySegmentation(type, useBinned);
BlobCornerHelper bch1 = new BlobCornerHelper(bph1, "1");
bch1.generatePerimeterCorners(type, useBinned);
BlobPerimeterHelper bph2 = new BlobPerimeterHelper(img2, "2");
bph2.applySegmentation(type, useBinned);
BlobCornerHelper bch2 = new BlobCornerHelper(bph2, "2");
bch2.generatePerimeterCorners(type, useBinned);
BlobCornersScaleFinder0 bsFinder = new BlobCornersScaleFinder0();
float[] outputScaleRotTransXYStDev = new float[4];
IntensityFeatures features1 = new IntensityFeatures(img1, 5, true);
IntensityFeatures features2 = new IntensityFeatures(img2, 5, true);
TransformationParameters params = bsFinder.solveForScale(
bch1, features1, type, useBinned,
bch2, features2, type, useBinned,
outputScaleRotTransXYStDev);
assertNotNull(params);
assertTrue(Math.abs(params.getScale() - 1) < 0.1);
}
} |
package net.sf.jaer.eventprocessing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.ToolTipManager;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.sf.jaer.graphics.GlobalViewer;
import net.sf.jaer.util.EngineeringFormat;
/**
* A panel for a filter that has Integer/Float/Boolean/String/enum getter/setter
* methods (bound properties). These methods are introspected and a set of
* controls are built for them. Enclosed filters and filter chains have panels
* built for them that are enlosed inside the filter panel, hierarchically.
* <ul>
* <li>Numerical properties (ints, floats, but not currently doubles) construct
* a JTextBox control that also allows changes from mouse wheel or arrow keys.
* <li> boolean properties construct a JCheckBox control.
* <li> String properties construct a JTextField control.
* <li> enum properties construct a JComboBox control, which all the possible
* enum constant values.
* </ul>
* <p>
* If a filter wants to automatically have the GUI controls reflect what the
* property state is, then it should fire PropertyChangeEvent when the property
* changes. For example, an {@link EventFilter} can implement a setter like
* this:
* <pre>
* public void setMapEventsToLearnedTopologyEnabled(boolean mapEventsToLearnedTopologyEnabled) {
* support.firePropertyChange("mapEventsToLearnedTopologyEnabled", this.mapEventsToLearnedTopologyEnabled, mapEventsToLearnedTopologyEnabled); // property, old value, new value
* this.mapEventsToLearnedTopologyEnabled = mapEventsToLearnedTopologyEnabled;
* getPrefs().putBoolean("TopologyTracker.mapEventsToLearnedTopologyEnabled", mapEventsToLearnedTopologyEnabled);
* }
* </pre> Here, <code>support</code> is a protected field of EventFilter. The
* change event comes here to FilterPanel and the appropriate automatically
* generated control is modified.
* <p>
* Note that calling firePropertyChange as shown above will inform listeners
* <em>before</em> the property has actually been changed (this.dt has not been
* set yet).
* <p>
* A tooltip for the property can be installed using the EventFilter
* setPropertyTooltip method, for example
* <pre>
* setPropertyTooltip("sizeClassificationEnabled", "Enables coloring cluster by size threshold");
* </pre> will install a tip for the property sizeClassificationEnabled.
* <p>
* <strong>Slider controls.</strong>
*
* If you want a slider for an int or float property, then create getMin and
* getMax methods for the property, e.g., for the property <code>dt</code>:
* <pre>
* public int getDt() {
* return this.dt;
* }
*
* public void setDt(final int dt) {
* getPrefs().putInt("BackgroundActivityFilter.dt",dt);
* support.firePropertyChange("dt",this.dt,dt);
* this.dt = dt;
* }
*
* public int getMinDt(){
* return 10;
* }
*
* public int getMaxDt(){
* return 100000;
* }
* </pre>
* <strong>Button control</strong>
* <p>
* To add a button control to a panel, implement a method starting with "do",
* e.g.
* <pre>
* public void doSendParameters() {
* sendParameters();
* }
* </pre> This method will construct a button with label "SendParameters" which,
* when pressed, will call the method "doSendParameters".
* <p>
* <strong>
* Grouping parameters.</strong>
* <p>
* Properties are normally sorted alphabetically, with button controls at the
* top. If you want to group parameters, use the built in EventFilter method
* {@link net.sf.jaer.eventprocessing.EventFilter#addPropertyToGroup}. All
* properties of a given group are grouped together. Within a group the
* parameters are sorted alphabetically, and the groups will also be sorted
* alphabetically and shown before any ungrouped parameters. E.g., to Create
* groups "Sizing" and "Tracking" and add properties to each, do
* <pre>
* addPropertyToGroup("Sizing", "clusterSize");
* addPropertyToGroup("Sizing", "aspectRatio");
* addPropertyToGroup("Sizing", "highwayPerspectiveEnabled");
* addPropertyToGroup("Tracking", "mixingFactor");
* addPropertyToGroup("Tracking", "velocityMixingFactor");
* </pre> Or, even simpler, if you have already defined tooltips for your
* properties, then you can use the overloaded
* {@link net.sf.jaer.eventprocessing.EventFilter#setPropertyTooltip(java.lang.String, java.lang.String, java.lang.String) setPropertyTooltip}
* of {@link net.sf.jaer.eventprocessing.EventFilter}, as shown next. Here two
* groups "Size" and "Timing" are defined and properties are added to each (or
* to neither for "multiOriOutputEnabled").
* <pre>
* final String size="Size", tim="Timing";
*
* setPropertyTooltip(disp,"showGlobalEnabled", "shows line of average orientation");
* setPropertyTooltip(tim,"minDtThreshold", "Coincidence time, events that pass this coincidence test are considerd for orientation output");
* setPropertyTooltip(tim,"dtRejectMultiplier", "reject delta times more than this factor times minDtThreshold to reduce noise");
* setPropertyTooltip(tim,"dtRejectThreshold", "reject delta times more than this time in us to reduce effect of very old events");
* setPropertyTooltip("multiOriOutputEnabled", "Enables multiple event output for all events that pass test");
* </pre>
*
*
* @author tobi
* @see
* net.sf.jaer.eventprocessing.EventFilter#setPropertyTooltip(java.lang.String,
* java.lang.String)
* @see
* net.sf.jaer.eventprocessing.EventFilter#setPropertyTooltip(java.lang.String,
* java.lang.String, java.lang.String)
* @see net.sf.jaer.eventprocessing.EventFilter
*/
public class FilterPanel extends javax.swing.JPanel implements PropertyChangeListener {
private interface HasSetter {
void set(Object o);
}
static final float ALIGNMENT = Component.LEFT_ALIGNMENT;
private BeanInfo info;
private PropertyDescriptor[] props;
private Method[] methods;
private static Logger log = Logger.getLogger("Filters");
private EventFilter filter = null;
final float fontSize = 10f;
private Border normalBorder, redLineBorder;
private TitledBorder titledBorder;
private HashMap<String, HasSetter> setterMap = new HashMap<String, HasSetter>(); // map from filter to property, to apply property change events to control
protected java.util.ArrayList<JComponent> controls = new ArrayList<JComponent>();
private HashMap<String, Container> groupContainerMap = new HashMap();
private JPanel inheritedPanel = null;
private float DEFAULT_REAL_VALUE = 0.01f; // value jumped to from zero on key or wheel up
/**
* Creates new form FilterPanel
*/
public FilterPanel() {
initComponents();
}
public FilterPanel(EventFilter f) {
// log.info("building FilterPanel for "+f);
this.setFilter(f);
initComponents();
String cn = getFilter().getClass().getName();
int lastdot = cn.lastIndexOf('.');
String name = cn.substring(lastdot + 1);
setName(name);
titledBorder = new TitledBorder(name);
titledBorder.getBorderInsets(this).set(1, 1, 1, 1);
setBorder(titledBorder);
normalBorder = titledBorder.getBorder();
redLineBorder = BorderFactory.createLineBorder(Color.red);
enabledCheckBox.setSelected(getFilter().isFilterEnabled());
addIntrospectedControls();
// when filter fires a property change event, we getString called here and we update all our controls
getFilter().getSupport().addPropertyChangeListener(this);
// // add ourselves to listen for all enclosed filter property changes as well
// EventFilter enclosed = getFilter().getEnclosedFilter();
// while (enclosed != null) {
// enclosed.getSupport().addPropertyChangeListener(this);
// enclosed = enclosed.getEnclosedFilter();
// FilterChain chain = getFilter().getEnclosedFilterChain();
// if (chain != null) {
// for (EventFilter f2 : chain) {
// EventFilter f3=f2;
// while (f3 != null) {
// f3.getSupport().addPropertyChangeListener(this);
// f3 = f3.getEnclosedFilter(); // for some very baroque arrangement
ToolTipManager.sharedInstance().setDismissDelay(10000); // to show tips
setToolTipText(f.getDescription());
helpBut.setToolTipText("<html>" + f.getDescription() + "<p>Click to show/create wiki page");
}
// checks for group container and adds to that if needed.
private void myadd(JComponent comp, String propertyName, boolean inherited) {
JPanel pan = new JPanel();
pan.setLayout(new BoxLayout(pan, BoxLayout.X_AXIS));
controls.add(pan);
if (!getFilter().hasPropertyGroups()) {
pan.add(comp);
// if(inherited){
// pan.setBorder(BorderFactory.createLineBorder(Color.yellow) );
pan.add(Box.createVerticalStrut(0));
add(pan);
controls.add(comp);
return;
}
String groupName = getFilter().getPropertyGroup(propertyName);
if (groupName != null) {
Container container = groupContainerMap.get(groupName);
comp.setAlignmentX(Component.LEFT_ALIGNMENT);
// if(inherited){
// JPanel inherPan=new JPanel();
// inherPan.setBorder(BorderFactory.createLineBorder(Color.yellow) );
// inherPan.add(comp,BorderLayout.WEST);
// container.add(inherPan);
// }else{
container.add(comp);
} else {
// add(Box.createHorizontalGlue());
comp.setAlignmentX(Component.LEFT_ALIGNMENT);
pan.add(comp);
pan.add(Box.createVerticalStrut(0));
}
add(pan); // to fix horizontal all left alignment
controls.add(comp);
}
// gets getter/setter methods for the filter and makes controls for them. enclosed filters are also added as submenus
private void addIntrospectedControls() {
JPanel control = null;
EventFilter filter = getFilter();
try {
info = Introspector.getBeanInfo(filter.getClass());
// TODO check if class is public, otherwise we can't access methods usually
props = info.getPropertyDescriptors();
methods = filter.getClass().getMethods();
control = new JPanel();
int numDoButtons = 0;
// first add buttons when the method name starts with "do". These methods are by convention associated with actions.
// these methods, e.g. "void doDisableServo()" do an action.
// also, a pair of methods doPressXXX and doReleaseXXX will add a button that calls the first method on press and the 2nd on release
Insets butInsets = new Insets(0, 0, 0, 0);
ArrayList<JButton> doButList = new ArrayList();
for (Method method : methods) {
// add a button XXX that calls doPressXXX on press and doReleaseXXX on release of button
if (method.getName().startsWith("doPress")
&& (method.getParameterTypes().length == 0)
&& (method.getReturnType() == void.class)) {
for (Method releasedMethod : methods) {
String suf = method.getName().substring(7);
if (releasedMethod.getName().equals("doRelease" + suf)
&& (releasedMethod.getParameterTypes().length == 0)
&& (releasedMethod.getReturnType() == void.class)) {
//found corresponding release method, add action listeners for press and release
numDoButtons++;
JButton button = new JButton(method.getName().substring(7));
button.setMargin(butInsets);
button.setFont(button.getFont().deriveFont(9f));
final EventFilter f = filter;
final Method pressedMethodFinal = method;
final Method releasedMethodFinal = releasedMethod;
button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
try {
pressedMethodFinal.invoke(f);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
@Override
public void mouseReleased(MouseEvent e) {
try {
releasedMethodFinal.invoke(f);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
});
addTip(f, button);
doButList.add(button);
break; // don't bother with rest of methods
}
}
}
// add a button that calls a method XXX for method void doXXX()
if (method.getName().startsWith("do") && !method.getName().startsWith("doPress") && !method.getName().startsWith("doRelease")
&& (method.getParameterTypes().length == 0)
&& (method.getReturnType() == void.class)) {
numDoButtons++;
JButton button = new JButton(method.getName().substring(2));
button.setMargin(butInsets);
button.setFont(button.getFont().deriveFont(9f));
final EventFilter f = filter;
final Method meth = method;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
meth.invoke(f);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
});
addTip(f, button);
doButList.add(button);
}
}
Comparator<AbstractButton> butComp = new Comparator<AbstractButton>() {
@Override
public int compare(AbstractButton o1, AbstractButton o2) {
if (o1 == null || o2 == null || o1.getText() == null || o2.getText() == null) {
return 0;
}
return o1.getText().compareToIgnoreCase(o2.getText());
}
};
Collections.sort(doButList, butComp);
for (AbstractButton b : doButList) {
control.add(b);
}
//if at least one button then we show the actions panel
if (control.getComponentCount() > 0) {
TitledBorder tb = new TitledBorder("Filter Actions");
tb.getBorderInsets(this).set(1, 1, 1, 1);
control.setBorder(tb);
control.setMinimumSize(new Dimension(0, 0));
add(control);
controls.add(control);
}
if (numDoButtons > 3) {
control.setLayout(new GridLayout(0, 3, 3, 3));
}
// next add enclosed Filter and enclosed FilterChain so they appear at top of list (they are processed first)
for (PropertyDescriptor p : props) {
Class c = p.getPropertyType();
if (p.getName().equals("enclosedFilter")) { //if(c==EventFilter2D.class){
// if type of property is an EventFilter, check if it has either an enclosed filter
// or an enclosed filter chain. If so, construct FilterPanels for each of them.
try {
Method r = p.getReadMethod(); // getString the getter for the enclosed filter
EventFilter2D enclFilter = (EventFilter2D) (r.invoke(getFilter()));
if (enclFilter != null) {
// log.info("EventFilter "+filter.getClass().getSimpleName()+" encloses EventFilter2D "+enclFilter.getClass().getSimpleName());
FilterPanel enclPanel = new FilterPanel(enclFilter);
this.add(enclPanel);
controls.add(enclPanel);
((TitledBorder) enclPanel.getBorder()).setTitle("enclosed: " + enclFilter.getClass().getSimpleName());
}
// FilterChain chain=getFilter().getEnclosedFilterChain();
// if(chain!=null){
// log.info("EventFilter "+filter.getClass().getSimpleName()+" encloses filterChain "+chain);
// for(EventFilter f:chain){
// FilterPanel enclPanel=new FilterPanel(f);
// this.add(enclPanel);
// controls.add(enclPanel);
// ((TitledBorder)enclPanel.getBorder()).setTitle("enclosed: "+f.getClass().getSimpleName());
} catch (Exception e) {
e.printStackTrace();
}
} else if (p.getName().equals("enclosedFilterChain")) {
// if type of property is a FilterChain, check if it has either an enclosed filter
// or an enclosed filter chain. If so, construct FilterPanels for each of them.
try {
Method r = p.getReadMethod(); // getString the getter for the enclosed filter chain
FilterChain chain = (FilterChain) (r.invoke(getFilter()));
if (chain != null) {
// log.info("EventFilter "+filter.getClass().getSimpleName()+" encloses filterChain "+chain);
for (EventFilter f : chain) {
FilterPanel enclPanel = new FilterPanel(f);
this.add(enclPanel);
controls.add(enclPanel);
((TitledBorder) enclPanel.getBorder()).setTitle("enclosed: " + f.getClass().getSimpleName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
String name = p.getName();
if (control != null) {
control.setToolTipText(getFilter().getPropertyTooltip(name));
}
}
}
// next add all other properties that we can handle
// these must be saved and then sorted in case there are property groups defined.
if (getFilter().hasPropertyGroups()) {
Set<String> groupSet = getFilter().getPropertyGroupSet();
ArrayList<String> setList = new ArrayList();
setList.addAll(groupSet);
Collections.sort(setList);
for (String s : setList) {
JPanel groupPanel = new JPanel();
groupPanel.setName(s);
groupPanel.setBorder(new TitledBorder(s));
groupPanel.setLayout(new GridLayout(0, 1));
groupContainerMap.put(s, groupPanel);
add(groupPanel);
controls.add(groupPanel); // visibility list
}
}
// ArrayList<Component> sortedControls=new ArrayList();
for (PropertyDescriptor p : props) {
// System.out.println("filter "+getFilter().getClass().getSimpleName()+" has property name="+p.getName()+" type="+p.getPropertyType());
// if(false){
//// System.out.println("prop "+p);
//// System.out.println("prop name="+p.getName());
//// System.out.println("prop write method="+p.getWriteMethod());
//// System.out.println("prop read method="+p.getReadMethod());
//// System.out.println("type "+p.getPropertyType());
//// System.out.println("bound: "+p.isBound());
//// System.out.println("");
try {
boolean inherited = false;
// TODO handle indexed properties
Class c = p.getPropertyType();
String name = p.getName();
// check if method comes from a superclass of this EventFilter
if ((control != null) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
Method m = p.getReadMethod();
if (m.getDeclaringClass() != getFilter().getClass()) {
inherited = true;
}
}
if ((c == Integer.TYPE) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
SliderParams params;
if ((params = isSliderType(p, filter)) != null) {
control = new IntSliderControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod(), params);
} else {
control = new IntControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
}
myadd(control, name, inherited);
} else if ((c == Float.TYPE) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
SliderParams params;
if ((params = isSliderType(p, filter)) != null) {
control = new FloatSliderControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod(), params);
} else {
control = new FloatControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
}
myadd(control, name, inherited);
} else if ((c == Boolean.TYPE) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
if (p.getName().equals("filterEnabled")) { // built in, skip
continue;
}
if (p.getName().equals("annotationEnabled")) {// built in, skip
continue;
}
if (p.getName().equals("selected")) {// built in, skip
continue;
}
control = new BooleanControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
myadd(control, name, inherited);
} else if ((c == String.class) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
if (p.getName().equals("filterEnabled")) {
continue;
}
if (p.getName().equals("annotationEnabled")) {
continue;
}
control = new StringControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
myadd(control, name, inherited);
} else if ((c != null) && c.isEnum() && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
control = new EnumControl(c, getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
myadd(control, name, inherited);
} else if ((c != null) && (c == Point2D.Float.class || c == Point2D.Double.class || c == Point2D.class) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
control = new Point2DControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
myadd(control, name, inherited);
} else {
// log.warning("unknown property type "+p.getPropertyType()+" for property "+p.getName());
}
if (control != null) {
control.setToolTipText(getFilter().getPropertyTooltip(name));
}
} catch (Exception e) {
log.warning(e + " caught on property " + p.getName() + " from EventFilter " + filter);
}
}
groupContainerMap = null;
// sortedControls=null;
} catch (Exception e) {
log.warning("on adding controls for EventFilter " + filter + " caught " + e);
e.printStackTrace();
}
add(Box.createHorizontalGlue());
setControlsVisible(
false);
// System.out.println("added glue to "+this);
}
void addTip(EventFilter f, JLabel label) {
String s = f.getPropertyTooltip(label.getText());
if (s == null) {
return;
}
label.setToolTipText(s);
label.setForeground(Color.BLUE);
}
void addTip(EventFilter f, JButton b) {
String s = f.getPropertyTooltip(b.getText());
if (s == null) {
return;
}
b.setToolTipText(s);
b.setForeground(Color.BLUE);
}
void addTip(EventFilter f, JCheckBox label) {
String s = f.getPropertyTooltip(label.getText());
if (s == null) {
return;
}
label.setToolTipText(s);
label.setForeground(Color.BLUE);
}
class EnumControl extends JPanel implements HasSetter {
Method write, read;
EventFilter filter;
boolean initValue = false, nval;
final JComboBox control;
@Override
public void set(Object o) {
control.setSelectedItem(o);
}
public EnumControl(final Class<? extends Enum> c, final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(ALIGNMENT);
final JLabel label = new JLabel(name);
label.setAlignmentX(ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
control = new JComboBox(c.getEnumConstants());
control.setFont(control.getFont().deriveFont(fontSize));
// control.setHorizontalAlignment(SwingConstants.LEADING);
add(label);
add(control);
try {
Object x = r.invoke(filter);
if (x == null) {
log.warning("null Object returned from read method " + r);
return;
}
control.setSelectedItem(x);
} catch (Exception e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
control.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
w.invoke(filter, control.getSelectedItem());
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
}
}
class StringControl extends JPanel implements HasSetter {
Method write, read;
EventFilter filter;
boolean initValue = false, nval;
final JTextField textField;
@Override
public void set(Object o) {
if (o instanceof String) {
String b = (String) o;
textField.setText(b);
}
}
public StringControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(ALIGNMENT);
final JLabel label = new JLabel(name);
label.setAlignmentX(ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
textField = new JTextField(name);
textField.setFont(textField.getFont().deriveFont(fontSize));
textField.setHorizontalAlignment(SwingConstants.LEADING);
textField.setColumns(10);
add(label);
add(textField);
try {
String x = (String) r.invoke(filter);
if (x == null) {
log.warning("null String returned from read method " + r);
return;
}
textField.setText(x);
textField.setToolTipText(x);
} catch (Exception e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
w.invoke(filter, textField.getText());
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
}
}
final float factor = 1.51f, wheelFactor = 1.05f; // factors to change by with arrow and mouse wheel
class BooleanControl extends JPanel implements HasSetter {
Method write, read;
EventFilter filter;
boolean initValue = false, nval;
final JCheckBox checkBox;
public BooleanControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(ALIGNMENT);
// setLayout(new FlowLayout(FlowLayout.LEADING));
checkBox = new JCheckBox(name);
checkBox.setAlignmentX(ALIGNMENT);
checkBox.setFont(checkBox.getFont().deriveFont(fontSize));
checkBox.setHorizontalTextPosition(SwingConstants.LEFT);
addTip(f, checkBox);
add(checkBox);
try {
Boolean x = (Boolean) r.invoke(filter);
if (x == null) {
log.warning("null Boolean returned from read method " + r);
return;
}
initValue = x.booleanValue();
checkBox.setSelected(initValue);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
checkBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
w.invoke(filter, checkBox.isSelected());
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
}
@Override
public void set(Object o) {
if (o instanceof Boolean) {
Boolean b = (Boolean) o;
checkBox.setSelected(b);
}
}
}
class IntSliderControl extends JPanel implements HasSetter {
Method write, read;
EventFilter filter;
int initValue = 0, nval;
JSlider slider;
JTextField tf;
private boolean sliderDontProcess = false;
@Override
public void set(Object o) {
if (o instanceof Integer) {
Integer b = (Integer) o;
slider.setValue(b);
}
}
public IntSliderControl(final EventFilter f, final String name, final Method w, final Method r, SliderParams params) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(ALIGNMENT);
final IntControl ic = new IntControl(f, name, w, r);
tf = ic.tf;
add(ic);
slider = new JSlider(params.minIntValue, params.maxIntValue);
slider.setMaximumSize(new Dimension(200, 50));
try {
Integer x = (Integer) r.invoke(filter); // read int value
if (x == null) {
log.warning("null Integer returned from read method " + r);
return;
}
initValue = x.intValue();
slider.setValue(initValue);
} catch (Exception e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
add(slider);
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (sliderDontProcess) {
return;
}
try {
w.invoke(filter, new Integer(slider.getValue())); // write int value
ic.set(slider.getValue());
// tf.setText(Integer.toString(slider.getValue()));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
ic.addPropertyChangeListener(ic.PROPERTY_VALUE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
if (pce.getNewValue() == null || !(pce.getNewValue() instanceof Integer)) {
return;
}
sliderDontProcess = true;
slider.setValue((Integer) (pce.getNewValue()));
sliderDontProcess = false;
}
});
}
}
class FloatSliderControl extends JPanel implements HasSetter {
Method write, read;
EventFilter filter;
JSlider slider;
JTextField tf;
EngineeringFormat engFmt;
FloatControl fc;
boolean dontProcessEvent = false; // to avoid slider callback loops
float minValue, maxValue, currentValue;
@Override
public void set(Object o) {
if (o instanceof Integer) {
Integer b = (Integer) o;
slider.setValue(b);
fc.set(b);
} else if (o instanceof Float) {
float f = (Float) o;
int sv = Math.round(((f - minValue) / (maxValue - minValue)) * (slider.getMaximum() - slider.getMinimum()));
slider.setValue(sv);
}
}
public FloatSliderControl(final EventFilter f, final String name, final Method w, final Method r, SliderParams params) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(ALIGNMENT);
fc = new FloatControl(f, name, w, r);
add(fc);
minValue = params.minFloatValue;
maxValue = params.maxFloatValue;
slider = new JSlider();
slider.setMaximumSize(new Dimension(200, 50));
engFmt = new EngineeringFormat();
try {
Float x = (Float) r.invoke(filter); // read int value
if (x == null) {
log.warning("null Float returned from read method " + r);
return;
}
currentValue = x.floatValue();
set(new Float(currentValue));
} catch (Exception e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
add(slider);
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
try {
int v = slider.getValue();
currentValue = minValue + ((maxValue - minValue) * ((float) slider.getValue() / (slider.getMaximum() - slider.getMinimum())));
w.invoke(filter, new Float(currentValue)); // write int value
fc.set(new Float(currentValue));
// tf.setText(engFmt.format(currentValue));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
}
}
class IntControl extends JPanel implements HasSetter {
Method write, read;
EventFilter filter;
int initValue = 0, nval;
final JTextField tf;
String PROPERTY_VALUE = "value";
@Override
public void set(Object o) {
if (o instanceof Integer) {
Integer b = (Integer) o;
tf.setText(b.toString());
}
}
public IntControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(ALIGNMENT);
// setLayout(new FlowLayout(FlowLayout.LEADING));
JLabel label = new JLabel(name);
label.setAlignmentX(ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
tf = new JTextField("", 8);
tf.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);
// otherwise TAB will just pass over field without entering a new value
tf.setMaximumSize(new Dimension(100, 50));
tf.setToolTipText("Integer control: use arrow keys or mouse wheel to change value by factor. Shift constrains to simple inc/dec");
try {
Integer x = (Integer) r.invoke(filter); // read int value
if (x == null) {
log.warning("null Integer returned from read method " + r);
return;
}
initValue = x.intValue();
String s = NumberFormat.getIntegerInstance().format(initValue);
// System.out.println("init value of "+name+" is "+s);
tf.setText(s);
fixIntValue(tf, r);
} catch (Exception e) {
e.printStackTrace();
}
add(tf);
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Integer newValue = null;
try {
NumberFormat format = NumberFormat.getNumberInstance();
Integer oldValue = null;
try {
oldValue = (Integer) r.invoke(filter);
} catch (Exception re) {
log.warning("could not read original value: " + re.toString());
}
int y = format.parse(tf.getText()).intValue();
newValue = new Integer(y);
w.invoke(filter, newValue); // write int value
firePropertyChange(PROPERTY_VALUE, oldValue, newValue);
} catch (ParseException pe) {
//Handle exception
} catch (NumberFormatException fe) {
tf.selectAll();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
tf.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
Integer newValue = null;
Integer oldValue = null;
try {
oldValue = (Integer) r.invoke(filter);
initValue = oldValue.intValue();
// System.out.println("x="+x);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int code = evt.getKeyCode();
int mod = evt.getModifiers();
boolean shift = evt.isShiftDown();
if (!shift) {
if (code == KeyEvent.VK_UP) {
try {
nval = initValue;
if (nval == 0) {
nval = 1;
} else {
nval = Math.round(initValue * factor);
}
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code == KeyEvent.VK_DOWN) {
try {
nval = initValue;
if (nval == 0) {
nval = 0;
} else {
nval = Math.round(initValue / factor);
}
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
} else // shifted int control just incs or decs by 1
{
if (code == KeyEvent.VK_UP) {
try {
nval = initValue + 1;
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code == KeyEvent.VK_DOWN) {
try {
nval = initValue - 1;
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
if (evt.getKeyCode() == evt.VK_TAB) {
try {
NumberFormat format = NumberFormat.getNumberInstance();
int y = format.parse(tf.getText()).intValue();
w.invoke(filter, newValue = new Integer(y)); // write int value
fixIntValue(tf, r);
} catch (ParseException pe) {
//Handle exception
} catch (NumberFormatException fe) {
tf.selectAll();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.focusNextComponent();
}
firePropertyChange(PROPERTY_VALUE, oldValue, newValue);
}
}
);
tf.addMouseWheelListener(
new java.awt.event.MouseWheelListener() {
@Override
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt
) {
Integer oldValue = null, newValue = null;
try {
oldValue = (Integer) r.invoke(filter);
initValue = oldValue.intValue();
// System.out.println("x="+x);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int code = evt.getWheelRotation();
int mod = evt.getModifiers();
boolean shift = evt.isShiftDown();
if (!shift) {
if (code < 0) {
try {
nval = initValue;
if (Math.round(initValue * wheelFactor) == initValue) {
nval++;
} else {
nval = Math.round(initValue * wheelFactor);
}
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code > 0) {
try {
nval = initValue;
if (Math.round(initValue / wheelFactor) == initValue) {
nval
} else {
nval = Math.round(initValue / wheelFactor);
}
if (nval < 0) {
nval = 0;
}
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
firePropertyChange(PROPERTY_VALUE, oldValue, newValue);
}
}
);
tf.addFocusListener(
new FocusListener() {
@Override
public void focusGained(FocusEvent e
) {
tf.setSelectionStart(0);
tf.setSelectionEnd(tf.getText().length());
}
@Override
public void focusLost(FocusEvent e
) {
}
}
);
}
}
void fixIntValue(JTextField tf, Method r) {
// set text to actual value
try {
Integer x = (Integer) r.invoke(getFilter()); // read int value
// initValue=x.intValue();
String s = NumberFormat.getIntegerInstance().format(x);
tf.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
class FloatControl extends JPanel implements HasSetter {
EngineeringFormat engFmt = new EngineeringFormat();
// final String format="%.6f";
Method write, read;
EventFilter filter;
float initValue = 0, nval;
final JTextField tf;
@Override
public void set(Object o) {
if (o instanceof Float) {
Float b = (Float) o;
tf.setText(b.toString());
}
}
public FloatControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(ALIGNMENT);
// setLayout(new FlowLayout(FlowLayout.LEADING));
JLabel label = new JLabel(name);
label.setAlignmentX(ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
tf = new JTextField("", 10);
tf.setMaximumSize(new Dimension(100, 50));
tf.setToolTipText("Float control: use arrow keys or mouse wheel to change value by factor. Shift reduces factor.");
try {
Float x = (Float) r.invoke(filter);
if (x == null) {
log.warning("null Float returned from read method " + r);
return;
}
initValue = x.floatValue();
tf.setText(engFmt.format(initValue));
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
add(tf);
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println(e);
try {
float y = engFmt.parseFloat(tf.getText());
w.invoke(filter, new Float(y));
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (NumberFormatException fe) {
tf.selectAll();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
tf.addKeyListener(new java.awt.event.KeyAdapter() {
{
}
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
try {
Float x = (Float) r.invoke(filter); // getString the value from the getter method
initValue = x.floatValue();
// System.out.println("x="+x);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int code = evt.getKeyCode();
int mod = evt.getModifiers();
boolean shift = evt.isShiftDown();
float floatFactor = factor;
if (shift) {
floatFactor = wheelFactor;
}
if (code == KeyEvent.VK_UP) {
try {
nval = initValue;
if (nval == 0) {
nval = DEFAULT_REAL_VALUE;
} else {
nval = (initValue * floatFactor);
}
w.invoke(filter, new Float(nval)); // setter the value
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code == KeyEvent.VK_DOWN) {
try {
nval = initValue;
if (nval == 0) {
nval = DEFAULT_REAL_VALUE;
} else {
nval = (initValue / floatFactor);
}
w.invoke(filter, new Float(initValue / floatFactor));
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
});
tf.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
@Override
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
try {
Float x = (Float) r.invoke(filter); // getString the value from the getter method
initValue = x.floatValue();
// System.out.println("x="+x);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int code = evt.getWheelRotation();
int mod = evt.getModifiers();
boolean shift = evt.isShiftDown();
if (!shift) {
if (code < 0) {
try {
nval = initValue;
if (nval == 0) {
nval = DEFAULT_REAL_VALUE;
} else {
nval = (initValue * wheelFactor);
}
w.invoke(filter, new Float(nval)); // setter the value
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code > 0) {
try {
nval = initValue;
if (nval == 0) {
nval = DEFAULT_REAL_VALUE;
} else {
nval = (initValue / wheelFactor);
}
w.invoke(filter, new Float(initValue / wheelFactor));
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
}
});
tf.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
tf.setSelectionStart(0);
tf.setSelectionEnd(tf.getText().length());
}
@Override
public void focusLost(FocusEvent e) {
}
});
}
}
private boolean printedSetterWarning = false;
/**
* Called when a filter calls firePropertyChange. The PropertyChangeEvent
* should send the bound property name and the old and new values. The GUI
* control is then updated by this method.
*
* @param propertyChangeEvent contains the property that has changed, e.g.
* it would be called from an EventFilter with
* <code>support.firePropertyChange("mapEventsToLearnedTopologyEnabled", mapEventsToLearnedTopologyEnabled, this.mapEventsToLearnedTopologyEnabled);</code>
*/
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
if (propertyChangeEvent.getSource() == getFilter()) {
if (propertyChangeEvent.getPropertyName().equals("selected")) {
return; // ignore changes to "selected" for filter because these are masked out from GUI building
} else if (propertyChangeEvent.getPropertyName().equals("filterEnabled")) { // comes from EventFilter when filter is enabled or disabled
// log.info("propertyChangeEvent name="+propertyChangeEvent.getPropertyName()+" src="+propertyChangeEvent.getSource()+" oldValue="+propertyChangeEvent.getOldValue()+" newValue="+propertyChangeEvent.getNewValue());
boolean yes = (Boolean) propertyChangeEvent.getNewValue();
enabledCheckBox.setSelected(yes);
setBorderActive(yes);
} else {
// we need to find the control and set it appropriately. we don't need to set the property itself since this has already been done!
try {
// log.info("PropertyChangeEvent received from " +
// propertyChangeEvent.getSource() + " for property=" +
// propertyChangeEvent.getPropertyName() +
// " newValue=" + propertyChangeEvent.getNewValue());
HasSetter setter = setterMap.get(propertyChangeEvent.getPropertyName());
if (setter == null) {
if (!printedSetterWarning) {
log.warning("in filter " + getFilter() + " there is no setter for property change from property named " + propertyChangeEvent.getPropertyName());
printedSetterWarning = true;
}
} else {
setter.set(propertyChangeEvent.getNewValue());
}
// PropertyDescriptor pd=new PropertyDescriptor(propertyChangeEvent.getPropertyName(), getFilter().getClass());
// Method wm=pd.getWriteMethod();
// wm.invoke(getFilter(), propertyChangeEvent.getNewValue());
} catch (Exception e) {
log.warning(e.toString());
}
// try{
// log.info("PropertyChangeEvent received for property="+propertyChangeEvent.getPropertyName()+" newValue="+propertyChangeEvent.getNewValue());
// PropertyDescriptor pd=new PropertyDescriptor(propertyChangeEvent.getPropertyName(), getFilter().getClass());
// Method wm=pd.getWriteMethod();
// wm.invoke(getFilter(), propertyChangeEvent.getNewValue());
// }catch(Exception e){
// log.warning(e.toString());
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
jPanel1 = new javax.swing.JPanel();
enabledCheckBox = new javax.swing.JCheckBox();
resetButton = new javax.swing.JButton();
showControlsToggleButton = new javax.swing.JToggleButton();
helpBut = new javax.swing.JButton();
setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.Y_AXIS));
jPanel1.setAlignmentX(1.0F);
jPanel1.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 2));
enabledCheckBox.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
enabledCheckBox.setToolTipText("Enable or disable the filter");
enabledCheckBox.setMargin(new java.awt.Insets(1, 1, 1, 1));
enabledCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enabledCheckBoxActionPerformed(evt);
}
});
jPanel1.add(enabledCheckBox);
resetButton.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
resetButton.setText("Reset");
resetButton.setToolTipText("Resets the filter");
resetButton.setMargin(new java.awt.Insets(1, 5, 1, 5));
resetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetButtonActionPerformed(evt);
}
});
jPanel1.add(resetButton);
showControlsToggleButton.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
showControlsToggleButton.setText("Controls");
showControlsToggleButton.setToolTipText("Show filter parameters, hides other filters. Click again to see all filters.");
showControlsToggleButton.setMargin(new java.awt.Insets(1, 5, 1, 5));
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${controlsVisible}"), showControlsToggleButton, org.jdesktop.beansbinding.BeanProperty.create("selected"));
bindingGroup.addBinding(binding);
jPanel1.add(showControlsToggleButton);
helpBut.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
helpBut.setText("?");
helpBut.setToolTipText("Shows help on jAER wiki");
helpBut.setMargin(new java.awt.Insets(1, 5, 1, 5));
helpBut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
helpButActionPerformed(evt);
}
});
jPanel1.add(helpBut);
add(jPanel1);
bindingGroup.bind();
}// </editor-fold>//GEN-END:initComponents
boolean controlsVisible = false;
public boolean isControlsVisible() {
return controlsVisible;
}
/**
* Set visibility of individual filter controls; hides other filters.
*
* @param visible true to show filter parameter controls, false to hide this
* filter's controls and to show all filters in chain.
*/
public void setControlsVisible(boolean visible) {
controlsVisible = visible;
getFilter().setSelected(visible); // exposing controls 'selects' this filter
setBorderActive(visible);
for (JComponent p : controls) {
p.setVisible(visible);
p.invalidate();
}
boolean globalEnable = false; // For compatibility with new version
invalidate();
Container c = getTopLevelAncestor();
if (c == null) {
return;
} else if (c instanceof GlobalViewer) // Added for compatibility with multi-input mode
{
c = ((GlobalViewer) c).getFilterPane();
globalEnable = true;
}
// TODO fix bug here with enclosed filters not showing up if they are enclosed in enclosed filter, unless they are declared as enclosed
if (!getFilter().isEnclosed() && ((c instanceof Window) || globalEnable)) {
if (c instanceof FilterFrame) {
// hide all filters except one that is being modified, *unless* we are an enclosed filter
FilterFrame<FilterPanel> ff = (FilterFrame) c;
for (FilterPanel f : ff.filterPanels) {
if (f == this) { // for us and if !visible
f.setVisible(true); // always set us visible in chain since we are the one being touched
continue;
}
f.setVisible(!visible); // hide / show other filters
}
}
// if (c instanceof Window) // Redundant
// ((Window) c).pack();
}
if (controlPanel != null) {
controlPanel.setVisible(visible);
}
if (c instanceof Window) {
((Window) c).pack();
}
if (!getFilter().isEnclosed()) { // store last selected top level filter
if (visible) {
getFilter().getChip().getPrefs().put(FilterFrame.LAST_FILTER_SELECTED_KEY, getFilter().getClass().toString());
} else {
getFilter().getChip().getPrefs().put(FilterFrame.LAST_FILTER_SELECTED_KEY, "");
}
}
if (visible) {
// Show only controls.
showControlsToggleButton.setSelected(true);
showControlsToggleButton.setText("Back to filters list");
} else {
showControlsToggleButton.setSelected(false);
showControlsToggleButton.setText("Controls");
}
}
private void setBorderActive(final boolean yes) {
if (yes) {
((TitledBorder) getBorder()).setTitleColor(SystemColor.textText);
titledBorder.setBorder(redLineBorder);
} else {
((TitledBorder) getBorder()).setTitleColor(SystemColor.textInactiveText);
titledBorder.setBorder(normalBorder);
}
}
void toggleControlsVisible() {
controlsVisible = !controlsVisible;
setControlsVisible(controlsVisible);
}
public EventFilter getFilter() {
return filter;
}
public void setFilter(EventFilter filter) {
this.filter = filter;
}
private void enabledCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enabledCheckBoxActionPerformed
boolean yes = enabledCheckBox.isSelected();
if (getFilter() != null) {
getFilter().setFilterEnabled(yes);
}
if (yes) {
((TitledBorder) getBorder()).setTitleColor(SystemColor.textText);
titledBorder.setBorder(redLineBorder);
} else {
((TitledBorder) getBorder()).setTitleColor(SystemColor.textInactiveText);
titledBorder.setBorder(normalBorder);
}
repaint();
getFilter().setSelected(yes);
}//GEN-LAST:event_enabledCheckBoxActionPerformed
private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
if (getFilter() != null) {
getFilter().resetFilter();
}
getFilter().setSelected(true);
}//GEN-LAST:event_resetButtonActionPerformed
private void helpButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpButActionPerformed
if (getFilter() != null) {
getFilter().showHelpInBrowser();
}
}//GEN-LAST:event_helpButActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
protected javax.swing.JCheckBox enabledCheckBox;
private javax.swing.JButton helpBut;
protected javax.swing.JPanel jPanel1;
private javax.swing.JButton resetButton;
private javax.swing.JToggleButton showControlsToggleButton;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
private class SliderParams {
Class paramClass = null;
int minIntValue, maxIntValue;
float minFloatValue, maxFloatValue;
SliderParams(Class clazz, int minIntValue, int maxIntValue, float minFloatValue, float maxFloatValue) {
this.minIntValue = minIntValue;
this.minFloatValue = minFloatValue;
this.maxIntValue = maxIntValue;
this.maxFloatValue = maxFloatValue;
}
}
private SliderParams isSliderType(PropertyDescriptor p, net.sf.jaer.eventprocessing.EventFilter filter) throws SecurityException {
// if(c instanceof Class) System.out.println("filter="+filter+" propertyType="+c);
//TODO add slider control type if property has getMin and getMax methods
boolean isSliderType = false;
// check for min/max methods for property, e.g. getMinDt, getMaxDt for property dt
String propCapped = p.getName().substring(0, 1).toUpperCase() + p.getName().substring(1); // eg. Dt for dt
String minMethName = "getMin" + propCapped;
String maxMethName = "getMax" + propCapped;
SliderParams params = null;
try {
Method minMethod = filter.getClass().getMethod(minMethName, (Class[]) null);
Method maxMethod = filter.getClass().getMethod(maxMethName, (Class[]) null);
isSliderType = true;
// log.info("property " + p.getName() + " for filter " + filter + " has min/max methods, constructing slider control for it");
if (p.getPropertyType() == Integer.TYPE) {
int min = (Integer) minMethod.invoke(filter);
int max = (Integer) maxMethod.invoke(filter);
params
= new SliderParams(Integer.class, min, max, 0, 0);
} else if (p.getPropertyType() == Float.TYPE) {
float min = (Float) minMethod.invoke(filter);
float max = (Float) maxMethod.invoke(filter);
params
= new SliderParams(Integer.class, 0, 0, min, max);
}
} catch (NoSuchMethodException e) {
} catch (Exception iae) {
log.warning(iae.toString() + " for property " + p + " in filter " + filter);
}
return params;
}
class Point2DControl extends JPanel implements HasSetter {
Method write, read;
EventFilter filter;
Point2D.Float point;
float initValue = 0, nval;
final JTextField tfx, tfy;
final String format = "%.1f";
final JButton nullifyButton;
@Override
final public void set(Object o) {
if (o == null) {
tfx.setText(null);
tfy.setText(null);
} else if (o instanceof Point2D) {
Point2D b = (Point2D) o;
tfx.setText(String.format(format, b.getX()));
tfy.setText(String.format(format, b.getY()));
}
}
final class PointActionListener implements ActionListener {
Method readMethod, writeMethod;
Point2D point = new Point2D.Float(0, 0);
public PointActionListener(Method readMethod, Method writeMethod) {
this.readMethod = readMethod;
this.writeMethod = writeMethod;
}
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println(e);
try {
float x = Float.parseFloat(tfx.getText());
float y = Float.parseFloat(tfy.getText());
point.setLocation(x, y);
writeMethod.invoke(filter, point);
point = (Point2D) readMethod.invoke(filter); // getString the value from the getter method to constrain it
set(point);
} catch (NumberFormatException fe) {
tfx.selectAll();
tfy.selectAll();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
final class PointNullifyActionListener implements ActionListener {
Method writeMethod;
public PointNullifyActionListener(Method writeMethod) {
this.writeMethod = writeMethod;
}
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println(e);
try {
Object arg = null;
writeMethod.invoke(filter, arg);
set(null);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
public Point2DControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(ALIGNMENT);
// setLayout(new FlowLayout(FlowLayout.LEADING));
JLabel label = new JLabel(name);
label.setAlignmentX(ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
tfx = new JTextField("", 10);
tfx.setMaximumSize(new Dimension(100, 50));
tfx.setToolTipText("Point2D X: type new value here and press enter. Set blank to set null value for Point2D.");
tfy = new JTextField("", 10);
tfy.setMaximumSize(new Dimension(100, 50));
tfy.setToolTipText("Point2D Y: type new value here and press enter. Set blank to set null value for Point2D.");
nullifyButton = new JButton("Nullify");
nullifyButton.setMaximumSize(new Dimension(100, 50));
nullifyButton.setToolTipText("Sets Point2D to null value");
try {
Point2D p = (Point2D) r.invoke(filter);
// if (p == null) {
// log.warning("null object returned from read method " + r);
// return;
set(p);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
log.warning("cannot access the field named " + name + " check if the class or method is not public?");
e.printStackTrace();
}
add(tfx);
add(new JLabel(", "));
add(tfy);
add(nullifyButton);
tfx.addActionListener(new PointActionListener(r, w));
tfy.addActionListener(new PointActionListener(r, w));
nullifyButton.addActionListener(new PointNullifyActionListener(write));
tfx.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
tfx.setSelectionStart(0);
tfx.setSelectionEnd(tfx.getText().length());
}
@Override
public void focusLost(FocusEvent e) {
}
});
tfy.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
tfy.setSelectionStart(0);
tfy.setSelectionEnd(tfy.getText().length());
}
@Override
public void focusLost(FocusEvent e) {
}
});
}
}
// Addition by Peter: Allow user to add custom filter controls
// ArrayList<JPanel> customControls=new ArrayList();
JPanel controlPanel;
public void addCustomControls(JPanel control) {
if (controlPanel == null) {
controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
this.add(controlPanel);
}
this.controlPanel.add(control);
// this.customControls.add(controls);
setControlsVisible(true);
// this.repaint();
// this.revalidate();
}
public void removeCustomControls() {
// for (JPanel p:customControls)
// controls.remove(p);
if (controlPanel != null) {
controlPanel.removeAll();
controlPanel.repaint();
}
// customControls.clear();
}
// public class ShowControlsAction extends AbstractAction{
// public ShowControlsAction() {
// super("Show controls");
// putValue(SELECTED_KEY, "Hide controls");
// putValue(SHORT_DESCRIPTION,"Toggles visibility of controls of this EventFilter");
// @Override
// public void actionPerformed(ActionEvent e) {
// setControlsVisible(enabled);
} |
package com.example.bkkinfoplus;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.example.bkkinfoplus.model.Alert;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class Utils {
public static String capitalizeString(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
public static class AlertStartTimestampComparator implements Comparator<Alert> {
@Override
public int compare(Alert lhs, Alert rhs) {
return Long.valueOf(lhs.getStart()).compareTo(rhs.getStart());
}
}
/**
* Detects if a route seems to be a replacement route by its ID format.
* It's needed because the API returns replacement routes mixed together with the affected routes.
* @param routeId
* @return
*/
public static boolean isRouteReplacement(String routeId) {
String replacementIdPattern = "BKK_(VP|TP|HP)[0-9]+";
return routeId.matches(replacementIdPattern);
}
public static List<String> jsonArrayToStringList(JSONArray array) throws JSONException {
List<String> list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
return list;
}
public static JSONArray jsonObjectToArray(JSONObject object) throws JSONException {
Iterator<String> keys = object.keys();
JSONArray result = new JSONArray();
while (keys.hasNext()) {
String key = keys.next();
result.put(object.getJSONObject(key));
}
return result;
}
/**
* Returns the appropriate error message depending on the concrete error type
* @param error VolleyError object
* @return ID of the String resource of the appropriate error message
*/
public static int volleyErrorTypeHandler(VolleyError error) {
int stringId;
if (error instanceof NoConnectionError) {
stringId = R.string.error_no_connection;
} else if (error instanceof NetworkError || error instanceof TimeoutError ) {
stringId = R.string.error_network;
} else if (error instanceof ServerError) {
stringId = R.string.error_response;
} else {
stringId = R.string.error_communication;
}
return stringId;
}
} |
package com.xlythe.sms;
import android.content.Context;
import android.graphics.PorterDuff;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.LruCache;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.xlythe.sms.util.ColorUtils;
import com.xlythe.sms.util.DateFormatter;
import com.xlythe.textmanager.text.Text;
import de.hdodenhof.circleimageview.CircleImageView;
public class MessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = MessageAdapter.class.getSimpleName();
private static final boolean DEBUG = true;
private static final int CACHE_SIZE = 50;
private Text.TextCursor mCursor;
private Context mContext;
private FailedViewHolder.ClickListener mClickListener;
private final LruCache<Integer, Text> mTextLruCache = new LruCache<>(CACHE_SIZE);
// Duration between considering a text to be part of the same message, or split into different messages
private static final long SPLIT_DURATION = 60 * 1000;
private static final int TYPE_TOP_RIGHT = 0;
private static final int TYPE_MIDDLE_RIGHT = 1;
private static final int TYPE_BOTTOM_RIGHT = 2;
private static final int TYPE_SINGLE_RIGHT = 3;
private static final int TYPE_TOP_LEFT = 4;
private static final int TYPE_MIDDLE_LEFT = 5;
private static final int TYPE_BOTTOM_LEFT = 6;
private static final int TYPE_SINGLE_LEFT = 7;
private static final int TYPE_ATTACHMENT = 8;
private static final int TYPE_FAILED = 9;
private static final SparseIntArray mMap = new SparseIntArray();
static {
mMap.put(TYPE_TOP_RIGHT,R.layout.right_top);
mMap.put(TYPE_MIDDLE_RIGHT,R.layout.right_middle);
mMap.put(TYPE_BOTTOM_RIGHT,R.layout.right_bottom);
mMap.put(TYPE_SINGLE_RIGHT,R.layout.right_single);
mMap.put(TYPE_TOP_LEFT,R.layout.left_top);
mMap.put(TYPE_MIDDLE_LEFT,R.layout.left_middle);
mMap.put(TYPE_BOTTOM_LEFT,R.layout.left_bottom);
mMap.put(TYPE_SINGLE_LEFT,R.layout.left_single);
mMap.put(TYPE_ATTACHMENT,R.layout.attachment);
mMap.put(TYPE_FAILED,R.layout.left_single);
};
public static abstract class MessageViewHolder extends RecyclerView.ViewHolder {
private Text mText;
private Context mContext;
public MessageViewHolder(View v) {
super(v);
}
public void setMessage(Context context, Text text) {
mText = text;
mContext = context;
}
public Text getMessage() {
return mText;
}
public Context getContext() {
return mContext;
}
}
public static class ViewHolder extends MessageViewHolder {
public TextView mTextView;
public TextView mDate;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.message);
mDate = (TextView) v.findViewById(R.id.date);
}
public void setMessage(Context context, Text text) {
super.setMessage(context, text);
setBodyText(text.getBody());
setDateText(DateFormatter.getFormattedDate(text));
}
public void setBodyText(String body) {
mTextView.setText(body);
}
public void setDateText(String dateText) {
if (mDate != null) {
mDate.setText(dateText);
}
}
}
public static class LeftViewHolder extends ViewHolder {
public FrameLayout mFrame;
private CircleImageView mProfile;
public LeftViewHolder(View v) {
super(v);
mFrame = (FrameLayout) v.findViewById(R.id.frame);
mProfile = (CircleImageView) v.findViewById(R.id.profile_image);
}
@Override
public void setMessage(Context context, Text text) {
super.setMessage(context, text);
setColor(ColorUtils.getColor(text.getThreadIdAsLong()));
setProfile();
}
public void setColor(int color) {
mFrame.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
}
public void setProfile() {
if (mProfile != null) {
ProfileDrawable border = new ProfileDrawable(getContext(),
getMessage().getSender().getDisplayName().charAt(0),
ColorUtils.getColor(getMessage().getThreadIdAsLong()),
getMessage().getSender().getPhotoUri());
mProfile.setImageDrawable(border);
}
}
}
public static class AttachmentViewHolder extends MessageViewHolder {
ImageView mImageView;
public AttachmentViewHolder(View v) {
super(v);
mImageView = (ImageView) v.findViewById(R.id.image);
}
@Override
public void setMessage(Context context, Text text) {
super.setMessage(context, text);
setImage();
}
public void setImage() {
Picasso.with(getContext()).load(getMessage().getAttachments().get(0).getUri()).into(mImageView);
}
}
public static class FailedViewHolder extends LeftViewHolder implements View.OnClickListener {
private ClickListener mListener;
public FailedViewHolder(View v, ClickListener listener) {
super(v);
mListener = listener;
v.setOnClickListener(this);
}
@Override
public void setMessage(Context context, Text text) {
super.setMessage(context, text);
}
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onItemClicked(getMessage());
}
}
public interface ClickListener {
void onItemClicked(Text text);
}
}
public MessageAdapter(Context context, Text.TextCursor cursor) {
mCursor = cursor;
mContext = context;
}
public void setOnClickListener(FailedViewHolder.ClickListener onClickListener) {
mClickListener = onClickListener;
}
// Create new views (invoked by the layout manager)
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch(viewType) {
case TYPE_TOP_RIGHT:
case TYPE_MIDDLE_RIGHT:
case TYPE_BOTTOM_RIGHT:
case TYPE_SINGLE_RIGHT:
return new ViewHolder(LayoutInflater.from(mContext).inflate(mMap.get(viewType), parent, false));
case TYPE_TOP_LEFT:
case TYPE_MIDDLE_LEFT:
case TYPE_BOTTOM_LEFT:
case TYPE_SINGLE_LEFT:
return new LeftViewHolder(LayoutInflater.from(mContext).inflate(mMap.get(viewType), parent, false));
case TYPE_ATTACHMENT:
return new AttachmentViewHolder(LayoutInflater.from(mContext).inflate(mMap.get(viewType), parent, false));
default:
return new FailedViewHolder(LayoutInflater.from(mContext).inflate(mMap.get(viewType), parent, false), mClickListener);
}
}
@Override
public int getItemViewType(int position) {
Text text = getText(position);
Text prevText = null;
if (position > 0) {
prevText = getText(position - 1);
}
Text nextText = null;
if (position + 1 < mCursor.getCount()) {
nextText = getText(position + 1);
}
if (text.isMms()) {
if (!text.getAttachments().isEmpty()) {
return TYPE_ATTACHMENT;
}
return TYPE_FAILED;
}
// Get the date of the current, previous and next message.
long dateCurrent = text.getTimestamp();
long datePrevious = 0;
long dateNext = 0;
// Get the sender of the current, previous and next message. (returns true if you)
boolean userCurrent = text.isIncoming();
boolean userPrevious = text.isIncoming();
boolean userNext = !text.isIncoming();
// Check if previous message exists, then get the date and sender.
if (prevText != null) {
datePrevious = prevText.getTimestamp();
userPrevious = prevText.isIncoming();
}
// Check if next message exists, then get the date and sender.
if (nextText != null) {
dateNext = nextText.getTimestamp();
userNext = nextText.isIncoming();
}
// Calculate time gap.
boolean largePC = dateCurrent - datePrevious > SPLIT_DURATION;
boolean largeCN = dateNext - dateCurrent > SPLIT_DURATION;
if (DEBUG) {
Log.d(TAG, String.format(
"userCurrent=%s, userPrevious=%s, userNext=%s," +
"dateCurrent=%s, datePrevious=%s, dateNext=%s," +
"largePC=%s, largeCN=%s",
userCurrent, userPrevious, userNext,
dateCurrent, datePrevious, dateNext,
largePC, largeCN));
}
if (!userCurrent && (userPrevious || largePC) && (!userNext && !largeCN)) {
return TYPE_TOP_RIGHT;
} else if (!userCurrent && (!userPrevious && !largePC) && (!userNext && !largeCN)) {
return TYPE_MIDDLE_RIGHT;
} else if (!userCurrent && (!userPrevious && !largePC)) {
return TYPE_BOTTOM_RIGHT;
} else if (!userCurrent) {
return TYPE_SINGLE_RIGHT;
} else if ((!userPrevious || largePC) && (userNext && !largeCN)) {
return TYPE_TOP_LEFT;
} else if ((userPrevious && !largePC) && (userNext && !largeCN)) {
return TYPE_MIDDLE_LEFT;
} else if (userPrevious && !largePC) {
return TYPE_BOTTOM_LEFT;
} else {
return TYPE_SINGLE_LEFT;
}
}
private Text getText(int position) {
Text text = mTextLruCache.get(position);
if (text == null) {
mCursor.moveToPosition(position);
text = mCursor.getText();
mTextLruCache.put(position, text);
}
return text;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((MessageViewHolder) holder).setMessage(mContext, getText(position));
}
@Override
public int getItemCount() {
return mCursor.getCount();
}
} |
package se.sics.cooja.dialogs;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import javax.swing.Action;
import org.apache.log4j.Logger;
import se.sics.cooja.GUI;
import se.sics.cooja.MoteType.MoteTypeCreationException;
import se.sics.cooja.contikimote.ContikiMoteType;
import se.sics.cooja.dialogs.MessageList;
/**
* Contiki compiler library.
* Uses notion of Contiki platforms to compile a Contiki firmware.
*
* @author Fredrik Osterlind
*/
public class CompileContiki {
private static Logger logger = Logger.getLogger(CompileContiki.class);
/**
* Executes a Contiki compilation command.
*
* @param command Command
* @param env (Optional) Environment. May be null.
* @param outputFile Expected output. May be null.
* @param directory Directory in which to execute command
* @param onSuccess Action called if compilation succeeds
* @param onFailure Action called if compilation fails
* @param compilationOutput Is written both std and err process output
* @param synchronous If true, method blocks until process completes
* @return Sub-process if called asynchronously
* @throws Exception If process returns error, or outputFile does not exist
*/
public static Process compile(
final String command,
final String[] env,
final File outputFile,
final File directory,
final Action onSuccess,
final Action onFailure,
final MessageList compilationOutput,
boolean synchronous)
throws Exception {
compilationOutput.addMessage("", MessageList.NORMAL);
compilationOutput.addMessage("> " + command, MessageList.NORMAL);
logger.info("> " + command);
final Process compileProcess;
try {
/* TODO Split into correct arguments: parse " and ' */
compileProcess = Runtime.getRuntime().exec(command, env, directory);
final BufferedReader processNormal = new BufferedReader(
new InputStreamReader(compileProcess.getInputStream()));
final BufferedReader processError = new BufferedReader(
new InputStreamReader(compileProcess.getErrorStream()));
if (outputFile != null) {
if (outputFile.exists()) {
outputFile.delete();
}
if (outputFile.exists()) {
compilationOutput.addMessage("Error when deleting old " + outputFile.getName(), MessageList.ERROR);
if (onFailure != null) {
onFailure.actionPerformed(null);
}
throw new MoteTypeCreationException("Error when deleting old " + outputFile.getName());
}
}
Thread readInput = new Thread(new Runnable() {
public void run() {
try {
String readLine;
while ((readLine = processNormal.readLine()) != null) {
if (compilationOutput != null) {
compilationOutput.addMessage(readLine, MessageList.NORMAL);
}
}
} catch (IOException e) {
logger.warn("Error while reading from process");
}
}
}, "read input stream thread");
Thread readError = new Thread(new Runnable() {
public void run() {
try {
String readLine;
while ((readLine = processError.readLine()) != null) {
if (compilationOutput != null) {
compilationOutput.addMessage(readLine, MessageList.ERROR);
}
}
} catch (IOException e) {
logger.warn("Error while reading from process");
}
}
}, "read error stream thread");
final MoteTypeCreationException syncException = new MoteTypeCreationException("");
Thread handleCompilationResultThread = new Thread(new Runnable() {
public void run() {
/* Wait for compilation to end */
try {
compileProcess.waitFor();
} catch (Exception e) {
compilationOutput.addMessage(e.getMessage(), MessageList.ERROR);
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
/* Check return value */
if (compileProcess.exitValue() != 0) {
compilationOutput.addMessage("Process returned error code " + compileProcess.exitValue(), MessageList.ERROR);
if (onFailure != null) {
onFailure.actionPerformed(null);
}
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
if (outputFile == null) {
/* No firmware to generate: OK */
if (onSuccess != null) {
onSuccess.actionPerformed(null);
}
return;
}
if (!outputFile.exists()) {
compilationOutput.addMessage("No firmware file: " + outputFile, MessageList.ERROR);
if (onFailure != null) {
onFailure.actionPerformed(null);
}
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
compilationOutput.addMessage("", MessageList.NORMAL);
compilationOutput.addMessage("Compilation succeded", MessageList.NORMAL);
if (onSuccess != null) {
onSuccess.actionPerformed(null);
}
}
}, "handle compilation results");
readInput.start();
readError.start();
handleCompilationResultThread.start();
if (synchronous) {
try {
handleCompilationResultThread.join();
} catch (Exception e) {
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Compilation error: " + e.getMessage()).initCause(e);
}
/* Detect error manually */
if (syncException.hasCompilationOutput()) {
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Bad return value").initCause(syncException);
}
}
} catch (IOException ex) {
if (onFailure != null) {
onFailure.actionPerformed(null);
}
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Compilation error: " + ex.getMessage()).initCause(ex);
}
return compileProcess;
}
/**
* Generate JNI enabled Contiki main source file.
* Used by Contiki Mote Type.
*
* @param sourceFile Source file to generate
* @param javaClass JNI Java class
* @param sensors Contiki sensors
* @param coreInterfaces Core interfaces
* @throws Exception At error
*
* @see ContikiMoteType
*/
public static void generateSourceFile(
File sourceFile,
String javaClass,
String[] sensors,
String[] coreInterfaces
) throws Exception {
if (sourceFile == null) {
throw new Exception("No output source file defined");
}
if (javaClass == null) {
throw new Exception("No Java class defined");
}
if (sensors == null) {
throw new Exception("No Contiki sensors defined");
}
if (coreInterfaces == null) {
throw new Exception("No Contiki dependencies defined");
}
/* SENSORS */
String sensorString = "";
String externSensorDefs = "";
for (String sensor : sensors) {
if (!sensorString.equals("")) {
sensorString += ", ";
}
sensorString += "&" + sensor;
externSensorDefs += "extern const struct sensors_sensor " + sensor
+ ";\n";
}
if (!sensorString.equals("")) {
sensorString = "SENSORS(" + sensorString + ");";
} else {
sensorString = "SENSORS(NULL);";
}
/* CORE INTERFACES */
String interfaceString = "";
String externInterfaceDefs = "";
for (String coreInterface : coreInterfaces) {
if (!interfaceString.equals("")) {
interfaceString += ", ";
}
interfaceString += "&" + coreInterface;
externInterfaceDefs += "SIM_INTERFACE_NAME(" + coreInterface + ");\n";
}
if (!interfaceString.equals("")) {
interfaceString = "SIM_INTERFACES(" + interfaceString + ");";
} else {
interfaceString = "SIM_INTERFACES(NULL);";
}
/* If directory does not exist, try creating it */
if (!sourceFile.getParentFile().exists()) {
logger.info("Creating source file directory: " + sourceFile.getParentFile().getAbsolutePath());
sourceFile.getParentFile().mkdir();
}
/* GENERATE SOURCE FILE */
BufferedReader templateReader = null;
BufferedWriter sourceFileWriter = null;
try {
Reader reader;
String mainTemplate = GUI.getExternalToolsSetting("CONTIKI_MAIN_TEMPLATE_FILENAME");
if ((new File(mainTemplate)).exists()) {
reader = new FileReader(mainTemplate);
} else {
/* Try JAR, or fail */
InputStream input = CompileContiki.class.getResourceAsStream('/' + mainTemplate);
if (input == null) {
throw new FileNotFoundException(mainTemplate + " not found");
}
reader = new InputStreamReader(input);
}
templateReader = new BufferedReader(reader);
sourceFileWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(sourceFile)));
// Replace special fields in template
String line;
while ((line = templateReader.readLine()) != null) {
line = line.replaceFirst("\\[SENSOR_DEFINITIONS\\]", externSensorDefs);
line = line.replaceFirst("\\[SENSOR_ARRAY\\]", sensorString);
line = line.replaceFirst("\\[INTERFACE_DEFINITIONS\\]", externInterfaceDefs);
line = line.replaceFirst("\\[INTERFACE_ARRAY\\]", interfaceString);
line = line.replaceFirst("\\[CLASS_NAME\\]", javaClass);
sourceFileWriter.write(line + "\n");
}
sourceFileWriter.close();
templateReader.close();
} catch (Exception e) {
try {
if (templateReader != null) {
templateReader.close();
}
if (sourceFileWriter != null) {
sourceFileWriter.close();
}
} catch (Exception e2) {
}
// Forward exception
throw e;
}
if (!sourceFile.exists()) {
throw new Exception("Output source file does not exist: " + sourceFile.getAbsolutePath());
}
logger.info("Generated Contiki main source: " + sourceFile.getName());
}
/**
* Generate compiler environment using external tools settings.
* Used by Contiki Mote Type.
*
* @param identifier Mote type identifier
* @param contikiApp Contiki application source
* @param mapFile Expected map file
* @param libFile Expected JNI Contiki library
* @param archiveFile Expected Contiki archive
* @return Environment
* @throws Exception At errors
*/
public static String[][] createCompilationEnvironment(
String identifier,
File contikiApp,
File mapFile,
File libFile,
File archiveFile)
throws Exception {
if (identifier == null) {
throw new Exception("No identifier specified");
}
if (contikiApp == null) {
throw new Exception("No Contiki application specified");
}
if (mapFile == null) {
throw new Exception("No map file specified");
}
if (libFile == null) {
throw new Exception("No library output specified");
}
if (archiveFile == null) {
throw new Exception("No archive file specified");
}
String[][] env = new String[13][];
boolean includeSymbols = false; /* TODO */
/* Fetch configuration from external tools */
String link1 = GUI.getExternalToolsSetting("LINK_COMMAND_1", "");
String link2 = GUI.getExternalToolsSetting("LINK_COMMAND_2", "");
String ar1 = GUI.getExternalToolsSetting("AR_COMMAND_1", "");
String ar2 = GUI.getExternalToolsSetting("AR_COMMAND_2", "");
String ccFlags = GUI.getExternalToolsSetting("COMPILER_ARGS", "");
/* Replace MAPFILE variable */
link1 = link1.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName());
link2 = link2.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName());
ar1 = ar1.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName());
ar2 = ar2.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName());
ccFlags = ccFlags.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName());
/* Replace LIBFILE variable */
link1 = link1.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName());
link2 = link2.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName());
ar1 = ar1.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName());
ar2 = ar2.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName());
ccFlags = ccFlags.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName());
/* Replace ARFILE variable */
link1 = link1.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName());
link2 = link2.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName());
ar1 = ar1.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName());
ar2 = ar2.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName());
ccFlags = ccFlags.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName());
/* Replace JAVA_HOME variable */
String javaHome = System.getenv().get("JAVA_HOME");
if (javaHome == null) {
javaHome = "";
}
link1 = link1.replace("$(JAVA_HOME)", javaHome);
link2 = link2.replace("$(JAVA_HOME)", javaHome);
ar1 = ar1.replace("$(JAVA_HOME)", javaHome);
ar2 = ar2.replace("$(JAVA_HOME)", javaHome);
ccFlags = ccFlags.replace("$(JAVA_HOME)", javaHome);
/* Strip away contiki application .c extension */
String contikiAppNoExtension = contikiApp.getName().substring(0, contikiApp.getName().length()-2);
env[0] = new String[] { "LIBNAME", identifier };
env[1] = new String[] { "CONTIKI_APP", contikiAppNoExtension };
env[2] = new String[] { "COOJA_SOURCEFILES", "cooja-radio.c init-net-rime.c" };
env[3] = new String[] { "CC", GUI.getExternalToolsSetting("PATH_C_COMPILER") };
env[4] = new String[] { "EXTRA_CC_ARGS", ccFlags };
env[5] = new String[] { "LD", GUI.getExternalToolsSetting("PATH_LINKER") };
env[6] = new String[] { "LINK_COMMAND_1", link1 };
env[7] = new String[] { "LINK_COMMAND_2", link2 };
env[8] = new String[] { "AR", GUI.getExternalToolsSetting("PATH_AR") };
env[9] = new String[] { "AR_COMMAND_1", ar1 };
env[10] = new String[] { "AR_COMMAND_2", ar2 };
env[11] = new String[] { "SYMBOLS", includeSymbols?"1":"" };
env[12] = new String[] { "PATH", System.getenv("PATH") };
return env;
}
} |
package de.xikolo.model;
import android.app.DownloadManager;
import android.os.Environment;
import android.util.Log;
import com.path.android.jobqueue.JobManager;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import de.xikolo.GlobalApplication;
import de.xikolo.R;
import de.xikolo.data.entities.Course;
import de.xikolo.data.entities.Download;
import de.xikolo.data.entities.Item;
import de.xikolo.data.entities.Module;
import de.xikolo.data.net.DownloadHelper;
import de.xikolo.model.jobs.RetrieveContentLengthJob;
import de.xikolo.util.Config;
import de.xikolo.util.ExternalStorageUtil;
import de.xikolo.util.ToastUtil;
public class DownloadModel extends BaseModel {
public static final String TAG = DownloadModel.class.getSimpleName();
public DownloadModel(JobManager jobManager) {
super(jobManager);
}
public void getRemoteDownloadFileSize(Result<Long> result, String url) {
mJobManager.addJobInBackground(new RetrieveContentLengthJob(result, url));
}
public long startDownload(String uri, DownloadFileType type, Course course, Module module, Item item) {
if (Config.DEBUG) {
Log.d(TAG, "Start download for " + uri);
}
if (ExternalStorageUtil.isExternalStorageWritable()) {
String file = this.escapeFilename(item.title) + type.getFileSuffix();
String filename = buildDownloadFilename(type, course, module, item);
if (downloadExists(filename)) {
ToastUtil.show(GlobalApplication.getInstance(), R.string.toast_file_already_downloaded);
} else {
File dlFile = new File(filename);
createFolderIfNotExists(new File(dlFile.getAbsolutePath().replace(file, "")));
return DownloadHelper.request(uri, "file://" + dlFile.getAbsolutePath(), file);
}
} else {
Log.w(TAG, "No write access for external storage");
ToastUtil.show(GlobalApplication.getInstance(), R.string.toast_no_external_write_access);
}
return 0;
}
public boolean deleteDownload(DownloadFileType type, Course course, Module module, Item item) {
if (ExternalStorageUtil.isExternalStorageWritable()) {
String filename = buildDownloadFilename(type, course, module, item);
if (Config.DEBUG) {
Log.d(TAG, "Delete download " + filename);
}
if (!downloadExists(filename)) {
return false;
} else {
File dlFile = new File(filename);
return dlFile.delete();
}
} else {
Log.w(TAG, "No write access for external storage");
ToastUtil.show(GlobalApplication.getInstance(), R.string.toast_no_external_write_access);
return false;
}
}
public void cancelDownload(DownloadFileType type, Course course, Module module, Item item) {
if (ExternalStorageUtil.isExternalStorageWritable()) {
String filename = buildDownloadFilename(type, course, module, item);
Download dl = new Download();
dl.localFilename = filename;
if (Config.DEBUG) {
Log.d(TAG, "Cancel download " + filename);
}
Set<Download> dlSet = DownloadHelper.getAllDownloads();
for (Download download : dlSet) {
if (download.equals(dl)) {
DownloadHelper.remove(download.id);
}
}
deleteDownload(type, course, module, item);
} else {
Log.w(TAG, "No write access for external storage");
ToastUtil.show(GlobalApplication.getInstance(), R.string.toast_no_external_write_access);
}
}
public Download getDownload(DownloadFileType type, Course course, Module module, Item item) {
String filename = buildDownloadFilename(type, course, module, item);
Download dl = new Download();
dl.localFilename = filename;
if (Config.DEBUG) {
Log.d(TAG, "Get download " + filename);
}
Set<Download> dlSet = DownloadHelper.getAllDownloads();
for (Download download : dlSet) {
if (download.equals(dl)) {
return download;
}
}
return null;
}
public boolean downloadRunning(DownloadFileType type, Course course, Module module, Item item) {
String dlFilename = buildDownloadFilename(type, course, module, item);
Download dl = new Download();
dl.localFilename = dlFilename;
int flags = DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING;
Set<Download> dlSet = DownloadHelper.getAllDownloadsForStatus(flags);
return dlSet.contains(dl);
}
public boolean downloadExists(DownloadFileType type, Course course, Module module, Item item) {
File file = new File(buildDownloadFilename(type, course, module, item));
return file.isFile() && file.exists();
}
private boolean downloadExists(String filename) {
File file = new File(filename);
return file.isFile() && file.exists();
}
public File getDownloadFile(DownloadFileType type, Course course, Module module, Item item) {
File file = new File(buildDownloadFilename(type, course, module, item));
if (file.isFile() && file.exists()) {
return file;
}
return null;
}
public long getDownloadFileSize(DownloadFileType type, Course course, Module module, Item item) {
File file = new File(buildDownloadFilename(type, course, module, item));
if (file.isFile() && file.exists()) {
return file.length();
}
return 0;
}
private String buildDownloadFilename(DownloadFileType type, Course course, Module module, Item item) {
File publicAppFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
+ GlobalApplication.getInstance().getString(R.string.app_name));
String file = this.escapeFilename(item.title) + type.getFileSuffix();
return publicAppFolder.getAbsolutePath() + File.separator
+ course.name.replaceAll("/", "-").replaceAll(":", "-").replaceAll(" ", "-") + "_" + course.id + File.separator
+ module.name.replaceAll("/", "-").replaceAll(":", "-").replaceAll(" ", "-") + "_" + module.id + File.separator
+ item.title.replaceAll("/", "-").replaceAll(":", "-").replaceAll(" ", "-") + "_" + item.id + File.separator
+ file;
}
private String escapeFilename(String filename) {
return filename.replaceAll("/", "-").replaceAll(":", "-").replaceAll(" ", "-");
}
public List<String> getFoldersWithDownloads() {
List<String> folders = new ArrayList<String>();
File publicAppFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
+ GlobalApplication.getInstance().getString(R.string.app_name));
if (publicAppFolder.isDirectory()) {
File[] files = publicAppFolder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
folders.add(file.getAbsolutePath());
}
}
}
return folders;
}
public String getAppFolder() {
File appFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
+ GlobalApplication.getInstance().getString(R.string.app_name));
createFolderIfNotExists(appFolder);
return appFolder.getAbsolutePath();
}
private void createFolderIfNotExists(File file) {
if (!file.exists()) {
if (file.isFile()) {
file = file.getParentFile();
}
Log.d(TAG, "Folder " + file.getAbsolutePath() + " not exists");
if (file.mkdirs()) {
Log.d(TAG, "Created Folder " + file.getAbsolutePath());
} else {
Log.w(TAG, "Failed creating Folder " + file.getAbsolutePath());
}
} else {
Log.d(TAG, "Folder " + file.getAbsolutePath() + " already exists");
}
}
public enum DownloadFileType {
SLIDES, TRANSCRIPT, VIDEO_SD, VIDEO_HD;
public static DownloadFileType getDownloadFileTypeFromUri(String uri) {
if (uri.endsWith(DownloadFileType.SLIDES.getFileSuffix())) {
return DownloadFileType.SLIDES;
} else if (uri.endsWith(DownloadFileType.TRANSCRIPT.getFileSuffix())) {
return DownloadFileType.TRANSCRIPT;
} else if (uri.endsWith(DownloadFileType.VIDEO_SD.getFileSuffix())) {
return DownloadFileType.VIDEO_SD;
} else if (uri.endsWith(DownloadFileType.VIDEO_HD.getFileSuffix())) {
return DownloadFileType.VIDEO_HD;
}
return null;
}
public String getFileSuffix() {
switch (this) {
case SLIDES:
return "_slides.pdf";
case TRANSCRIPT:
return "_transcript.pdf";
case VIDEO_SD:
return "_video_sd.mp4";
case VIDEO_HD:
return "_video_hd.mp4";
default:
return "";
}
}
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package support;
import java.util.LinkedList;
import java.util.List;
import jolie.lang.parse.ast.OLSyntaxNode;
/**
*
* @author balint
*/
public class treeOLObject {
private OLSyntaxNode olSyntaxNode;
private List<treeOLObject> linkList;
private String nameFile;
private treeOLObject fatherObject;
public treeOLObject(OLSyntaxNode olSyntaxNode, treeOLObject fatherObject){
this.olSyntaxNode=olSyntaxNode;
this.nameFile=olSyntaxNode.context().sourceName();
linkList= new LinkedList<treeOLObject>();
this.fatherObject=fatherObject;
}
public void SetLinkedObject(OLSyntaxNode olSyntaxNode){
treeOLObject supportObjet= new treeOLObject(olSyntaxNode,this);
linkList.add(supportObjet);
}
public treeOLObject GetLinkedObject(int i){
return linkList.get(i);
}
public OLSyntaxNode GetOLSyntaxNode()
{
return olSyntaxNode;
}
public int GetLinkedObjetSize(){
return linkList.size();
}
public treeOLObject GetFatherObject(){
return this.fatherObject;
}
} |
package opendap.aws.glacier;
import opendap.aws.AwsUtil;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class GlacierVaultManager {
Logger _log = LoggerFactory.getLogger(this.getClass());
private String _name;
private String _parentContext;
private String _serviceContext;
private String _pathDelimiter = "/";
public static final String DefaultIndexDirectoryName = "index";
private File _indexDirectory;
public static final String DefaultArchiveRecordsDirectoryName = "archive";
private File _archiveRecordsDirectory;
public static final String DefaultResourceCacheDirectoryName = "cache";
private File _resourceCacheDirectory;
public static int DEFAULT_MAX_RECORDS_IN_MEMORY = 100;
private int _max_records;
//private ConcurrentHashMap<String, GlacierRecord> _archiveRecords;
private ConcurrentHashMap<String, Index> _indexObjects;
private ConcurrentHashMap<String, ResourceId> _resourceIds;
private ConcurrentSkipListMap<ResourceId, GlacierRecord> _glacierRecords;
public GlacierVaultManager(String vaultName, File glacierRootDir) throws IOException {
if(vaultName ==null){
throw new IOException("Vault name was null!");
}
_name = vaultName;
File vaultDir = mkDir(glacierRootDir,_name);
_indexDirectory = mkDir(vaultDir,DefaultIndexDirectoryName);
_archiveRecordsDirectory = mkDir(vaultDir,DefaultArchiveRecordsDirectoryName);
_resourceCacheDirectory = mkDir(glacierRootDir,DefaultResourceCacheDirectoryName);
_resourceIds = new ConcurrentHashMap<String, ResourceId>();
_glacierRecords = new ConcurrentSkipListMap<ResourceId, GlacierRecord>();
_indexObjects = new ConcurrentHashMap<String, Index>();
_max_records = DEFAULT_MAX_RECORDS_IN_MEMORY;
}
public String getServiceContext(){
return _serviceContext;
}
public void setParentContext(String parentContext){
_parentContext = parentContext;
String myContext = _parentContext + _pathDelimiter + name();
_serviceContext = myContext;
}
public String name(){
return _name;
}
public File getIndexDir() throws IOException {
if(_indexDirectory ==null)
throw new IOException("Index directory was null valued.");
return new File(_indexDirectory.getCanonicalPath());
}
public File getArchiveRecordsDir() throws IOException {
if(_archiveRecordsDirectory ==null)
throw new IOException("Archive Records directory was null valued.");
return new File(_archiveRecordsDirectory.getCanonicalPath());
}
public File getResourceCacheDir() throws IOException {
if(_resourceCacheDirectory ==null)
throw new IOException("Resource Cache directory was null valued.");
return new File(_resourceCacheDirectory.getCanonicalPath());
}
public File mkDir(File parent, String dirName) throws IOException {
File newDir = new File(parent,dirName);
if(!newDir.exists() && !newDir.mkdirs()){
throw new IOException("Unable to create directory: "+newDir);
}
if(!newDir.canWrite()){
throw new IOException("Unable to write to directory: "+newDir);
}
return newDir;
}
public void cacheArchiveRecord(GlacierRecord gar) throws IOException {
File targetFile = new File(getArchiveRecordsDir(), AwsUtil.encodeKeyForFileSystemName(gar.getResourceId()));
_log.debug("cacheArchiveRecord() - targetFile: '{}'", targetFile);
if(targetFile.exists()){
_log.warn("cacheArchiveRecord() - OVERWRITING RESOURCE ARCHIVE RECORD: '{}'", targetFile);
}
else {
File parent = targetFile.getParentFile();
if(!parent.exists() && !parent.mkdirs()){
throw new IOException("Couldn't create the parent directory: " + parent);
}
_log.debug("Attempting to create target file: '{}'", targetFile.getAbsolutePath());
targetFile.createNewFile();
}
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
FileOutputStream fis = null;
try {
fis = new FileOutputStream(targetFile);
xmlo.output(gar.getArchiveRecordDocument(),fis);
}
finally {
if(fis!=null)
fis.close();
}
}
public GlacierRecord getArchiveRecord(String resourceId) throws IOException, JDOMException {
ResourceId id = _resourceIds.get(resourceId);
if(id==null)
return loadArchiveRecord(resourceId);
id.updateLastAccessed();
return _glacierRecords.get(id);
}
public Index getIndex(String resourceId){
return _indexObjects.get(resourceId);
}
/*
public void loadArchiveRecords() throws IOException, JDOMException {
GlacierRecord gar;
File archiveDir = getArchiveRecordsDir();
File[] archiveRecords = archiveDir.listFiles((FileFilter) HiddenFileFilter.VISIBLE);
if (archiveRecords != null) {
for (File archiveRecord : archiveRecords) {
if (archiveRecord.isFile()) {
gar = new GlacierRecord(archiveRecord);
gar.createCacheFile(_resourceCacheDirectory);
ResourceId resourceId = new ResourceId(gar.getResourceId());
_resourceIds.put(resourceId.toString(), resourceId);
_glacierRecords.put(resourceId,gar);
_log.debug("Loaded Glacier Archive Record. vault: {} resourceId: {}", name(), resourceId);
}
else {
_log.debug("Skipping directory/link {}", archiveRecord);
}
}
} else {
_log.debug("No archive records found for vault {}", name());
}
}
*/
private GlacierRecord loadArchiveRecord(String resourceId) throws IOException, JDOMException {
GlacierRecord gar;
String baseFileName = AwsUtil.encodeKeyForFileSystemName(resourceId);
File archiveRecord = new File(getArchiveRecordsDir(),baseFileName);
if (archiveRecord.isFile()) {
gar = new GlacierRecord(archiveRecord);
gar.createCacheFile(_resourceCacheDirectory);
ResourceId rId = new ResourceId(gar.getResourceId());
while(_resourceIds.size() >= _max_records){
_log.debug("loadArchiveRecord() - Max Records limit reached. Unloading Glacier Archive Record. vault: {} resourceId: {}", name(), resourceId);
ResourceId mostStaleId = _glacierRecords.firstKey();
_resourceIds.remove(mostStaleId.getId());
_glacierRecords.remove(mostStaleId);
}
_resourceIds.put(rId.toString(), rId);
_glacierRecords.put(rId,gar);
_log.debug("loadArchiveRecord() - Loaded Glacier Archive Record. vault: {} resourceId: {}", name(), resourceId);
return gar;
}
_log.warn("loadArchiveRecord() - Could not locate Glacier Archive Record. vault: {} resourceId: {}", name(), resourceId);
return null;
}
public void loadIndexObjects() throws IOException, JDOMException {
Index index;
File indexDir = getIndexDir();
File[] indexFiles = indexDir.listFiles((FileFilter) HiddenFileFilter.VISIBLE);
if (indexFiles != null) {
for (File indexFile : indexFiles) {
if (indexFile.isFile()) {
index = new Index(indexFile);
StringBuilder resourceId = new StringBuilder();
String pathDelimiter = index.getDelimiter();
resourceId
//.append(getGlacierServiceContext())
.append(index.getPath())
.append(pathDelimiter)
.append(index.getIndexFileConvention());
index.setResourceId(resourceId.toString());
_indexObjects.put(index.getResourceId(),index);
_log.debug("Loaded Index. Vault: {} resourceId: {}", name(), index.getResourceId());
}
else {
_log.debug("Skipping directory/link {}", indexFile);
}
}
} else {
_log.debug("No index files found for vault {}", name());
}
}
} |
package com.tinkerpop.gremlin.lang;
public class Tokens {
public static final String ASSIGNMENT = ":=";
public static final String FOREACH = "foreach";
public static final String IN = "in";
public static final String WHILE = "while";
public static final String REPEAT = "repeat";
public static final String DO = "do";
public static final String DOLLAR_SIGN = "$";
public static final String EMPTY_STRING = "";
public static final String AT_VARIABLE = "$_";
public static final String LAST_VALUE = "$_last";
protected static final String NEWLINE = "\n";
protected static final String ANY_WHITESPACE_REGEX = "[' '\t]+";
protected static final String SINGLESPACE = " ";
public static final String OUT_EDGES = "outEdges";
public static final String IN_EDGES = "inEdges";
public static final String BOTH_EDGES = "bothEdges";
public static final String OUT_VERTEX = "outVertex";
public static final String IN_VERTEX = "inVertex";
public static final String LABEL = "label";
} |
package team046;
import battlecode.common.*;
public class RobotPlayer {
private static RobotController rc;
private static int round;
private static double power;
private static int zergRushChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
private static int zergRushCode = randomWithRange(2, GameConstants.BROADCAST_MAX_CHANNELS);
private static int EncampmentBuilderChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
private static int EncampmentSearchStartedChannel = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
private static int FirstSupplierBuilt = randomWithRange(0, GameConstants.BROADCAST_MAX_CHANNELS);
public static void run(RobotController MyJohn12LongRC) {
rc = MyJohn12LongRC;
while (true) {
try {
round = Clock.getRoundNum();
power = rc.getTeamPower();
if (rc.getType() == RobotType.HQ) {
HQ();
}
else if (rc.getType() == RobotType.SOLDIER) {
Soldier();
}
rc.yield();
}
catch (Exception e) {
e.printStackTrace();
break;
}
}
}
private static void HQ() throws GameActionException {
if (rc.isActive()) {
if (rc.senseEnemyNukeHalfDone() && rc.readBroadcast(zergRushChannel) != zergRushCode) {
rc.broadcast(zergRushChannel, zergRushCode);
}
else if (round > 250 && !rc.hasUpgrade(Upgrade.FUSION)) {
rc.researchUpgrade(Upgrade.FUSION);
return;
}
else if (round > 500 && !rc.hasUpgrade(Upgrade.VISION)) {
rc.researchUpgrade(Upgrade.VISION);
return;
}
else {
Robot[] myBuddies = rc.senseNearbyGameObjects(Robot.class, 14, rc.getTeam());
if (round > 500 && myBuddies.length > 20) {
rc.researchUpgrade(Upgrade.NUKE);
return;
}
}
// Find an available spawn direction
MapLocation hqLocation = rc.senseHQLocation();
MapLocation nextLoc;
for (Direction dir : Direction.values()) {
if (dir != Direction.NONE && dir != Direction.OMNI && rc.canMove(dir)) {
nextLoc = hqLocation.add(dir);
if (rc.senseMine(nextLoc) == null) {
rc.spawn(dir);
break;
}
}
}
}
}
private static void Soldier() throws GameActionException {
if (rc.isActive()) {
int EncampmentBuilderRobotID;
int EncampmentSearchStartedRound;
MapLocation rLoc = rc.getLocation();
MapLocation targetLoc = null;
// Get the Encampment builder robot ID (or zero)
if (power > GameConstants.BROADCAST_READ_COST * 2) {
EncampmentBuilderRobotID = rc.readBroadcast(EncampmentBuilderChannel);
EncampmentSearchStartedRound = rc.readBroadcast(EncampmentSearchStartedChannel);
power -= GameConstants.BROADCAST_READ_COST * 2;
}
else {
EncampmentBuilderRobotID = -1;
EncampmentSearchStartedRound = 0;
}
if (EncampmentBuilderRobotID == 0
|| EncampmentSearchStartedRound + GameConstants.CAPTURE_ROUND_DELAY * 2 < round) {
rc.broadcast(EncampmentBuilderChannel, rc.getRobot().getID());
if (power > GameConstants.BROADCAST_SEND_COST) {
rc.broadcast(EncampmentSearchStartedChannel, round);
power -= GameConstants.BROADCAST_SEND_COST * 2;
}
EncampmentBuilderRobotID = rc.getRobot().getID();
}
// Check for zerg command
if (power > GameConstants.BROADCAST_READ_COST && rc.readBroadcast(zergRushChannel) == zergRushCode) {
targetLoc = rc.senseEnemyHQLocation();
power -= GameConstants.BROADCAST_READ_COST;
}
// Handle Encampment builder robot (including movement)
else if (EncampmentBuilderRobotID == rc.getRobot().getID()) {
BuildEncampment(rLoc);
return;
}
else {
// Get scared
Robot[] nearbyEnemies = rc.senseNearbyGameObjects(Robot.class, 3, rc.getTeam().opponent());
if (nearbyEnemies.length > 0) {
return;
}
}
// Set rally point
if (targetLoc == null) {
MapLocation goodHQ = rc.senseHQLocation();
if (goodHQ.x <= 1) {
targetLoc = new MapLocation(goodHQ.x + 3, goodHQ.y);
}
else if (goodHQ.x >= rc.getMapWidth() - 1) {
targetLoc = new MapLocation(goodHQ.x - 3, goodHQ.y);
}
else {
MapLocation rallyPoints[] = {
new MapLocation(goodHQ.x + randomWithRange(1,2), goodHQ.y + randomWithRange(1,2)),
new MapLocation(goodHQ.x - randomWithRange(1,2), goodHQ.y - randomWithRange(1,2))
};
targetLoc = rallyPoints[randomWithRange(0, rallyPoints.length - 1)];
}
}
MoveRobot(rLoc, targetLoc);
}
}
private static void MoveRobot(MapLocation rLoc, MapLocation targetLoc) throws GameActionException {
Direction dir = rLoc.directionTo(targetLoc);
if (dir == Direction.NONE) {
return;
}
else if (dir == Direction.OMNI) {
dir = Direction.EAST;
}
while (!rc.canMove(dir)) {
dir = dir.rotateRight();
}
MapLocation nextLoc = rLoc.add(dir);
if (rc.senseMine(nextLoc) != null) {
rc.defuseMine(nextLoc);
}
else {
rc.move(dir);
}
}
private static void BuildEncampment(MapLocation rLoc) throws GameActionException {
if (rc.senseEncampmentSquare(rLoc)) {
if (power > GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST
&& rc.readBroadcast(FirstSupplierBuilt) == 0) {
rc.captureEncampment(RobotType.SUPPLIER);
rc.broadcast(FirstSupplierBuilt, 1);
power -= GameConstants.BROADCAST_READ_COST + GameConstants.BROADCAST_SEND_COST;
}
else {
rc.captureEncampment(RobotType.GENERATOR);
}
}
else {
MapLocation encampmentSquares[] = rc.senseAllEncampmentSquares();
MapLocation goodEncampments[] = rc.senseAlliedEncampmentSquares();
MapLocation targetLoc = encampmentSquares[0];
int closest = 1000;
checkLocations:
for (MapLocation loc: encampmentSquares) {
int dist = rLoc.distanceSquaredTo(loc);
if (dist < closest) {
for (MapLocation goodLoc: goodEncampments) {
if (goodLoc.equals(loc)) {
continue checkLocations;
}
}
targetLoc = loc;
closest = dist;
}
}
MoveRobot(rLoc, targetLoc);
}
}
private static int randomWithRange(int min, int max) {
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
} |
package opendap.wcs.v2_0;
import opendap.coreServlet.Scrub;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class GetCapabilitiesRequest {
private static final String _request = "GetCapabilities";
private String updateSequence = null;
private String[] AcceptVersions = null;
private HashSet<String> Sections = new HashSet<String>();
private boolean hasSectionsElement;
private boolean _hasCountElement;
private long _maxContentsSectionsCount;
public static final long DEFAULT_MAX_CONTENTS_SECTIONS_COUNT = 10000;
private String[] AcceptFormats = null;
private String[] AcceptLanguages = null;
private String[] _coverageIds;
public static final String SERVICE_IDENTIFICATION = "ServiceIdentification";
public static final String SERVICE_PROVIDER = "ServiceProvider";
public static final String OPERATIONS_METADATA = "OperationsMetadata";
public static final String SERVICE_METADATA = "ServiceMetadata";
public static final String CONTENTS = "Contents";
public static final String ALL = "All";
// Earth Observation Profile sections
public static final String DATASET_SERIES_SUMMARY = "DatasetSeriesSummary";
public static final String COVERAGE_SUMMARY = "CoverageSummary";
private static final HashSet<String> sectionNames = new HashSet<String>();
static {
sectionNames.add(SERVICE_IDENTIFICATION);
sectionNames.add(SERVICE_PROVIDER);
sectionNames.add(OPERATIONS_METADATA);
sectionNames.add(CONTENTS);
sectionNames.add(ALL);
}
public String getUpdateSequence() {
return updateSequence;
}
public void setUpdateSequence(String updateSequence) {
this.updateSequence = updateSequence;
}
public String[] getAcceptVersions() {
return AcceptVersions;
}
public void setAcceptVersions(String[] acceptVersions) {
AcceptVersions = acceptVersions;
}
public Iterator<String> getSections() {
return Sections.iterator();
}
public boolean hasSection(String s) {
return Sections.contains(s);
}
public boolean sectionsIsEmtpty() {
return Sections.isEmpty();
}
public boolean hasSectionsElement() {
return hasSectionsElement;
}
public boolean hasCountElement() {
return _hasCountElement;
}
public long getCount(){
return _maxContentsSectionsCount;
}
public String[] getAcceptFormats() {
return AcceptFormats;
}
public void setAcceptFormats(String[] acceptFormats) {
AcceptFormats = acceptFormats;
}
public GetCapabilitiesRequest() {
_coverageIds = null;
}
public GetCapabilitiesRequest(Element getCRElem) throws WcsException{
this();
Element e;
String s;
Iterator i;
int index;
_maxContentsSectionsCount = DEFAULT_MAX_CONTENTS_SECTIONS_COUNT;
// Make sure we got the correct request object.
WCS.checkNamespace(getCRElem,_request,WCS.WCS_NS);
// Make sure the client is looking for a WCS service....
WCS.checkService(getCRElem.getAttributeValue("service"));
s=getCRElem.getAttributeValue("updateSequence");
if(s!=null)
updateSequence =s;
// Get the clients accepted versions.
e = getCRElem.getChild("AcceptVersions",WCS.WCS_NS);
if(e!=null ){
List vlist = e.getChildren("Version",WCS.WCS_NS);
if(vlist.size()==0){
throw new WcsException("The ows:AcceptVersions element is required " +
"to have one or more ows:Version child elements.",
WcsException.MISSING_PARAMETER_VALUE,
"ows:Version");
}
s = "";
AcceptVersions = new String[vlist.size()];
i = vlist.iterator();
index = 0;
while(i.hasNext()){
e = (Element) i.next();
AcceptVersions[index++] = e.getTextNormalize();
s += s.equals("")?s:", "+ e.getTextNormalize();
}
boolean compatible = false;
for(String version:AcceptVersions){
if(WCS.CURRENT_VERSION.equals(version)){
compatible=true;
}
}
if(!compatible)
throw new WcsException("Client requested unsupported WCS " +
"version(s): ["+s+"]\nThis WCS supports version(s) "+WCS.CURRENT_VERSION,
WcsException.VERSION_NEGOTIATION_FAILED,null);
}
// Get the sections the client wants.
hasSectionsElement = false;
e = getCRElem.getChild("Sections",WCS.WCS_NS);
if(e!=null ){
hasSectionsElement = true;
List vlist = e.getChildren("Section",WCS.WCS_NS);
i = vlist.iterator();
while(i.hasNext()){
e = (Element) i.next();
s = e.getTextNormalize();
if(!sectionNames.contains(s))
throw new WcsException("Client requested unsupported " +
"section name: "+ Scrub.simpleString(s),
WcsException.INVALID_PARAMETER_VALUE,"ows:Section");
Sections.add(e.getTextNormalize());
}
}
// Get the formats the client wants.
e = getCRElem.getChild("AcceptFormats",WCS.WCS_NS);
if(e!=null ){
List vlist = e.getChildren("OutputFormat",WCS.WCS_NS);
if(vlist.size()==0){
throw new WcsException("The ows:AcceptFormats element is required to have " +
"one or more ows:OutputFormat child elements.",
WcsException.MISSING_PARAMETER_VALUE,
"ows:OutputFormat");
}
AcceptFormats = new String[vlist.size()];
i = vlist.iterator();
index = 0;
while(i.hasNext()){
e = (Element) i.next();
AcceptFormats[index++] = e.getTextNormalize();
}
}
// Get the formats the client wants.
e = getCRElem.getChild("AcceptLanguages",WCS.WCS_NS);
if(e!=null ){
List vlist = e.getChildren("Language",WCS.WCS_NS);
if(vlist.size()==0){
throw new WcsException("The ows:AcceptFormats element is required to have " +
"one or more ows:OutputFormat child elements.",
WcsException.MISSING_PARAMETER_VALUE,
"ows:OutputFormat");
}
AcceptLanguages = new String[vlist.size()];
i = vlist.iterator();
index = 0;
while(i.hasNext()){
e = (Element) i.next();
AcceptLanguages[index++] = e.getTextNormalize();
}
}
}
public GetCapabilitiesRequest(Map<String,String[]> kvp)
throws WcsException {
this();
String tmp[], s[];
// Make sure the client is looking for a WCS service....
s = kvp.get("service");
WCS.checkService(s==null? null : s[0]);
// Make sure the client is actually asking for this operation
s = kvp.get("request");
if(s == null){
throw new WcsException("Poorly formatted request URL. Missing " +
"key value pair for 'request'",
WcsException.MISSING_PARAMETER_VALUE,"request");
}
else if(!s[0].equalsIgnoreCase(_request)){
throw new WcsException("The servers internal dispatch operations " +
"have failed. The WCS request for the operation '"+s[0]+"' " +
"has been incorrectly routed to the 'GetCapabilities' " +
"request processor.",
WcsException.NO_APPLICABLE_CODE);
}
// Make sure the client can accept the correct WCS version...
boolean compatible = false;
s = kvp.get("AcceptVersions".toLowerCase());
if(s!=null){
tmp = s[0].split(",");
for(String ver:tmp){
if(WCS.CURRENT_VERSION.equals(ver)){
compatible=true;
}
}
if(!compatible)
throw new WcsException("Client requested unsupported WCS " +
"version(s) ["+s[0]+"]\nThis WCS supports version(s) "+WCS.CURRENT_VERSION,
WcsException.VERSION_NEGOTIATION_FAILED,null);
AcceptVersions = tmp;
}
// Get the list of section the client has requested. Returning
// individual sections may not be supported, but we'll keep track of
// that partof the request regardless.
_hasCountElement = false;
_maxContentsSectionsCount = DEFAULT_MAX_CONTENTS_SECTIONS_COUNT;
s = kvp.get("count".toLowerCase());
if(s!=null){
_hasCountElement = true;
try {
_maxContentsSectionsCount = Long.parseLong(s[0]);
}
catch (NumberFormatException e){
// Nobody cares...
}
}
// Get the list of section the client has requested. Returning
// individual sections may not be supported, but we'll keep track of
// that partof the request regardless.
hasSectionsElement = false;
s = kvp.get("Sections".toLowerCase());
if(s!=null){
hasSectionsElement = true;
tmp = s[0].split(",");
for(String section:tmp){
if(!sectionNames.contains(section)){
throw new WcsException("Client requested unsupported " +
"section name: "+ Scrub.simpleString(section),
WcsException.INVALID_PARAMETER_VALUE,"Sections");
}
Sections.add(section);
}
}
// Store the updatSequence information in the event that the server
// supports it at some point...
s = kvp.get("updateSequence".toLowerCase());
updateSequence = s==null? null : s[0];
// Store the AccptedFormats offered by the client in the event that the
// the server eventually supports more than text/html
s = kvp.get("AcceptFormats".toLowerCase());
if(s!=null){
tmp = s[0].split(",");
AcceptFormats = tmp;
}
// Store the AccptedFormats offered by the client in the event that the
// the server eventually supports more than text/html
s = kvp.get("AcceptLanguages".toLowerCase());
if(s!=null){
tmp = s[0].split(",");
AcceptLanguages = tmp;
}
// Get the list of identifiers for the coverage to describe in the contents section.
s = kvp.get("coverageId".toLowerCase());
if(s!=null){
tmp = s[0].split(",");
_coverageIds = tmp;
}
}
public String[] getRequestedCoverageIds(){
return _coverageIds;
}
public Element getRequestElement(){
Element requestElement;
String _schemaLocation = "";
requestElement = new Element(_request, WCS.WCS_NS);
_schemaLocation += WCS.WCS_NAMESPACE_STRING + " " +WCS.WCS_SCHEMA_LOCATION_BASE+"wcsGetCapabilities.xsd ";
requestElement.addNamespaceDeclaration(WCS.XSI_NS);
requestElement.addNamespaceDeclaration(WCS.OWS_NS);
_schemaLocation += WCS.OWS_NAMESPACE_STRING + " " +WCS.OWS_SCHEMA_LOCATION_BASE+"owsGetCapabilities.xsd ";
requestElement.setAttribute("schemaLocation", _schemaLocation,WCS.XSI_NS);
requestElement.setAttribute("service", WCS.SERVICE);
if(updateSequence !=null)
requestElement.setAttribute("updateSequence", updateSequence);
if(AcceptVersions != null){
Element av = new Element("AcceptVersions",WCS.WCS_NS);
Element ver;
for(String v: AcceptVersions){
ver = new Element("Version",WCS.WCS_NS);
ver.setText(v);
av.addContent(ver);
}
requestElement.addContent(av);
}
if(!Sections.isEmpty()){
Element sections = new Element("Sections",WCS.WCS_NS);
Element sec;
for(String sv : Sections){
sec = new Element("Section",WCS.WCS_NS);
sec.setText(sv);
sections.addContent(sec);
}
requestElement.addContent(sections);
}
if(AcceptFormats != null){
Element af = new Element("AcceptFormats",WCS.WCS_NS);
Element fe;
for(String f : AcceptFormats){
fe = new Element("OutputFormat",WCS.WCS_NS);
fe.setText(f);
af.addContent(fe);
}
requestElement.addContent(af);
}
if(AcceptLanguages != null){
Element af = new Element("AcceptLanguages",WCS.WCS_NS);
Element fe;
for(String f : AcceptLanguages){
fe = new Element("Language",WCS.WCS_NS);
fe.setText(f);
af.addContent(fe);
}
requestElement.addContent(af);
}
return requestElement;
}
public Document getRequestDoc(){
return new Document(getRequestElement());
}
public void serialize(OutputStream os) throws IOException {
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
xmlo.output(getRequestDoc(), os);
}
public String toString(){
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
return xmlo.outputString(getRequestDoc());
}
} |
package org.adligo.i.util.client;
public class HashCollection implements I_Collection {
//Math.abs(Integer.MIN_VALUE) = 2147483648
// but java wouln't compute it :(
public static final long INT_SPAN = (long) (21474836.48 * 100) + 1 + Integer.MAX_VALUE;
private int max = Integer.MAX_VALUE;
private int min = Integer.MIN_VALUE;
/**
* this turns into the maximum number of b tree lookups
*/
private short max_depth = 25;
/**
* this is the depth of the current HashCollection
* depth starts at 0 and moves tword max_depth
*/
private short depth = 0;
private long span = INT_SPAN;
/**
* this is the limit of objects in non max_depth HashCollection.splits
*/
private int chunkSize = 100;
/**
* the number of buckets that are created from a split
*/
private int bucketsFromSplit = 16;
/**
* if true the object array collection contains objects
* if false the objects are in the splits (HashContainers)
*/
private boolean containsObjects = true;
/**
* HashLocation's
*/
private ArrayCollection hashToLocations;
private ArrayCollection objects;
/**
* HashContainers
*/
private HashCollection[] splits;
public synchronized boolean add(Object p) {
if (p == null) {
return false;
}
//System.out.println(this.getClass().getName() + " adding" + p);
return putOrAdd(p, false);
}
public synchronized boolean put(Object p) {
return putOrAdd(p, true);
}
private boolean putOrAdd(Object p, boolean put) {
if (p == null) {
return false;
}
if (hashToLocations == null) {
hashToLocations = new ArrayCollection();
objects = new ArrayCollection();
}
int hash = p.hashCode();
if (containsObjects) {
if (objects.size() < chunkSize) {
return forceAddOrPut(hash, p, put);
} else {
if (depth < max_depth) {
split(hash, p, put);
return true;
} else {
return forceAddOrPut(hash, p, put);
}
}
} else {
int chunckSpan = getSpan(span, bucketsFromSplit);
Integer bucket = getBucket(p.hashCode(), min, max, chunckSpan);
HashCollection hc = (HashCollection) splits[bucket.intValue()];
//System.out.println(this.getClass().getName() + " adding" + p + " to " + hc);
if (put) {
return hc.put(p);
} else {
return hc.add(p);
}
}
}
private boolean forceAddOrPut(int hash, Object p, boolean put) {
HashLocation hl = getHashLocation(hash);
if (put) {
if (hl != null) {
hashToLocations.remove(hl);
objects.remove(hl.getLocation());
}
Integer loc = objects.addInternal(p);
hashToLocations.add(new HashLocation(hash, loc.intValue()));
return true;
} else {
if (hl != null) {
return false;
}
Integer loc = objects.addInternal(p);
hashToLocations.add(new HashLocation(hash, loc.intValue()));
return true;
}
}
private HashLocation getHashLocation(int hash) {
I_Iterator it = hashToLocations.getIterator();
while (it.hasNext()) {
HashLocation hl = (HashLocation) it.next();
if (hl.getHash() == hash) {
return hl;
}
}
return null;
}
private void split(int hash, Object p, boolean put) {
//System.out.println(this.getClass().getName() + " splitting " + this);
containsObjects = false;
int chunckSpan = getSpan(span, bucketsFromSplit);
/**
* the child hash containers will be in order
*/
int bucket = 0;
long next = min;
splits = new HashCollection[bucketsFromSplit];
for (int i = 0; i < bucketsFromSplit; i++) {
if (next <= Integer.MAX_VALUE) {
HashCollection hc = new HashCollection();
hc.min = new Long(next).intValue();
long nextMax = new Long(hc.min).longValue() + new Long(chunckSpan).longValue();
if (nextMax >= Integer.MAX_VALUE) {
hc.max = Integer.MAX_VALUE;
} else {
hc.max = new Long(nextMax).intValue();
}
hc.depth = (short) (depth + 1);
hc.max_depth = max_depth;
hc.span = chunckSpan;
/*
System.out.println(this.getClass().getName() + " in split adding " + hc +
" nextMax was " + nextMax);
*/
//System.out.println(this.getClass().getName() + " in split adding bucket " + hc);
splits[bucket] = hc;
bucket++;
next = hc.max + 1;
}
}
I_Iterator it = objects.getIterator();
int counter = 0;
while (it.hasNext()) {
Object obj = it.next();
HashLocation objHash = (HashLocation) hashToLocations.get(counter);
putObjectInternal(chunckSpan, obj, objHash.getHash(), put);
counter++;
}
//add the new one
putObjectInternal(chunckSpan, p, hash, put);
}
private void putObjectInternal(int chunckSpan, Object obj,
int objHash, boolean put) {
Integer bucket = getBucket(objHash, min, max, chunckSpan);
HashCollection hc = (HashCollection) splits[bucket.intValue()];
if (hc == null) {
throw new NullPointerException("No HashContainer found for bucket " + bucket);
}
if (put) {
hc.put(obj);
} else {
hc.add(obj);
}
}
public static int getSpan(long p_totalSpan, long p_chunckSize) {
double d = p_totalSpan / p_chunckSize;
/*
System.out.println(HashContainer.class.getClass().getName() + " " + p_totalSpan + "/" +
p_chunckSize + " is " + d);
*/
return new Double(d).intValue();
}
/**
* this should return the hash bucket
*
* @param hashCode the hash code
* @param min the min hash code for the container
* @param max the max hash code for the container
* @param span the numbers(size) of a hashBucket
* @return
*/
public static Integer getBucket(int hashCode, int min, int max, int span) {
if (hashCode < min) {
return null;
}
if (hashCode > max) {
return null;
}
int currentBucket = 0;
long currentLong = min;
while (currentLong < max) {
long next = currentLong + span;
/*
System.out.println(HashContainer.class + " in getBucket hashCode = " +
hashCode + " min = " + min + " next = " + next );
*/
if (hashCode <= next) {
return new Integer(currentBucket);
}
currentLong = currentLong + span + 1;
currentBucket++;
/*
System.out.println(HashContainer.class + " in getBucket currentBucket = " +
currentBucket + " currentLong = " + currentLong);
*/
}
return null;
}
public Object get(int hash) {
if (containsObjects) {
if (hashToLocations == null) {
return null;
}
I_Iterator it = hashToLocations.getIterator();
while (it.hasNext()) {
HashLocation hl = (HashLocation) it.next();
if (hash == hl.getHash()) {
return objects.get(hl.getLocation());
}
}
} else {
int chunckSpan = getSpan(span, bucketsFromSplit);
Integer bucket = getBucket(hash, min, max, chunckSpan);
HashCollection hc = (HashCollection) splits[bucket.intValue()];
return hc.get(hash);
}
return null;
}
public synchronized boolean remove(int hash) {
if (containsObjects) {
I_Iterator it = hashToLocations.getIterator();
while (it.hasNext()) {
HashLocation hl = (HashLocation) it.next();
if (hash == hl.getHash()) {
Object obj = objects.get(hl.getLocation());
objects.remove(obj);
hashToLocations.clear();
//rehash
I_Iterator itRH = objects.getIterator();
int locationCounter = 0;
while (itRH.hasNext()) {
Object o = itRH.next();
hashToLocations.add(new HashLocation(o.hashCode(), locationCounter));
locationCounter++;
}
return true;
}
}
} else {
for (int i = 0; i < splits.length; i++) {
int chunckSpan = getSpan(span, bucketsFromSplit);
Integer bucket = getBucket(hash, min, max, chunckSpan);
HashCollection hc = (HashCollection) splits[bucket.intValue()];
return hc.remove(hash);
}
}
return false;
}
public void clear() {
containsObjects = true;
hashToLocations = new ArrayCollection();
objects = new ArrayCollection();
splits = null;
}
public String toString() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < depth; i++) {
sb.append("\t");
}
sb.append(super.toString());
sb.append("[min=");
sb.append(min);
sb.append(",max=");
sb.append(max);
if (containsObjects) {
sb.append(",objects=");
sb.append(objects);
sb.append(",hashToLocations=");
sb.append(hashToLocations);
} else {
sb.append(",splits;\n");
for (int i = 0; i < splits.length; i++) {
//null should only happen during debugging
if (splits[i] != null) {
if (splits[i].size() > 0) {
sb.append(splits[i]);
sb.append("\n");
}
}
}
}
sb.append("]");
return sb.toString();
}
public boolean contains(Object other) {
if (other == null) {
return false;
}
Object mine = get(other.hashCode());
if (other.equals(mine)) {
return true;
}
return false;
}
public I_Iterator getIterator() {
Object[] objs = getObjects();
return new ArrayIterator(objs);
}
private Object[] getObjects() {
Object[] objs = new Object[size()];
if (containsObjects) {
objs = objects.toArray();
} else {
int counter = 0;
for (int i = 0; i < splits.length; i++) {
Object[] child = splits[i].getObjects();
for (int j = 0; j < child.length; j++) {
objs[counter] = child[j];
counter++;
}
}
}
return objs;
}
public boolean remove(Object o) {
return remove(((Integer) o).intValue());
}
public int size() {
if (containsObjects) {
if (objects == null) {
return 0;
}
return objects.size();
} else {
int total = 0;
for (int i = 0; i < splits.length; i++) {
total = total + splits[i].size();
}
return total;
}
}
public Object getWrapped() {
return this;
}
} |
package org.apache.xerces.impl;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.QName;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.impl.io.UCSReader;
import org.apache.xerces.util.XMLStringBuffer;
import java.io.IOException;
import java.io.EOFException;
import java.util.Locale;
/**
* Implements the entity scanner methods.
*
* @author Andy Clark, IBM
* @author Neil Graham, IBM
* @version $Id$
*/
public class XMLEntityScanner implements XMLLocator {
// constants
private static final boolean DEBUG_ENCODINGS = false;
private static final boolean DEBUG_BUFFER = false;
private XMLEntityManager fEntityManager = null;
protected XMLEntityManager.ScannedEntity fCurrentEntity = null;
protected SymbolTable fSymbolTable = null;
protected int fBufferSize = XMLEntityManager.DEFAULT_BUFFER_SIZE;
// Constructors
/** Default constructor. */
public XMLEntityScanner( ) {
} // <init>()
// XMLEntityScanner methods
/**
* Returns the base system identifier of the currently scanned
* entity, or null if none is available.
*/
public String getBaseSystemId() {
return (fCurrentEntity != null && fCurrentEntity.entityLocation != null) ? fCurrentEntity.entityLocation.getExpandedSystemId() : null;
} // getBaseSystemId():String
/**
* Sets the encoding of the scanner. This method is used by the
* scanners if the XMLDecl or TextDecl line contains an encoding
* pseudo-attribute.
* <p>
* <strong>Note:</strong> The underlying character reader on the
* current entity will be changed to accomodate the new encoding.
* However, the new encoding is ignored if the current reader was
* not constructed from an input stream (e.g. an external entity
* that is resolved directly to the appropriate java.io.Reader
* object).
*
* @param encoding The IANA encoding name of the new encoding.
*
* @throws IOException Thrown if the new encoding is not supported.
*
* @see org.apache.xerces.util.EncodingMap
*/
public void setEncoding(String encoding) throws IOException {
if (DEBUG_ENCODINGS) {
System.out.println("$$$ setEncoding: "+encoding);
}
if (fCurrentEntity.stream != null) {
// if the encoding is the same, don't change the reader and
// re-use the original reader used by the OneCharReader
// NOTE: Besides saving an object, this overcomes deficiencies
// in the UTF-16 reader supplied with the standard Java
// distribution (up to and including 1.3). The UTF-16
// decoder buffers 8K blocks even when only asked to read
// a single char! -Ac
if (fCurrentEntity.encoding == null ||
!fCurrentEntity.encoding.equals(encoding)) {
// UTF-16 is a bit of a special case. If the encoding is UTF-16,
// and we know the endian-ness, we shouldn't change readers.
// If it's ISO-10646-UCS-(2|4), then we'll have to deduce
// the endian-ness from the encoding we presently have.
if(fCurrentEntity.encoding != null && fCurrentEntity.encoding.startsWith("UTF-16")) {
String ENCODING = encoding.toUpperCase(Locale.ENGLISH);
if(ENCODING.equals("UTF-16")) return;
if(ENCODING.equals("ISO-10646-UCS-4")) {
if(fCurrentEntity.encoding.equals("UTF-16BE")) {
fCurrentEntity.reader = new UCSReader(fCurrentEntity.stream, UCSReader.UCS4BE);
} else {
fCurrentEntity.reader = new UCSReader(fCurrentEntity.stream, UCSReader.UCS4LE);
}
return;
}
if(ENCODING.equals("ISO-10646-UCS-2")) {
if(fCurrentEntity.encoding.equals("UTF-16BE")) {
fCurrentEntity.reader = new UCSReader(fCurrentEntity.stream, UCSReader.UCS2BE);
} else {
fCurrentEntity.reader = new UCSReader(fCurrentEntity.stream, UCSReader.UCS2LE);
}
return;
}
}
// wrap a new reader around the input stream, changing
// the encoding
if (DEBUG_ENCODINGS) {
System.out.println("$$$ creating new reader from stream: "+
fCurrentEntity.stream);
}
//fCurrentEntity.stream.reset();
fCurrentEntity.setReader(fCurrentEntity.stream, encoding, null);
} else {
if (DEBUG_ENCODINGS)
System.out.println("$$$ reusing old reader on stream");
}
}
} // setEncoding(String)
/** Returns true if the current entity being scanned is external. */
public boolean isExternal() {
return fCurrentEntity.isExternal();
} // isExternal():boolean
/**
* Returns the next character on the input.
* <p>
* <strong>Note:</strong> The character is <em>not</em> consumed.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public int peekChar() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(peekChar: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// peek at character
int c = fCurrentEntity.ch[fCurrentEntity.position];
// return peeked character
if (DEBUG_BUFFER) {
System.out.print(")peekChar: ");
XMLEntityManager.print(fCurrentEntity);
if (fCurrentEntity.isExternal()) {
System.out.println(" -> '"+(c!='\r'?(char)c:'\n')+"'");
}
else {
System.out.println(" -> '"+(char)c+"'");
}
}
if (fCurrentEntity.isExternal()) {
return c != '\r' ? c : '\n';
}
else {
return c;
}
} // peekChar():int
/**
* Returns the next character on the input.
* <p>
* <strong>Note:</strong> The character is consumed.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public int scanChar() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanChar: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// scan character
int c = fCurrentEntity.ch[fCurrentEntity.position++];
boolean external = false;
if (c == '\n' ||
(c == '\r' && (external = fCurrentEntity.isExternal()))) {
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.ch[0] = (char)c;
load(1, false);
}
if (c == '\r' && external) {
if (fCurrentEntity.ch[fCurrentEntity.position++] != '\n') {
fCurrentEntity.position
}
c = '\n';
}
}
// return character that was scanned
if (DEBUG_BUFFER) {
System.out.print(")scanChar: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> '"+(char)c+"'");
}
fCurrentEntity.columnNumber++;
return c;
} // scanChar():int
/**
* Returns a string matching the NMTOKEN production appearing immediately
* on the input as a symbol, or null if NMTOKEN Name string is present.
* <p>
* <strong>Note:</strong> The NMTOKEN characters are consumed.
* <p>
* <strong>Note:</strong> The string returned must be a symbol. The
* SymbolTable can be used for this purpose.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*
* @see org.apache.xerces.util.SymbolTable
* @see org.apache.xerces.util.XMLChar#isName
*/
public String scanNmtoken() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanNmtoken: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// scan nmtoken
int offset = fCurrentEntity.position;
while (XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) {
if (++fCurrentEntity.position == fCurrentEntity.count) {
int length = fCurrentEntity.position - offset;
if (length == fBufferSize) {
// bad luck we have to resize our buffer
char[] tmp = new char[fBufferSize * 2];
System.arraycopy(fCurrentEntity.ch, offset,
tmp, 0, length);
fCurrentEntity.ch = tmp;
fBufferSize *= 2;
}
else {
System.arraycopy(fCurrentEntity.ch, offset,
fCurrentEntity.ch, 0, length);
}
offset = 0;
if (load(length, false)) {
break;
}
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length;
// return nmtoken
String symbol = null;
if (length > 0) {
symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, offset, length);
}
if (DEBUG_BUFFER) {
System.out.print(")scanNmtoken: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> "+String.valueOf(symbol));
}
return symbol;
} // scanNmtoken():String
/**
* Returns a string matching the Name production appearing immediately
* on the input as a symbol, or null if no Name string is present.
* <p>
* <strong>Note:</strong> The Name characters are consumed.
* <p>
* <strong>Note:</strong> The string returned must be a symbol. The
* SymbolTable can be used for this purpose.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*
* @see org.apache.xerces.util.SymbolTable
* @see org.apache.xerces.util.XMLChar#isName
* @see org.apache.xerces.util.XMLChar#isNameStart
*/
public String scanName() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanName: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// scan name
int offset = fCurrentEntity.position;
if (XMLChar.isNameStart(fCurrentEntity.ch[offset])) {
if (++fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.ch[0] = fCurrentEntity.ch[offset];
offset = 0;
if (load(1, false)) {
fCurrentEntity.columnNumber++;
String symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, 0, 1);
if (DEBUG_BUFFER) {
System.out.print(")scanName: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> "+String.valueOf(symbol));
}
return symbol;
}
}
while (XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) {
if (++fCurrentEntity.position == fCurrentEntity.count) {
int length = fCurrentEntity.position - offset;
if (length == fBufferSize) {
// bad luck we have to resize our buffer
char[] tmp = new char[fBufferSize * 2];
System.arraycopy(fCurrentEntity.ch, offset,
tmp, 0, length);
fCurrentEntity.ch = tmp;
fBufferSize *= 2;
}
else {
System.arraycopy(fCurrentEntity.ch, offset,
fCurrentEntity.ch, 0, length);
}
offset = 0;
if (load(length, false)) {
break;
}
}
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length;
// return name
String symbol = null;
if (length > 0) {
symbol = fSymbolTable.addSymbol(fCurrentEntity.ch, offset, length);
}
if (DEBUG_BUFFER) {
System.out.print(")scanName: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> "+String.valueOf(symbol));
}
return symbol;
} // scanName():String
/**
* Scans a qualified name from the input, setting the fields of the
* QName structure appropriately.
* <p>
* <strong>Note:</strong> The qualified name characters are consumed.
* <p>
* <strong>Note:</strong> The strings used to set the values of the
* QName structure must be symbols. The SymbolTable can be used for
* this purpose.
*
* @param qname The qualified name structure to fill.
*
* @return Returns true if a qualified name appeared immediately on
* the input and was scanned, false otherwise.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*
* @see org.apache.xerces.util.SymbolTable
* @see org.apache.xerces.util.XMLChar#isName
* @see org.apache.xerces.util.XMLChar#isNameStart
*/
public boolean scanQName(QName qname) throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanQName, "+qname+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// scan qualified name
int offset = fCurrentEntity.position;
if (XMLChar.isNameStart(fCurrentEntity.ch[offset])) {
if (++fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.ch[0] = fCurrentEntity.ch[offset];
offset = 0;
if (load(1, false)) {
fCurrentEntity.columnNumber++;
String name =
fSymbolTable.addSymbol(fCurrentEntity.ch, 0, 1);
qname.setValues(null, name, name, null);
if (DEBUG_BUFFER) {
System.out.print(")scanQName, "+qname+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> true");
}
return true;
}
}
int index = -1;
while (XMLChar.isName(fCurrentEntity.ch[fCurrentEntity.position])) {
char c = fCurrentEntity.ch[fCurrentEntity.position];
if (c == ':') {
if (index != -1) {
break;
}
index = fCurrentEntity.position;
}
if (++fCurrentEntity.position == fCurrentEntity.count) {
int length = fCurrentEntity.position - offset;
if (length == fBufferSize) {
// bad luck we have to resize our buffer
char[] tmp = new char[fBufferSize * 2];
System.arraycopy(fCurrentEntity.ch, offset,
tmp, 0, length);
fCurrentEntity.ch = tmp;
fBufferSize *= 2;
}
else {
System.arraycopy(fCurrentEntity.ch, offset,
fCurrentEntity.ch, 0, length);
}
if (index != -1) {
index = index - offset;
}
offset = 0;
if (load(length, false)) {
break;
}
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length;
if (length > 0) {
String prefix = null;
String localpart = null;
String rawname = fSymbolTable.addSymbol(fCurrentEntity.ch,
offset, length);
if (index != -1) {
int prefixLength = index - offset;
prefix = fSymbolTable.addSymbol(fCurrentEntity.ch,
offset, prefixLength);
int len = length - prefixLength - 1;
localpart = fSymbolTable.addSymbol(fCurrentEntity.ch,
index + 1, len);
}
else {
localpart = rawname;
}
qname.setValues(prefix, localpart, rawname, null);
if (DEBUG_BUFFER) {
System.out.print(")scanQName, "+qname+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> true");
}
return true;
}
}
// no qualified name found
if (DEBUG_BUFFER) {
System.out.print(")scanQName, "+qname+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> false");
}
return false;
} // scanQName(QName):boolean
/**
* Scans a range of parsed character data, setting the fields of the
* XMLString structure, appropriately.
* <p>
* <strong>Note:</strong> The characters are consumed.
* <p>
* <strong>Note:</strong> This method does not guarantee to return
* the longest run of parsed character data. This method may return
* before markup due to reaching the end of the input buffer or any
* other reason.
* <p>
* <strong>Note:</strong> The fields contained in the XMLString
* structure are not guaranteed to remain valid upon subsequent calls
* to the entity scanner. Therefore, the caller is responsible for
* immediately using the returned character data or making a copy of
* the character data.
*
* @param content The content structure to fill.
*
* @return Returns the next character on the input, if known. This
* value may be -1 but this does <em>note</em> designate
* end of file.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public int scanContent(XMLString content) throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanContent: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
else if (fCurrentEntity.position == fCurrentEntity.count - 1) {
fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1];
load(1, false);
fCurrentEntity.position = 0;
}
// normalize newlines
int offset = fCurrentEntity.position;
int c = fCurrentEntity.ch[offset];
int newlines = 0;
boolean external = fCurrentEntity.isExternal();
if (c == '\n' || (c == '\r' && external)) {
if (DEBUG_BUFFER) {
System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
do {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == '\r' && external) {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
offset++;
}
/*** NEWLINE NORMALIZATION ***/
else {
newlines++;
}
}
else if (c == '\n') {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
}
else {
fCurrentEntity.position
break;
}
} while (fCurrentEntity.position < fCurrentEntity.count - 1);
for (int i = offset; i < fCurrentEntity.position; i++) {
fCurrentEntity.ch[i] = '\n';
}
int length = fCurrentEntity.position - offset;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
content.setValues(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
return -1;
}
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
}
// inner loop, scanning for content
while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (!XMLChar.isContent(c)) {
fCurrentEntity.position
break;
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
content.setValues(fCurrentEntity.ch, offset, length);
// return next character
if (fCurrentEntity.position != fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position];
// REVISIT: Does this need to be updated to fix the
// #x0D ^#x0A newline normalization problem? -Ac
if (c == '\r' && external) {
c = '\n';
}
}
else {
c = -1;
}
if (DEBUG_BUFFER) {
System.out.print(")scanContent: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> '"+(char)c+"'");
}
return c;
} // scanContent(XMLString):int
/**
* Scans a range of attribute value data, setting the fields of the
* XMLString structure, appropriately.
* <p>
* <strong>Note:</strong> The characters are consumed.
* <p>
* <strong>Note:</strong> This method does not guarantee to return
* the longest run of attribute value data. This method may return
* before the quote character due to reaching the end of the input
* buffer or any other reason.
* <p>
* <strong>Note:</strong> The fields contained in the XMLString
* structure are not guaranteed to remain valid upon subsequent calls
* to the entity scanner. Therefore, the caller is responsible for
* immediately using the returned character data or making a copy of
* the character data.
*
* @param quote The quote character that signifies the end of the
* attribute value data.
* @param content The content structure to fill.
*
* @return Returns the next character on the input, if known. This
* value may be -1 but this does <em>note</em> designate
* end of file.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public int scanLiteral(int quote, XMLString content)
throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(scanLiteral, '"+(char)quote+"': ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
else if (fCurrentEntity.position == fCurrentEntity.count - 1) {
fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1];
load(1, false);
fCurrentEntity.position = 0;
}
// normalize newlines
int offset = fCurrentEntity.position;
int c = fCurrentEntity.ch[offset];
int newlines = 0;
boolean external = fCurrentEntity.isExternal();
if (c == '\n' || (c == '\r' && external)) {
if (DEBUG_BUFFER) {
System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
do {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == '\r' && external) {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
offset++;
}
/*** NEWLINE NORMALIZATION ***/
else {
newlines++;
}
}
else if (c == '\n') {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
}
else {
fCurrentEntity.position
break;
}
} while (fCurrentEntity.position < fCurrentEntity.count - 1);
for (int i = offset; i < fCurrentEntity.position; i++) {
fCurrentEntity.ch[i] = '\n';
}
int length = fCurrentEntity.position - offset;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
content.setValues(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
return -1;
}
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
}
// scan literal value
while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if ((c == quote &&
(!fCurrentEntity.literal || external))
|| c == '%' || !XMLChar.isContent(c)) {
fCurrentEntity.position
break;
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
content.setValues(fCurrentEntity.ch, offset, length);
// return next character
if (fCurrentEntity.position != fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position];
// NOTE: We don't want to accidentally signal the
// end of the literal if we're expanding an
// entity appearing in the literal. -Ac
if (c == quote && fCurrentEntity.literal) {
c = -1;
}
}
else {
c = -1;
}
if (DEBUG_BUFFER) {
System.out.print(")scanLiteral, '"+(char)quote+"': ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> '"+(char)c+"'");
}
return c;
} // scanLiteral(int,XMLString):int
/**
* Scans a range of character data up to the specified delimiter,
* setting the fields of the XMLString structure, appropriately.
* <p>
* <strong>Note:</strong> The characters are consumed.
* <p>
* <strong>Note:</strong> This assumes that the internal buffer is
* at least the same size, or bigger, than the length of the delimiter
* and that the delimiter contains at least one character.
* <p>
* <strong>Note:</strong> This method does not guarantee to return
* the longest run of character data. This method may return before
* the delimiter due to reaching the end of the input buffer or any
* other reason.
* <p>
* <strong>Note:</strong> The fields contained in the XMLString
* structure are not guaranteed to remain valid upon subsequent calls
* to the entity scanner. Therefore, the caller is responsible for
* immediately using the returned character data or making a copy of
* the character data.
*
* @param delimiter The string that signifies the end of the character
* data to be scanned.
* @param data The data structure to fill.
*
* @return Returns true if there is more data to scan, false otherwise.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public boolean scanData(String delimiter, XMLStringBuffer buffer)
throws IOException {
// REVISIT: This method does not need to use a string buffer.
// The change would avoid the array copies and increase
// performance. -Ac
// Currently, this method is called for scanning CDATA
// sections, comments, and processing instruction data.
// So if this code is updated to NOT buffer, the scanning
// code for comments and processing instructions will
// need to be updated to do its own buffering. The code
// for CDATA sections is safe as-is. -Ac
boolean found = false;
int delimLen = delimiter.length();
char charAt0 = delimiter.charAt(0);
boolean external = fCurrentEntity.isExternal();
if (DEBUG_BUFFER) {
System.out.print("(scanData: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
boolean bNextEntity = false;
while ((fCurrentEntity.position >= fCurrentEntity.count - delimLen)
&& (!bNextEntity))
{
System.arraycopy(fCurrentEntity.ch,
fCurrentEntity.position,
fCurrentEntity.ch,
0,
fCurrentEntity.count - fCurrentEntity.position);
bNextEntity = load(fCurrentEntity.count - fCurrentEntity.position, false);
fCurrentEntity.position = 0;
}
if (fCurrentEntity.position >= fCurrentEntity.count - delimLen) {
// something must be wrong with the input: e.g., file ends an unterminated comment
int length = fCurrentEntity.count - fCurrentEntity.position;
buffer.append (fCurrentEntity.ch, fCurrentEntity.position, length);
fCurrentEntity.columnNumber += fCurrentEntity.count;
fCurrentEntity.position = fCurrentEntity.count;
load(0,true);
return false;
}
// normalize newlines
int offset = fCurrentEntity.position;
int c = fCurrentEntity.ch[offset];
int newlines = 0;
if (c == '\n' || (c == '\r' && external)) {
if (DEBUG_BUFFER) {
System.out.print("[newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
do {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == '\r' && external) {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
if (load(newlines, false)) {
break;
}
}
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
offset++;
}
/*** NEWLINE NORMALIZATION ***/
else {
newlines++;
}
}
else if (c == '\n') {
newlines++;
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count) {
offset = 0;
fCurrentEntity.position = newlines;
fCurrentEntity.count = newlines;
if (load(newlines, false)) {
break;
}
}
}
else {
fCurrentEntity.position
break;
}
} while (fCurrentEntity.position < fCurrentEntity.count - 1);
for (int i = offset; i < fCurrentEntity.position; i++) {
fCurrentEntity.ch[i] = '\n';
}
int length = fCurrentEntity.position - offset;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
buffer.append(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
return true;
}
if (DEBUG_BUFFER) {
System.out.print("]newline, "+offset+", "+fCurrentEntity.position+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
}
// iterate over buffer looking for delimiter
OUTER: while (fCurrentEntity.position < fCurrentEntity.count) {
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c == charAt0) {
// looks like we just hit the delimiter
int delimOffset = fCurrentEntity.position - 1;
for (int i = 1; i < delimLen; i++) {
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.position -= i;
break OUTER;
}
c = fCurrentEntity.ch[fCurrentEntity.position++];
if (delimiter.charAt(i) != c) {
fCurrentEntity.position
break;
}
}
if (fCurrentEntity.position == delimOffset + delimLen) {
found = true;
break;
}
}
else if (c == '\n' || (external && c == '\r')) {
fCurrentEntity.position
break;
}
else if (XMLChar.isInvalid(c)) {
fCurrentEntity.position
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
buffer.append(fCurrentEntity.ch, offset, length);
return true;
}
}
int length = fCurrentEntity.position - offset;
fCurrentEntity.columnNumber += length - newlines;
if (found) {
length -= delimLen;
}
buffer.append (fCurrentEntity.ch, offset, length);
// return true if string was skipped
if (DEBUG_BUFFER) {
System.out.print(")scanData: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> " + !found);
}
return !found;
} // scanData(String,XMLString):boolean
/**
* Skips a character appearing immediately on the input.
* <p>
* <strong>Note:</strong> The character is consumed only if it matches
* the specified character.
*
* @param c The character to skip.
*
* @return Returns true if the character was skipped.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public boolean skipChar(int c) throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(skipChar, '"+(char)c+"': ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip character
int cc = fCurrentEntity.ch[fCurrentEntity.position];
if (cc == c) {
fCurrentEntity.position++;
if (c == '\n') {
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
}
else {
fCurrentEntity.columnNumber++;
}
if (DEBUG_BUFFER) {
System.out.print(")skipChar, '"+(char)c+"': ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> true");
}
return true;
}
else if (c == '\n' && cc == '\r' && fCurrentEntity.isExternal()) {
// handle newlines
if (fCurrentEntity.position == fCurrentEntity.count) {
fCurrentEntity.ch[0] = (char)cc;
load(1, false);
}
fCurrentEntity.position++;
if (fCurrentEntity.ch[fCurrentEntity.position] == '\n') {
fCurrentEntity.position++;
}
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (DEBUG_BUFFER) {
System.out.print(")skipChar, '"+(char)c+"': ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> true");
}
return true;
}
// character was not skipped
if (DEBUG_BUFFER) {
System.out.print(")skipChar, '"+(char)c+"': ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> false");
}
return false;
} // skipChar(int):boolean
/**
* Skips space characters appearing immediately on the input.
* <p>
* <strong>Note:</strong> The characters are consumed only if they are
* space characters.
*
* @return Returns true if at least one space character was skipped.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*
* @see org.apache.xerces.util.XMLChar#isSpace
*/
public boolean skipSpaces() throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(skipSpaces: ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip spaces
int c = fCurrentEntity.ch[fCurrentEntity.position];
if (XMLChar.isSpace(c)) {
boolean external = fCurrentEntity.isExternal();
do {
boolean entityChanged = false;
// handle newlines
if (c == '\n' || (external && c == '\r')) {
fCurrentEntity.lineNumber++;
fCurrentEntity.columnNumber = 1;
if (fCurrentEntity.position == fCurrentEntity.count - 1) {
fCurrentEntity.ch[0] = (char)c;
entityChanged = load(1, true);
if (!entityChanged)
// the load change the position to be 1,
// need to restore it when entity not changed
fCurrentEntity.position = 0;
}
if (c == '\r' && external) {
// REVISIT: Does this need to be updated to fix the
// #x0D ^#x0A newline normalization problem? -Ac
if (fCurrentEntity.ch[++fCurrentEntity.position] != '\n') {
fCurrentEntity.position
}
}
/**
* Skips the specified string appearing immediately on the input.
* <p>
* <strong>Note:</strong> The characters are consumed only if they are
* space characters.
*
* @param s The string to skip.
*
* @return Returns true if the string was skipped.
*
* @throws IOException Thrown if i/o error occurs.
* @throws EOFException Thrown on end of file.
*/
public boolean skipString(String s) throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(skipString, \""+s+"\": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip string
final int length = s.length();
for (int i = 0; i < length; i++) {
char c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c != s.charAt(i)) {
fCurrentEntity.position -= i + 1;
if (DEBUG_BUFFER) {
System.out.print(")skipString, \""+s+"\": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> false");
}
return false;
}
if (i < length - 1 && fCurrentEntity.position == fCurrentEntity.count) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.count - i - 1, fCurrentEntity.ch, 0, i + 1);
// REVISIT: Can a string to be skipped cross an
// entity boundary? -Ac
if (load(i + 1, false)) {
fCurrentEntity.position -= i + 1;
if (DEBUG_BUFFER) {
System.out.print(")skipString, \""+s+"\": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> false");
}
return false;
}
}
}
if (DEBUG_BUFFER) {
System.out.print(")skipString, \""+s+"\": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println(" -> true");
}
fCurrentEntity.columnNumber += length;
return true;
} // skipString(String):boolean
// Locator methods
/**
* Return the public identifier for the current document event.
* <p>
* The return value is the public identifier of the document
* entity or of the external parsed entity in which the markup
* triggering the event appears.
*
* @return A string containing the public identifier, or
* null if none is available.
*/
public String getPublicId() {
return (fCurrentEntity != null && fCurrentEntity.entityLocation != null) ? fCurrentEntity.entityLocation.getPublicId() : null;
} // getPublicId():String
/**
* Return the expanded system identifier for the current document event.
* <p>
* The return value is the expanded system identifier of the document
* entity or of the external parsed entity in which the markup
* triggering the event appears.
* <p>
* If the system identifier is a URL, the parser must resolve it
* fully before passing it to the application.
*
* @return A string containing the expanded system identifier, or null
* if none is available.
*/
public String getExpandedSystemId() {
if (fCurrentEntity != null) {
if (fCurrentEntity.entityLocation != null &&
fCurrentEntity.entityLocation.getExpandedSystemId() != null ) {
return fCurrentEntity.entityLocation.getExpandedSystemId();
}
else {
// get the current entity to return something appropriate:
return fCurrentEntity.getExpandedSystemId();
}
}
return null;
} // getExpandedSystemId():String
/**
* Return the literal system identifier for the current document event.
* <p>
* The return value is the literal system identifier of the document
* entity or of the external parsed entity in which the markup
* triggering the event appears.
* <p>
* @return A string containing the literal system identifier, or null
* if none is available.
*/
public String getLiteralSystemId() {
if (fCurrentEntity != null) {
if (fCurrentEntity.entityLocation != null &&
fCurrentEntity.entityLocation.getLiteralSystemId() != null ) {
return fCurrentEntity.entityLocation.getLiteralSystemId();
}
else {
// get the current entity to do it:
return fCurrentEntity.getLiteralSystemId();
}
}
return null;
} // getLiteralSystemId():String
/**
* Return the line number where the current document event ends.
* <p>
* <strong>Warning:</strong> The return value from the method
* is intended only as an approximation for the sake of error
* reporting; it is not intended to provide sufficient information
* to edit the character content of the original XML document.
* <p>
* The return value is an approximation of the line number
* in the document entity or external parsed entity where the
* markup triggering the event appears.
* <p>
* If possible, the SAX driver should provide the line position
* of the first character after the text associated with the document
* event. The first line in the document is line 1.
*
* @return The line number, or -1 if none is available.
*/
public int getLineNumber() {
if (fCurrentEntity != null) {
if (fCurrentEntity.isExternal()) {
return fCurrentEntity.lineNumber;
}
else {
// ask the current entity to return something appropriate:
return fCurrentEntity.getLineNumber();
}
}
return -1;
} // getLineNumber():int
/**
* Return the column number where the current document event ends.
* <p>
* <strong>Warning:</strong> The return value from the method
* is intended only as an approximation for the sake of error
* reporting; it is not intended to provide sufficient information
* to edit the character content of the original XML document.
* <p>
* The return value is an approximation of the column number
* in the document entity or external parsed entity where the
* markup triggering the event appears.
* <p>
* If possible, the SAX driver should provide the line position
* of the first character after the text associated with the document
* event.
* <p>
* If possible, the SAX driver should provide the line position
* of the first character after the text associated with the document
* event. The first column in each line is column 1.
*
* @return The column number, or -1 if none is available.
*/
public int getColumnNumber() {
if (fCurrentEntity != null) {
if (fCurrentEntity.isExternal()) {
return fCurrentEntity.columnNumber;
}
else {
// ask current entity to find appropriate column number
return fCurrentEntity.getColumnNumber();
}
}
return -1;
} // getColumnNumber():int
/**
* @see org.apache.xerces.xni.XMLLocator#setColumnNumber(int)
*/
public void setColumnNumber(int col) {
// no-op
}
/**
* @see org.apache.xerces.xni.XMLLocator#setLineNumber(int)
*/
public void setLineNumber(int line) {
//no-op
}
/**
* @see org.apache.xerces.xni.XMLResourceIdentifier#setBaseSystemId(String)
*/
public void setBaseSystemId(String systemId) {
//no-op
}
/**
* @see org.apache.xerces.xni.XMLResourceIdentifier#setExpandedSystemId(String)
*/
public void setExpandedSystemId(String systemId) {
//no-op
}
/**
* @see org.apache.xerces.xni.XMLResourceIdentifier#setLiteralSystemId(String)
*/
public void setLiteralSystemId(String systemId) {
//no-op
}
/**
* @see org.apache.xerces.xni.XMLResourceIdentifier#setPublicId(String)
*/
public void setPublicId(String publicId) {
//no-op
}
// allow entity manager to tell us what the current entityis:
public void setCurrentEntity(XMLEntityManager.ScannedEntity ent) {
fCurrentEntity = ent;
}
// set buffer size:
public void setBufferSize(int size) {
fBufferSize = size;
}
// reset what little state we have...
public void reset(SymbolTable symbolTable, XMLEntityManager entityManager) {
fCurrentEntity = null;
fSymbolTable = symbolTable;
fEntityManager = entityManager;
}
// Private methods
/**
* Loads a chunk of text.
*
* @param offset The offset into the character buffer to
* read the next batch of characters.
* @param changeEntity True if the load should change entities
* at the end of the entity, otherwise leave
* the current entity in place and the entity
* boundary will be signaled by the return
* value.
*
* @returns Returns true if the entity changed as a result of this
* load operation.
*/
final boolean load(int offset, boolean changeEntity)
throws IOException {
if (DEBUG_BUFFER) {
System.out.print("(load, "+offset+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
// read characters
int length = fCurrentEntity.mayReadChunks?
(fCurrentEntity.ch.length - offset):
(XMLEntityManager.DEFAULT_XMLDECL_BUFFER_SIZE);
if (DEBUG_BUFFER) System.out.println(" length to try to read: "+length);
int count = fCurrentEntity.reader.read(fCurrentEntity.ch, offset, length);
if (DEBUG_BUFFER) System.out.println(" length actually read: "+count);
// reset count and position
boolean entityChanged = false;
if (count != -1) {
if (count != 0) {
fCurrentEntity.count = count + offset;
fCurrentEntity.position = offset;
}
}
// end of this entity
else {
fCurrentEntity.count = offset;
fCurrentEntity.position = offset;
entityChanged = true;
if (changeEntity) {
fEntityManager.endEntity();
if (fCurrentEntity == null) {
throw new EOFException();
}
// handle the trailing edges
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
}
}
if (DEBUG_BUFFER) {
System.out.print(")load, "+offset+": ");
XMLEntityManager.print(fCurrentEntity);
System.out.println();
}
return entityChanged;
} // load(int, boolean):boolean
} // class XMLEntityScanner |
package org.bouncycastle.cms;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.AttributeCertificate;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jce.interfaces.GOST3410PrivateKey;
import org.bouncycastle.util.Store;
import org.bouncycastle.x509.X509AttributeCertificate;
import org.bouncycastle.x509.X509Store;
public class CMSSignedGenerator
{
/**
* Default type for the signed data.
*/
public static final String DATA = CMSObjectIdentifiers.data.getId();
public static final String DIGEST_SHA1 = OIWObjectIdentifiers.idSHA1.getId();
public static final String DIGEST_SHA224 = NISTObjectIdentifiers.id_sha224.getId();
public static final String DIGEST_SHA256 = NISTObjectIdentifiers.id_sha256.getId();
public static final String DIGEST_SHA384 = NISTObjectIdentifiers.id_sha384.getId();
public static final String DIGEST_SHA512 = NISTObjectIdentifiers.id_sha512.getId();
public static final String DIGEST_MD5 = PKCSObjectIdentifiers.md5.getId();
public static final String DIGEST_GOST3411 = CryptoProObjectIdentifiers.gostR3411.getId();
public static final String DIGEST_RIPEMD128 = TeleTrusTObjectIdentifiers.ripemd128.getId();
public static final String DIGEST_RIPEMD160 = TeleTrusTObjectIdentifiers.ripemd160.getId();
public static final String DIGEST_RIPEMD256 = TeleTrusTObjectIdentifiers.ripemd256.getId();
public static final String ENCRYPTION_RSA = PKCSObjectIdentifiers.rsaEncryption.getId();
public static final String ENCRYPTION_DSA = X9ObjectIdentifiers.id_dsa_with_sha1.getId();
public static final String ENCRYPTION_ECDSA = X9ObjectIdentifiers.ecdsa_with_SHA1.getId();
public static final String ENCRYPTION_RSA_PSS = PKCSObjectIdentifiers.id_RSASSA_PSS.getId();
public static final String ENCRYPTION_GOST3410 = CryptoProObjectIdentifiers.gostR3410_94.getId();
public static final String ENCRYPTION_ECGOST3410 = CryptoProObjectIdentifiers.gostR3410_2001.getId();
private static final String ENCRYPTION_ECDSA_WITH_SHA1 = X9ObjectIdentifiers.ecdsa_with_SHA1.getId();
private static final String ENCRYPTION_ECDSA_WITH_SHA224 = X9ObjectIdentifiers.ecdsa_with_SHA224.getId();
private static final String ENCRYPTION_ECDSA_WITH_SHA256 = X9ObjectIdentifiers.ecdsa_with_SHA256.getId();
private static final String ENCRYPTION_ECDSA_WITH_SHA384 = X9ObjectIdentifiers.ecdsa_with_SHA384.getId();
private static final String ENCRYPTION_ECDSA_WITH_SHA512 = X9ObjectIdentifiers.ecdsa_with_SHA512.getId();
private static final Set NO_PARAMS = new HashSet();
private static final Map EC_ALGORITHMS = new HashMap();
static
{
NO_PARAMS.add(ENCRYPTION_DSA);
NO_PARAMS.add(ENCRYPTION_ECDSA);
NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA1);
NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA224);
NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA256);
NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA384);
NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA512);
EC_ALGORITHMS.put(DIGEST_SHA1, ENCRYPTION_ECDSA_WITH_SHA1);
EC_ALGORITHMS.put(DIGEST_SHA224, ENCRYPTION_ECDSA_WITH_SHA224);
EC_ALGORITHMS.put(DIGEST_SHA256, ENCRYPTION_ECDSA_WITH_SHA256);
EC_ALGORITHMS.put(DIGEST_SHA384, ENCRYPTION_ECDSA_WITH_SHA384);
EC_ALGORITHMS.put(DIGEST_SHA512, ENCRYPTION_ECDSA_WITH_SHA512);
}
protected List certs = new ArrayList();
protected List crls = new ArrayList();
protected List _signers = new ArrayList();
protected List signerGens = new ArrayList();
protected Map digests = new HashMap();
protected final SecureRandom rand;
/**
* base constructor
*/
protected CMSSignedGenerator()
{
this(new SecureRandom());
}
/**
* constructor allowing specific source of randomness
* @param rand instance of SecureRandom to use
*/
protected CMSSignedGenerator(
SecureRandom rand)
{
this.rand = rand;
}
protected String getEncOID(
PrivateKey key,
String digestOID)
{
String encOID = null;
if (key instanceof RSAPrivateKey || "RSA".equalsIgnoreCase(key.getAlgorithm()))
{
encOID = ENCRYPTION_RSA;
}
else if (key instanceof DSAPrivateKey || "DSA".equalsIgnoreCase(key.getAlgorithm()))
{
encOID = ENCRYPTION_DSA;
if (!digestOID.equals(DIGEST_SHA1))
{
throw new IllegalArgumentException("can't mix DSA with anything but SHA1");
}
}
else if ("ECDSA".equalsIgnoreCase(key.getAlgorithm()) || "EC".equalsIgnoreCase(key.getAlgorithm()))
{
encOID = (String)EC_ALGORITHMS.get(digestOID);
if (encOID == null)
{
throw new IllegalArgumentException("can't mix ECDSA with anything but SHA family digests");
}
}
else if (key instanceof GOST3410PrivateKey || "GOST3410".equalsIgnoreCase(key.getAlgorithm()))
{
encOID = ENCRYPTION_GOST3410;
}
else if ("ECGOST3410".equalsIgnoreCase(key.getAlgorithm()))
{
encOID = ENCRYPTION_ECGOST3410;
}
return encOID;
}
protected Map getBaseParameters(DERObjectIdentifier contentType, AlgorithmIdentifier digAlgId, byte[] hash)
{
Map param = new HashMap();
param.put(CMSAttributeTableGenerator.CONTENT_TYPE, contentType);
param.put(CMSAttributeTableGenerator.DIGEST_ALGORITHM_IDENTIFIER, digAlgId);
param.put(CMSAttributeTableGenerator.DIGEST, hash.clone());
return param;
}
protected ASN1Set getAttributeSet(
AttributeTable attr)
{
if (attr != null)
{
return new DERSet(attr.toASN1EncodableVector());
}
return null;
}
/**
* add the certificates and CRLs contained in the given CertStore
* to the pool that will be included in the encoded signature block.
* <p>
* Note: this assumes the CertStore will support null in the get
* methods.
* @param certStore CertStore containing the public key certificates and CRLs
* @throws java.security.cert.CertStoreException if an issue occurs processing the CertStore
* @throws CMSException if an issue occurse transforming data from the CertStore into the message
* @deprecated use addCertificates and addCRLs
*/
public void addCertificatesAndCRLs(
CertStore certStore)
throws CertStoreException, CMSException
{
certs.addAll(CMSUtils.getCertificatesFromStore(certStore));
crls.addAll(CMSUtils.getCRLsFromStore(certStore));
}
public void addCertificates(
Store certStore)
throws CMSException
{
certs.addAll(CMSUtils.getCertificatesFromStore(certStore));
}
public void addCRLs(
Store crlStore)
throws CMSException
{
crls.addAll(CMSUtils.getCRLsFromStore(crlStore));
}
public void addAttributeCertificates(
Store attrStore)
throws CMSException
{
certs.addAll(CMSUtils.getAttributeCertificatesFromStore(attrStore));
}
/**
* Add the attribute certificates contained in the passed in store to the
* generator.
*
* @param store a store of Version 2 attribute certificates
* @throws CMSException if an error occurse processing the store.
* @deprecated use basic Store method
*/
public void addAttributeCertificates(
X509Store store)
throws CMSException
{
try
{
for (Iterator it = store.getMatches(null).iterator(); it.hasNext();)
{
X509AttributeCertificate attrCert = (X509AttributeCertificate)it.next();
certs.add(new DERTaggedObject(false, 2,
AttributeCertificate.getInstance(ASN1Primitive.fromByteArray(attrCert.getEncoded()))));
}
}
catch (IllegalArgumentException e)
{
throw new CMSException("error processing attribute certs", e);
}
catch (IOException e)
{
throw new CMSException("error processing attribute certs", e);
}
}
/**
* Add a store of precalculated signers to the generator.
*
* @param signerStore store of signers
*/
public void addSigners(
SignerInformationStore signerStore)
{
Iterator it = signerStore.getSigners().iterator();
while (it.hasNext())
{
_signers.add(it.next());
}
}
public void addSignerInfoGenerator(SignerInfoGenerator infoGen)
{
signerGens.add(infoGen);
}
/**
* Return a map of oids and byte arrays representing the digests calculated on the content during
* the last generate.
*
* @return a map of oids (as String objects) and byte[] representing digests.
*/
public Map getGeneratedDigests()
{
return new HashMap(digests);
}
} |
package org.concord.datagraph.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.text.NumberFormat;
import javax.swing.JMenuItem;
import org.concord.datagraph.engine.DataGraphable;
import org.concord.framework.data.stream.DataChannelDescription;
import org.concord.framework.data.stream.DataStoreEvent;
import org.concord.framework.data.stream.DataStoreListener;
import org.concord.graph.engine.CoordinateSystem;
import org.concord.graph.engine.GraphableList;
import org.concord.graph.util.ui.PointTextLabel;
/**
* DataPointLabel
* Class name and description
*
* Date created: Mar 1, 2005
*
* @author imoncada<p>
*
*/
public class DataPointLabel extends PointTextLabel
implements DataStoreListener, DataAnnotation
{
//Variables to watch the graphables that it's mousing over
protected GraphableList objList;
protected int indexPointOver = -1;
protected DataGraphable graphableOver = null;
//Actual graphable that the label is linked to
//(this is temporary because it should be a data point)
protected DataGraphable dataGraphable;
protected float fx = Float.NaN;
protected float fy = Float.NaN;
private DashedDataLine verticalDDL = new DashedDataLine(DashedDataLine.VERTICAL_LINE);
private DashedDataLine horizontalDDL = new DashedDataLine(DashedDataLine.HORIZONTAL_LINE);
//Labels and Units
protected String xLabel = null;
protected String xUnits = null;
protected String yLabel = null;
protected String yUnits = null;
protected int xPrecision = 2;
protected int yPrecision = 2;
protected String pointLabel = null; // format: (x, y)
protected String pointInfoLabel = null; //format: xlabel: x unit ylabel: y unit
private boolean showCoordinates = true;
private boolean mouseDown;
public DataPointLabel()
{
this("Message");
}
public DataPointLabel(boolean newNote)
{
this();
this.newNote = newNote;
}
public DataPointLabel(String msg)
{
super(msg);
}
/**
* @param gList The GraphableList to set.
*/
public void setGraphableList(GraphableList gList)
{
this.objList = gList;
}
/**
* @see org.concord.graph.util.ui.BoxTextLabel#populatePopUpMenu()
*/
protected void populatePopUpMenu()
{
super.populatePopUpMenu();
JMenuItem disconnectItem = new JMenuItem("Disconnect");
popUpMenu.add(disconnectItem);
disconnectItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setDataPoint(null);
setDataGraphable(null);
}
});
}
/**
* This method is used to see whether this label should be listening
* to mouse actions. In this case, we want the label to only listen to mouse
* actions if the mouse is directly over a data line.
*/
public boolean isPointInProximity(Point location)
{
if (newNote){
findAvailablePointOver(location);
return (indexPointOver > -1);
} else {
if (isSelected() && mouseDown)
return true;
return super.isPointInProximity(location);
}
}
/**
* @see org.concord.graph.engine.MouseMotionReceiver#mouseMoved(java.awt.Point)
*/
public boolean mouseMoved(Point p)
{
if (newNote){
findAvailablePointOver(p);
}
return super.mouseMoved(p);
}
private void findAvailablePointOver(Point p)
{
if (objList != null){
//Look for a point in one of the graphables in the list
int index = -1;
DataGraphable dg = null;
for (int i=0; i<objList.size(); i++){
Object obj = objList.elementAt(i);
if (obj instanceof DataGraphable){
dg = (DataGraphable)obj;
if(dg.isVisible()) {
index = dg.getIndexValueAtDisplay(p, 10);
}
if (index != -1) break;
}
}
if(index == -1) {
if (index != indexPointOver || graphableOver != null){
indexPointOver = index;
graphableOver = null;
}
} else {
//Found a point!
if (index != indexPointOver || dg != graphableOver){
indexPointOver = index;
graphableOver = dg;
foreColor = dg.getColor();
}
}
notifyChange();
}
}
/**
* @see org.concord.graph.engine.MouseControllable#mouseDragged(java.awt.Point)
*/
public boolean mouseDragged(Point p)
{
if (mouseInsideDataPoint || newEndPoint){
findAvailablePointOver(p);
notifyChange();
}
return super.mouseDragged(p);
}
public boolean mousePressed(Point p){
mouseDown = true;
return super.mousePressed(p);
}
/**
* @see org.concord.graph.engine.MouseControllable#mouseReleased(java.awt.Point)
*/
public boolean mouseReleased(Point p)
{
mouseDown = false;
if (dragEnabled){
if (indexPointOver != -1 && graphableOver != null){
Point2D pW = getPointDataGraphable(graphableOver, indexPointOver);
setDataPoint(pW);
}
else{
restoreOriginalDataPoint();
}
}
indexPointOver = -1;
graphableOver = null;
findAvailablePointOver(p);
if (indexPointOver != -1 && graphableOver != null){
float f1 = Float.NaN;
float f2 = Float.NaN;
Point2D p2 = getPointDataGraphable(graphableOver, indexPointOver);
setDataPoint(p2);
newEndPoint = false;
}
return super.mouseReleased(p);
}
private void restoreOriginalDataPoint()
{
if (dataPoint != null){
setDataPoint(originalDataPoint);
}
}
/**
* @see org.concord.graph.util.ui.BoxTextLabel#addAtPoint(java.awt.Point)
*/
public boolean addAtPoint(Point2D pD, Point2D pW)
{
if (indexPointOver != -1 && graphableOver != null){
setDataGraphable(graphableOver);
Point2D p = getPointDataGraphable(graphableOver, indexPointOver);
return super.addAtPoint(null, p);
}
else{
//super.addAtPoint(pD, pW);
setDataGraphable(null);
return false;
}
}
/**
* @param graphableOver2
* @param indexPointOver2
* @return
*/
protected static Point2D getPointDataGraphable(DataGraphable dg, int index)
{
Object objVal;
double x,y;
objVal = dg.getValueAt(index, 0);
if (!(objVal instanceof Float)) return null;
x = ((Float)objVal).floatValue();
objVal = dg.getValueAt(index, 1);
if (!(objVal instanceof Float)) return null;
y = ((Float)objVal).floatValue();
return new Point2D.Double(x, y);
}
/**
* @see org.concord.graph.engine.Drawable#draw(java.awt.Graphics2D)
*/
public void draw(Graphics2D g)
{
if (newNote || mouseInsideDataPoint || newEndPoint){
if (indexPointOver != -1 && graphableOver != null){
float f1 = Float.NaN;
float f2 = Float.NaN;
Point2D p = getPointDataGraphable(graphableOver, indexPointOver);
CoordinateSystem cs = graphArea.getCoordinateSystem();
Point2D pD = cs.transformToDisplay(p);
if (p != null){
f1 = (float)(p.getX());
f2 = (float)(p.getY());
fx = f1;
fy = f2;
g.drawOval((int)pD.getX() - 7, (int)pD.getY() - 7, 13, 13);
drawDashedLines(g, fx, fy);
updateDataPointLabels(p);
}
}
}
if(isSelected()) {
int pointInfoLabelLeft = graphArea.getInsets().left + 20;
int pointInfoLabelTop = Math.max(graphArea.getInsets().top, 20);
g.setColor(foreColor);
if(pointInfoLabel != null)
g.drawString(pointInfoLabel, pointInfoLabelLeft, pointInfoLabelTop);
}
// If the graphable is null we draw ourselves no matter what
// if the graphable is not null then we draw ourselves only if it's visible
if(dataGraphable == null || dataGraphable.isVisible()) {
super.draw(g);
}
}
/**
* @return Returns the dataGraphable.
*/
public DataGraphable getDataGraphable()
{
return dataGraphable;
}
/**
* @param dataGraphable The dataGraphable to set.
*/
public void setDataGraphable(DataGraphable dataGraphable)
{
if (this.dataGraphable == dataGraphable) return;
if (this.dataGraphable != null){
this.dataGraphable.removeDataStoreListener(this);
}
this.dataGraphable = dataGraphable;
if (this.dataGraphable != null){
this.dataGraphable.addDataStoreListener(this);
int numberOfChannels = dataGraphable.getTotalNumChannels();
if(numberOfChannels < 2) return;
DataChannelDescription dcd1 = dataGraphable.getDataChannelDescription(0);
DataChannelDescription dcd2 = dataGraphable.getDataChannelDescription(1);
if(dcd1 == null) return;
if(dcd2 == null) return;
xLabel = dcd1.getName();
if(xLabel == null || xLabel.length() == 0) xLabel = "";
else xLabel = xLabel +": ";
if(dcd1.getUnit() != null) xUnits = dcd1.getUnit().getDimension();
else xUnits = "";
if(dcd1.isUsePrecision()) xPrecision = dcd1.getPrecision() + 1;
else xPrecision = 2;
yLabel = dcd2.getName();
if(yLabel == null || yLabel.length() == 0) yLabel = "";
else yLabel = yLabel + ": ";
if(dcd2.getUnit() != null) yUnits = dcd2.getUnit().getDimension();
else yUnits = "";
if(dcd2.isUsePrecision()) yPrecision = dcd2.getPrecision() + 1;
else yPrecision = 2;
Point2D point = getDataPoint();
if(point != null) {
updateDataPointLabels();
}
}
}
/**
* @see org.concord.graph.util.ui.BoxTextLabel#doRemove()
*/
protected void doRemove()
{
setDataGraphable(null);
super.doRemove();
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataAdded(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataAdded(DataStoreEvent evt)
{
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataChanged(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataChanged(DataStoreEvent evt)
{
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataRemoved(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataRemoved(DataStoreEvent evt)
{
//FIXME See if the point is still in the DataGraphable?
//For now, I'll check if the graphable is empty
if(this.dataGraphable == null) return;
if (this.dataGraphable.getTotalNumSamples() == 0){
remove();
}
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataChannelDescChanged(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataChannelDescChanged(DataStoreEvent evt)
{
}
protected void drawDashedLines(Graphics2D g, float d1, float d2) {
setDashedLines(d1, d2);
verticalDDL.draw(g);
horizontalDDL.draw(g);
}
protected void setDashedLines(float d1, float d2) {
Point2D pVO = new Point2D.Double(d1,0);
Point2D pD = new Point2D.Double(d1,d2);
Point2D pHO = new Point2D.Double(0, d2);
verticalDDL.setDataPrecision(xPrecision);
horizontalDDL.setDataPrecision(yPrecision);
verticalDDL.setPoints(pVO, pD);
horizontalDDL.setPoints(pHO, pD);
DashedDataLine.setGraphArea(graphArea);
}
protected void updateDataPointLabels(Point2D p)
{
float f1 = (float)p.getX();
float f2 = (float)p.getY();
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(xPrecision);
pointInfoLabel = ((xLabel== null)?"":xLabel) + nf.format(f1) + ((xUnits== null)?"":xUnits) + " ";
pointLabel = "(" + nf.format(f1) + ((xUnits== null)?"":xUnits) + ", ";
nf.setMaximumFractionDigits(yPrecision);
pointInfoLabel += ((yLabel== null)?"":yLabel) + nf.format(f2) + ((yUnits== null)?"":yUnits);
pointLabel += nf.format(f2) + ((yUnits== null)?"":yUnits) + ")";
}
protected void updateDataPointLabels()
{
Point2D p = getDataPoint();
if (p == null){
pointLabel = "";
return;
}
updateDataPointLabels(p);
}
public void setDataPoint(Point2D p) {
super.setDataPoint(p);
updateDataPointLabels();
}
protected void drawMessage(Graphics2D g, boolean bDraw)
{
String words[];
String word;
double xIni = displayPositionIni.getX() + 3;
double yIni = displayPositionIni.getY() + 12;
double x = xIni;
double y = yIni;
double ww, w = 0, h;
FontMetrics fontM;
if (message == null) return;
fontM = g.getFontMetrics();
h = fontM.getHeight() - 2;
g.setColor(foreColor);
g.setFont(font);
words = message.split(" ");
for (int i=0; i < words.length; i++){
word = words[i] + " ";
//System.out.println("\""+word+"\"");
w = fontM.stringWidth(word);
if (x + w - xIni > maxWidth){
y += h;
x = xIni;
}
if (bDraw){
g.drawString(word, (int)x, (int)y);
}
x += w;
}
//// Draw uneditable coordinate values
double labelWidth = Double.NaN;
if(pointLabel != null && pointLabel.length() > 0 && getShowCoordinates()) {
y+= h;
Color oldColor = g.getColor();
Color backColor = g.getBackground();
Color newColor = new Color(255-backColor.getRed(), 255-backColor.getGreen(), 255-backColor.getBlue());
g.setColor(newColor);
g.drawString(pointLabel, (int)xIni, (int)y);
labelWidth = fontM.stringWidth(pointLabel);
g.setColor(oldColor);
msgChanged = true;
}
if (msgChanged){
msgChanged = false;
if(labelWidth != Double.NaN) ww = Math.max(maxWidth, labelWidth);
else ww = maxWidth;
if (y == yIni && !message.equals("")){
ww = x - xIni;
}
y += h;
Dimension d = new Dimension((int)(ww), (int)(y - yIni + 6));
setSize(d);
}
}
public void setShowCoordinates(boolean showCoordinates)
{
this.showCoordinates = showCoordinates;
}
public boolean getShowCoordinates()
{
return showCoordinates;
}
public void setCoordinateDecimalPlaces(int coordinateDecimalPlaces)
{
this.xPrecision = coordinateDecimalPlaces;
this.yPrecision = coordinateDecimalPlaces;
updateDataPointLabels();
}
} |
package org.concord.datagraph.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.text.NumberFormat;
import org.concord.datagraph.engine.DataGraphable;
import org.concord.framework.data.stream.DataChannelDescription;
import org.concord.framework.data.stream.DataStoreEvent;
import org.concord.framework.data.stream.DataStoreListener;
import org.concord.graph.engine.DefaultCoordinateSystem2D;
import org.concord.graph.engine.GraphableList;
import org.concord.graph.util.ui.PointTextLabel;
/**
* DataPointLabel
* Class name and description
*
* Date created: Mar 1, 2005
*
* @author imoncada<p>
*
*/
public class DataPointLabel extends PointTextLabel
implements DataStoreListener
{
//Variables to watch the graphables that it's mousing over
private GraphableList objList;
private int indexPointOver = -1;
private DataGraphable graphableOver = null;
//Actual graphable that the label is linked to
//(this is temporary because it should be a data point)
private DataGraphable dataGraphable;
private float fx = Float.NaN;
private float fy = Float.NaN;
private DashedDataLine verticalDDL = new DashedDataLine(DashedDataLine.VERTICAL_LINE);
private DashedDataLine horizontalDDL = new DashedDataLine(DashedDataLine.HORIZONTAL_LINE);
//Labels and Units
private String xLabel = null;
private String xUnits = null;
private String yLabel = null;
private String yUnits = null;
private int xPrecision = 0;
private int yPrecision = 0;
private String pointLabel = null; // format: (x, y)
private String pointInfoLabel = null; //format: xlabel: x+unit ylabel: y+unit
public DataPointLabel()
{
this("Message");
}
public DataPointLabel(boolean newNote)
{
this();
this.newNote = newNote;
}
public DataPointLabel(String msg)
{
super(msg);
}
/**
* @param gList The GraphableList to set.
*/
public void setGraphableList(GraphableList gList)
{
this.objList = gList;
}
/**
* @see org.concord.graph.engine.MouseMotionReceiver#mouseMoved(java.awt.Point)
*/
public boolean mouseMoved(Point p)
{
if (newNote){
findAvailablePointOver(p);
}
return super.mouseMoved(p);
}
private void findAvailablePointOver(Point p)
{
if (objList != null){
//Look for a point in one of the graphables in the list
int index = -1;
DataGraphable dg = null;
for (int i=0; i<objList.size(); i++){
Object obj = objList.elementAt(i);
if (obj instanceof DataGraphable){
dg = (DataGraphable)obj;
index = dg.getIndexValueAtDisplay(p, 10);
if (index != -1) break;
}
}
if (index != -1){
//Found a point!
//System.out.println("Found a point!!!");
if (index != indexPointOver || dg != graphableOver){
indexPointOver = index;
graphableOver = dg;
notifyChange();
}
}
else{
//System.out.println("No point!");
if (index != indexPointOver || graphableOver != null){
indexPointOver = index;
graphableOver = null;
notifyChange();
}
}
}
}
/**
* @see org.concord.graph.engine.MouseControllable#mouseDragged(java.awt.Point)
*/
public boolean mouseDragged(Point p)
{
if (mouseInsideDataPoint){
findAvailablePointOver(p);
}
return super.mouseDragged(p);
}
/**
* @see org.concord.graph.engine.MouseControllable#mouseReleased(java.awt.Point)
*/
public boolean mouseReleased(Point p)
{
if (dragEnabled){
if (indexPointOver != -1 && graphableOver != null){
Point2D pW = getPointDataGraphable(graphableOver, indexPointOver);
setDataPoint(pW);
}
else{
restoreOriginalDataPoint();
}
}
indexPointOver = -1;
graphableOver = null;
return super.mouseReleased(p);
}
private void restoreOriginalDataPoint()
{
if (dataPoint != null){
setDataPoint(originalDataPoint);
}
}
/**
* @see org.concord.graph.util.ui.BoxTextLabel#addAtPoint(java.awt.Point)
*/
public boolean addAtPoint(Point2D pD, Point2D pW)
{
if (indexPointOver != -1 && graphableOver != null){
setDataGraphable(graphableOver);
Point2D p = getPointDataGraphable(graphableOver, indexPointOver);
return super.addAtPoint(null, p);
}
else{
//super.addAtPoint(pD, pW);
setDataGraphable(null);
return false;
}
}
/**
* @param graphableOver2
* @param indexPointOver2
* @return
*/
private static Point2D getPointDataGraphable(DataGraphable dg, int index)
{
Object objVal;
double x,y;
objVal = dg.getValueAt(index, 0);
if (!(objVal instanceof Float)) return null;
x = ((Float)objVal).floatValue();
objVal = dg.getValueAt(index, 1);
if (!(objVal instanceof Float)) return null;
y = ((Float)objVal).floatValue();
return new Point2D.Double(x, y);
}
/**
* @see org.concord.graph.engine.Drawable#draw(java.awt.Graphics2D)
*/
public void draw(Graphics2D g)
{
float f1 = Float.NaN;
float f2 = Float.NaN;
if (newNote || mouseInsideDataPoint){
if (indexPointOver != -1 && graphableOver != null){
// FIXME: Shengyao, should the graphable be set here?
// the graphable over is just the one the mouse is over
// but they might not have clicked yet. So this might
// just be a temporary thing. In that case the graphable
// shouldn't be set yet.
setDataGraphable(graphableOver);
//System.out.println("painting an oval");
Point2D p = getPointDataGraphable(graphableOver, indexPointOver);
DefaultCoordinateSystem2D cs = (DefaultCoordinateSystem2D) graphArea.getCoordinateSystem();
Point2D pD = cs.transformToDisplay(p);
if (p != null){
//System.out.println("painting an oval 2");
f1 = (float)(p.getX());
f2 = (float)(p.getY());
fx = f1;
fy = f2;
g.drawOval((int)pD.getX() - 7, (int)pD.getY() - 7, 13, 13);
drawDashedLine(g, fx, fy);
if(xLabel != null || yLabel != null) {
// FIXME: Shengyao, should the datapoint be set here?
// this point is just the one the mouse is over, but
// they might not have clicked yet. So this might
// just be a temporary thing. In that case the point
// shouldn't be set yet.
setDataPoint(p);//, coordinateLabel);
}
}
}
}
if(isSelected()) {
int pointInfoLabelLeft = graphArea.getInsets().left + 20;
int pointInfoLabelTop = Math.max(graphArea.getInsets().top, 20);
g.setColor(Color.RED);
if(pointInfoLabel != null)
g.drawString(pointInfoLabel, pointInfoLabelLeft, pointInfoLabelTop);
}
super.draw(g);
}
/**
* @return Returns the dataGraphable.
*/
public DataGraphable getDataGraphable()
{
return dataGraphable;
}
/**
* @param dataGraphable The dataGraphable to set.
*/
public void setDataGraphable(DataGraphable dataGraphable)
{
if (this.dataGraphable == dataGraphable) return;
if (this.dataGraphable != null){
this.dataGraphable.removeDataStoreListener(this);
}
this.dataGraphable = dataGraphable;
if (this.dataGraphable != null){
this.dataGraphable.addDataStoreListener(this);
int numberOfChannels = dataGraphable.getTotalNumChannels();
if(numberOfChannels < 2) return;
//System.out.println("number of channels: " + numberOfChannels);
DataChannelDescription dcd1 = dataGraphable.getDataChannelDescription(0);
DataChannelDescription dcd2 = dataGraphable.getDataChannelDescription(1);
if(dcd1 == null) return;
if(dcd2 == null) return;
xLabel = dcd1.getName();
if(xLabel == null || xLabel.length() == 0) xLabel = "";
else xLabel = xLabel +": ";
if(dcd1.getUnit() != null) xUnits = dcd1.getUnit().getDimension();
else xUnits = "";
if(dcd1.isUsePrecision()) xPrecision = dcd1.getPrecision() + 1;
else xPrecision = 2;
yLabel = dcd2.getName();
if(yLabel == null || yLabel.length() == 0) yLabel = "";
else yLabel = yLabel + ": ";
if(dcd2.getUnit() != null) yUnits = dcd2.getUnit().getDimension();
else yUnits = "";
if(dcd2.isUsePrecision()) yPrecision = dcd2.getPrecision() + 1;
else yPrecision = 2;
Point2D point = getDataPoint();
if(point != null) {
updateDataPointLabels();
}
}
}
/**
* @see org.concord.graph.util.ui.BoxTextLabel#doRemove()
*/
protected void doRemove()
{
setDataGraphable(null);
super.doRemove();
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataAdded(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataAdded(DataStoreEvent evt)
{
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataChanged(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataChanged(DataStoreEvent evt)
{
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataRemoved(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataRemoved(DataStoreEvent evt)
{
//FIXME See if the point is still in the DataGraphable?
//For now, I'll check if the graphable is empty
if(this.dataGraphable == null) return;
if (this.dataGraphable.getTotalNumSamples() == 0){
remove();
}
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataChannelDescChanged(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataChannelDescChanged(DataStoreEvent evt)
{
}
protected void drawDashedLine(Graphics2D g, float d1, float d2) {
setDashedLines(d1, d2);
verticalDDL.draw(g);
horizontalDDL.draw(g);
}
private void setDashedLines(float d1, float d2) {
Point2D pVO = new Point2D.Double(d1,0);
Point2D pD = new Point2D.Double(d1,d2);
Point2D pHO = new Point2D.Double(0, d2);
verticalDDL.setDataPrecision(xPrecision);
horizontalDDL.setDataPrecision(yPrecision);
verticalDDL.setPoints(pVO, pD);
horizontalDDL.setPoints(pHO, pD);
DashedDataLine.setGraphArea(graphArea);
}
protected void updateDataPointLabels()
{
Point2D p = getDataPoint();
float f1 = (float)p.getX();
float f2 = (float)p.getY();
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(xPrecision);
pointInfoLabel = xLabel + nf.format(f1) + xUnits + " ";
pointLabel = "(" + nf.format(f1) + xUnits + ", ";
nf.setMaximumFractionDigits(yPrecision);
pointInfoLabel += yLabel + nf.format(f2) + yUnits;
pointLabel += nf.format(f2) + yUnits + ")";
}
public void setDataPoint(Point2D p) {
super.setDataPoint(p);
updateDataPointLabels();
}
protected void drawMessage(Graphics2D g)
{
drawMessage(g, true);
}
protected void drawMessage(Graphics2D g, boolean bDraw)
{
String words[];
String word;
double xIni = displayPositionIni.getX() + 3;
double yIni = displayPositionIni.getY() + 12;
double x = xIni;
double y = yIni;
double ww, w = 0, h;
FontMetrics fontM;
fontM = g.getFontMetrics();
h = fontM.getHeight() - 2;
g.setColor(foreColor);
g.setFont(font);
words = message.split(" ");
for (int i=0; i < words.length; i++){
word = words[i] + " ";
//System.out.println("\""+word+"\"");
w = fontM.stringWidth(word);
if (x + w - xIni > maxWidth){
y += h;
x = xIni;
}
if (bDraw){
g.drawString(word, (int)x, (int)y);
}
x += w;
}
//// Draw uneditable coordinate values
double labelWidth = Double.NaN;
if(pointLabel != null && pointLabel.length() > 0) {
y+= h;
Color oldColor = g.getColor();
Color backColor = g.getBackground();
Color newColor = new Color(255-backColor.getRed(), 255-backColor.getGreen(), 255-backColor.getBlue());
g.setColor(newColor);
g.drawString(pointLabel, (int)xIni, (int)y);
labelWidth = fontM.stringWidth(pointLabel);
g.setColor(oldColor);
msgChanged = true;
}
if (msgChanged){
msgChanged = false;
if(labelWidth != Double.NaN) ww = Math.max(maxWidth, labelWidth);
else ww = maxWidth;
if (y == yIni && !message.equals("")){
ww = x - xIni;
}
y += h;
Dimension d = new Dimension((int)(ww), (int)(y - yIni + 6));
setSize(d);
}
}
} |
package org.nschmidt.ldparteditor.data;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Event;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector4f;
import org.nschmidt.csg.CSG;
import org.nschmidt.csg.CSGCircle;
import org.nschmidt.csg.CSGCone;
import org.nschmidt.csg.CSGCube;
import org.nschmidt.csg.CSGCylinder;
import org.nschmidt.csg.CSGExtrude;
import org.nschmidt.csg.CSGMesh;
import org.nschmidt.csg.CSGQuad;
import org.nschmidt.csg.CSGSphere;
import org.nschmidt.csg.Plane;
import org.nschmidt.csg.Polygon;
import org.nschmidt.csg.VectorCSGd;
import org.nschmidt.ldparteditor.composites.Composite3D;
import org.nschmidt.ldparteditor.enums.MyLanguage;
import org.nschmidt.ldparteditor.enums.View;
import org.nschmidt.ldparteditor.helpers.Cocoa;
import org.nschmidt.ldparteditor.helpers.composite3d.PathTruderSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.PerspectiveCalculator;
import org.nschmidt.ldparteditor.helpers.math.HashBiMap;
import org.nschmidt.ldparteditor.helpers.math.MathHelper;
import org.nschmidt.ldparteditor.helpers.math.PowerRay;
import org.nschmidt.ldparteditor.helpers.math.ThreadsafeHashMap;
import org.nschmidt.ldparteditor.helpers.math.ThreadsafeTreeMap;
import org.nschmidt.ldparteditor.i18n.I18n;
import org.nschmidt.ldparteditor.logger.NLogger;
import org.nschmidt.ldparteditor.project.Project;
import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow;
import org.nschmidt.ldparteditor.text.DatParser;
/**
* @author nils
*
*/
public final class GDataCSG extends GData {
final byte type;
static volatile Lock static_lock = new ReentrantLock();
private final static ThreadsafeHashMap<DatFile, HashMap<String, CSG>> linkedCSG = new ThreadsafeHashMap<DatFile, HashMap<String, CSG>>();
private final static ThreadsafeHashMap<DatFile, HashBiMap<Integer, GDataCSG>> idToGDataCSG = new ThreadsafeHashMap<DatFile, HashBiMap<Integer, GDataCSG>>();
private final static ThreadsafeHashMap<DatFile, HashSet<GData3>> selectedTrianglesMap = new ThreadsafeHashMap<DatFile, HashSet<GData3>>();
private final static ThreadsafeHashMap<DatFile, HashSet<GDataCSG>> selectedBodyMap = new ThreadsafeHashMap<DatFile, HashSet<GDataCSG>>();
private final static ThreadsafeHashMap<DatFile, HashSet<GData3>> backupSelectedTrianglesMap = new ThreadsafeHashMap<DatFile, HashSet<GData3>>();
private final static ThreadsafeHashMap<DatFile, HashSet<GDataCSG>> backupSelectedBodyMap = new ThreadsafeHashMap<DatFile, HashSet<GDataCSG>>();
private static boolean deleteAndRecompile = true;
private final static ThreadsafeHashMap<DatFile, HashSet<GDataCSG>> registeredData = new ThreadsafeHashMap<DatFile, HashSet<GDataCSG>>();
private final static ThreadsafeHashMap<DatFile, HashSet<GDataCSG>> parsedData = new ThreadsafeHashMap<DatFile, HashSet<GDataCSG>>();
private final static ThreadsafeHashMap<DatFile, PathTruderSettings> globalExtruderConfig = new ThreadsafeHashMap<DatFile, PathTruderSettings>();
private final static ThreadsafeHashMap<DatFile, Boolean> clearPolygonCache = new ThreadsafeHashMap<DatFile, Boolean>();
private final static ThreadsafeHashMap<DatFile, Boolean> fullClearPolygonCache = new ThreadsafeHashMap<DatFile, Boolean>();
private final static ThreadsafeHashMap<DatFile, ArrayList<VectorCSGd[]>> allNewPolygonVertices = new ThreadsafeHashMap<DatFile, ArrayList<VectorCSGd[]>>();
private final static ThreadsafeHashMap<DatFile, Boolean> compileAndInline = new ThreadsafeHashMap<DatFile, Boolean>();
private final ArrayList<GData> cachedData = new ArrayList<GData>();
private final List<Polygon> polygonCache = new ArrayList<Polygon>();
private PathTruderSettings extruderConfig = new PathTruderSettings();
private static int quality = 16;
private int global_quality = 16;
private double global_epsilon = 1e-6;
private final String ref1;
private final String ref2;
private final String ref3;
private CSG compiledCSG = null;
private CSG dataCSG = null;
private final DatFile myDat;
private final GColour colour;
final Matrix4f matrix;
public synchronized static void forceRecompile(DatFile df) {
registeredData.putIfAbsent(df, new HashSet<GDataCSG>()).add(null);
allNewPolygonVertices.putIfAbsent(df, new ArrayList<VectorCSGd[]>()).clear();
clearPolygonCache.putIfAbsent(df, true);
Plane.EPSILON = 1e-3;
}
public synchronized static void fullReset(DatFile df) {
quality = 16;
registeredData.putIfAbsent(df, new HashSet<GDataCSG>()).clear();
linkedCSG.putIfAbsent(df, new HashMap<String, CSG>()).clear();
parsedData.putIfAbsent(df, new HashSet<GDataCSG>()).clear();
idToGDataCSG.putIfAbsent(df, new HashBiMap<Integer, GDataCSG>()).clear();
selectedTrianglesMap.putIfAbsent(df, new HashSet<GData3>()).clear();
selectedBodyMap.putIfAbsent(df, new HashSet<GDataCSG>()).clear();
allNewPolygonVertices.putIfAbsent(df, new ArrayList<VectorCSGd[]>()).clear();
backupSelectionClear(df);
Plane.EPSILON = 1e-3;
}
public GColour getColour() {
return colour;
}
public synchronized static void resetCSG(DatFile df, boolean useLowQuality) {
if (useLowQuality) {
if (allNewPolygonVertices.containsKey(df)) {
allNewPolygonVertices.get(df).clear();
}
quality = 12;
} else {
quality = 16;
}
HashSet<GDataCSG> ref = new HashSet<GDataCSG>(registeredData.putIfAbsent(df, new HashSet<GDataCSG>()));
ref.removeAll(parsedData.putIfAbsent(df, new HashSet<GDataCSG>()));
clearPolygonCache.putIfAbsent(df, true);
fullClearPolygonCache.putIfAbsent(df, true);
compileAndInline.putIfAbsent(df, false);
deleteAndRecompile = !ref.isEmpty();
if (deleteAndRecompile) {
globalExtruderConfig.put(df, new PathTruderSettings());
registeredData.get(df).clear();
registeredData.get(df).add(null);
linkedCSG.putIfAbsent(df, new HashMap<String, CSG>()).clear();
idToGDataCSG.putIfAbsent(df, new HashBiMap<Integer, GDataCSG>()).clear();
}
parsedData.get(df).clear();
}
public byte getCSGtype() {
return type;
}
public GDataCSG(DatFile df, final int colourNumber, float r, float g, float b, float a, GDataCSG c) {
this(df, c.type, c.colourReplace(new GColour(colourNumber, r, g, b, a).toString()), c.parent);
}
public GDataCSG(DatFile df, Matrix4f m, GDataCSG c) {
this(df, c.type, c.transform(m), c.parent);
}
// CASE 0 0 !LPE [CSG TAG] [ID] [ID2] [COLOUR] [MATRIX] 17
// CASE 1 0 !LPE [CSG TAG] [ID] [COLOUR] [MATRIX] 17
// CASE 2 0 !LPE [CSG TAG] [ID] [ID2] [ID3] 6
// CASE 3 0 !LPE [CSG TAG] [ID] 4
public GDataCSG(DatFile df, byte type, String csgLine, GData1 parent) {
super(parent);
clearPolygonCache.put(df, true);
fullClearPolygonCache.put(df, false);
myDat = df;
registeredData.putIfAbsent(df, new HashSet<GDataCSG>()).add(this);
String[] data_segments = csgLine.trim().split("\\s+"); //$NON-NLS-1$
final GColour col16 = View.getLDConfigColour(16);
this.type = type;
this.text = csgLine;
switch (type) {
case CSG.COMPILE:
if (data_segments.length == 4) {
ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$
} else {
ref1 = null;
}
ref2 = null;
ref3 = null;
colour = null;
matrix = null;
break;
case CSG.QUAD:
case CSG.CIRCLE:
case CSG.ELLIPSOID:
case CSG.CUBOID:
case CSG.CYLINDER:
case CSG.MESH:
case CSG.EXTRUDE:
case CSG.CONE:
if (data_segments.length == 17) {
ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$
GColour c = DatParser.validateColour(data_segments[4], col16.getR(), col16.getG(), col16.getB(), 1f);
if (c != null) {
colour = c.clone();
} else {
colour = View.getLDConfigColour(16);
}
matrix = MathHelper.matrixFromStrings(data_segments[5], data_segments[6], data_segments[7], data_segments[8], data_segments[11], data_segments[14], data_segments[9],
data_segments[12], data_segments[15], data_segments[10], data_segments[13], data_segments[16]);
} else {
colour = null;
matrix = null;
ref1 = null;
}
ref2 = null;
ref3 = null;
break;
case CSG.DIFFERENCE:
case CSG.INTERSECTION:
case CSG.UNION:
if (data_segments.length == 6) {
ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$
ref2 = data_segments[4] + "#>" + parent.shortName; //$NON-NLS-1$
ref3 = data_segments[5] + "#>" + parent.shortName; //$NON-NLS-1$
} else {
ref1 = null;
ref2 = null;
ref3 = null;
}
colour = null;
matrix = null;
break;
case CSG.TRANSFORM:
if (data_segments.length == 18) {
ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$
ref2 = data_segments[4] + "#>" + parent.shortName; //$NON-NLS-1$
GColour c = DatParser.validateColour(data_segments[5], col16.getR(), col16.getG(), col16.getB(), 1f);
if (c != null) {
colour = c.clone();
} else {
colour = View.getLDConfigColour(16);
}
matrix = MathHelper.matrixFromStrings(data_segments[6], data_segments[7], data_segments[8], data_segments[9], data_segments[10], data_segments[11], data_segments[12],
data_segments[13], data_segments[14], data_segments[15], data_segments[16], data_segments[17]);
} else {
colour = null;
ref1 = null;
ref2 = null;
matrix = null;
}
ref3 = null;
break;
case CSG.QUALITY:
if (data_segments.length == 4) {
try {
int q = Integer.parseInt(data_segments[3]);
if (q > 0 && q < 49) {
global_quality = q;
}
} catch (NumberFormatException e) {
}
ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$
} else {
ref1 = null;
}
ref2 = null;
ref3 = null;
colour = null;
matrix = null;
break;
case CSG.EPSILON:
if (data_segments.length == 4) {
try {
double q = Double.parseDouble(data_segments[3]);
if (q > 0d) {
global_epsilon = q;
}
} catch (NumberFormatException e) {
}
ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$
} else {
ref1 = null;
}
ref2 = null;
ref3 = null;
colour = null;
matrix = null;
break;
case CSG.EXTRUDE_CFG:
if (data_segments.length == 4 && "DEFAULT".equals(data_segments[3])) { //$NON-NLS-1$
extruderConfig = new PathTruderSettings();
ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$
} else if (data_segments.length == 17) {
try {
extruderConfig.setMaxPathSegmentLength(new BigDecimal(data_segments[4]));
extruderConfig.setTransitionCount(Integer.parseInt(data_segments[6]));
extruderConfig.setTransitionCurveControl(new BigDecimal(data_segments[8]));
extruderConfig.setTransitionCurveCenter(new BigDecimal(data_segments[10]));
extruderConfig.setRotation(new BigDecimal(data_segments[12]));
extruderConfig.setCompensation(Boolean.parseBoolean(data_segments[14]));
extruderConfig.setInverted(Boolean.parseBoolean(data_segments[16]));
} catch (Exception ex) {
extruderConfig = new PathTruderSettings();
}
ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$
} else {
ref1 = null;
}
ref2 = null;
ref3 = null;
colour = null;
matrix = null;
break;
default:
ref1 = null;
ref2 = null;
ref3 = null;
colour = null;
matrix = null;
break;
}
}
private void drawAndParse(Composite3D c3d) {
final DatFile df = c3d.getLockableDatFileReference();
drawAndParse(c3d, df, true);
}
public void drawAndParse(Composite3D c3d, DatFile df, boolean doDraw) {
final boolean clearCaches = clearPolygonCache.putIfAbsent(df, true) || type == CSG.MESH && CSGMesh.needCacheRefresh(cachedData, this, df) || type == CSG.EXTRUDE && CSGExtrude.needCacheRefresh(cachedData, this, df);
if (clearCaches) {
clearPolygonCache.put(df, true);
}
final HashSet<GDataCSG> parsedData = GDataCSG.parsedData.putIfAbsent(df, new HashSet<GDataCSG>());
parsedData.add(this);
final boolean modified = c3d != null && c3d.getManipulator().isModified();
if (deleteAndRecompile || modified || clearCaches) {
final HashBiMap<Integer, GDataCSG> idToGDataCSG = GDataCSG.idToGDataCSG.putIfAbsent(df, new HashBiMap<Integer, GDataCSG>());
final HashMap<String, CSG> linkedCSG = GDataCSG.linkedCSG.putIfAbsent(df, new HashMap<String, CSG>());
final HashSet<GDataCSG> registeredData = GDataCSG.registeredData.putIfAbsent(df, new HashSet<GDataCSG>());
final Matrix4f m;
if (modified) {
m = c3d.getManipulator().getTempTransformationCSG4f();
} else {
m = View.ID;
}
registeredData.remove(null);
try {
compiledCSG = null;
registeredData.add(this);
if (ref1 != null) {
switch (type) {
case CSG.QUAD:
case CSG.CIRCLE:
case CSG.ELLIPSOID:
case CSG.CUBOID:
case CSG.CYLINDER:
case CSG.CONE:
case CSG.MESH:
case CSG.EXTRUDE:
if (matrix != null) {
switch (type) {
case CSG.QUAD:
CSGQuad quad = new CSGQuad();
idToGDataCSG.put(quad.ID, this);
CSG csgQuad = quad.toCSG(df, colour);
if (modified && isSelected(df)) {
csgQuad = transformWithManipulator(csgQuad, m, matrix);
} else {
csgQuad = csgQuad.transformed(matrix);
}
dataCSG = csgQuad;
linkedCSG.put(ref1, csgQuad);
break;
case CSG.CIRCLE:
CSGCircle circle = new CSGCircle(quality);
idToGDataCSG.put(circle.ID, this);
CSG csgCircle = circle.toCSG(df, colour);
if (modified && isSelected(df)) {
csgCircle = transformWithManipulator(csgCircle, m, matrix);
} else {
csgCircle = csgCircle.transformed(matrix);
}
dataCSG = csgCircle;
linkedCSG.put(ref1, csgCircle);
break;
case CSG.ELLIPSOID:
CSGSphere sphere = new CSGSphere(quality, quality / 2);
idToGDataCSG.put(sphere.ID, this);
CSG csgSphere = sphere.toCSG(df, colour);
if (modified && isSelected(df)) {
csgSphere = transformWithManipulator(csgSphere, m, matrix);
} else {
csgSphere = csgSphere.transformed(matrix);
}
dataCSG = csgSphere;
linkedCSG.put(ref1, csgSphere);
break;
case CSG.CUBOID:
CSGCube cube = new CSGCube();
idToGDataCSG.put(cube.ID, this);
CSG csgCube = cube.toCSG(df, colour);
if (modified && isSelected(df)) {
csgCube = transformWithManipulator(csgCube, m, matrix);
} else {
csgCube = csgCube.transformed(matrix);
}
dataCSG = csgCube;
linkedCSG.put(ref1, csgCube);
break;
case CSG.CYLINDER:
CSGCylinder cylinder = new CSGCylinder(quality);
idToGDataCSG.put(cylinder.ID, this);
CSG csgCylinder = cylinder.toCSG(df, colour);
if (modified && isSelected(df)) {
csgCylinder = transformWithManipulator(csgCylinder, m, matrix);
} else {
csgCylinder = csgCylinder.transformed(matrix);
}
dataCSG = csgCylinder;
linkedCSG.put(ref1, csgCylinder);
break;
case CSG.CONE:
CSGCone cone = new CSGCone(quality);
idToGDataCSG.put(cone.ID, this);
CSG csgCone = cone.toCSG(df, colour);
if (modified && isSelected(df)) {
csgCone = transformWithManipulator(csgCone, m, matrix);
} else {
csgCone = csgCone.transformed(matrix);
}
dataCSG = csgCone;
linkedCSG.put(ref1, csgCone);
break;
case CSG.MESH:
if (clearCaches) {
polygonCache.clear();
}
CSGMesh mesh = new CSGMesh(this, cachedData, polygonCache);
CSGMesh.fillCache(cachedData, this);
CSG csgMesh = mesh.toCSG(df, colour);
idToGDataCSG.put(mesh.ID, this);
if (modified && isSelected(df)) {
csgMesh = transformWithManipulator(csgMesh, m, matrix);
} else {
csgMesh = csgMesh.transformed(matrix);
}
dataCSG = csgMesh;
linkedCSG.put(ref1, csgMesh);
break;
case CSG.EXTRUDE:
if (clearCaches) {
polygonCache.clear();
}
PathTruderSettings gconf = globalExtruderConfig.putIfAbsent(df, extruderConfig);
if (gconf != extruderConfig) {
extruderConfig = gconf;
polygonCache.clear();
}
CSGExtrude extruder = new CSGExtrude(this, cachedData, extruderConfig, polygonCache);
CSGExtrude.fillCache(cachedData, this);
CSG csgExtruder = extruder.toCSG(df, colour);
idToGDataCSG.put(extruder.ID, this);
if (modified && isSelected(df)) {
csgExtruder = transformWithManipulator(csgExtruder, m, matrix);
} else {
csgExtruder = csgExtruder.transformed(matrix);
}
dataCSG = csgExtruder;
linkedCSG.put(ref1, csgExtruder);
break;
default:
break;
}
}
break;
case CSG.COMPILE:
if (linkedCSG.containsKey(ref1)) {
compiledCSG = linkedCSG.get(ref1);
if (GDataCSG.isInlining(df)) {
// FIXME compiledCSG.compile_without_t_junctions(df);
compiledCSG.compile();
} else {
compiledCSG.compile();
}
} else {
compiledCSG = null;
}
break;
case CSG.DIFFERENCE:
if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) {
linkedCSG.put(ref3, linkedCSG.get(ref1).difference(linkedCSG.get(ref2)));
}
break;
case CSG.INTERSECTION:
if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) {
linkedCSG.put(ref3, linkedCSG.get(ref1).intersect(linkedCSG.get(ref2)));
}
break;
case CSG.UNION:
if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) {
linkedCSG.put(ref3, linkedCSG.get(ref1).union(linkedCSG.get(ref2)));
}
break;
case CSG.TRANSFORM:
if (linkedCSG.containsKey(ref1) && matrix != null) {
idToGDataCSG.put(ID, this);
if (modified && isSelected(df)) {
dataCSG = linkedCSG.get(ref1).transformed(matrix).transformed(m, colour, ID);
} else {
dataCSG = linkedCSG.get(ref1).transformed(matrix, colour, ID);
}
linkedCSG.put(ref2, dataCSG);
}
break;
case CSG.QUALITY:
quality = c3d != null && c3d.getManipulator().isModified() ? 12 : global_quality;
break;
case CSG.EPSILON:
Plane.EPSILON = global_epsilon;
break;
case CSG.EXTRUDE_CFG:
globalExtruderConfig.put(df, extruderConfig);
break;
default:
break;
}
}
/* Is not possible anymore...
} catch (StackOverflowError e) {
*/
} catch (Exception e) {
NLogger.error(getClass(), e);
}
}
if (compiledCSG != null && c3d != null && doDraw) {
if (c3d.getRenderMode() != 5) {
compiledCSG.draw(c3d);
} else {
compiledCSG.draw_textured(c3d);
}
}
}
private CSG transformWithManipulator(CSG csg, Matrix4f transformation4f, Matrix4f myMatrix) {
return csg.transformed(myMatrix).transformed(transformation4f);
}
@Override
public synchronized void drawGL20(Composite3D c3d) {
drawAndParse(c3d);
}
@Override
public synchronized void drawGL20_RandomColours(Composite3D c3d) {
drawAndParse(c3d);
}
@Override
public synchronized void drawGL20_BFC(Composite3D c3d) {
drawAndParse(c3d);
}
@Override
public synchronized void drawGL20_BFCuncertified(Composite3D c3d) {
drawAndParse(c3d);
}
@Override
public synchronized void drawGL20_BFC_backOnly(Composite3D c3d) {
drawAndParse(c3d);
}
@Override
public synchronized void drawGL20_BFC_Colour(Composite3D c3d) {
drawAndParse(c3d);
}
@Override
public synchronized void drawGL20_BFC_Textured(Composite3D c3d) {
drawAndParse(c3d);
}
@Override
public synchronized void drawGL20_WhileAddCondlines(Composite3D c3d) {
drawAndParse(c3d);
}
@Override
public int type() {
return 8;
}
@Override
String getNiceString() {
return text;
}
@Override
public synchronized String inlinedString(final byte bfc, final GColour colour) {
try {
static_lock.lock();
switch (type) {
case CSG.COMPILE:
if (compiledCSG != null) {
compileAndInline.put(myDat, true);
resetCSG(myDat, false);
GDataCSG.forceRecompile(myDat);
GData g = myDat.getDrawChainStart();
deleteAndRecompile = true;
while ((g = g.getNext()) != null) {
if (g.type() == 8) {
GDataCSG gcsg = (GDataCSG) g;
gcsg.drawAndParse(null, myDat, false);
}
}
if (!deleteAndRecompile) {
return getNiceString() + "<br>0 // INLINE FAILED! :("; //$NON-NLS-1$
}
compileAndInline.put(Project.getFileToEdit(), false);
allNewPolygonVertices.get(myDat).clear();
final StringBuilder sb = new StringBuilder();
try {
new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(false, false, new IRunnableWithProgress() {
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
Editor3DWindow.getWindow().getShell().getDisplay().readAndDispatch();
Object[] messageArguments = {getNiceString()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DATFILE_Inlined);
sb.append(formatter.format(messageArguments) + "<br>"); //$NON-NLS-1$
TreeMap<GData3, Integer> result = compiledCSG.getResult();
for (GData3 g3 : result.keySet()) {
StringBuilder lineBuilder3 = new StringBuilder();
lineBuilder3.append("3 "); //$NON-NLS-1$
if (g3.colourNumber == -1) {
lineBuilder3.append("0x2"); //$NON-NLS-1$
lineBuilder3.append(MathHelper.toHex((int) (255f * g3.r)).toUpperCase());
lineBuilder3.append(MathHelper.toHex((int) (255f * g3.g)).toUpperCase());
lineBuilder3.append(MathHelper.toHex((int) (255f * g3.b)).toUpperCase());
} else {
lineBuilder3.append(g3.colourNumber);
}
Vector4f g3_v1 = new Vector4f(g3.x1, g3.y1, g3.z1, 1f);
Vector4f g3_v2 = new Vector4f(g3.x2, g3.y2, g3.z2, 1f);
Vector4f g3_v3 = new Vector4f(g3.x3, g3.y3, g3.z3, 1f);
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v1.x / 1000f));
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v1.y / 1000f));
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v1.z / 1000f));
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v2.x / 1000f));
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v2.y / 1000f));
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v2.z / 1000f));
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v3.x / 1000f));
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v3.y / 1000f));
lineBuilder3.append(" "); //$NON-NLS-1$
lineBuilder3.append(floatToString(g3_v3.z / 1000f));
sb.append(lineBuilder3.toString() + "<br>"); //$NON-NLS-1$
}
}
});
} catch (InvocationTargetException consumed) {
consumed.printStackTrace();
} catch (InterruptedException consumed) {
consumed.printStackTrace();
}
return sb.toString();
} else {
return getNiceString();
}
default:
return getNiceString();
}
} finally {
static_lock.unlock();
}
}
private String floatToString(float flt) {
String result;
if (flt == (int) flt) {
result = String.format("%d", (int) flt); //$NON-NLS-1$
} else {
result = String.format("%s", flt); //$NON-NLS-1$
}
if (result.equals("0.0"))result = "0"; //$NON-NLS-1$ //$NON-NLS-2$
if (result.startsWith("-0.")) return "-" + result.substring(2); //$NON-NLS-1$ //$NON-NLS-2$
if (result.startsWith("0.")) return result.substring(1); //$NON-NLS-1$
return result;
}
@Override
public synchronized String transformAndColourReplace(String colour2, Matrix matrix) {
boolean notChoosen = true;
String t = null;
switch (type) {
case CSG.QUAD:
if (notChoosen) {
t = " CSG_QUAD "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CIRCLE:
if (notChoosen) {
t = " CSG_CIRCLE "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.ELLIPSOID:
if (notChoosen) {
t = " CSG_ELLIPSOID "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CUBOID:
if (notChoosen) {
t = " CSG_CUBOID "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CYLINDER:
if (notChoosen) {
t = " CSG_CYLINDER "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.MESH:
if (notChoosen) {
t = " CSG_MESH "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.EXTRUDE:
if (notChoosen) {
t = " CSG_EXTRUDE "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.TRANSFORM:
if (notChoosen) {
t = " CSG_TRANSFORM "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CONE:
if (notChoosen) {
t = " CSG_CONE "; //$NON-NLS-1$
notChoosen = false;
}
StringBuilder colourBuilder = new StringBuilder();
if (colour == null) {
colourBuilder.append(16);
} else if (colour.getColourNumber() == -1) {
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getB())).toUpperCase());
} else {
colourBuilder.append(colour.getColourNumber());
}
Matrix4f newMatrix = new Matrix4f(this.matrix);
Matrix4f newMatrix2 = new Matrix4f(matrix.getMatrix4f());
Matrix4f.transpose(newMatrix, newMatrix);
newMatrix.m30 = newMatrix.m03;
newMatrix.m31 = newMatrix.m13;
newMatrix.m32 = newMatrix.m23;
newMatrix.m03 = 0f;
newMatrix.m13 = 0f;
newMatrix.m23 = 0f;
Matrix4f.mul(newMatrix2, newMatrix, newMatrix);
String col = colourBuilder.toString();
if (col.equals(colour2))
col = "16"; //$NON-NLS-1$
String tag = ref1.substring(0, ref1.lastIndexOf("#>")); //$NON-NLS-1$
return "0 !LPE" + t + tag + " " + col + " " + MathHelper.matrixToString(newMatrix); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
default:
return text;
}
}
public synchronized String transform(Matrix4f m) {
boolean notChoosen = true;
String t = null;
switch (type) {
case CSG.QUAD:
if (notChoosen) {
t = " CSG_QUAD "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CIRCLE:
if (notChoosen) {
t = " CSG_CIRCLE "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.ELLIPSOID:
if (notChoosen) {
t = " CSG_ELLIPSOID "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CUBOID:
if (notChoosen) {
t = " CSG_CUBOID "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CYLINDER:
if (notChoosen) {
t = " CSG_CYLINDER "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.MESH:
if (notChoosen) {
t = " CSG_MESH "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.EXTRUDE:
if (notChoosen) {
t = " CSG_EXTRUDE "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.TRANSFORM:
if (notChoosen) {
t = " CSG_TRANSFORM "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CONE:
if (notChoosen) {
t = " CSG_CONE "; //$NON-NLS-1$
notChoosen = false;
}
StringBuilder colourBuilder = new StringBuilder();
if (colour == null) {
colourBuilder.append(16);
} else if (colour.getColourNumber() == -1) {
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getB())).toUpperCase());
} else {
colourBuilder.append(colour.getColourNumber());
}
Matrix4f oldMatrix = new Matrix4f(matrix);
oldMatrix.m30 = oldMatrix.m30 / 1000f;
oldMatrix.m31 = oldMatrix.m31 / 1000f;
oldMatrix.m32 = oldMatrix.m32 / 1000f;
Matrix4f.transpose(oldMatrix, oldMatrix);
oldMatrix.m30 = oldMatrix.m03;
oldMatrix.m31 = oldMatrix.m13;
oldMatrix.m32 = oldMatrix.m23;
oldMatrix.m03 = 0f;
oldMatrix.m13 = 0f;
oldMatrix.m23 = 0f;
Matrix accurateLocalMatrix = new Matrix(oldMatrix);
Matrix transformation = new Matrix(m);
transformation = transformation.transpose();
BigDecimal tx = accurateLocalMatrix.M30.add(BigDecimal.ZERO);
BigDecimal ty = accurateLocalMatrix.M31.add(BigDecimal.ZERO);
BigDecimal tz = accurateLocalMatrix.M32.add(BigDecimal.ZERO);
accurateLocalMatrix = accurateLocalMatrix.translate(new BigDecimal[] { tx.negate(), ty.negate(), tz.negate() });
accurateLocalMatrix = Matrix.mul(transformation, accurateLocalMatrix);
accurateLocalMatrix = accurateLocalMatrix.translate(new BigDecimal[] { tx, ty, tz });
String tag = ref1.substring(0, ref1.lastIndexOf("#>")); //$NON-NLS-1$
if (type == CSG.TRANSFORM) {
tag = tag + " " + ref2.substring(0, ref2.lastIndexOf("#>")); //$NON-NLS-1$ //$NON-NLS-2$
accurateLocalMatrix = accurateLocalMatrix.transpose();
accurateLocalMatrix = accurateLocalMatrix.transposeXYZ();
}
return "0 !LPE" + t + tag + " " + colourBuilder.toString() + accurateLocalMatrix.toLDrawString(); //$NON-NLS-1$ //$NON-NLS-2$
default:
return text;
}
}
public synchronized String colourReplace(String colour2) {
boolean notChoosen = true;
String t = null;
switch (type) {
case CSG.QUAD:
if (notChoosen) {
t = " CSG_QUAD "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CIRCLE:
if (notChoosen) {
t = " CSG_CIRCLE "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.ELLIPSOID:
if (notChoosen) {
t = " CSG_ELLIPSOID "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CUBOID:
if (notChoosen) {
t = " CSG_CUBOID "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CYLINDER:
if (notChoosen) {
t = " CSG_CYLINDER "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.MESH:
if (notChoosen) {
t = " CSG_MESH "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.EXTRUDE:
if (notChoosen) {
t = " CSG_EXTRUDE "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.TRANSFORM:
if (notChoosen) {
t = " CSG_TRANSFORM "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CONE:
if (notChoosen) {
t = " CSG_CONE "; //$NON-NLS-1$
notChoosen = false;
}
Matrix4f newMatrix = new Matrix4f(this.matrix);
Matrix4f.transpose(newMatrix, newMatrix);
newMatrix.m30 = newMatrix.m03;
newMatrix.m31 = newMatrix.m13;
newMatrix.m32 = newMatrix.m23;
newMatrix.m03 = 0f;
newMatrix.m13 = 0f;
newMatrix.m23 = 0f;
String col = colour2;
String tag = ref1.substring(0, ref1.lastIndexOf("#>")); //$NON-NLS-1$
if (type == CSG.TRANSFORM) {
tag = tag + " " + ref2.substring(0, ref2.lastIndexOf("#>")); //$NON-NLS-1$ //$NON-NLS-2$
}
return "0 !LPE" + t + tag + " " + col + " " + MathHelper.matrixToString(newMatrix); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
default:
return text;
}
}
@Override
public void getBFCorientationMap(HashMap<GData, Byte> map) {}
@Override
public void getBFCorientationMapNOCERTIFY(HashMap<GData, Byte> map) {}
@Override
public void getBFCorientationMapNOCLIP(HashMap<GData, Byte> map) {}
@Override
public void getVertexNormalMap(GDataState state, ThreadsafeTreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, ThreadsafeHashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) {}
@Override
public void getVertexNormalMapNOCERTIFY(GDataState state, ThreadsafeTreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, ThreadsafeHashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) {}
@Override
public void getVertexNormalMapNOCLIP(GDataState state, ThreadsafeTreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, ThreadsafeHashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) {}
public synchronized static boolean hasSelectionCSG(DatFile df) {
return !selectedBodyMap.putIfAbsent(df, new HashSet<GDataCSG>()).isEmpty();
}
public synchronized boolean isSelected(DatFile df) {
return selectedBodyMap.putIfAbsent(df, new HashSet<GDataCSG>()).contains(this);
}
public synchronized static void drawSelectionCSG(Composite3D c3d, final boolean modifiedManipulator) {
final HashSet<GData3> selectedTriangles = selectedTrianglesMap.putIfAbsent(c3d.getLockableDatFileReference(), new HashSet<GData3>());
if (!selectedTriangles.isEmpty()) {
GL11.glColor3f(View.vertex_selected_Colour_r[0], View.vertex_selected_Colour_g[0], View.vertex_selected_Colour_b[0]);
GL11.glBegin(GL11.GL_LINES);
for (GData3 tri : selectedTriangles) {
GL11.glVertex3f(tri.x1, tri.y1, tri.z1);
GL11.glVertex3f(tri.x2, tri.y2, tri.z2);
GL11.glVertex3f(tri.x2, tri.y2, tri.z2);
GL11.glVertex3f(tri.x3, tri.y3, tri.z3);
GL11.glVertex3f(tri.x3, tri.y3, tri.z3);
GL11.glVertex3f(tri.x1, tri.y1, tri.z1);
}
GL11.glEnd();
}
}
public static void selectCSG(Composite3D c3d, Event event) {
try {
static_lock.lock();
final DatFile df = c3d.getLockableDatFileReference();
final HashSet<GData3> selectedTriangles = selectedTrianglesMap.putIfAbsent(df, new HashSet<GData3>());
if (!(c3d.getKeys().isCtrlPressed() || (Cocoa.isCocoa && c3d.getKeys().isCmdPressed()))) {
selectedTriangles.clear();
}
final Integer selectedBodyID = selectCSG_helper(c3d, event);
if (selectedBodyID != null) {
for (Entry<String, CSG> csg_pair : linkedCSG.putIfAbsent(df, new HashMap<String, CSG>()).entrySet()) {
if (csg_pair.getKey() != null && csg_pair.getKey().endsWith("#>null")) { //$NON-NLS-1$
CSG csg = csg_pair.getValue();
if (csg != null) {
for(Entry<GData3, Integer> pair : csg.getResult().entrySet()) {
if (selectedBodyID.equals(pair.getValue())) {
selectedTriangles.add(pair.getKey());
}
}
}
}
}
}
} finally {
static_lock.unlock();
}
}
private static Integer selectCSG_helper(Composite3D c3d, Event event) {
final PowerRay powerRay = new PowerRay();
final DatFile df = c3d.getLockableDatFileReference();
final HashBiMap<Integer, GData> dpl = df.getDrawPerLine_NOCLONE();
registeredData.putIfAbsent(df, new HashSet<GDataCSG>());
PerspectiveCalculator perspective = c3d.getPerspectiveCalculator();
Matrix4f viewport_rotation = c3d.getRotation();
Vector4f zAxis4f = new Vector4f(0, 0, -1f, 1f);
Matrix4f ovr_inverse2 = Matrix4f.invert(viewport_rotation, null);
Matrix4f.transform(ovr_inverse2, zAxis4f, zAxis4f);
Vector4f rayDirection = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise();
rayDirection.w = 1f;
Vertex[] triQuadVerts = new Vertex[3];
Vector4f orig = perspective.get3DCoordinatesFromScreen(event.x, event.y);
Vector4f point = new Vector4f(orig);
double minDist = Double.MAX_VALUE;
final double[] dist = new double[1];
Integer result = null;
GDataCSG resultObj = null;
for (CSG csg : linkedCSG.putIfAbsent(df, new HashMap<String, CSG>()).values()) {
for(Entry<GData3, Integer> pair : csg.getResult().entrySet()) {
final GData3 triangle = pair.getKey();
triQuadVerts[0] = new Vertex(triangle.x1, triangle.y1, triangle.z1);
triQuadVerts[1] = new Vertex(triangle.x2, triangle.y2, triangle.z2);
triQuadVerts[2] = new Vertex(triangle.x3, triangle.y3, triangle.z3);
if (powerRay.TRIANGLE_INTERSECT(orig, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2], point, dist)) {
if (dist[0] < minDist) {
Integer result2 = pair.getValue();
if (result2 != null) {
for (GDataCSG c : registeredData.get(df)) {
if (dpl.containsValue(c) && idToGDataCSG.putIfAbsent(df, new HashBiMap<Integer, GDataCSG>()).containsKey(result2)) {
if (c.type == CSG.TRANSFORM && c.ref1 != null && c.ref2 != null || c.ref1 != null && c.ref2 == null && c.ref3 == null && c.type != CSG.COMPILE) {
resultObj = idToGDataCSG.get(df).getValue(result2);
if (resultObj != null && resultObj.ref1 != null && resultObj.ref1.endsWith("#>null")) { //$NON-NLS-1$
minDist = dist[0];
result = result2;
break;
}
}
}
}
}
}
}
}
}
selectedBodyMap.putIfAbsent(df, new HashSet<GDataCSG>());
if (!(c3d.getKeys().isCtrlPressed() || (Cocoa.isCocoa && c3d.getKeys().isCmdPressed()))) {
selectedBodyMap.get(df).clear();
}
selectedBodyMap.get(df).add(resultObj);
return result;
}
public synchronized static HashSet<GDataCSG> getSelection(DatFile df) {
HashSet<GDataCSG> result = selectedBodyMap.putIfAbsent(df, new HashSet<GDataCSG>());
for (Iterator<GDataCSG> it = result.iterator(); it.hasNext();) {
if (it.next() == null) it.remove();
}
return result;
}
public synchronized static void selectAll(DatFile df) {
clearSelection(df);
HashSet<GDataCSG> newSelection = new HashSet<GDataCSG>(registeredData.putIfAbsent(df, new HashSet<GDataCSG>()));
for (Iterator<GDataCSG> it = newSelection.iterator(); it.hasNext();) {
final GDataCSG g = it.next();
if (g != null && g.canSelect()) {
continue;
}
it.remove();
}
selectedBodyMap.get(df).addAll(newSelection);
}
public synchronized boolean canSelect() {
if (ref1 != null && ref2 == null && ref3 == null && type != CSG.COMPILE) {
if (ref1.endsWith("#>null") && type != CSG.QUALITY && type != CSG.EPSILON) { //$NON-NLS-1$
return true;
}
}
return false;
}
public synchronized static HashSet<GColour> getSelectedColours(DatFile df) {
final HashSet<GColour> colours = new HashSet<GColour>();
final HashSet<GDataCSG> selection = getSelection(df);
for (GDataCSG g : selection) {
colours.add(g.colour);
}
return colours;
}
public synchronized static void selectAllWithSameColours(DatFile df, Set<GColour> allColours) {
HashSet<GDataCSG> newSelection = new HashSet<GDataCSG>(registeredData.putIfAbsent(df, new HashSet<GDataCSG>()));
for (Iterator<GDataCSG> it = newSelection.iterator(); it.hasNext();) {
final GDataCSG g = it.next();
if (g != null && g.canSelect() && allColours.contains(g.colour)) {
continue;
}
it.remove();
}
selectedBodyMap.get(df).addAll(newSelection);
}
public synchronized static void clearSelection(DatFile df) {
selectedBodyMap.putIfAbsent(df, new HashSet<GDataCSG>()).clear();
}
public static void rebuildSelection(DatFile df) {
final Composite3D c3d = df.getLastSelectedComposite();
if (c3d == null || df.getLastSelectedComposite().isDisposed()) return;
final HashSet<GData3> selectedTriangles = selectedTrianglesMap.putIfAbsent(df, new HashSet<GData3>());
final HashSet<GDataCSG> selectedBodies = selectedBodyMap.get(df);
selectedTriangles.clear();
if (selectedBodies != null) {
try {
for (GDataCSG c : selectedBodies) {
if (c == null) {
selectedTriangles.clear();
selectedBodies.clear();
return;
}
if (c.dataCSG == null) {
selectedTriangles.clear();
} else {
for (Polygon p : c.dataCSG.getPolygons()) {
Matrix4f id = new Matrix4f();
Matrix4f.setIdentity(id);
GData1 g1 = new GData1(-1, .5f, .5f, .5f, 1f, id, View.ACCURATE_ID, new ArrayList<String>(), null, null, 1, false, id, View.ACCURATE_ID, null, View.DUMMY_REFERENCE, true, false,
new HashSet<String>(), View.DUMMY_REFERENCE);
selectedTriangles.addAll(p.toLDrawTriangles(g1).keySet());
}
}
}
if (selectedTriangles.isEmpty()) {
selectedBodies.clear();
}
} catch (ConcurrentModificationException consumed) {
}
}
}
public synchronized Matrix4f getLDrawMatrix() {
Matrix4f oldMatrix = new Matrix4f(matrix);
Matrix4f.transpose(oldMatrix, oldMatrix);
oldMatrix.m30 = oldMatrix.m03;
oldMatrix.m31 = oldMatrix.m13;
oldMatrix.m32 = oldMatrix.m23;
oldMatrix.m03 = 0f;
oldMatrix.m13 = 0f;
oldMatrix.m23 = 0f;
return oldMatrix;
}
public synchronized String getRoundedString(int coordsDecimalPlaces, int matrixDecimalPlaces, final boolean onX, final boolean onY, final boolean onZ) {
boolean notChoosen = true;
String t = null;
switch (type) {
case CSG.QUAD:
if (notChoosen) {
t = " CSG_QUAD "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CIRCLE:
if (notChoosen) {
t = " CSG_CIRCLE "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.ELLIPSOID:
if (notChoosen) {
t = " CSG_ELLIPSOID "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CUBOID:
if (notChoosen) {
t = " CSG_CUBOID "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CYLINDER:
if (notChoosen) {
t = " CSG_CYLINDER "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.MESH:
if (notChoosen) {
t = " CSG_MESH "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.EXTRUDE:
if (notChoosen) {
t = " CSG_EXTRUDE "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.TRANSFORM:
if (notChoosen) {
t = " CSG_TRANSFORM "; //$NON-NLS-1$
notChoosen = false;
}
case CSG.CONE:
if (notChoosen) {
t = " CSG_CONE "; //$NON-NLS-1$
notChoosen = false;
}
StringBuilder colourBuilder = new StringBuilder();
if (colour == null) {
colourBuilder.append(16);
} else if (colour.getColourNumber() == -1) {
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * colour.getB())).toUpperCase());
} else {
colourBuilder.append(colour.getColourNumber());
}
Matrix4f newMatrix = new Matrix4f(this.matrix);
Matrix4f.transpose(newMatrix, newMatrix);
newMatrix.m30 = newMatrix.m03;
newMatrix.m31 = newMatrix.m13;
newMatrix.m32 = newMatrix.m23;
newMatrix.m03 = 0f;
newMatrix.m13 = 0f;
newMatrix.m23 = 0f;
String tag = ref1.substring(0, ref1.lastIndexOf("#>")); //$NON-NLS-1$
if (type == CSG.TRANSFORM) {
tag = tag + " " + ref2.substring(0, ref2.lastIndexOf("#>")); //$NON-NLS-1$ //$NON-NLS-2$
}
return "0 !LPE" + t + tag + " " + colourBuilder.toString() + " " + MathHelper.matrixToString(newMatrix, coordsDecimalPlaces, matrixDecimalPlaces, onX, onY, onZ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
return null;
}
public static synchronized void backupSelection(DatFile linkedDatFile) {
while (true) {
try {
backupSelectedBodyMap.put(linkedDatFile, new HashSet<GDataCSG>(selectedBodyMap.putIfAbsent(linkedDatFile, new HashSet<GDataCSG>())));
backupSelectedTrianglesMap.put(linkedDatFile, new HashSet<GData3>(selectedTrianglesMap.putIfAbsent(linkedDatFile, new HashSet<GData3>())));
break;
} catch (ConcurrentModificationException cme) {}
}
}
public static synchronized void backupSelectionClear(DatFile linkedDatFile) {
while (true) {
try {
backupSelectedBodyMap.put(linkedDatFile, new HashSet<GDataCSG>());
backupSelectedTrianglesMap.put(linkedDatFile, new HashSet<GData3>());
break;
} catch (ConcurrentModificationException cme) {}
}
}
public static synchronized void restoreSelection(DatFile linkedDatFile) {
while (true) {
try {
selectedBodyMap.put(linkedDatFile, backupSelectedBodyMap.putIfAbsent(linkedDatFile, new HashSet<GDataCSG>()));
selectedTrianglesMap.put(linkedDatFile, backupSelectedTrianglesMap.putIfAbsent(linkedDatFile, new HashSet<GData3>()));
break;
} catch (ConcurrentModificationException cme) {}
}
}
public static Collection<CSG> getCSGs(final DatFile df) {
return linkedCSG.putIfAbsent(df, new HashMap<String, CSG>()).values();
}
public static void finishCacheCleanup(DatFile df) {
if (clearPolygonCache.get(df) == true) {
if (fullClearPolygonCache.get(df) != true) {
fullClearPolygonCache.put(df, true);
clearPolygonCache.put(df, true);
if (allNewPolygonVertices.containsKey(df)) {
allNewPolygonVertices.get(df).clear();
}
} else {
clearPolygonCache.put(df, false);
}
}
}
public static List<VectorCSGd[]> getNewPolyVertices(DatFile df) {
ArrayList<VectorCSGd[]> result = new ArrayList<VectorCSGd[]>();
if (compileAndInline.get(df)) {
return allNewPolygonVertices.putIfAbsent(df, result);
} else {
return result;
}
}
public static boolean isInlining(DatFile df) {
return compileAndInline.get(df);
}
public int[] getDataSize() {
final int[] result = new int[]{0, 0, 0};
if (compiledCSG != null) {
TreeMap<GData3, Integer> resultData = compiledCSG.getResult();
for (GData3 tri : resultData.keySet()) {
if (tri.a < 1f) {
result[2] += 6;
} else {
result[1] += 6;
}
}
result[0] = 60 * resultData.size();
}
return result;
}
public Set<GData3> getSurfaces() {
if (compiledCSG == null) {
return new HashSet<GData3>();
} else {
return compiledCSG.getResult().keySet();
}
}
public static HashSet<GData3> getSelectionData(DatFile df) {
return selectedTrianglesMap.putIfAbsent(df, new HashSet<GData3>());
}
} |
package cogmac.glui;
import java.awt.Color;
import javax.media.opengl.GL;
import static javax.media.opengl.GL.*;
/**
* @author decamp
*/
public class GColor {
public static final GColor BLACK = new GColor( 0f, 0f, 0f );
public static final GColor BLUE = new GColor( Color.BLUE );
public static final GColor CYAN = new GColor( Color.CYAN );
public static final GColor DARK_GRAY = new GColor( Color.DARK_GRAY );
public static final GColor GRAY = new GColor( Color.GRAY );
public static final GColor GREEN = new GColor( Color.GREEN );
public static final GColor LIGHT_GRAY = new GColor( Color.LIGHT_GRAY );
public static final GColor MAGENTA = new GColor( Color.MAGENTA );
public static final GColor ORANGE = new GColor( Color.ORANGE );
public static final GColor PINK = new GColor( Color.PINK );
public static final GColor RED = new GColor( Color.RED );
public static final GColor WHITE = new GColor( 1f, 1f, 1f );
public static final GColor YELLOW = new GColor( Color.YELLOW );
public static final GColor CLEAR_WHITE = new GColor( 1f, 1f, 1f, 0f );
public static final GColor CLEAR_BLACK = new GColor( 0f, 0f, 0f, 1f );
public static GColor fromCurrent( GL gl ) {
float[] arr = new float[4];
gl.glGetFloatv( GL_CURRENT_COLOR, arr, 0 );
return new GColor( arr[0], arr[1], arr[2], arr[3] );
}
public static GColor fromRgba( float[] rgba, int off ) {
return new GColor( rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3] );
}
public static GColor fromRgb( float[] rgb, int off ) {
return new GColor( rgb[off], rgb[off + 1], rgb[off + 2], 1f );
}
public static GColor fromRgba( double[] rgba, int off ) {
return new GColor( (float) rgba[off], (float) rgba[off + 1], (float) rgba[off + 2], (float) rgba[off + 3] );
}
public static GColor fromRgb( double[] rgb, int off ) {
return new GColor( (float) rgb[off], (float) rgb[off + 1], (float) rgb[off + 2], 1f );
}
public static GColor fromRgba( int rgba ) {
return new GColor( ( rgba >>> 24) / 255f,
( ( rgba >> 16) & 0xFF) / 255f,
( ( rgba >> 8) & 0xFF) / 255f,
( ( rgba) & 0xFF) / 255f );
}
public static GColor fromArgb( int argb ) {
return new GColor( ( ( argb >> 16) & 0xFF) / 255f,
( ( argb >> 8) & 0xFF) / 255f,
( ( argb) & 0xFF) / 255f,
( ( argb >>> 24) / 255f) );
}
public static GColor fromBgra( int bgra ) {
return new GColor( ( ( bgra >> 8) & 0xFF) / 255f,
( ( bgra >> 16) & 0xFF) / 255f,
( ( bgra >>> 24)) / 255f,
( ( bgra) & 0xFF) / 255f );
}
public static GColor fromHsb( float hue, float saturation, float brightness ) {
return fromHsba( hue, saturation, brightness, 1.0f );
}
public static GColor fromHsba( float hue, float saturation, float brightness, float alpha ) {
if( saturation == 0 )
return new GColor( brightness, brightness, brightness, alpha );
float h = ( hue - (float) Math.floor( hue )) * 6.0f;
float f = h - (float) Math.floor( h );
float p = brightness * ( 1.0f - saturation);
float q = brightness * ( 1.0f - saturation * f);
float t = brightness * ( 1.0f - ( saturation * ( 1.0f - f)));
switch( (int) h ) {
case 0:
return new GColor( brightness, t, p, alpha );
case 1:
return new GColor( q, brightness, p, alpha );
case 2:
return new GColor( p, brightness, t, alpha );
case 3:
return new GColor( p, q, brightness, alpha );
case 4:
return new GColor( t, p, brightness, alpha );
case 5:
return new GColor( brightness, p, q, alpha );
default:
return new GColor( 0, 0, 0, alpha );
}
}
private final float mRed;
private final float mGreen;
private final float mBlue;
private final float mAlpha;
public GColor( float r, float g, float b ) {
this( r, g, b, 1f );
}
public GColor( float r, float g, float b, float a ) {
mRed = r;
mGreen = g;
mBlue = b;
mAlpha = a;
}
public GColor( double r, double g, double b ) {
this( r, g, b, 1.0 );
}
public GColor( double r, double g, double b, double a ) {
mRed = (float)r;
mGreen = (float)g;
mBlue = (float)b;
mAlpha = (float)a;
}
public GColor( Color c ) {
mRed = c.getRed() / 255f;
mGreen = c.getGreen() / 255f;
mBlue = c.getBlue() / 255f;
mAlpha = c.getAlpha() / 255f;
}
public float r() {
return mRed;
}
public float g() {
return mGreen;
}
public float b() {
return mBlue;
}
public float a() {
return mAlpha;
}
public GColor r( double r ) {
return new GColor( (float)r, mGreen, mBlue, mAlpha );
}
public GColor g( double g ) {
return new GColor( mRed, (float)g, mBlue, mAlpha );
}
public GColor b( double b ) {
return new GColor( mRed, mGreen, (float)b, mAlpha );
}
public GColor a( double a ) {
return new GColor( mRed, mGreen, mBlue, (float)a );
}
public final void apply( GL gl ) {
gl.glColor4f( mRed, mGreen, mBlue, mAlpha );
}
public Color toAwt() {
return new Color(mRed, mGreen, mBlue, mAlpha);
}
public float[] toFloatArray() {
return new float[]{ mRed, mGreen, mBlue, mAlpha };
}
public void toFloatArray( float[] out4x1 ) {
out4x1[0] = mRed;
out4x1[1] = mGreen;
out4x1[2] = mBlue;
out4x1[3] = mAlpha;
}
public double[] toDoubleArray() {
return new double[]{ mRed, mGreen, mBlue, mAlpha };
}
public void toDoubleArray( double[] out4x1 ) {
out4x1[0] = mRed;
out4x1[1] = mGreen;
out4x1[2] = mBlue;
out4x1[3] = mAlpha;
}
} |
package org.opencms.workplace.editors;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.i18n.CmsEncoder;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsDialog;
import org.opencms.workplace.CmsFrameset;
import org.opencms.workplace.CmsWorkplace;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.jsp.JspException;
import org.apache.commons.logging.Log;
/**
* Provides basic methods for building the file editors of OpenCms.<p>
*
* The editor classes have to extend this class and implement action methods for common editor actions.<p>
*
* @author Andreas Zahner
*
* @version $Revision: 1.28 $
*
* @since 6.0.0
*/
public abstract class CmsEditor extends CmsDialog {
/** Value for the action: change the body. */
public static final int ACTION_CHANGE_BODY = 124;
/** Value for the action: exit. */
public static final int ACTION_EXIT = 122;
/** Value for the action: show a preview. */
public static final int ACTION_PREVIEW = 126;
/** Value for the action: save. */
public static final int ACTION_SAVE = 121;
/** Constant value for the customizable action button. */
public static final int ACTION_SAVEACTION = 130;
/** Value for the action: save and exit. */
public static final int ACTION_SAVEEXIT = 123;
/** Value for the action: show the editor. */
public static final int ACTION_SHOW = 125;
/** Value for the action: an error occured. */
public static final int ACTION_SHOW_ERRORMESSAGE = 127;
/** Stores the VFS editor path. */
public static final String PATH_EDITORS = PATH_WORKPLACE + "editors/";
/** Constant for the Editor special "save error" confirmation dialog. */
public static final String FILE_DIALOG_EDITOR_CONFIRM = PATH_EDITORS + "dialogs/confirm.jsp";
/** Value for the action parameter: change the element. */
public static final String EDITOR_CHANGE_ELEMENT = "changeelement";
/** Value for the action parameter: cleanup content. */
public static final String EDITOR_CLEANUP = "cleanup";
/** Value for the action parameter: exit editor. */
public static final String EDITOR_EXIT = "exit";
/** Value for the action parameter: show a preview. */
public static final String EDITOR_PREVIEW = "preview";
/** Value for the action parameter: save content. */
public static final String EDITOR_SAVE = "save";
/** Value for the customizable action button. */
public static final String EDITOR_SAVEACTION = "saveaction";
/** Value for the action parameter: save and exit. */
public static final String EDITOR_SAVEEXIT = "saveexit";
/** Value for the action parameter: show the editor. */
public static final String EDITOR_SHOW = "show";
/** Value for the action parameter: an error occured. */
public static final String EDITOR_SHOW_ERRORMESSAGE = "error";
/** Parameter name for the request parameter "backlink". */
public static final String PARAM_BACKLINK = "backlink";
/** Parameter name for the request parameter "content". */
public static final String PARAM_CONTENT = "content";
/** Parameter name for the request parameter "directedit". */
public static final String PARAM_DIRECTEDIT = "directedit";
/** Parameter name for the request parameter "editastext". */
public static final String PARAM_EDITASTEXT = "editastext";
/** Parameter name for the request parameter "editormode". */
public static final String PARAM_EDITORMODE = "editormode";
/** Parameter name for the request parameter "element language". */
public static final String PARAM_ELEMENTLANGUAGE = "elementlanguage";
/** Parameter name for the request parameter "loaddefault". */
public static final String PARAM_LOADDEFAULT = "loaddefault";
/** Parameter name for the request parameter "modified". */
public static final String PARAM_MODIFIED = "modified";
/** Parameter name for the request parameter "old element language". */
public static final String PARAM_OLDELEMENTLANGUAGE = "oldelementlanguage";
/** Parameter name for the request parameter "tempfile". */
public static final String PARAM_TEMPFILE = "tempfile";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsEditor.class);
/** The encoding to use (will be read from the file property). */
private String m_fileEncoding;
// some private members for parameter storage
private String m_paramBackLink;
private String m_paramContent;
private String m_paramDirectedit;
private String m_paramEditAsText;
private String m_paramEditormode;
private String m_paramElementlanguage;
private String m_paramLoadDefault;
private String m_paramModified;
private String m_paramOldelementlanguage;
private String m_paramTempFile;
/** Helper variable to store the uri to the editors pictures. */
private String m_picsUri;
/**
* Public constructor.<p>
*
* @param jsp an initialized JSP action element
*/
public CmsEditor(CmsJspActionElement jsp) {
super(jsp);
}
/**
* Unlocks the edited resource when in direct edit mode or when the resource was not modified.<p>
*
* @param forceUnlock if true, the resource will be unlocked anyway
*/
public abstract void actionClear(boolean forceUnlock);
/**
* Performs the exit editor action.<p>
*
* @throws CmsException if something goes wrong
* @throws IOException if a redirection fails
* @throws JspException if including an element fails
*/
public abstract void actionExit() throws CmsException, IOException, JspException;
/**
* Performs the save content action.<p>
*
* @throws IOException if a redirection fails
* @throws JspException if including an element fails
*/
public abstract void actionSave() throws IOException, JspException;
/**
* Builds the html String for the element language selector.<p>
*
* @param attributes optional attributes for the <select> tag
* @param resource the name of the resource to edit
* @param selectedLocale the currently selected Locale
* @return the html for the element language selectbox
*/
public String buildSelectElementLanguage(String attributes, String resource, Locale selectedLocale) {
// get locale names based on properties and global settings
List locales = OpenCms.getLocaleManager().getAvailableLocales(getCms(), resource);
List options = new ArrayList(locales.size());
List selectList = new ArrayList(locales.size());
int currentIndex = -1;
for (int counter = 0; counter < locales.size(); counter++) {
// create the list of options and values
Locale curLocale = (Locale)locales.get(counter);
selectList.add(curLocale.toString());
options.add(curLocale.getDisplayName(getLocale()));
if (curLocale.equals(selectedLocale)) {
// set the selected index of the selector
currentIndex = counter;
}
}
if (currentIndex == -1) {
// no matching element language found, use first element language in list
if (selectList != null && selectList.size() > 0) {
currentIndex = 0;
setParamElementlanguage((String)selectList.get(0));
}
}
return buildSelect(attributes, options, selectList, currentIndex, false);
}
/**
* Generates a button for the OpenCms editor.<p>
*
* @param href the href link for the button, if none is given the button will be disabled
* @param target the href link target for the button, if none is given the target will be same window
* @param image the image name for the button, skin path will be automattically added as prefix
* @param label the label for the text of the button
* @param type 0: image only (default), 1: image and text, 2: text only
* @param useCustomImage if true, the button has to be placed in the editors "custom pics" folder
*
* @return a button for the OpenCms editor
*/
public String button(String href, String target, String image, String label, int type, boolean useCustomImage) {
if (useCustomImage) {
// search the picture in the "custom pics" folder
return button(href, target, image, label, type, getPicsUri());
} else {
// search the picture in the common "buttons" folder
return button(href, target, image, label, type);
}
}
/**
* Returns the editor action for a "cancel" button.<p>
*
* This overwrites the cancel method of the CmsDialog class.<p>
*
* Always use this value, do not write anything directly in the html page.<p>
*
* @return the default action for a "cancel" button
*/
public String buttonActionCancel() {
String target = null;
if ("true".equals(getParamDirectedit())) {
// editor is in direct edit mode
if (!"".equals(getParamBacklink())) {
// set link to the specified back link target
target = getParamBacklink();
} else {
// set link to the edited resource
target = getParamResource();
}
} else {
// in workplace mode, show explorer view
target = OpenCms.getLinkManager().substituteLink(getCms(), CmsFrameset.JSP_WORKPLACE_URI);
}
return "onclick=\"top.location.href='" + getJsp().link(target) + "';\"";
}
/**
* Builds the html to display the special action button for the direct edit mode of the editor.<p>
*
* @param jsFunction the JavaScript function which will be executed on the mouseup event
* @param type 0: image only (default), 1: image and text, 2: text only
* @return the html to display the special action button
*/
public String buttonActionDirectEdit(String jsFunction, int type) {
// get the action class from the OpenCms runtime property
I_CmsEditorActionHandler actionClass = OpenCms.getWorkplaceManager().getEditorActionHandler();
String url;
String name;
boolean active = false;
if (actionClass != null) {
// get button parameters and state from action class
url = actionClass.getButtonUrl(getJsp(), getParamResource());
name = actionClass.getButtonName();
active = actionClass.isButtonActive(getJsp(), getParamResource());
} else {
// action class not defined, display inactive button
url = getSkinUri() + "buttons/publish_in.png";
name = "explorer.context.publish";
}
String image = url.substring(url.lastIndexOf("/") + 1);
if (url.endsWith(".gif")) {
image = image.substring(0, image.length() - 4);
}
if (active) {
// create the link for the button
return button("javascript:" + jsFunction, null, image, name, type, url.substring(
0,
url.lastIndexOf("/") + 1));
} else {
// create the inactive button
return button(null, null, image, name + "_in", type, url.substring(0, url.lastIndexOf("/") + 1));
}
}
/**
* @see org.opencms.workplace.CmsWorkplace#checkLock(java.lang.String, int)
*/
public void checkLock(String resource, int mode) throws CmsException {
CmsResource res = getCms().readResource(resource, CmsResourceFilter.ALL);
if (!getCms().getLock(res).isNullLock()) {
setParamModified(Boolean.TRUE.toString());
}
super.checkLock(resource, mode);
}
/**
* Returns the instanciated editor display option class from the workplace manager.<p>
*
* This is a convenience method to be used on editor JSPs.<p>
*
* @return the instanciated editor display option class
*/
public CmsEditorDisplayOptions getEditorDisplayOptions() {
return OpenCms.getWorkplaceManager().getEditorDisplayOptions();
}
/**
* Returns the URI to the editor resource folder where button images and javascripts are located.<p>
*
* @return the URI to the editor resource folder
*/
public abstract String getEditorResourceUri();
/**
* Returns the OpenCms request context path.<p>
*
* This is a convenience method to use in the editor.<p>
*
* @return the OpenCms request context path
*/
public String getOpenCmsContext() {
return OpenCms.getSystemInfo().getOpenCmsContext();
}
/**
* Returns the back link when closing the editor.<p>
*
* @return the back link
*/
public String getParamBacklink() {
if (m_paramBackLink == null) {
m_paramBackLink = "";
}
return m_paramBackLink;
}
/**
* Returns the content of the editor.<p>
* @return the content of the editor
*/
public String getParamContent() {
if (m_paramContent == null) {
m_paramContent = "";
}
return m_paramContent;
}
/**
* Returns the direct edit flag parameter.<p>
*
* @return the direct edit flag parameter
*/
public String getParamDirectedit() {
return m_paramDirectedit;
}
/**
* Returns the edit as text parameter.<p>
*
* @return the edit as text parameter
*/
public String getParamEditastext() {
return m_paramEditAsText;
}
/**
* Returns the editor mode parameter.<p>
*
* @return the editor mode parameter
*/
public String getParamEditormode() {
return m_paramEditormode;
}
/**
* Returns the current element language.<p>
*
* @return the current element language
*/
public String getParamElementlanguage() {
return m_paramElementlanguage;
}
/**
* Returns the "loaddefault" parameter to determine if the default editor should be loaded.<p>
*
* @return the "loaddefault" parameter
*/
public String getParamLoaddefault() {
return m_paramLoadDefault;
}
/**
* Returns the modified parameter indicating if the resource has been saved.<p>
*
* @return the modified parameter indicating if the resource has been saved
*/
public String getParamModified() {
return m_paramModified;
}
/**
* Returns the old element language.<p>
*
* @return the old element language
*/
public String getParamOldelementlanguage() {
return m_paramOldelementlanguage;
}
/**
* Returns the name of the temporary file.<p>
*
* @return the name of the temporary file
*/
public String getParamTempfile() {
return m_paramTempFile;
}
/**
* Returns the path to the images used by this editor.<p>
*
* @return the path to the images used by this editor
*/
public String getPicsUri() {
if (m_picsUri == null) {
m_picsUri = getEditorResourceUri() + "pics/";
}
return m_picsUri;
}
/**
* Sets the back link when closing the editor.<p>
*
* @param backLink the back link
*/
public void setParamBacklink(String backLink) {
m_paramBackLink = backLink;
}
/**
* Sets the content of the editor.<p>
*
* @param content the content of the editor
*/
public void setParamContent(String content) {
if (content == null) {
content = "";
}
m_paramContent = content;
}
/**
* Sets the direct edit flag parameter.<p>
*
* @param direct the direct edit flag parameter
*/
public void setParamDirectedit(String direct) {
m_paramDirectedit = direct;
}
/**
* Sets the edit as text parameter.<p>
*
* @param editAsText "true" if the resource should be handled like a text file
*/
public void setParamEditastext(String editAsText) {
m_paramEditAsText = editAsText;
}
/**
* Sets the editor mode parameter.<p>
*
* @param mode the editor mode parameter
*/
public void setParamEditormode(String mode) {
m_paramEditormode = mode;
}
/**
* Sets the current element language.<p>
*
* @param elementLanguage the current element language
*/
public void setParamElementlanguage(String elementLanguage) {
m_paramElementlanguage = elementLanguage;
}
/**
* Sets the "loaddefault" parameter to determine if the default editor should be loaded.<p>
*
* @param loadDefault the "loaddefault" parameter
*/
public void setParamLoaddefault(String loadDefault) {
m_paramLoadDefault = loadDefault;
}
/**
* Sets the modified parameter indicating if the resource has been saved.<p>
*
* @param modified the modified parameter indicating if the resource has been saved
*/
public void setParamModified(String modified) {
m_paramModified = modified;
}
/**
* Sets the old element language.<p>
*
* @param oldElementLanguage the old element language
*/
public void setParamOldelementlanguage(String oldElementLanguage) {
m_paramOldelementlanguage = oldElementLanguage;
}
/**
* Sets the name of the temporary file.<p>
*
* @param fileName the name of the temporary file
*/
public void setParamTempfile(String fileName) {
m_paramTempFile = fileName;
}
/**
* Closes the editor and redirects to the workplace or the resource depending on the editor mode.<p>
*
* @throws IOException if a redirection fails
* @throws JspException if including a JSP fails
*/
protected void actionClose() throws IOException, JspException {
if ("true".equals(getParamDirectedit())) {
// editor is in direct edit mode
if (!"".equals(getParamBacklink())) {
// set link to the specified back link target
setParamCloseLink(getJsp().link(getParamBacklink()));
} else {
// set link to the edited resource
setParamCloseLink(getJsp().link(getParamResource()));
}
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
// load the common JSP close dialog
getJsp().include(FILE_DIALOG_CLOSE);
} else {
// redirect to the workplace explorer view
sendCmsRedirect(CmsFrameset.JSP_WORKPLACE_URI);
}
}
/**
* Writes the content of a temporary file back to the original file.<p>
*
* @throws CmsException if something goes wrong
*/
protected void commitTempFile() throws CmsException {
switchToTempProject();
CmsFile tempFile;
List properties;
try {
tempFile = getCms().readFile(getParamTempfile(), CmsResourceFilter.ALL);
properties = getCms().readPropertyObjects(getParamTempfile(), false);
} finally {
// make sure the project is reset in case of any exception
switchToCurrentProject();
}
// update properties of original file first (required if change in encoding occured)
getCms().writePropertyObjects(getParamResource(), properties);
// now replace the content of the original file
CmsFile orgFile = getCms().readFile(getParamResource(), CmsResourceFilter.ALL);
orgFile.setContents(tempFile.getContents());
getCms().writeFile(orgFile);
}
/**
* Creates a temporary file which is needed while working in an editor with preview option.<p>
*
* @return the file name of the temporary file
* @throws CmsException if something goes wrong
*/
protected String createTempFile() throws CmsException {
// read the selected file
CmsResource file = getCms().readResource(getParamResource(), CmsResourceFilter.ALL);
// create the filename of the temporary file
String temporaryFilename = CmsResource.getFolderPath(getCms().getSitePath(file))
+ CmsWorkplace.TEMP_FILE_PREFIX
+ file.getName();
// check if the temporary file is already present
if (getCms().existsResource(temporaryFilename, CmsResourceFilter.ALL)) {
// delete old temporary file
if (!getCms().getLock(temporaryFilename).equals(CmsLock.getNullLock())) {
// steal lock
getCms().changeLock(temporaryFilename);
} else {
// lock resource to current user
getCms().lockResource(temporaryFilename);
}
getCms().deleteResource(temporaryFilename, CmsResource.DELETE_PRESERVE_SIBLINGS);
}
// switch to the temporary file project
switchToTempProject();
// copy the file to edit to a temporary file
try {
getCms().copyResource(getCms().getSitePath(file), temporaryFilename, CmsResource.COPY_AS_NEW);
getCms().touch(
temporaryFilename,
System.currentTimeMillis(),
CmsResource.DATE_RELEASED_DEFAULT,
CmsResource.DATE_EXPIRED_DEFAULT,
false);
} catch (CmsException e) {
switchToCurrentProject();
throw e;
}
// switch back to current project
switchToCurrentProject();
return temporaryFilename;
}
/**
* Decodes the given content the same way the client would do it.<p>
*
* Content is decoded as if it was encoded using the JavaScript
* "encodeURIComponent()" function.<p>
*
* @param content the content to decode
* @return the decoded content
*/
protected String decodeContent(String content) {
return CmsEncoder.unescape(content, CmsEncoder.ENCODING_UTF_8);
}
/**
* Decodes an individual parameter value, ensuring the content is always decoded in UTF-8.<p>
*
* For editors the content is always encoded using the
* JavaScript encodeURIComponent() method on the client,
* which always encodes in UTF-8.<p>
*
* @param paramName the name of the parameter
* @param paramValue the unencoded value of the parameter
* @return the encoded value of the parameter
*/
protected String decodeParamValue(String paramName, String paramValue) {
if ((paramName != null) && (paramValue != null)) {
if (PARAM_CONTENT.equals(paramName)) {
// content will be always encoded in UTF-8 unicode by the editor client
return CmsEncoder.decode(paramValue, CmsEncoder.ENCODING_UTF_8);
} else if (PARAM_RESOURCE.equals(paramName) || PARAM_TEMPFILE.equals(paramName)) {
String filename = CmsEncoder.decode(paramValue, getCms().getRequestContext().getEncoding());
if (PARAM_TEMPFILE.equals(paramName) || CmsStringUtil.isEmpty(getParamTempfile())) {
// always use value from temp file if it is available
setFileEncoding(getFileEncoding(getCms(), filename));
}
return filename;
} else {
return CmsEncoder.decode(paramValue, getCms().getRequestContext().getEncoding());
}
} else {
return null;
}
}
/**
* Deletes a temporary file from the OpenCms VFS, needed when exiting an editor.<p>
*/
protected void deleteTempFile() {
try {
// switch to the temporary file project
switchToTempProject();
// delete the temporary file
getCms().deleteResource(getParamTempfile(), CmsResource.DELETE_PRESERVE_SIBLINGS);
// switch back to the current project
switchToCurrentProject();
} catch (CmsException e) {
// should usually never happen
if (LOG.isInfoEnabled()) {
LOG.info(e);
}
}
}
/**
* Encodes the given content so that it can be transfered to the client.<p>
*
* Content is encoded so that it is compatible with the JavaScript
* "decodeURIComponent()" function.<p>
*
* @param content the content to encode
* @return the encoded content
*/
protected String encodeContent(String content) {
return CmsEncoder.escapeWBlanks(content, CmsEncoder.ENCODING_UTF_8);
}
/**
* Returns the encoding parameter.<p>
*
* @return the encoding parameter
*/
protected String getFileEncoding() {
return m_fileEncoding;
}
/**
* Helper method to determine the encoding of the given file in the VFS,
* which must be set using the "content-encoding" property.<p>
*
* @param cms the CmsObject
* @param filename the name of the file which is to be checked
* @return the encoding for the file
*/
protected String getFileEncoding(CmsObject cms, String filename) {
try {
return cms.readPropertyObject(filename, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, false).getValue(
OpenCms.getSystemInfo().getDefaultEncoding());
} catch (CmsException e) {
return OpenCms.getSystemInfo().getDefaultEncoding();
}
}
/**
* Initializes the editor content when openening the editor for the first time.<p>
*/
protected abstract void initContent();
/**
* Sets the encoding parameter.<p>
*
* @param value the encoding value to set
*/
protected void setFileEncoding(String value) {
m_fileEncoding = CmsEncoder.lookupEncoding(value, value);
}
/**
* Shows the selected error page in case of an exception.<p>
*
* @param exception the current exception
* @throws JspException if inclusion of the error page fails
*/
protected void showErrorPage(Exception exception) throws JspException {
// reset the action parameter
setParamAction("");
showErrorPage(this, exception);
// save not successful, set cancel action
setAction(ACTION_CANCEL);
return;
}
/**
* Shows the selected error page in case of an exception.<p>
*
* @param editor initialized instance of the editor class
* @param exception the current exception
* @throws JspException if inclusion of the error page fails
*/
protected void showErrorPage(Object editor, Exception exception) throws JspException {
// save initialized instance of the editor class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, editor);
// reading of file contents failed, show error dialog
setAction(ACTION_SHOW_ERRORMESSAGE);
setParamTitle(key("title.edit") + ": " + CmsResource.getName(getParamResource()));
if (exception != null) {
getJsp().getRequest().setAttribute(ATTRIBUTE_THROWABLE, exception);
if (CmsLog.getLog(editor).isWarnEnabled()) {
CmsLog.getLog(editor).warn(exception.getLocalizedMessage(), exception);
}
}
// include the common error dialog
getJsp().include(FILE_DIALOG_SCREEN_ERRORPAGE);
}
} |
// ZAP: 2011/09/19 Added debugging
// ZAP: 2012/04/23 Removed unnecessary cast.
// ZAP: 2012/05/08 Use custom http client on "Connection: Upgrade" in executeMethod().
// Retrieve upgraded socket and save for later use in send() method.
// ZAP: 2012/08/07 Issue 342 Support the HttpSenderListener
// ZAP: 2012/12/27 Do not read request body on Server-Sent Event streams.
// ZAP: 2013/01/03 Resolved Checkstyle issues: removed throws HttpException
// declaration where IOException already appears,
// introduced two helper methods for notifying listeners.
// ZAP: 2013/01/19 Issue 459: Active scanner locking
// ZAP: 2013/01/23 Clean up of exception handling/logging.
// ZAP: 2013/01/30 Issue 478: Allow to choose to send ZAP's managed cookies on
// a single Cookie request header and set it as the default
// ZAP: 2013/07/10 Issue 720: Cannot send non standard http methods
// ZAP: 2013/07/14 Issue 729: Update NTLM authentication code
// ZAP: 2013/07/25 Added support for sending the message from the perspective of a User
// ZAP: 2013/08/31 Reauthentication when sending a message from the perspective of a User
// ZAP: 2013/09/07 Switched to using HttpState for requesting User for cookie management
// ZAP: 2013/09/26 Issue 716: ZAP flags its own HTTP responses
// ZAP: 2013/09/26 Issue 656: Content-length: 0 in GET requests
// ZAP: 2013/09/29 Deprecating configuring HTTP Authentication through Options
// ZAP: 2013/11/16 Issue 837: Update, always, the HTTP request sent/forward by ZAP's proxy
// ZAP: 2013/12/11 Corrected log.info calls to use debug
// ZAP: 2014/03/04 Issue 1043: Custom active scan dialog
package org.parosproxy.paros.network;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.log4j.Logger;
import org.zaproxy.zap.ZapGetMethod;
import org.zaproxy.zap.ZapHttpConnectionManager;
import org.zaproxy.zap.network.HttpSenderListener;
import org.zaproxy.zap.network.ZapNTLMScheme;
import org.zaproxy.zap.users.User;
public class HttpSender {
public static final int PROXY_INITIATOR = 1;
public static final int ACTIVE_SCANNER_INITIATOR = 2;
public static final int SPIDER_INITIATOR = 3;
public static final int FUZZER_INITIATOR = 4;
public static final int AUTHENTICATION_INITIATOR = 5;
public static final int MANUAL_REQUEST_INITIATOR = 6;
public static final int CHECK_FOR_UPDATES_INITIATOR = 7;
public static final int BEAN_SHELL_INITIATOR = 8;
private static Logger log = Logger.getLogger(HttpSender.class);
private static ProtocolSocketFactory sslFactory = null;
private static Protocol protocol = null;
// Issue 90
private static boolean allowUnsafeSSLRenegotiation = false;
private static List<HttpSenderListener> listeners = new ArrayList<>();
private static Comparator<HttpSenderListener> listenersComparator = null;;
private User user = null;
static {
try {
protocol = Protocol.getProtocol("https");
sslFactory = protocol.getSocketFactory();
} catch (Exception e) {
}
// avoid init again if already initialized
if (sslFactory == null || !(sslFactory instanceof SSLConnector)) {
Protocol.registerProtocol("https", new Protocol("https",
(ProtocolSocketFactory) new SSLConnector(), 443));
}
AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, ZapNTLMScheme.class);
}
private static HttpMethodHelper helper = new HttpMethodHelper();
private static String userAgent = "";
private HttpClient client = null;
private HttpClient clientViaProxy = null;
private ConnectionParam param = null;
private MultiThreadedHttpConnectionManager httpConnManager = null;
private MultiThreadedHttpConnectionManager httpConnManagerProxy = null;
private boolean followRedirect = false;
private boolean allowState = false;
private int initiator = -1;
/*
* public HttpSender(ConnectionParam connectionParam, boolean allowState) { this
* (connectionParam, allowState, -1); }
*/
public HttpSender(ConnectionParam connectionParam, boolean allowState, int initiator) {
this.param = connectionParam;
this.allowState = allowState;
this.initiator = initiator;
client = createHttpClient();
clientViaProxy = createHttpClientViaProxy();
if (this.allowState) {
checkState();
}
addAuth(client);
addAuth(clientViaProxy);
}
public static SSLConnector getSSLConnector() {
return (SSLConnector) protocol.getSocketFactory();
}
public static void setAllowUnsafeSSLRenegotiation(boolean enabled) {
allowUnsafeSSLRenegotiation = enabled;
if (allowUnsafeSSLRenegotiation) {
log.info("Unsafe SSL renegotiation enabled.");
} else {
log.info("Unsafe SSL renegotiation disabled.");
}
String value = String.valueOf(allowUnsafeSSLRenegotiation).toLowerCase();
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", value);
}
private void checkState() {
if (param.isHttpStateEnabled()) {
client.setState(param.getHttpState());
clientViaProxy.setState(param.getHttpState());
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
clientViaProxy.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
final boolean singleCookieRequestHeader = param.isSingleCookieRequestHeader();
client.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER,
singleCookieRequestHeader);
clientViaProxy.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER,
singleCookieRequestHeader);
} else {
client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
clientViaProxy.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
}
}
private HttpClient createHttpClient() {
httpConnManager = new MultiThreadedHttpConnectionManager();
setCommonManagerParams(httpConnManager);
return new HttpClient(httpConnManager);
}
private HttpClient createHttpClientViaProxy() {
if (param.getProxyChainName().equals("")) {
return createHttpClient();
}
httpConnManagerProxy = new MultiThreadedHttpConnectionManager();
setCommonManagerParams(httpConnManagerProxy);
HttpClient clientProxy = new HttpClient(httpConnManagerProxy);
clientProxy.getHostConfiguration().setProxy(param.getProxyChainName(), param.getProxyChainPort());
if (!param.getProxyChainUserName().equals("")) {
// NTCredentials credentials = new NTCredentials(
// param.getProxyChainUserName(), param.getProxyChainPassword(),
// param.getProxyChainName(), param.getProxyChainName());
NTCredentials credentials = new NTCredentials(param.getProxyChainUserName(),
param.getProxyChainPassword(), "", param.getProxyChainRealm().equals("") ? ""
: param.getProxyChainRealm());
// Below is the original code, but user reported that above code works.
// UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
// param.getProxyChainUserName(), param.getProxyChainPassword());
AuthScope authScope = new AuthScope(param.getProxyChainName(), param.getProxyChainPort(), param
.getProxyChainRealm().equals("") ? AuthScope.ANY_REALM : param.getProxyChainRealm());
clientProxy.getState().setProxyCredentials(authScope, credentials);
}
return clientProxy;
}
public int executeMethod(HttpMethod method, HttpState state) throws IOException {
int responseCode = -1;
String hostName;
hostName = method.getURI().getHost();
method.setDoAuthentication(true);
HttpClient requestClient;
if (param.isUseProxy(hostName)) {
requestClient = clientViaProxy;
} else {
// ZAP: use custom client on upgrade connection and on event-source data type
Header connectionHeader = method.getRequestHeader("connection");
boolean isUpgrade = connectionHeader != null
&& connectionHeader.getValue().toLowerCase().contains("upgrade");
// ZAP: try to apply original handling of ParosProxy
requestClient = client;
if (isUpgrade) {
// Unless upgrade, when using another client that allows us to expose the socket
// connection.
requestClient = new HttpClient(new ZapHttpConnectionManager());
}
}
// ZAP: Check if a custom state is being used
if (state != null) {
// Make sure cookies are enabled and restore the cookie policy afterwards
String originalCookiePolicy = requestClient.getParams().getCookiePolicy();
requestClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
responseCode = requestClient.executeMethod(null, method, state);
requestClient.getParams().setCookiePolicy(originalCookiePolicy);
} else
responseCode = requestClient.executeMethod(method);
return responseCode;
}
public void shutdown() {
if (httpConnManager != null) {
httpConnManager.shutdown();
}
if (httpConnManagerProxy != null) {
httpConnManagerProxy.shutdown();
}
}
// ZAP: Deprecating configuring HTTP Authentication through Options
@Deprecated
private void addAuth(HttpClient client) {
List<HostAuthentication> list = param.getListAuthEnabled();
for (int i = 0; i < list.size(); i++) {
HostAuthentication auth = list.get(i);
AuthScope authScope = null;
NTCredentials credentials = null;
try {
authScope = new AuthScope(auth.getHostName(), auth.getPort(),
(auth.getRealm() == null || auth.getRealm().equals("")) ? AuthScope.ANY_REALM
: auth.getRealm());
credentials = new NTCredentials(auth.getUserName(), auth.getPassword(), InetAddress
.getLocalHost().getCanonicalHostName(), auth.getHostName());
client.getState().setCredentials(authScope, credentials);
} catch (UnknownHostException e1) {
log.error(e1.getMessage(), e1);
}
}
}
public void sendAndReceive(HttpMessage msg) throws IOException {
sendAndReceive(msg, followRedirect);
}
/**
* Do not use this unless sure what is doing. This method works but proxy may skip the pipe
* without properly handle the filter.
*
* Made this method private as it doesnt appear to be used anywhere...
*
* @param msg
* @param pipe
* @param buf
* @throws HttpException
* @throws IOException
*/
/*
* private void sendAndReceive(HttpMessage msg, HttpOutputStream pipe, byte[] buf) throws
* HttpException, IOException { sendAndReceive(msg, followRedirect, pipe, buf);
*
* }
*/
/**
* Send and receive a HttpMessage.
*
* @param msg
* @param isFollowRedirect
* @throws HttpException
* @throws IOException
*/
public void sendAndReceive(HttpMessage msg, boolean isFollowRedirect) throws IOException {
log.debug("sendAndReceive " + msg.getRequestHeader().getMethod() + " "
+ msg.getRequestHeader().getURI() + " start");
msg.setTimeSentMillis(System.currentTimeMillis());
try {
notifyRequestListeners(msg);
if (!isFollowRedirect
|| !(msg.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.POST) || msg
.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.PUT))) {
// ZAP: Reauthentication when sending a message from the perspective of a User
sendAuthenticated(msg, isFollowRedirect);
return;
}
// ZAP: Reauthentication when sending a message from the perspective of a User
sendAuthenticated(msg, false);
HttpMessage temp = msg.cloneAll();
// POST/PUT method cannot be redirected by library. Need to follow by code
// loop 1 time only because httpclient can handle redirect itself after first GET.
for (int i = 0; i < 1
&& (HttpStatusCode.isRedirection(temp.getResponseHeader().getStatusCode()) && temp
.getResponseHeader().getStatusCode() != HttpStatusCode.NOT_MODIFIED); i++) {
String location = temp.getResponseHeader().getHeader(HttpHeader.LOCATION);
URI baseUri = temp.getRequestHeader().getURI();
URI newLocation = new URI(baseUri, location, false);
temp.getRequestHeader().setURI(newLocation);
temp.getRequestHeader().setMethod(HttpRequestHeader.GET);
temp.getRequestHeader().setHeader(HttpHeader.CONTENT_LENGTH, null);
// ZAP: Reauthentication when sending a message from the perspective of a User
sendAuthenticated(temp, true);
}
msg.setResponseHeader(temp.getResponseHeader());
msg.setResponseBody(temp.getResponseBody());
} finally {
msg.setTimeElapsedMillis((int) (System.currentTimeMillis() - msg.getTimeSentMillis()));
log.debug("sendAndReceive " + msg.getRequestHeader().getMethod() + " "
+ msg.getRequestHeader().getURI() + " took " + msg.getTimeElapsedMillis());
notifyResponseListeners(msg);
}
}
private void notifyRequestListeners(HttpMessage msg) {
for (HttpSenderListener listener : listeners) {
try {
listener.onHttpRequestSend(msg, initiator);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
private void notifyResponseListeners(HttpMessage msg) {
for (HttpSenderListener listener : listeners) {
try {
listener.onHttpResponseReceive(msg, initiator);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
private User getUser (HttpMessage msg) {
if (this.user != null) {
// If its set for the sender it overrides the message
return user;
}
return msg.getRequestingUser();
}
// ZAP: Make sure a message that needs to be authenticated is authenticated
private void sendAuthenticated(HttpMessage msg, boolean isFollowRedirect) throws IOException {
// Modify the request message if a 'Requesting User' has been set
User forceUser = this.getUser(msg);
if (initiator != AUTHENTICATION_INITIATOR && forceUser != null)
forceUser.processMessageToMatchUser(msg);
log.debug("Sending message to: " + msg.getRequestHeader().getURI().toString());
// Send the message
send(msg, isFollowRedirect);
// If there's a 'Requesting User', make sure the response corresponds to an authenticated
// session and, if not, attempt a reauthentication and try again
if (initiator != AUTHENTICATION_INITIATOR && forceUser != null
&& msg.getResponseBody() != null && !msg.getRequestHeader().isImage()
&& !forceUser.isAuthenticated(msg)) {
log.debug("First try to send authenticated message failed for " + msg.getRequestHeader().getURI()
+ ". Authenticating and trying again...");
forceUser.queueAuthentication(msg);
forceUser.processMessageToMatchUser(msg);
send(msg, isFollowRedirect);
} else
log.debug("SUCCESSFUL");
}
private void send(HttpMessage msg, boolean isFollowRedirect) throws IOException {
HttpMethod method = null;
HttpResponseHeader resHeader = null;
try {
method = runMethod(msg, isFollowRedirect);
// successfully executed;
resHeader = HttpMethodHelper.getHttpResponseHeader(method);
resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null); // replaceAll("Transfer-Encoding: chunked\r\n",
msg.setResponseHeader(resHeader);
msg.getResponseBody().setCharset(resHeader.getCharset());
msg.getResponseBody().setLength(0);
// ZAP: Do not read response body for Server-Sent Events stream
// ZAP: Moreover do not set content length to zero
if (!msg.isEventStream()) {
msg.getResponseBody().append(method.getResponseBody());
}
msg.setResponseFromTargetHost(true);
// ZAP: set method to retrieve upgraded channel later
if (method instanceof ZapGetMethod) {
msg.setUserObject(method);
}
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
private HttpMethod runMethod(HttpMessage msg, boolean isFollowRedirect) throws IOException {
HttpMethod method = null;
// no more retry
modifyUserAgent(msg);
method = helper.createRequestMethod(msg.getRequestHeader(), msg.getRequestBody());
if (!(method instanceof EntityEnclosingMethod)) {
// cant do this for EntityEnclosingMethod methods - it will fail
method.setFollowRedirects(isFollowRedirect);
}
// ZAP: Use custom HttpState if needed
User forceUser = this.getUser(msg);
if (forceUser != null) {
this.executeMethod(method, forceUser.getCorrespondingHttpState());
} else {
this.executeMethod(method, null);
}
HttpMethodHelper.updateHttpRequestHeaderSent(msg.getRequestHeader(), method);
return method;
}
public void setFollowRedirect(boolean followRedirect) {
this.followRedirect = followRedirect;
}
private void modifyUserAgent(HttpMessage msg) {
try {
// no modification to user agent if empty
if (userAgent.equals("") || msg.getRequestHeader().isEmpty()) {
return;
}
// append new user agent to existing user agent
String currentUserAgent = msg.getRequestHeader().getHeader(HttpHeader.USER_AGENT);
if (currentUserAgent == null) {
currentUserAgent = "";
}
if (currentUserAgent.indexOf(userAgent) >= 0) {
// user agent already in place, exit
return;
}
String delimiter = "";
if (!currentUserAgent.equals("") && !currentUserAgent.endsWith(" ")) {
delimiter = " ";
}
currentUserAgent = currentUserAgent + delimiter + userAgent;
msg.getRequestHeader().setHeader(HttpHeader.USER_AGENT, currentUserAgent);
} catch (Exception e) {
}
}
/**
* @return Returns the userAgent.
*/
public static String getUserAgent() {
return userAgent;
}
/**
* @param userAgent The userAgent to set.
*/
public static void setUserAgent(String userAgent) {
HttpSender.userAgent = userAgent;
}
private void setCommonManagerParams(MultiThreadedHttpConnectionManager mgr) {
// ZAP: set timeout
mgr.getParams().setSoTimeout(this.param.getTimeoutInSecs() * 1000);
mgr.getParams().setStaleCheckingEnabled(true);
// Set to arbitrary large values to prevent locking
mgr.getParams().setDefaultMaxConnectionsPerHost(10000);
mgr.getParams().setMaxTotalConnections(200000);
// to use for HttpClient 3.0.1
// mgr.getParams().setDefaultMaxConnectionsPerHost((Constant.MAX_HOST_CONNECTION > 5) ? 15 :
// 3*Constant.MAX_HOST_CONNECTION);
// mgr.getParams().setMaxTotalConnections(mgr.getParams().getDefaultMaxConnectionsPerHost()*10);
// mgr.getParams().setConnectionTimeout(60000); // use default
}
/*
* Send and receive a HttpMessage.
*
* @param msg
*
* @param isFollowRedirect
*
* @throws HttpException
*
* @throws IOException
*/
/*
* private void sendAndReceive(HttpMessage msg, boolean isFollowRedirect, HttpOutputStream pipe,
* byte[] buf) throws HttpException, IOException { log.debug("sendAndReceive " +
* msg.getRequestHeader().getMethod() + " " + msg.getRequestHeader().getURI() + " start");
* msg.setTimeSentMillis(System.currentTimeMillis());
*
* try { if (!isFollowRedirect || !
* (msg.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.POST) ||
* msg.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.PUT)) ) { send(msg,
* isFollowRedirect, pipe, buf); return; } else { send(msg, false, pipe, buf); }
*
* HttpMessage temp = msg.cloneAll(); // POST/PUT method cannot be redirected by library. Need
* to follow by code
*
* // loop 1 time only because httpclient can handle redirect itself after first GET. for (int
* i=0; i<1 && (HttpStatusCode.isRedirection(temp.getResponseHeader().getStatusCode()) &&
* temp.getResponseHeader().getStatusCode() != HttpStatusCode.NOT_MODIFIED); i++) { String
* location = temp.getResponseHeader().getHeader(HttpHeader.LOCATION); URI baseUri =
* temp.getRequestHeader().getURI(); URI newLocation = new URI(baseUri, location, false);
* temp.getRequestHeader().setURI(newLocation);
*
* temp.getRequestHeader().setMethod(HttpRequestHeader.GET);
* temp.getRequestHeader().setContentLength(0); send(temp, true, pipe, buf); }
*
* msg.setResponseHeader(temp.getResponseHeader()); msg.setResponseBody(temp.getResponseBody());
*
* } finally { msg.setTimeElapsedMillis((int)
* (System.currentTimeMillis()-msg.getTimeSentMillis())); log.debug("sendAndReceive " +
* msg.getRequestHeader().getMethod() + " " + msg.getRequestHeader().getURI() + " took " +
* msg.getTimeElapsedMillis()); } }
*/
/*
* Do not use this unless sure what is doing. This method works but proxy may skip the pipe
* without properly handle the filter.
*
* @param msg
*
* @param isFollowRedirect
*
* @param pipe
*
* @param buf
*
* @throws HttpException
*
* @throws IOException
*/
/*
* private void send(HttpMessage msg, boolean isFollowRedirect, HttpOutputStream pipe, byte[]
* buf) throws HttpException, IOException { HttpMethod method = null; HttpResponseHeader
* resHeader = null;
*
* try { method = runMethod(msg, isFollowRedirect); // successfully executed; resHeader =
* HttpMethodHelper.getHttpResponseHeader(method);
* resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null); //
* replaceAll("Transfer-Encoding: chunked\r\n", ""); msg.setResponseHeader(resHeader);
* msg.getResponseBody().setCharset(resHeader.getCharset()); msg.getResponseBody().setLength(0);
*
* // process response for each listner
*
* pipe.write(msg.getResponseHeader()); pipe.flush();
*
* if (msg.getResponseHeader().getContentLength() >= 0 &&
* msg.getResponseHeader().getContentLength() < 20480) { // save time expanding buffer in
* HttpBody if (msg.getResponseHeader().getContentLength() > 0) {
* msg.getResponseBody().setBody(method.getResponseBody()); pipe.write(msg.getResponseBody());
* pipe.flush();
*
* } } else { //byte[] buf = new byte[4096]; InputStream in = method.getResponseBodyAsStream();
*
* int len = 0; while (in != null && (len = in.read(buf)) > 0) { pipe.write(buf, 0, len);
* pipe.flush();
*
* msg.getResponseBody().append(buf, len); } } } finally { if (method != null) {
* method.releaseConnection(); } } }
*/
public static void addListener(HttpSenderListener listener) {
listeners.add(listener);
Collections.sort(listeners, getListenersComparator());
}
private static Comparator<HttpSenderListener> getListenersComparator() {
if (listenersComparator == null) {
createListenersComparator();
}
return listenersComparator;
}
private static synchronized void createListenersComparator() {
if (listenersComparator == null) {
listenersComparator = new Comparator<HttpSenderListener>() {
@Override
public int compare(HttpSenderListener o1, HttpSenderListener o2) {
int order1 = o1.getListenerOrder();
int order2 = o2.getListenerOrder();
if (order1 < order2) {
return -1;
} else if (order1 > order2) {
return 1;
}
return 0;
}
};
}
}
/**
* Set the user to scan as. If null then the current session will be used.
* @param user
*/
public void setUser(User user) {
this.user = user;
}
} |
package org.usfirst.frc.team4536.robot;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.DigitalInput;
public class Elevator {
Talon elevatorTalon;
DigitalInput topLimitSwitch;
DigitalInput middleLimitSwitch;
DigitalInput bottomLimitSwitch;
/*
* This function is the constructor for the Elevator class
* It takes in four arguments - one talon channel, and the channels of the top, bottom, and middle limit switches
*/
public Elevator(int talonChannel,
int topLimitSwitchChannel,
int middleLimitSwitchChannel,
int bottomLimitSwitchChannel)
{
elevatorTalon = new Talon(talonChannel);
topLimitSwitch = new DigitalInput(topLimitSwitchChannel);
middleLimitSwitch = new DigitalInput(middleLimitSwitchChannel);
bottomLimitSwitch = new DigitalInput(bottomLimitSwitchChannel);
}
/*
* This function is called in order to make the elevator drive
* It takes in one arguments - the amount of vertical throttle (1 to -1)
* To go up the value would be 1. To go down the value would be -1
*/
public void driveFullRange(double verticalThrottle) {
double elevatorTalonThrottle = -verticalThrottle;
// Makes sure the elevator talon throttle is between -1 and 1
Utilities.limit(elevatorTalonThrottle);
// limit switches are reversed, so that when it's pressed it outputs true
if(!topLimitSwitch.get() == true && elevatorTalonThrottle > 0) {
// If the top limit switch is engaged, and the elevator is going up, set it as 0
elevatorTalon.set(0);
}
else if(!bottomLimitSwitch.get() && elevatorTalonThrottle < 0) {
// If the bottom limit switch is engaged, and the elevator motor is going down, set it as 0
elevatorTalon.set(0);
}
else {
// If neither limit switch is engaged, the elevator motor can go both up and down
elevatorTalon.set(elevatorTalonThrottle);
}
}
public void driveSmallRange(double verticalThrottle) {
double elevatorTalonThrottle = -verticalThrottle;
// Makes sure the elevator talon throttle is between -1 and 1
Utilities.limit(elevatorTalonThrottle);
// limit switches are reversed, so that when it's pressed it outputs true
if(!topLimitSwitch.get() == true && elevatorTalonThrottle > 0) {
// If the top limit switch is engaged, and the elevator is going up, set it as 0
elevatorTalon.set(0);
}
else if(!middleLimitSwitch.get() == true && elevatorTalonThrottle < 0) {
// If the bottom limit switch is engaged, and the elevator motor is going down, set it as 0
elevatorTalon.set(0);
}
else {
// If neither limit switch is engaged, the elevator motor can go both up and down
elevatorTalon.set(elevatorTalonThrottle);
}
}
/*
* Returns the boolean value of the top limit switch
* A return value of true indicates that the limit switch is pressed
*/
public boolean topLimitSwitchValue() {
// Boolean value is reversed because the limit switch outputs false when not pressed
return !topLimitSwitch.get();
}
/*
* Returns the boolean value of the middle limit switch
* A return value of true indicates that the limit switch is pressed
*/
public boolean middleLimitSwitchValue() {
// Boolean value is reversed because the limit switch outputs false when not pressed
return !middleLimitSwitch.get();
}
/*
* Returns the boolean value of the bottom limit switch
* A return value of true indicates that the limit switch is pressed
*/
public boolean bottomLimitSwitchValue() {
// Boolean value is reversed because the limit switch outputs false when not pressed
return !bottomLimitSwitch.get();
}
/*
* Returns the double throttle value of the elevator
* Positive return value means the elevator is going up
*/
public double getThrottle() {
return elevatorTalon.get();
}
} |
package common.graph;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* <p>A graph whose connection data is stored in adjacency list form, each {@link Vertex vertex}
* keeping track of with which other vertices it shares an edge.</p>
* @author fiveham
* @param <T>
*/
public interface Graph<T extends Vertex<T>> extends Iterable<T>{
/**
* <p>Returns the number of vertices in this Graph.</p>
* @return the number of vertices in this Graph
*/
public int size();
/**
* <p>Returns the number of edges to be traversed to move on the Graph from {@code t1} to
* {@code t2}, or -1 if there is no path connecting {@code t1} and {@code t2}.</p>
* @param t1 a vertex in this Graph
* @param t2 a vertex in this Graph
* @return the number of edges to be traversed to move on the Graph from {@code t1} to
* {@code t2}, or -1 if there is no path connecting {@code t1} and {@code t2}
*/
public int distance(T t1, T t2);
/**
* <p>Returns a stream based on the underlying collection of nodes.</p>
* @return a stream backed by this Graph's underlying collection of nodes
*/
public Stream<T> nodeStream();
/**
* <p>Adds the specified event-listener-supplier to this Graph then returns this Graph.</p>
* @param newEL an event-listener-supplier to be added
* @return this Graph
*/
public Graph<T> addGrowthListenerFactory(Supplier<Consumer<Set<T>>> newEL);
/**
* <p>Returns a list of all the registered event-listeners for a contraction event during the
* construction of connected components.</p>
* @return a list of all the registered event-listeners for a contraction event during the
* construction of connected components
*/
public List<Consumer<Set<T>>> growthListeners();
/**
* <p>Returns a collection of all the connected components of this Graph.</p>
* @param eventListeners event-listeners that respond to the contractions that occur in
* connected components while they build
* @param seedSrc a function that selects an element from a list of nodes in this Graph from
* which to begin building a given connected component
* @return a collection of all the connected components of this Graph
*/
public Collection<Graph<T>> connectedComponents(List<Consumer<Set<T>>> eventListeners, Function<List<T>,T> seedSrc);
/**
* <p>Returns a collection of all the connected components of this Graph. This is a convenience
* method supplying default arguments to
* {@link #connectedComponents(List<Consumer<Set<T>>>, Function<List<T>,T>) connectedComponents(List<Consumer<Set<T>>>, Function<List<T>,T>)}.
* The default list of event-listeners supplied is the list returned by
* {@link contractEventListeners() contractEventListeners()}. The default {@code seedSrc}
* supplied is a function that removes and returns the last element of the list it is given.</p>
* @return
*/
public Collection<Graph<T>> connectedComponents();
/**
* <p>Returns the connected component of this Graph that contains the {@code T} output by
* {@code seedSrc} when {@code unassignedNodes} is given to it as input.</p>
* @param unassignedNodes nodes from this Puzzle for which a connected component will be built
* @param seedSrc a function that specifies an element from {@code unassignedNodes} with which
* to begin building the connected component that is returned
* @param eventListeners a list of event-listeners that respond when the connected component
* being built moves newly-added nodes inward and out of the outermost layer
* @return the connected component of this Grapht hat contains the {@code T} output by
* {@code seedSrc} when {@code unassignedNodes} is given to it as input
*/
public Graph<T> component(List<T> unassignedNodes, Function<List<T>,T> seedSrc, List<Consumer<Set<T>>> eventListeners);
public List<T> path(T t1, T t2);
} |
package com.clescot.webappender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
public class Row {
private String message;
private String template;
private List<Object> args;
private String level;
private long timestamp;
private String relativeTime;
private String threadName;
private String classOfCaller;
private String methodOfCaller;
private String mdc;
private String throwableProxy;
private String contextName;
private String callerData;
private String marker;
public void setPathName(String pathName) {
this.pathName = pathName;
}
private String time;
private String name;
private String pathName;
private String lineno;
public Row(ILoggingEvent event) {
this.template = event.getMessage();
this.args = Lists.newArrayList();
if (event.getArgumentArray() != null) {
args.addAll(Arrays.asList(event.getArgumentArray()));
}
this.message = event.getFormattedMessage();
this.level = Level.getLevel(event.getLevel()).toString();
this.timestamp = event.getTimeStamp();
this.name = event.getLoggerName();
}
public String getMessage() {
return message;
}
public String getTemplate() {
return template;
}
public List<Object> getArgs() {
return args;
}
public String getLevel() {
return level;
}
public long getTimestamp() {
return timestamp;
}
public String getTime() {
return time;
}
public String getName() {
return name;
}
public String getPathName() {
return pathName;
}
public String getLineno() {
return lineno;
}
public void setTime(String time) {
this.time = time;
}
public void setLineno(String lineno) {
this.lineno = lineno;
}
public void setRelativeTime(String relativeTime) {
this.relativeTime = relativeTime;
}
public String getRelativeTime() {
return relativeTime;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
public String getThreadName() {
return threadName;
}
public void setClassOfCaller(String classOfCaller) {
this.classOfCaller = classOfCaller;
}
public String getClassOfCaller() {
return classOfCaller;
}
public void setMethodOfCaller(String methodOfCaller) {
this.methodOfCaller = methodOfCaller;
}
public String getMethodOfCaller() {
return methodOfCaller;
}
public void setMDC(String mdc) {
this.mdc = mdc;
}
public String getMDC() {
return mdc;
}
public void setThrowableProxy(String throwableProxy) {
this.throwableProxy = throwableProxy;
}
public String getThrowableProxy() {
return throwableProxy;
}
public void setContextName(String contextName) {
this.contextName = contextName;
}
public String getContextName() {
return contextName;
}
public void setCallerData(String callerData) {
this.callerData = callerData;
}
public String getCallerData() {
return callerData;
}
public void setMarker(String marker) {
this.marker = marker;
}
public String getMarker() {
return marker;
}
private enum Level {
DEBUG("debug", ch.qos.logback.classic.Level.DEBUG),
WARNING("warning", ch.qos.logback.classic.Level.WARN),
ERROR("error", ch.qos.logback.classic.Level.ERROR),
INFO("info", ch.qos.logback.classic.Level.INFO);
// CRITICAL("critical", ???? not mapped);
private String fireLoggerLevel;
private ch.qos.logback.classic.Level logbackLevel;
Level(String fireLoggerLevel, ch.qos.logback.classic.Level logbackLevel) {
this.fireLoggerLevel = fireLoggerLevel;
this.logbackLevel = logbackLevel;
}
public String getFireLoggerLevel() {
return fireLoggerLevel;
}
public ch.qos.logback.classic.Level getLogbackLevel() {
return logbackLevel;
}
public static String getLevel(ch.qos.logback.classic.Level logbackLevel) {
for (Level level : values()) {
if (level.getLogbackLevel().equals(logbackLevel)) {
return level.getFireLoggerLevel();
}
}
return Level.INFO.getFireLoggerLevel();
}
}
} |
public class Dice {
public int[] output = {1, 2, 3, 4, 5, 6}
public void roll() {
for(int i : output) {
System.out.println("Dice roll output: " + i + "!");
}
}
} |
package com.webimageloader.ext;
import com.webimageloader.ImageLoader;
import com.webimageloader.ImageLoader.Listener;
import com.webimageloader.transformation.Transformation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.util.Log;
import android.widget.ImageView;
/**
* Helper class for loading images into a {@link ImageView}
*
* @author Alexander Blom <alexanderblom.se>
*/
public class ImageHelper {
private static final String TAG = "ImageHelper";
private Context context;
private ImageLoader loader;
private int loadingResource;
private int errorResource;
private boolean fadeIn = false;
private LoadingListener listener;
/**
* Create a new {@link ImageHelper} using the specified loader
*
* @param context the context when getting resources
* @param loader the load to use
*/
public ImageHelper(Context context, ImageLoader loader) {
this.context = context;
this.loader = loader;
listener = new LoadingListener();
}
/**
* Set an image to be displayed when an image is loading
*
* @param loadingResource the resource to use
*
* @return this helper
*/
public ImageHelper setLoadingResource(int loadingResource) {
this.loadingResource = loadingResource;
return this;
}
/**
* Set an image to be displayed if an error occurred
*
* @param errorResource the resource to use
* @return this helper
*/
public ImageHelper setErrorResource(int errorResource) {
this.errorResource = errorResource;
return this;
}
/**
* Set wether to fade in after loading
*
* @param fadeIn true or false
* @return this helper
*/
public ImageHelper setFadeIn(boolean fadeIn) {
this.fadeIn = fadeIn;
return this;
}
/**
* Load the specified url into this {@link ImageView}.
*
* @param v the target view
* @param url the url to load
* @return this helper
*
* @see #load(ImageView, String, Transformation)
*/
public ImageHelper load(ImageView v, String url) {
return load(v, url, null);
}
/**
* Load the specified url into this {@link ImageView}.
*
* @param v the target view
* @param url the url to load
* @param transformation transformation to apply, can be null
* @return this helper
*/
public ImageHelper load(ImageView v, String url, Transformation transformation) {
Bitmap b = loader.load(v, url, transformation, listener);
if (b != null) {
v.setImageBitmap(b);
} else if (loadingResource != 0) {
v.setImageResource(loadingResource);
} else {
v.setImageBitmap(null);
}
return this;
}
private class LoadingListener implements Listener<ImageView> {
@Override
public void onSuccess(ImageView v, Bitmap b) {
if (!fadeIn) {
v.setImageBitmap(b);
} else {
Drawable old = v.getDrawable();
if (old == null) {
old = new ColorDrawable(android.R.color.transparent);
}
TransitionDrawable d = new TransitionDrawable(new Drawable[] {
old,
new BitmapDrawable(context.getResources(), b)
});
v.setImageDrawable(d);
d.startTransition(300);
}
}
@Override
public void onError(ImageView v, Throwable t) {
Log.d(TAG, "Error loading bitmap", t);
if (errorResource > 0) {
v.setImageResource(errorResource);
}
}
}
} |
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package propsandcovariants;
import acq.AcquisitionEvent;
import acq.FixedAreaAcquisition;
import coordinates.AffineUtils;
import coordinates.XYStagePosition;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.List;
import misc.Log;
import surfacesandregions.CurvedSurfaceCovariantCreationDialog;
import surfacesandregions.SingleResolutionInterpolation;
import surfacesandregions.SurfaceInterpolator;
/**
* Category about interpolated surface (e.g. distance below surface) to be used in
* covaried settings
*/
public class SurfaceData implements Covariant {
//all data must start with this prefix so they can be reconstructed when read from a text file on disk
public static String PREFIX = "Surface data: ";
//number of test points per dimension for finding minimum distance to surface
private static final int NUM_XY_TEST_POINTS = 9;
//number of test points per dimension for finding minimum distance to surface within angle
// private static final int NUM_XY_TEST_POINTS_ANGLE = 5;
public static String SPACER = "
public static String DISTANCE_BELOW_SURFACE_CENTER = "Vertical distance below at XY position center";
public static String DISTANCE_BELOW_SURFACE_MINIMUM = "Minimum vertical distance below at XY position";
public static String DISTANCE_BELOW_SURFACE_MAXIMUM = "Maximum vertical distance below at XY position";
public static String CURVED_SURFACE_RELATIVE_POWER = "Relative power for curved surface";
private String category_;
private SurfaceInterpolator surface_;
//used for curved surface calculations
private int radiusOfCurvature_, meanFreePath_;
private double basePower_;
private int curvedSurfaceMode_;
public SurfaceData(SurfaceInterpolator surface, String type) throws Exception {
category_ = type;
surface_ = surface;
if (!Arrays.asList(enumerateDataTypes()).contains(type)) {
//not a recognized type
throw new Exception();
}
}
public void initializeCurvedSurfaceData() throws Exception {
if (category_.equals(CURVED_SURFACE_RELATIVE_POWER)) {
CurvedSurfaceCovariantCreationDialog creator = new CurvedSurfaceCovariantCreationDialog();
creator.waitForCreationOrCancel();
if (creator.wasCanceled()) {
throw new Exception("Surface data canceled");
}
radiusOfCurvature_ = creator.getRadiusOfCurvature();
meanFreePath_ = creator.getMFP();
basePower_ = creator.getBasePower();
curvedSurfaceMode_ = creator.getMode();
}
}
public SurfaceInterpolator getSurface() {
return surface_;
}
public static String[] enumerateDataTypes() {
return new String[] {DISTANCE_BELOW_SURFACE_CENTER, DISTANCE_BELOW_SURFACE_MINIMUM,
DISTANCE_BELOW_SURFACE_MAXIMUM, CURVED_SURFACE_RELATIVE_POWER};
}
@Override
public String toString() {
return getName();
}
@Override
public String getAbbreviatedName() {
if (category_.equals(DISTANCE_BELOW_SURFACE_CENTER)) {
return "Vertical distance to " + surface_.getName();
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MINIMUM)) {
return "Min vertical distance to " + surface_.getName();
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MAXIMUM)) {
return "Min distance to " + surface_.getName();
} else if (category_.equals(CURVED_SURFACE_RELATIVE_POWER)) {
return "Relative power for " + surface_.getName() + " R"+radiusOfCurvature_+" MFP"+meanFreePath_+" Base"+basePower_;
} else {
Log.log("Unknown Surface data type");
throw new RuntimeException();
}
}
@Override
public String getName() {
return PREFIX + surface_.getName() + SPACER + category_;
}
@Override
public boolean isValid(CovariantValue potentialValue) {
return potentialValue.getType() == CovariantType.DOUBLE;
}
@Override
public CovariantValue[] getAllowedValues() {
//not applicable because all numerical for now
return null;
}
@Override
public boolean isDiscrete() {
return false;
}
@Override
public boolean hasLimits() {
return false;
}
@Override
public CovariantValue getLowerLimit() {
return null;
}
@Override
public CovariantValue getUpperLimit() {
return null;
}
@Override
public CovariantType getType() {
return CovariantType.DOUBLE;
}
@Override
public CovariantValue getValidValue(List<CovariantValue> vals) {
double d = 0;
while (true) {
if (!vals.contains(new CovariantValue(d))) {
return new CovariantValue(d);
}
d++;
}
}
private double curvedSurfacePower(XYStagePosition xyPos, double zPosition) {
try{
double[] vals = distanceAndNormalCalc(xyPos.getFullTileCorners(), zPosition);
double minDist = vals[0];
double maxDist = vals[1];
double maxNormal = vals[3];
if (curvedSurfaceMode_ == CurvedSurfaceCovariantCreationDialog.SURFACE_CONSERVATIVE_POWER_MODE) {
//Non-exploding exciation scheme:
// Min distance < 30 um -- use surface minimum distance
// Next 100 um -- increase from minimum distance to maximum distance
// Below 130 um -- use max distance
//always use max normal
double dist;
if (minDist < 30) {
dist = minDist;
} else if (minDist < 130) {
dist = minDist + ((maxDist - minDist) / 100.0) * (minDist - 30);
} else {
dist = maxDist;
}
double relPower = CurvedSurfaceCalculations.getRelativePower(meanFreePath_, dist, maxNormal, radiusOfCurvature_);
//relative power is fold increase needed from base power
return basePower_ * relPower;
} else {
//if interpolation is undefined at position center, assume distance below is 0
double centerDistance = 0;
//likewise, take biggest defined normal
double normal = maxNormal;
Point2D.Double center = xyPos.getCenter();
SingleResolutionInterpolation interp = surface_.waitForCurentInterpolation();
if (interp.isInterpDefined(center.x, center.y)) {
centerDistance = Math.max(0, zPosition - interp.getInterpolatedValue(center.x, center.y));
normal = surface_.waitForCurentInterpolation().getNormalAngleToVertical(center.x, center.y);
}
double relPower = CurvedSurfaceCalculations.getRelativePower(meanFreePath_, centerDistance, normal, radiusOfCurvature_);
//relative power is fold increase needed from base power
return basePower_ * relPower;
}
} catch (Exception e) {
Log.log("Couldn't calculate curved surface power");
Log.log(e);
return 0;
}
}
/**
*
* @param corners
* @param min true to get min, false to get max
* @return {minDistance,maxDistance, minNormalAngle, maxNormalAngle)
*/
private double[] distanceAndNormalCalc(Point2D.Double[] corners, double zVal) throws InterruptedException {
//check a grid of points spanning entire position
//square is aligned with axes in pixel space, so convert to pixel space to generate test points
double xSpan = corners[2].getX() - corners[0].getX();
double ySpan = corners[2].getY() - corners[0].getY();
Point2D.Double pixelSpan = new Point2D.Double();
AffineTransform transform = AffineUtils.getAffineTransform(surface_.getCurrentPixelSizeConfig(),0, 0);
try {
transform.inverseTransform(new Point2D.Double(xSpan, ySpan), pixelSpan);
} catch (NoninvertibleTransformException ex) {
Log.log("Problem inverting affine transform");
}
double minDistance = Integer.MAX_VALUE;
double maxDistance = 0;
double minNormalAngle = 90;
double maxNormalAngle = 0;
for (double x = 0; x <= pixelSpan.x; x += pixelSpan.x / (double) NUM_XY_TEST_POINTS) {
for (double y = 0; y <= pixelSpan.y; y += pixelSpan.y / (double) NUM_XY_TEST_POINTS) {
//convert these abritray pixel coordinates back to stage coordinates
double[] transformMaxtrix = new double[6];
transform.getMatrix(transformMaxtrix);
transformMaxtrix[4] = corners[0].getX();
transformMaxtrix[5] = corners[0].getY();
//create new transform with translation applied
transform = new AffineTransform(transformMaxtrix);
Point2D.Double stageCoords = new Point2D.Double();
transform.transform(new Point2D.Double(x, y), stageCoords);
//test point for inclusion of position
if (!surface_.waitForCurentInterpolation().isInterpDefined(stageCoords.x, stageCoords.y)) {
//if position is outside of convex hull, assume min distance is 0
minDistance = 0;
//get extrapolated value for max distance
float interpVal = surface_.waitForCurentInterpolation().getExtrapolatedValue(stageCoords.x, stageCoords.y);
maxDistance = Math.max(zVal - interpVal, maxDistance);
//only take actual values for normals
} else {
float interpVal = surface_.waitForCurentInterpolation().getInterpolatedValue(stageCoords.x, stageCoords.y);
float normalAngle = surface_.waitForCurentInterpolation().getNormalAngleToVertical(stageCoords.x, stageCoords.y);
minDistance = Math.min(Math.max(0,zVal - interpVal), minDistance);
maxDistance = Math.max(zVal - interpVal, maxDistance);
minNormalAngle = Math.min(minNormalAngle, normalAngle);
maxNormalAngle = Math.max(maxNormalAngle, normalAngle);
}
}
}
return new double[]{minDistance, maxDistance, minNormalAngle, maxNormalAngle};
}
@Override
public CovariantValue getCurrentValue(AcquisitionEvent event) throws Exception {
XYStagePosition xyPos = event.xyPosition_;
if (category_.equals(DISTANCE_BELOW_SURFACE_CENTER)) {
//if interpolation is undefined at position center, assume distance below is 0
Point2D.Double center = xyPos.getCenter();
SingleResolutionInterpolation interp = surface_.waitForCurentInterpolation();
if (interp.isInterpDefined(center.x, center.y)) {
return new CovariantValue( event.zPosition_ - interp.getInterpolatedValue(center.x, center.y));
}
return new CovariantValue(0.0);
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MINIMUM)) {
return new CovariantValue(distanceAndNormalCalc(xyPos.getFullTileCorners(), event.zPosition_)[0]);
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MAXIMUM)) {
return new CovariantValue(distanceAndNormalCalc(xyPos.getFullTileCorners(), event.zPosition_)[1]);
} else if (category_.equals(CURVED_SURFACE_RELATIVE_POWER)) {
return new CovariantValue(curvedSurfacePower(xyPos, event.zPosition_));
} else {
Log.log("Unknown Surface data type",true);
throw new RuntimeException();
}
}
@Override
public void updateHardwareToValue(CovariantValue dVal) {
Log.log("No hardware associated with Surface data",true);
throw new RuntimeException();
}
} |
package org.noear.weed.xml;
import org.noear.weed.utils.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XmlSqlCompiler {
//xmljava code
public static String parse(URL xmlFile) throws Exception{
if(xmlFile == null){
return null;
}
Document doc = parseDoc(xmlFile);
Node nm = doc.getDocumentElement();
String filepath = xmlFile.getPath();
int filename_idx = filepath.lastIndexOf("/")+1;
String filename = filepath.substring(filename_idx);
String namespace = attr(nm, "namespace");
String _import = attr(nm, "import");
String classname = filename.replace(".","_"); //namespace.replace(".","_"); //"weed_xml_sql";
StringBuilder sb = new StringBuilder();
sb.append("package ").append(namespace).append(";\n\n");
sb.append("import java.math.*;\n");
sb.append("import java.util.*;\n");
sb.append("import org.noear.weed.utils.*;\n");
sb.append("import org.noear.weed.SQLBuilder;\n");
sb.append("import org.noear.weed.xml.XmlSqlFactory;\n");
if(StringUtils.isEmpty(_import) == false) {
String[] ss = _import.split(";");
for (String s : ss) {
if (s.length() > 2) {
sb.append("import ").append(s).append(";\n");
}
}
}
sb.append("\n");
Map<String,Node> node_map = new HashMap<>();
NodeList sql_list = doc.getElementsByTagName("sql");
for (int i = 0, len = sql_list.getLength(); i < len; i++) {
Node n = sql_list.item(i);
String id = attr(n,"id");
if(id!=null){
node_map.put(id,n);
}
}
sb.append("public class ").append(classname).append("{");
newLine(sb, 1).append("private static final String _namespace=\"").append(namespace).append("\";");
newLine(sb, 1).append("public ").append(classname).append("(){");
for (int i = 0, len = sql_list.getLength(); i < len; i++) {
Node n = sql_list.item(i);
String id_str = attr(n,"id");
if(id_str!= null){
newLine(sb,2).append("XmlSqlFactory.register(_namespace + \".")
.append(id_str).append("\",")
.append("this::").append(id_str).append(");");
}
}
newLine(sb, 1).append("}");
for (int i = 0, len = sql_list.getLength(); i < len; i++) {
Node n = sql_list.item(i);
parseSqlNode(node_map, sb, n, _import, namespace, classname);
}
sb.append("}\n");
node_map.clear();
return sb.toString();
}
private static DocumentBuilderFactory dbf = null;
private static DocumentBuilder db = null;
//xml:
private static Document parseDoc(URL xmlFile) throws Exception{
if(dbf ==null) {
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
}
return db.parse(xmlFile.openStream());
}
//xml: sql
private static void parseSqlNode(Map<String,Node> nodeMap, StringBuilder sb,Node n, String _import, String namespace, String classname) {
int depth = 1;
XmlSqlBlock dblock = new XmlSqlBlock();
dblock.__nodeMap = nodeMap;
if (_import != null) {
for (String s : _import.split(";")) {
dblock._import.add(s.trim());
}
}
dblock._namespace = namespace;
dblock._classname = classname;
dblock._classcode = sb;
dblock._id = attr(n, "id");
dblock._param = attr(n, ":param");
dblock._declare = attr(n, ":declare");
dblock._return = attr(n, ":return");
if (dblock._return != null && dblock._return.indexOf("[") > 0) {
dblock._return = dblock._return.replace("[", "<")
.replace("]", ">");
int start = dblock._return.indexOf("<");
int end = dblock._return.indexOf(">");
if (start >= 0 && end > start) {
dblock._return_item = dblock._return.substring(start + 1, end);
}
}
dblock._caching = attr(n, ":caching");
dblock._usingCache = attr(n, ":usingCache");
dblock._cacheTag = attr(n, ":cacheTag");
dblock._cacheClear = attr(n, ":cacheClear");
_parseSqlDeclare(dblock);
_parseSqlCachaTag(dblock);
newLine(sb, depth).append("public SQLBuilder ").append(dblock._id).append("(Map map) throws Exception{");
StringBuilder sb2 = new StringBuilder();
{
newLine(sb2, depth + 1).append("SQLBuilder sb = new SQLBuilder();\n");
_parseNodeList(n.getChildNodes(), "sb", sb2, dblock, depth + 1);
}
int var_num = 0;
for (XmlSqlVar dv : dblock.varMap.values()) {
if (dv.type != null && dv.type.length() > 0) {
var_num++;
newLine(sb, depth + 1)
.append(dv.type).append(" ").append(dv.name).append(" = ")
.append("(").append(dv.type).append(")map.get(\"").append(dv.name).append("\");");
}
}
if (var_num > 0) {
sb.append("\n");
}
sb.append(sb2);
//3.cache tag .
if (dblock.tagMap.size() > 0) {
sb.append("\n");
}
for (XmlSqlVar dv : dblock.tagMap.values()) {
if (dv.name.indexOf(".") > 0) {
newLine(sb, depth + 1)
.append("map.put(\"").append(dv.name).append("\", ")
.append(dv.name).append(");");
}
}
sb.append("\n");
newLine(sb, depth + 1).append("return sb;");
newLine(sb, depth).append("}\n");
dblock.__nodeMap = null;
{
String txt2 = dblock._texts.insert(0, "# ").toString().trim().toUpperCase();
if (dblock._action == null && txt2.indexOf(" INSERT ") > 0) {
dblock._action = "INSERT";
}
if (dblock._action == null && txt2.indexOf(" DELETE ") > 0) {
dblock._action = "DELETE";
}
if (dblock._action == null && txt2.indexOf(" UPDATE ") > 0) {
dblock._action = "UPDATE";
}
if (dblock._action == null && txt2.indexOf(" SELECT ") > 0) {
dblock._action = "SELECT";
}
dblock._texts = null;
}
String tmp = dblock._return_item;
dblock._return_item = dblock.newType(dblock._return_item);
dblock._return = dblock.newType(dblock._return);
if (tmp != null && tmp.equals(dblock._return_item) == false) {
//List<User> List<xx.xx.User>
dblock._return = dblock._return.replace("<" + tmp + ">", "<" + dblock._return_item + ">");
}
XmlSqlFactory.register(namespace + "." + dblock._id, dblock);
}
private static void _parseSqlDeclare(XmlSqlBlock dblock) {
if (dblock._param != null) {
String[] ss = dblock._param.split(",");
for (int i = 0, len = ss.length; i < len; i++) {
String tmp = ss[i].trim();
if (tmp.indexOf(":") > 0 && tmp.length() > 3) {
String[] kv = tmp.split(":");
XmlSqlVar dv = new XmlSqlVar(tmp, kv[0].trim(), kv[1].trim());
dblock.varPut(dv);
}
}
}
if (dblock._declare != null) {
String[] ss = dblock._declare.split(",");
for (int i = 0, len = ss.length; i < len; i++) {
String tmp = ss[i].trim();
if (tmp.indexOf(":") > 0 && tmp.length() > 3) {
String[] kv = tmp.split(":");
XmlSqlVar dv = new XmlSqlVar(tmp, kv[0].trim(), kv[1].trim());
dblock.varPut(dv);
}
}
}
}
private static void _parseSqlCachaTag(XmlSqlBlock dblock) {
if (dblock._cacheClear != null) {
Matcher m = XmlSqlVar.varRepExp.matcher(dblock._cacheClear);
while (m.find()) {
XmlSqlVar dv = parseTxtVar(m);
dv.label = 0;//cache clear
dblock.tagMap.put(dv.mark, dv);
}
}
if (dblock._cacheTag != null) {
Matcher m = XmlSqlVar.varRepExp.matcher(dblock._cacheTag);
while (m.find()) {
XmlSqlVar dv = parseTxtVar(m);
dv.label = 1; //cache tag
dblock.tagMap.put(dv.mark, dv);
}
}
}
private static void _parseNodeList(NodeList nl, String sqlBuilderName, StringBuilder sb, XmlSqlBlock dblock, int depth) {
for (int i = 0, len = nl.getLength(); i < len; i++) {
Node n = nl.item(i);
_parseNode(n,sqlBuilderName, sb,dblock,depth);
}
}
private static void _parseNode(Node n, String sqlBuilderName, StringBuilder sb, XmlSqlBlock dblock, int depth){
int type = n.getNodeType();
if (type == 3 || type == 4) {//text or CDATA
String text = n.getTextContent().trim();
if (text.length() > 0) {
newLine(sb, depth).append(sqlBuilderName).append(".append(");
parseTxt(sb,dblock,text);
sb.append(");");
}
}
if (type == 1) {//elem
String tagName = n.getNodeName();
if ("if".equals(tagName)) {
parseIfNode(sb, sqlBuilderName, dblock, n, depth);
return;
}
//for
if ("for".equals(tagName)) {
parseForNode(sb, sqlBuilderName, dblock, n, depth);
return;
}
if ("ref".equals(tagName)) {
parseRefNode(sb, sqlBuilderName, dblock, n, depth);
return;
}
if ("trim".equals(tagName)) {
parseTrimNode(sb, sqlBuilderName, dblock, n, depth);
return;
}
_parseNodeList(n.getChildNodes(), sqlBuilderName, sb, dblock, depth);
}
}
//xml: trim
private static void parseTrimNode(StringBuilder sb, String sqlBuilderName , XmlSqlBlock dblock, Node n , int depth) {
String _trimStart = attr(n, "trimStart");
String _trimEnd = attr(n, "trimEnd");
String _prefix = attr(n, "prefix");
String _suffix = attr(n, "suffix");
dblock.varNum++;
String varName = "sb"+dblock.varNum;
sb.append("\n");
newLine(sb, depth).append("SQLBuilder ").append(varName).append(" = new SQLBuilder(); /*trim node*/");
_parseNodeList(n.getChildNodes(), varName, sb, dblock, depth);
if(StringUtils.isEmpty(_trimStart) == false){
newLine(sb, depth).append(varName).append(".trimStart(\"").append(_trimStart.trim()).append("\");");
}
if(StringUtils.isEmpty(_trimEnd) == false){
newLine(sb, depth).append(varName).append(".trimEnd(\"").append(_trimEnd.trim()).append("\");");
}
if(StringUtils.isEmpty(_prefix) == false){
newLine(sb, depth).append(varName).append(".addPrefix(\"").append(_prefix.trim()).append("\");");
}
if(StringUtils.isEmpty(_suffix) == false){
newLine(sb, depth).append(varName).append(".addSuffix(\"").append(_suffix.trim()).append("\");");
}
newLine(sb, depth).append(sqlBuilderName).append(".append(").append(varName).append(");\n");
}
//xml: if
private static void parseIfNode(StringBuilder sb,String sqlBuilderName, XmlSqlBlock dblock, Node n , int depth) {
String _test = attr(n, "test")
.replace(" lt "," < ")
.replace(" lte "," <= ")
.replace(" gt "," > ")
.replace(" gte "," >= ")
.replace(" and ", " && ")
.replace(" or ", " || ");
if(_test.indexOf("?")>0){
_test = parseIfTestExpr(_test);
}
newLine(sb, depth).append("if(").append(_test).append("){ /*if node*/");
_parseNodeList(n.getChildNodes(),sqlBuilderName, sb, dblock, depth + 1);
newLine(sb, depth).append("}");
}
private static String parseIfTestExpr(String test) {
Pattern r = Pattern.compile("([\\w\\.]*?)\\?(\\?|\\!|\\w*)");
Matcher m = r.matcher(test);
if (m.find()) {
String vname = m.group(1);
String vfun = "?" + m.group(2);
if ("??".equals(vfun)) {
String newStr = vname+" != null";
test = test.replace(m.group(), newStr);
}
if ("?!".equals(vfun)) {
String newStr = "StringUtils.isEmpty(" + vname + ") == false";
test = test.replace(m.group(), newStr);
}
}
return test;
}
//xml: ref
private static void parseRefNode(StringBuilder sb, String sqlBuilderName,XmlSqlBlock dblock, Node n , int depth) {
String _sql_id = attr(n, "sql");
if (StringUtils.isEmpty(_sql_id) == false) {
Node ref_n = dblock.__nodeMap.get(_sql_id);
if (ref_n == null) {
throw new RuntimeException("sql node @" + _sql_id + " can't find");
}
_parseNode(ref_n,sqlBuilderName, sb, dblock, depth);
}
}
//xml: for
private static void parseForNode(StringBuilder sb,String sqlBuilderName, XmlSqlBlock dblock, Node n , int depth) {
/**
* //
* {
* int m_index = 0; // m_index
* Iterator<weed3demo.mapper.UserModel> m_iterator = list.iterator(); //@items
* while (m_iterator.hasNext()) {
* weed3demo.mapper.UserModel m = m_iterator.next(); //@var
*
* sb.append("(?,?,?) ", m.user_id, m.mobile, m.sex);
*
* if (m_iterator.hasNext()) { // @sep
* sb.append(",");
* }
* m_index++;
* }
* }
* */
String _items = attr(n, "items");
String _sep_str = attr(n, "sep");
String _var_str = attr(n, "var").trim();
if(_var_str.indexOf(":")<0 || _var_str.length() < 3){
StringBuilder eb = new StringBuilder();
eb.append(dblock._namespace).append("/").append(dblock._id).append("::")
.append("for/var(").append(_var_str).append(") must declare the type");
throw new RuntimeException(eb.toString());
}
String[] kv = _var_str.split(":");
XmlSqlVar _var = new XmlSqlVar(_var_str,kv[0].trim(),kv[1].trim());
int depth0 = depth;
depth++;
newLine(sb, depth0).append("{ /*for node*/"); |
package com.wegas.app.pdf;
import com.lowagie.text.DocumentException;
import com.wegas.core.Helper;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.logging.Level;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xhtmlrenderer.pdf.ITextOutputDevice;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.pdf.ITextUserAgent;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
*
* Filter that capture Servlet response and transform its content into PDF
*
* @author Maxence Laurent (maxence.laurent at gmail.com)
*/
@WebFilter(filterName = "PdfRenderer", urlPatterns = {"/print.html"}, dispatcherTypes = {DispatcherType.REQUEST})
public class PdfRenderer implements Filter {
private static final Logger logger = LoggerFactory.getLogger(PdfRenderer.class);
private static final boolean debug = true;
// The filter configuration object we are associated with. If
// this value is null, this filter instance is not currently
// configured.
private FilterConfig filterConfig = null;
private DocumentBuilder documentBuilder;
@Override
public void init(FilterConfig config) throws ServletException {
try {
this.filterConfig = config;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
documentBuilder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new ServletException(e);
}
}
public PdfRenderer() {
}
/**
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (debug) {
log("PdfRenderer:doFilter()");
}
Throwable problem = null;
try {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String renderType = req.getParameter("outputType");
if (renderType != null && renderType.equals("pdf")) {
// specific type ? capture response
ContentCaptureServletResponse capContent = new ContentCaptureServletResponse(resp);
chain.doFilter(req, capContent);
/*
* convert xhtml from String to XML Document
*/
StringReader contentReader = new StringReader(capContent.getContent());
InputSource source = new InputSource(contentReader);
Document xhtmlDocument = documentBuilder.parse(source);
if (debug) {
Helper.logEnv();
Element utf8Test = xhtmlDocument.getElementById("testUTF8");
log("UTF-8 P test" + utf8Test.getTextContent());
log("Default charset: " + Charset.defaultCharset());
}
ITextRenderer renderer = new ITextRenderer();
CookieUserAgent userAgentCallback = new CookieUserAgent(renderer.getOutputDevice(), req.getCookies());
userAgentCallback.setSharedContext(renderer.getSharedContext());
renderer.getSharedContext().setUserAgentCallback(userAgentCallback);
final String baseUrl = req.getRequestURL().toString().replace(req.getServletPath(), "/");
renderer.setDocument(xhtmlDocument, baseUrl);
renderer.layout();
resp.setContentType("application/pdf; charset=UTF-8");
OutputStream browserStream = resp.getOutputStream();
renderer.createPDF(browserStream);
renderer.finishPDF();
} else {
// no specific type ? -> normal processing
log("PdfRenderer:Normal output", null);
chain.doFilter(request, response);
}
} catch (DocumentException | IOException | ServletException | DOMException | SAXException t) {
problem = t;
log("ERROR", t);
}
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}
/**
* Return the filter configuration object for this filter.
*
* @return
*/
public FilterConfig getFilterConfig() {
return (this.filterConfig);
}
/**
* Set the filter configuration object for this filter.
*
* @param filterConfig The filter configuration object
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
* Destroy method for this filter
*/
@Override
public void destroy() {
}
/**
* Return a String representation of this object.
*
* @return
*/
@Override
public String toString() {
if (filterConfig == null) {
return ("PdfRenderer()");
}
StringBuilder sb = new StringBuilder("PdfRenderer(");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
private void sendProcessingError(Throwable t, ServletResponse response) {
String stackTrace = getStackTrace(t);
if (stackTrace != null && !stackTrace.equals("")) {
try {
response.setContentType("text/html");
try (PrintStream ps = new PrintStream(response.getOutputStream()); PrintWriter pw = new PrintWriter(ps)) {
pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N
// PENDING! Localize this for next official release
pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
pw.print(stackTrace);
pw.print("</pre></body>\n</html>"); //NOI18N
}
response.getOutputStream().close();
} catch (IOException ex) {
}
} else {
try {
try (PrintStream ps = new PrintStream(response.getOutputStream())) {
t.printStackTrace(ps);
}
response.getOutputStream().close();
} catch (IOException ex) {
}
}
}
public static String getStackTrace(Throwable t) {
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (IOException ex) {
}
return stackTrace;
}
public void log(String msg) {
log(msg, null);
}
public void log(String msg, Throwable t) {
if (t != null) {
logger.info(msg, t);
} else {
logger.info(msg);
}
}
/**
* UserAgentCallback with cookies.
*/
private static class CookieUserAgent extends ITextUserAgent {
private final Cookie[] cookies;
public CookieUserAgent(ITextOutputDevice outputDevice, Cookie[] cookies) {
super(outputDevice);
this.cookies = cookies;
}
@Override
protected InputStream resolveAndOpenStream(String uri) {
java.io.InputStream is = null;
try {
URL url = new URL(uri);
URLConnection uc = url.openConnection();
uc.setRequestProperty("Cookie", joinCookies(this.cookies));
is = uc.getInputStream();
} catch (MalformedURLException ex) {
java.util.logging.Logger.getLogger(PdfRenderer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
java.util.logging.Logger.getLogger(PdfRenderer.class.getName()).log(Level.SEVERE, null, ex);
}
return is;
}
/**
* Make a Cookie string
*
* @param cookies
* @return
*/
private static String joinCookies(Cookie[] cookies) {
final String token = "; ";
if (cookies.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(cookies[0].getName()).append("=").append(cookies[0].getValue());
int i;
for (i = 1; i < cookies.length; i++) {
sb.append(token).append(cookies[i].getName()).append("=").append(cookies[i].getValue());
}
return sb.toString();
}
}
} |
package p012;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@SuppressWarnings("serial")
public class Billiards extends JFrame {
public static int Width = 800;
public static int Height = 600;
private JButton b_start, b_stop;
private Board board;
// TODO update with number of group label. See practice statement.
private final int N_BALL = 13;
private Ball[] balls;
public Billiards() {
board = new Board();
board.setForeground(new Color(0, 128, 0));
board.setBackground(new Color(0, 128, 0));
initBalls();
b_start = new JButton("Empezar");
b_start.addActionListener(new StartListener());
b_stop = new JButton("Parar");
b_stop.addActionListener(new StopListener());
JPanel p_Botton = new JPanel();
p_Botton.setLayout(new FlowLayout());
p_Botton.add(b_start);
p_Botton.add(b_stop);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(board, BorderLayout.CENTER);
getContentPane().add(p_Botton, BorderLayout.PAGE_END);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(Width, Height);
setLocationRelativeTo(null);
setTitle("Práctica programación concurrente objetos móviles independientes");
setResizable(false);
setVisible(true);
}
private void initBalls() {
// TODO init balls
}
private class StartListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Code is executed when start button is pushed
}
}
private class StopListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Code is executed when stop button is pushed
}
}
public static void main(String[] args) {
new Billiards();
}
} |
import java.util.*;
import java.io.*;
/*
* Infinite plane.
*/
public class Grid
{
public Grid (String fileName, boolean debug)
{
this(GridData.DEFAULT_HEIGHT, GridData.DEFAULT_WIDTH, fileName, debug);
}
public Grid (int height, int width, String fileName, boolean debug)
{
_theWorld = new Level[GridData.DEFAULT_LEVELS*2 +1];
_height = height;
_width = width;
_debug = debug;
int layer = -GridData.DEFAULT_LEVELS;
// initialise
for (int i = 0; i < GridData.DEFAULT_LEVELS*2 +1; i++)
{
_theWorld[i] = new Level(layer, _height, _width, _debug);
layer++;
}
loadWorld(fileName);
}
/**
* Each minute, The bugs live and die based on the number of bugs in the four adjacent tiles:
*
* - A bug dies (becoming an empty space) unless there is exactly one bug adjacent to it.
* - An empty space becomes infested with a bug if exactly one or two bugs are adjacent to it.
*
* Otherwise, a bug or empty space remains the same. (Tiles on the edges of the grid have fewer than
* four adjacent tiles; the missing tiles count as empty space.) This process happens in every location
* simultaneously; that is, within the same minute, the number of adjacent bugs is counted for every tile
* first, and then the tiles are updated.
*
* For the infinite plane ...
*
* Tile 19 has four adjacent tiles: 14, 18, 20, and 24.
* Tile G has four adjacent tiles: B, F, H, and L.
* Tile D has four adjacent tiles: 8, C, E, and I.
* Tile E has four adjacent tiles: 8, D, 14, and J.
* Tile 14 has eight adjacent tiles: 9, E, J, O, T, Y, 15, and 19.
* Tile N has eight adjacent tiles: I, O, S, and five tiles within the sub-grid marked ?.
*/
public void evolve ()
{
HashSet<ThreeDPoint> allBugs = mergeLayers();
HashSet<ThreeDPoint> evolvedBugs = new HashSet<ThreeDPoint>();
System.out.println("Starting bugs "+allBugs);
for (int x = 0; x < GridData.DEFAULT_WIDTH; x++)
{
for (int y = 0; y < GridData.DEFAULT_HEIGHT; y++)
{
if ((x != GridData.CENTRE_X) && (y != GridData.CENTRE_Y))
{
for (int z = -GridData.DEFAULT_LEVELS; z <= GridData.DEFAULT_LEVELS; z++) // go through the layers
{
ThreeDPoint coord = new ThreeDPoint(x, y, z);
long totalBugs = numberOfBugs(allBugs, coord);
if (!allBugs.contains(coord))
{
if ((totalBugs == 1) || (totalBugs == 2))
evolvedBugs.add(coord);
}
else
{
if (totalBugs == 1)
evolvedBugs.add(coord);
}
}
}
}
}
//System.out.println("ending bugs "+evolvedBugs);
splitLayers(evolvedBugs); // split to make printing easier
}
@Override
public String toString ()
{
String str = "";
for (int i = 0; i < _theWorld.length; i++)
{
str += "\nDepth "+_theWorld[i].getLevel()+":\n";
str += _theWorld[i];
}
return str;
}
@Override
public boolean equals (Object obj)
{
if (obj == null)
return false;
if (this == obj)
return true;
if (getClass() == obj.getClass())
{
Grid temp = (Grid) obj;
if (_theWorld.length == temp._theWorld.length)
{
boolean same = true;
for (int i = 0; (i < _theWorld.length) && same; i++)
{
if (!_theWorld[i].equals(temp._theWorld[i]))
same = false;
}
return same;
}
}
return false;
}
private final HashSet<ThreeDPoint> mergeLayers ()
{
HashSet<ThreeDPoint> merged = new HashSet<ThreeDPoint>();
for (int i = 0; i < _theWorld.length; i++)
{
merged.addAll(_theWorld[i].getBugs());
}
return merged;
}
private final void splitLayers (HashSet<ThreeDPoint> merged)
{
int layer = -GridData.DEFAULT_LEVELS;
for (int i = 0; i < GridData.DEFAULT_LEVELS*2 +1; i++)
{
_theWorld[i] = new Level(layer, _height, _width, _debug);
layer++;
}
Iterator<ThreeDPoint> iter = merged.iterator();
while (iter.hasNext())
{
ThreeDPoint position = iter.next();
int index = position.getZ() + GridData.DEFAULT_LEVELS;
_theWorld[index].addBug(position);
}
}
private HashSet<ThreeDPoint> adjacentTileCoordinates (ThreeDPoint position)
{
HashSet<ThreeDPoint> tiles = new HashSet<ThreeDPoint>();
System.out.println("Starting coord "+position);
// could generate invalid coordinates but we'll deal with that later ...
tiles.add(new ThreeDPoint(position.getX() - 1, position.getY(), position.getZ()));
tiles.add(new ThreeDPoint(position.getX() + 1, position.getY(), position.getZ()));
tiles.add(new ThreeDPoint(position.getX(), position.getY() - 1, position.getZ()));
tiles.add(new ThreeDPoint(position.getX(), position.getY() + 1, position.getZ()));
if (position.getX() == 0)
tiles.add(GridData.leftOuterEdge(position));
if (position.getX() == GridData.DEFAULT_HEIGHT -1)
tiles.add(GridData.rightOuterEdge(position));
if (position.getY() == 0)
tiles.add(GridData.topOuterEdge(position));
if (position.getY() == GridData.DEFAULT_HEIGHT -1)
tiles.add(GridData.bottomOuterEdge(position));
if ((position.getX() == GridData.CENTRE_X) && (position.getY() == GridData.TOP_INNER_EDGE_Y))
GridData.topInnerEdge(position, tiles);
if ((position.getX() == GridData.CENTRE_X) && (position.getY() == GridData.BOTTOM_INNER_EDGE_Y))
GridData.bottomInnerEdge(position, tiles);
if ((position.getX() == GridData.LEFT_INNER_EDGE_X) && (position.getY() == GridData.CENTRE_Y))
GridData.leftInnerEdge(position, tiles);
if ((position.getX() == GridData.RIGHT_INNER_EDGE_X) && (position.getY() == GridData.CENTRE_Y))
GridData.rightInnerEdge(position, tiles);
// Nove remove any invalid points
pruneInvalid(tiles);
System.out.println("tiles "+tiles);
return tiles;
}
private void pruneInvalid (HashSet<ThreeDPoint> tiles)
{
// remove the nested grid marker/coordinate
tiles.removeIf(p -> p.getX() == GridData.CENTRE_X && p.getY() == GridData.CENTRE_Y);
// now remove anything with invalid coordinates
tiles.removeIf(p -> p.getX() < 0 || p.getX() > (GridData.DEFAULT_WIDTH -1) || p.getY() < 0 || p.getY() > (GridData.DEFAULT_HEIGHT -1));
}
private long numberOfBugs (HashSet<ThreeDPoint> allBugs, ThreeDPoint position)
{
return adjacentTileCoordinates(position).stream()
.filter(p -> allBugs.contains(p))
.count();
}
private void loadWorld (String inputFile)
{
BufferedReader reader = null;
int h = 0;
try
{
reader = new BufferedReader(new FileReader(inputFile));
String line = null;
while ((line = reader.readLine()) != null)
{
System.out.println("line "+line);
for (int i = 0; i < line.length(); i++)
{
if (TileId.BUG == line.charAt(i))
{
System.out.println("Bug at "+i+" "+h);
_theWorld[GridData.DEFAULT_LEVELS].addBug(new ThreeDPoint(i, h, 0));
}
}
h++;
}
}
catch (Throwable ex)
{
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (Throwable ex)
{
}
}
}
private Level[] _theWorld;
private int _height;
private int _width;
private boolean _debug;
} |
import java.util.*;
public class Total
{
public Total (Vector<Integer> list, boolean debug)
{
_numbers = list;
_debug = debug;
if (_debug)
System.out.println("Size of numbers: "+_numbers.size());
}
public Integer[] sum (int total)
{
if (_debug)
System.out.println("Checking for "+total);
Integer[] toReturn = new Integer[3];
boolean found = false;
for (int i = 0; (i < _numbers.size()) && !found; i++)
{
toReturn[0] = _numbers.elementAt(i);
if (_debug)
System.out.println("First number: "+toReturn[0]);
for (int j = i+1; (j < _numbers.size()) && !found; j++)
{
toReturn[1] = _numbers.elementAt(j);
if (_debug)
System.out.println("Second number: "+toReturn[1]);
for (int k = j+1; (k < _numbers.size()) && !found; k++)
{
if (_debug)
System.out.println("Checking "+toReturn[0]+" and "+toReturn[1]+" and "+_numbers.elementAt(k));
if (toReturn[0] + toReturn[1] + _numbers.elementAt(k) == total)
{
toReturn[2] = _numbers.elementAt(k);
found = true;
}
}
}
}
if (found)
return toReturn;
else
return null;
}
private Vector<Integer> _numbers;
private boolean _debug;
} |
public class Tile
{
public static final int TOP = 0;
public static final int LEFT = 1;
public static final int BOTTOM = 2;
public static final int RIGHT = 3;
public Tile (long number, String[] data)
{
_id = number;
_data = new char[data.length][data[0].length()];
_originalState = new char[data.length][data[0].length()];
for (int i = 0; i < data.length; i++)
{
for (int j = 0; j < data[0].length(); j++)
{
_data[i][j] = data[i].charAt(j);
_originalState[i][j] = data[i].charAt(j);
}
}
_freeze = false; // should the tile move?
_isConnected = new boolean[4]; // edges connected?
_connections = new long[4]; // if so, which ones?
for (int i = 0; i < 4; i++)
{
_isConnected[i] = false; // which edges are connected?
_connections[i] = 0;
}
_numberOfConnections = 0;
}
public final void removeBorders ()
{
}
public final boolean hasSeaMonster (int x, int y)
{
if ((_data[y + 1][x + 1] == TileData.HASH) && (_data[y + 1][x + 4] == TileData.HASH)
&& (_data[y][x + 5] == TileData.HASH) && (_data[y][x + 6] == TileData.HASH)
&& (_data[y + 1][x + 7] == TileData.HASH) && (_data[y + 1][x + 10] == TileData.HASH)
&& (_data[y][x + 11] == TileData.HASH) && (_data[y][x + 12] == TileData.HASH)
&& (_data[y + 1][x + 13] == TileData.HASH) && (_data[y + 1][x + 16] == TileData.HASH)
&& (_data[y][x + 17] == TileData.HASH) && (_data[y][x + 18] == TileData.HASH)
&& (_data[y][x + 19] == TileData.HASH) && (_data[y - 1][x + 18] == TileData.HASH))
{
return true;
}
return false;
}
public final long getID ()
{
return _id;
}
public final boolean isFrozen ()
{
return _freeze;
}
public final void freeze ()
{
_freeze = true;
}
public final boolean[] getConnectionStatuses ()
{
return _isConnected;
}
public final long[] getConnections ()
{
return _connections;
}
/*
* rotates tile 90 degrees clockwise. Assume you
* have to call it multiple times to get through
* all 360 degrees.
*/
public void rotate ()
{
int x = _data.length;
int y = _data[0].length;
char[][] temp = new char[x][y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
temp[j][x - 1 - i] = _data[i][j];
}
}
_data = temp;
}
/*
* Flip top to bottom.
*/
public void invert ()
{
int x = _data.length;
int y = _data[0].length;
char[][] temp = new char[x][y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
temp[i][_data[i].length - j - 1] = _data[i][j];
}
}
_data = temp;
}
public boolean connectTopToBottom (Tile toCheck)
{
// check edges match
// store the edges separately again?
for (int i = 0; i < _data.length; i++)
{
if (_data[0][i] != toCheck._data[_data.length - 1][i])
return false;
}
connect(toCheck, TOP, BOTTOM);
System.out.println("connectTopToBottom");
return true;
}
public boolean connectBottomToTop (Tile toCheck)
{
// check edges match
for (int i = 0; i < _data.length; i++)
{
if (_data[_data.length - 1][i] != toCheck._data[0][i])
return false;
}
connect(toCheck, BOTTOM, TOP);
System.out.println("connectBottomToTop");
return true;
}
public boolean connectLeftToRight (Tile toCheck)
{
// check edges match
for (int i = 0; i < _data.length; i++)
{
if (_data[i][0] != toCheck._data[i][_data.length - 1])
return false;
}
connect(toCheck, LEFT, RIGHT);
System.out.println("connectLeftToRight");
return true;
}
public boolean connectRightToLeft (Tile toCheck)
{
// check edges match
for (int i = 0; i < _data.length; i++)
{
if (_data[i][_data.length - 1] != toCheck._data[i][0])
return false;
}
connect(toCheck, RIGHT, LEFT);
System.out.println("connectRightToLeft");
return true;
}
private final void connect (Tile toCheck, int thisEdge, int otherEdge)
{
if ((_connections[thisEdge] == 0) && (toCheck._connections[otherEdge] == 0))
{
_connections[thisEdge] = toCheck.getID();
_isConnected[thisEdge] = true;
_numberOfConnections++;
toCheck._connections[otherEdge] = getID();
toCheck._isConnected[otherEdge] = true;
toCheck._numberOfConnections++;
}
}
@Override
public boolean equals (Object obj)
{
if (obj == null)
return false;
if (this == obj)
return true;
if (getClass() == obj.getClass())
{
Tile temp = (Tile) obj;
return (_id == temp._id);
}
return false;
}
@Override
public String toString ()
{
String str = TileData.TILE_ID+_id+":\n";
for (int i = 0; i < _data.length; i++)
{
for (int j = 0; j < _data[0].length; j++)
{
str += _data[i][j];
}
str += "\n";
}
return str;
}
private long _id;
private char[][] _data;
private char[][] _originalState;
private boolean _freeze;
private boolean[] _isConnected;
private long[] _connections;
private int _numberOfConnections;
} |
package org.adonai;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public enum Key {
C(0, 0, "C"),
G(0, 1, "G"),
D(0, 2, "D"),
A(0, 3, "A"),
E(0, 4, "E"),
H(0, 5, "H"),
Fis(0, 6, "F
Cis(0, 7, "C
Gis(0, 8, "G
Dis(0, 9, "D
F (1, 0, "F"),
Bb (2, 0, "Bb"),
Eb (3, 0, "Eb"),
Ab (4, 0, "Ab"),
Db (5, 0, "Db"),
Gb (6, 0, "Gb"),
Cb (7, 0, "Cb");
int decrementSigns = 0;
int incrementSigns = 0;
private String description;
Key (final int decrementSigns, final int incrementSigns, final String description) {
this.decrementSigns = decrementSigns;
this.incrementSigns = incrementSigns;
this.description = description;
}
public static Key fromString (String key) {
try {
key = key.replace("
return Key.valueOf(key);
} catch (Exception e) {
log.info("No key found for <" + key + ">");
throw new RuntimeException(e);
}
}
public String getDescription () {
return description;
}
} |
package org.commcare.adapters;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import org.commcare.CommCareApplication;
import org.commcare.activities.CommCareActivity;
import org.commcare.cases.entity.Entity;
import org.commcare.cases.entity.EntitySortNotificationInterface;
import org.commcare.cases.entity.EntitySorter;
import org.commcare.cases.entity.NodeEntityFactory;
import org.commcare.dalvik.R;
import org.commcare.models.AsyncNodeEntityFactory;
import org.commcare.preferences.CommCarePreferences;
import org.commcare.session.SessionInstanceBuilder;
import org.commcare.suite.model.Action;
import org.commcare.suite.model.Detail;
import org.commcare.utils.AndroidUtil;
import org.commcare.utils.CachingAsyncImageLoader;
import org.commcare.utils.StringUtils;
import org.commcare.views.EntityActionViewUtils;
import org.commcare.views.EntityView;
import org.commcare.views.EntityViewTile;
import org.commcare.views.notifications.NotificationMessageFactory;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.OrderedHashtable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
/**
* This adapter class handles displaying the cases for a CommCareODK user.
* Depending on the <grid> block of the Detail this adapter is constructed with, cases might be
* displayed as normal EntityViews or as AdvancedEntityViews
*
* @author ctsims
* @author wspride
*/
public class EntityListAdapter implements ListAdapter, EntitySortNotificationInterface {
public static final int ENTITY_TYPE = 0;
public static final int ACTION_TYPE = 1;
public static final int DIVIDER_TYPE = 2;
public static final int DIVIDER_ID = -2;
private int dividerPosition = 0;
private final int actionsCount;
private final int dividerCount;
private boolean mFuzzySearchEnabled = true;
private boolean isFilteringByCalloutResult = false;
private final CommCareActivity commCareActivity;
private final Detail detail;
private final List<DataSetObserver> observers;
private final List<Entity<TreeReference>> full;
private List<Entity<TreeReference>> current;
private final List<TreeReference> references;
private final List<Action> actions;
private TreeReference selected;
private int[] currentSort = {};
private boolean reverseSort = false;
private final NodeEntityFactory mNodeFactory;
private boolean mAsyncMode = false;
private String[] currentSearchTerms;
private String searchQuery = "";
private EntityFiltererBase entityFilterer = null;
// Asyncronous image loader, allows rows with images to scroll smoothly
private final CachingAsyncImageLoader mImageLoader;
// false until we determine the Detail has at least one <grid> block
private boolean usesCaseTiles = false;
// key to data mapping used to attach callout results to individual entities
private OrderedHashtable<String, String> calloutResponseData = new OrderedHashtable<>();
private final boolean selectActivityInAwesomeMode;
public EntityListAdapter(CommCareActivity activity, Detail detail,
List<TreeReference> references,
List<Entity<TreeReference>> full,
int[] sort, NodeEntityFactory factory,
boolean hideActions, List<Action> actions, boolean inAwesomeMode) {
this.detail = detail;
this.selectActivityInAwesomeMode = inAwesomeMode;
this.actions = actions;
if (actions == null || actions.isEmpty() || hideActions) {
actionsCount = 0;
dividerCount = 0;
} else {
actionsCount = actions.size();
dividerCount = 2;
}
this.full = full;
this.references = references;
this.commCareActivity = activity;
this.observers = new ArrayList<>();
this.mNodeFactory = factory;
//TODO: I am a bad person and I should feel bad. This should get encapsulated
//somewhere in the factory as a callback (IE: How to sort/or whether to or something)
mAsyncMode = (factory instanceof AsyncNodeEntityFactory);
//TODO: Maybe we can actually just replace by checking whether the node is ready?
if (!mAsyncMode) {
if (sort.length != 0) {
sort(sort);
}
}
if (android.os.Build.VERSION.SDK_INT >= 14) {
mImageLoader = new CachingAsyncImageLoader(commCareActivity);
} else {
mImageLoader = null;
}
this.usesCaseTiles = detail.usesEntityTileView();
this.mFuzzySearchEnabled = CommCarePreferences.isFuzzySearchEnabled();
setCurrent(new ArrayList<>(full));
}
/**
* Set the current display set for this adapter
*/
void setCurrent(List<Entity<TreeReference>> arrayList) {
current = arrayList;
if (actionsCount > 0) {
dividerPosition = current.size();
}
update();
}
void clearSearch() {
currentSearchTerms = null;
searchQuery = "";
}
public void clearCalloutResponseData() {
isFilteringByCalloutResult = false;
setCurrent(full);
calloutResponseData.clear();
}
private void sort(int[] fields) {
//The reversing here is only relevant if there's only one sort field and we're on it
sort(fields, (currentSort.length == 1 && currentSort[0] == fields[0]) && !reverseSort);
}
private void sort(int[] fields, boolean reverse) {
this.reverseSort = reverse;
currentSort = fields;
java.util.Collections.sort(full, new EntitySorter(detail.getFields(), reverseSort, currentSort, this));
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int position) {
return true;
}
/**
* Includes action, if enabled, as an item.
*/
@Override
public int getCount() {
return getCurrentCountWithActions();
}
public int getFullCount() {
return full.size();
}
public int getCurrentCount() {
return current.size();
}
public int getCurrentCountWithActions() {
return current.size() + actionsCount + dividerCount;
}
@Override
public TreeReference getItem(int position) {
return current.get(position).getElement();
}
@Override
public long getItemId(int position) {
int type = getItemViewType(position);
switch (type) {
case ENTITY_TYPE:
return references.indexOf(current.get(position).getElement());
case ACTION_TYPE:
return dividerPosition + actions.indexOf(getAction(position));
case DIVIDER_TYPE:
return -2;
default:
throw new RuntimeException("Invalid view type");
}
}
private Action getAction(int position) {
int baseActionPosition = dividerPosition + 1;
return actions.get(position - baseActionPosition);
}
@Override
public int getItemViewType(int position) {
if (actionsCount > 0) {
if (position > dividerPosition && position != getCount() - 1) {
return ACTION_TYPE;
} else if (position == dividerPosition || position == getCount() - 1) {
return DIVIDER_TYPE;
}
}
return ENTITY_TYPE;
}
/**
* Note that position gives a unique "row" id, EXCEPT that the header row AND the first content row
* are both assigned position 0 -- this is not an issue for current usage, but it could be in future
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
switch (type) {
case ENTITY_TYPE:
return getEntityView(position, convertView);
case ACTION_TYPE:
return getActionView(position, (FrameLayout)convertView, parent);
case DIVIDER_TYPE:
return getDividerView((LinearLayout)convertView, parent);
default:
throw new RuntimeException("Invalid view type");
}
}
private View getEntityView(int position, View convertView) {
Entity<TreeReference> entity = current.get(position);
if (usesCaseTiles) {
// if we use a <grid>, setup an AdvancedEntityView
return getTileView(entity, (EntityViewTile)convertView);
} else {
return getListEntityView(entity, (EntityView)convertView, position);
}
}
private View getTileView(Entity<TreeReference> entity, EntityViewTile tile) {
int[] titleColor = AndroidUtil.getThemeColorIDs(commCareActivity, new int[]{R.attr.entity_select_title_text_color});
if (tile == null) {
tile = EntityViewTile.createTileForEntitySelectDisplay(commCareActivity, detail, entity,
currentSearchTerms, mImageLoader, mFuzzySearchEnabled, selectActivityInAwesomeMode);
} else {
tile.setSearchTerms(currentSearchTerms);
tile.addFieldViews(commCareActivity, detail, entity);
}
tile.setTitleTextColor(titleColor[0]);
return tile;
}
private View getListEntityView(Entity<TreeReference> entity, EntityView emv, int position) {
if (emv == null) {
emv = EntityView.buildEntryEntityView(
commCareActivity, detail, entity,
currentSearchTerms, position, mFuzzySearchEnabled,
getCalloutDataForEntity(entity));
} else {
emv.setSearchTerms(currentSearchTerms);
if (detail.getCallout() != null) {
emv.setExtraData(detail.getCallout().getResponseDetailField(), getCalloutDataForEntity(entity));
}
emv.refreshViewsForNewEntity(entity, entity.getElement().equals(selected), position);
}
return emv;
}
private String getCalloutDataForEntity(Entity<TreeReference> entity) {
if (entity.extraKey != null) {
return calloutResponseData.get(entity.extraKey);
} else {
return null;
}
}
private View getActionView(int position, FrameLayout actionCardView, ViewGroup parent) {
if (actionCardView == null) {
actionCardView = (FrameLayout)LayoutInflater.from(parent.getContext()).inflate(R.layout.action_card, parent, false);
}
EntityActionViewUtils.buildActionView(actionCardView,
getAction(position),
commCareActivity);
return actionCardView;
}
private LinearLayout getDividerView(LinearLayout convertView, ViewGroup parent) {
if (convertView == null) {
return (LinearLayout)LayoutInflater.from(parent.getContext()).inflate(R.layout.line_separator, parent, false);
}
convertView.setOnClickListener(null);
convertView.setEnabled(false);
convertView.setFocusable(false);
return convertView;
}
@Override
public int getViewTypeCount() {
return (actionsCount > 0) ? 3 : 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEmpty() {
return getCount() > 0;
}
public synchronized void filterByString(String filterRaw) {
if (entityFilterer != null) {
entityFilterer.cancelSearch();
}
// split by whitespace
String[] searchTerms = filterRaw.split("\\s+");
for (int i = 0; i < searchTerms.length; ++i) {
searchTerms[i] = StringUtils.normalize(searchTerms[i]);
}
currentSearchTerms = searchTerms;
searchQuery = filterRaw;
entityFilterer =
new EntityStringFilterer(this, searchTerms, mAsyncMode,
mFuzzySearchEnabled, mNodeFactory, full, commCareActivity);
entityFilterer.start();
}
/**
* Filter entity list to only include entities that have extra keys present
* in the provided mapping. Reorders entities by the key ordering of the
* mapping.
*/
public synchronized void filterByKeyedCalloutData(OrderedHashtable<String, String> keyToExtraDataMapping) {
calloutResponseData = keyToExtraDataMapping;
if (entityFilterer != null) {
entityFilterer.cancelSearch();
}
LinkedHashSet<String> keysToFilterBy = new LinkedHashSet<>();
for (Enumeration en = calloutResponseData.keys(); en.hasMoreElements(); ) {
String key = (String)en.nextElement();
keysToFilterBy.add(key);
}
isFilteringByCalloutResult = true;
entityFilterer =
new EntityKeyFilterer(this, mNodeFactory, full, commCareActivity, keysToFilterBy);
entityFilterer.start();
}
void update() {
for (DataSetObserver o : observers) {
o.onChanged();
}
}
public void sortEntities(int[] keys) {
sort(keys);
}
public int[] getCurrentSort() {
return currentSort;
}
public boolean isCurrentSortReversed() {
return reverseSort;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
if (!observers.contains(observer)) {
this.observers.add(observer);
}
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
this.observers.remove(observer);
}
public void notifyCurrentlyHighlighted(TreeReference chosen) {
this.selected = chosen;
update();
}
public int getPosition(TreeReference chosen) {
for (int i = 0; i < current.size(); ++i) {
Entity<TreeReference> e = current.get(i);
if (e.getElement().equals(chosen)) {
return i;
}
}
return -1;
}
/**
* Signal that this adapter is dying. If we are doing any asynchronous work,
* we need to stop doing so.
*/
public synchronized void signalKilled() {
if (entityFilterer != null) {
entityFilterer.cancelSearch();
}
}
public String getSearchNotificationText() {
if (isFilteringByCalloutResult) {
return Localization.get("select.callout.search.status", new String[]{
"" + getCurrentCount(),
"" + getFullCount()});
} else {
return Localization.get("select.search.status", new String[]{
"" + getCurrentCount(),
"" + getFullCount(),
searchQuery});
}
}
public String getSearchQuery() {
return searchQuery;
}
public boolean isFilteringByCalloutResult() {
return isFilteringByCalloutResult;
}
public boolean hasCalloutResponseData() {
return !calloutResponseData.isEmpty();
}
public void loadCalloutDataFromSession() {
OrderedHashtable<String, String> externalData =
(OrderedHashtable<String, String>)CommCareApplication.instance()
.getCurrentSession()
.getCurrentFrameStepExtra(SessionInstanceBuilder.KEY_ENTITY_LIST_EXTRA_DATA);
if (externalData != null) {
filterByKeyedCalloutData(externalData);
}
}
public void saveCalloutDataToSession() {
if (isFilteringByCalloutResult) {
CommCareApplication.instance().getCurrentSession().addExtraToCurrentFrameStep(SessionInstanceBuilder.KEY_ENTITY_LIST_EXTRA_DATA, calloutResponseData);
}
}
@Override
public void notifyBadfilter(String[] args) {
CommCareApplication.instance().reportNotificationMessage(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Bad_Case_Filter, args));
}
} |
package org.yamcs.tctm;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.ConfigurationException;
import org.yamcs.YConfiguration;
import org.yamcs.YamcsServer;
import org.yamcs.cmdhistory.CommandHistoryPublisher;
import org.yamcs.commanding.PreparedCommand;
import org.yamcs.parameter.ParameterValue;
import org.yamcs.parameter.SystemParametersCollector;
import org.yamcs.parameter.SystemParametersProducer;
import org.yamcs.protobuf.Commanding.CommandId;
import org.yamcs.time.TimeService;
import org.yamcs.utils.LoggingUtils;
import org.yamcs.utils.TimeEncoding;
import com.google.common.util.concurrent.AbstractService;
/**
* Sends raw packets on Tcp socket.
* @author nm
*
*/
public class TcpTcDataLink extends AbstractService implements Runnable, TcDataLink, SystemParametersProducer {
protected SocketChannel socketChannel=null;
protected String host="whirl";
protected int port=10003;
protected CommandHistoryPublisher commandHistoryListener;
protected Selector selector;
SelectionKey selectionKey;
protected CcsdsSeqAndChecksumFiller seqAndChecksumFiller=new CcsdsSeqAndChecksumFiller();
protected ScheduledThreadPoolExecutor timer;
protected volatile boolean disabled=false;
protected int minimumTcPacketLength = -1; //the minimum size of the CCSDS packets uplinked
protected Queue<PreparedCommand> commandQueue;
protected long tcDelay;
protected volatile long tcCount;
private String sv_linkStatus_id, sp_dataCount_id;
private SystemParametersCollector sysParamCollector;
protected final Logger log;
private String yamcsInstance;
private String name;
TimeService timeService;
class TcSendQueue extends LinkedBlockingQueue<PreparedCommand>{
private static final long serialVersionUID = 1L;
ReentrantLock lock = new ReentrantLock();
private int capacity;
public TcSendQueue(int capacity) {
this.capacity = capacity;
}
public TcSendQueue() {
this.capacity = -1;
}
@Override
public boolean offer(PreparedCommand e) {
if(capacity > -1 && size() >= capacity)
return false;
return super.offer(e);
}
@Override
public PreparedCommand poll() {
lock.lock();
timer.schedule(new Runnable() {
@Override
public void run() {
lock.unlock();
}
}, tcDelay, TimeUnit.MILLISECONDS);
return super.poll();
}
}
public TcpTcDataLink(String yamcsInstance, String name, String spec) throws ConfigurationException {
log = LoggingUtils.getLogger(this.getClass(), yamcsInstance);
YConfiguration c = YConfiguration.getConfiguration("tcp");
this.yamcsInstance = yamcsInstance;
host = c.getString(spec, "tcHost");
port = c.getInt(spec, "tcPort");
this.name = name;
if(c.containsKey(spec, "minimumTcPacketLength")) {
minimumTcPacketLength = c.getInt(spec, "minimumTcPacketLength");
} else {
log.debug("minimumTcPacketLength not defined, using the default value {}", minimumTcPacketLength);
}
if(c.containsKey(spec, "tcQueueSize")) {
commandQueue = new TcSendQueue(c.getInt(spec, "tcQueueSize"));
} else {
commandQueue = new TcSendQueue();
}
if(c.containsKey(spec, "tcMaxRate")) {
tcDelay = 100000/c.getInt(spec, "tcMaxRate"); //TODO test
}
timeService = YamcsServer.getTimeService(yamcsInstance);
}
protected TcpTcDataLink() {
log=LoggerFactory.getLogger(this.getClass().getName());
} // dummy constructor which is automatically invoked by subclass constructors
public TcpTcDataLink(String host, int port) {
this.host=host;
this.port=port;
openSocket();
log=LoggerFactory.getLogger(this.getClass().getName());
}
protected long getCurrentTime() {
if(timeService!=null) {
return timeService.getMissionTime();
} else {
return TimeEncoding.fromUnixTime(System.currentTimeMillis());
}
}
@Override
protected void doStart() {
setupSysVariables();
this.timer=new ScheduledThreadPoolExecutor(1);
timer.scheduleWithFixedDelay(this, 0, 10, TimeUnit.SECONDS);
notifyStarted();
}
protected void openSocket() {
try {
InetAddress address=InetAddress.getByName(host);
socketChannel=SocketChannel.open(new InetSocketAddress(address,port));
socketChannel.configureBlocking(false);
socketChannel.socket().setKeepAlive(true);
selector = Selector.open();
selectionKey = socketChannel.register(selector,SelectionKey.OP_WRITE|SelectionKey.OP_READ);
log.info("TC connection established to {}:{}", host, port);
} catch (IOException e) {
String exc = (e instanceof ConnectException) ? ((ConnectException) e).getMessage() : e.toString();
log.info("Cannot open TC connection to {}:{} '{}'. Retrying in 10s", host, port, exc.toString());
try {
socketChannel.close();
} catch (Exception e1) {}
try {
selector.close();
} catch (Exception e1) {}
socketChannel=null;
}
}
protected void disconnect() {
if(socketChannel==null) {
return;
}
try {
socketChannel.close();
selector.close();
socketChannel=null;
} catch (IOException e) {
log.warn("Exception caught when checking if the socket to {}:{} is open", host, port, e);
}
}
/**
* we check if the socket is open by trying a select on the read part of it
* @return
*/
protected boolean isSocketOpen() {
final ByteBuffer bb=ByteBuffer.allocate(16);
if(socketChannel==null) {
return false;
}
boolean connected=false;
try {
selector.select();
if(selectionKey.isReadable()) {
int read = socketChannel.read(bb);
if(read>0) {
log.info("Data read on the TC socket to {}:{}!! : {}",host, port, bb);
connected=true;
} else if(read<0) {
log.warn("TC socket to "+host+":"+port+" has been closed");
socketChannel.close();
selector.close();
socketChannel=null;
connected=false;
}
} else if(selectionKey.isWritable()){
connected=true;
} else {
log.warn("The TC socket to "+host+":"+port+" is neither writable nor readable");
connected=false;
}
} catch (IOException e) {
log.warn("Exception caught when checking if the socket to {}:{} is open:",host, port, e);
connected=false;
}
return connected;
}
/**
* Sends
*/
@Override
public void sendTc(PreparedCommand pc) {
if(disabled) {
log.warn("TC disabled, ignoring command "+pc.getCommandId());
return;
}
if(!commandQueue.offer(pc)) {
timer.schedule(new TcAckStatus(pc.getCommandId(), "Acknowledge_FSC_Status","NACK"), 100, TimeUnit.MILLISECONDS);
}
timer.schedule(new TcSend(), 0, TimeUnit.MILLISECONDS);
}
protected void handleAcks(CommandId cmdId, int seqCount ) {
timer.schedule(new TcAck(cmdId,"Final_Sequence_Count", Integer.toString(seqCount)), 200, TimeUnit.MILLISECONDS);
timer.schedule(new TcAckStatus(cmdId,"Acknowledge_FSC","ACK: OK"), 400, TimeUnit.MILLISECONDS);
timer.schedule(new TcAckStatus(cmdId,"Acknowledge_FRC","ACK: OK"), 800, TimeUnit.MILLISECONDS);
timer.schedule(new TcAckStatus(cmdId,"Acknowledge_DASS","ACK: OK"), 1200, TimeUnit.MILLISECONDS);
timer.schedule(new TcAckStatus(cmdId,"Acknowledge_MCS","ACK: OK"), 1600, TimeUnit.MILLISECONDS);
}
@Override
public void setCommandHistoryPublisher(CommandHistoryPublisher commandHistoryListener) {
this.commandHistoryListener=commandHistoryListener;
}
@Override
public String getLinkStatus() {
if (disabled) {
return "DISABLED";
}
if(isSocketOpen()) {
return "OK";
} else {
return "UNAVAIL";
}
}
@Override
public String getDetailedStatus() {
if(disabled)
return String.format("DISABLED (should connect to %s:%d)", host, port);
if(isSocketOpen()) {
return String.format("OK, connected to %s:%d", host, port);
} else {
return String.format("Not connected to %s:%d", host, port);
}
}
@Override
public void disable() {
disabled=true;
if(isRunning()) {
disconnect();
}
}
@Override
public void enable() {
disabled=false;
}
@Override
public boolean isDisabled() {
return disabled;
}
@Override
public void run() {
if(!isRunning() || disabled) {
return;
}
if (!isSocketOpen()) {
openSocket();
}
}
@Override
public void doStop() {
disconnect();
notifyStopped();
}
class TcAck implements Runnable {
CommandId cmdId;
String name;
String value;
TcAck(CommandId cmdId, String name, String value) {
this.cmdId=cmdId;
this.name=name;
this.value=value;
}
@Override
public void run() {
commandHistoryListener.updateStringKey(cmdId,name,value);
}
}
public class TcAckStatus extends TcAck {
public TcAckStatus(CommandId cmdId, String name, String value) {
super(cmdId, name, value);
}
@Override
public void run() {
long instant = getCurrentTime();
commandHistoryListener.updateStringKey(cmdId,name+"_Status",value);
commandHistoryListener.updateTimeKey(cmdId,name+"_Time", instant);
}
}
public class TcSend implements Runnable {
@Override
public void run() {
PreparedCommand pc = commandQueue.poll();
ByteBuffer bb = null;
if(pc.getBinary().length<minimumTcPacketLength) { //enforce the minimum packet length
bb=ByteBuffer.allocate(minimumTcPacketLength);
bb.put(pc.getBinary());
bb.putShort(4, (short)(minimumTcPacketLength - 7)); // fix packet length
} else {
int checksumIndicator = pc.getBinary()[2] & 0x04;
if(checksumIndicator ==1) {
bb=ByteBuffer.allocate(pc.getBinary().length +2); //extra slots for check sum
} else {
bb=ByteBuffer.wrap(pc.getBinary());
}
bb.putShort(4, (short)(pc.getBinary().length - 7));
}
int retries=5;
boolean sent=false;
int seqCount=seqAndChecksumFiller.fill(bb, pc.getCommandId().getGenerationTime());
bb.rewind();
while (!sent&&(retries>0)) {
if (!isSocketOpen()) {
openSocket();
}
if(isSocketOpen()) {
try {
socketChannel.write(bb);
tcCount++;
sent=true;
} catch (IOException e) {
log.warn("Error writing to TC socket to {}:{} : {}", host, port, e.getMessage());
try {
if(socketChannel.isOpen()) {
socketChannel.close();
}
selector.close();
socketChannel = null;
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
retries
if(!sent && (retries>0)) {
try {
log.warn("Command not sent, retrying in 2 seconds");
Thread.sleep(2000);
} catch (InterruptedException e) {
log.warn("exception {} thrown when sleeping 2 sec", e.toString());
Thread.currentThread().interrupt();
}
}
}
commandHistoryListener.publish(pc.getCommandId(), "ccsds-seqcount", seqCount);
if(sent) {
handleAcks(pc.getCommandId(), seqCount);
} else {
timer.schedule(new TcAckStatus(pc.getCommandId(), "Acknowledge_FSC_Status","NACK"), 100, TimeUnit.MILLISECONDS);
}
}
}
@Override
public long getDataCount() {
return tcCount;
}
protected void setupSysVariables() {
this.sysParamCollector = SystemParametersCollector.getInstance(yamcsInstance);
if(sysParamCollector!=null) {
sysParamCollector.registerProvider(this, null);
sv_linkStatus_id = sysParamCollector.getNamespace()+"/"+name+"/linkStatus";
sp_dataCount_id = sysParamCollector.getNamespace()+"/"+name+"/dataCount";
} else {
log.info("System variables collector not defined for instance {} ", yamcsInstance);
}
}
@Override
public Collection<ParameterValue> getSystemParameters() {
long time = getCurrentTime();
ParameterValue linkStatus = SystemParametersCollector.getPV(sv_linkStatus_id, time, getLinkStatus());
ParameterValue dataCount = SystemParametersCollector.getPV(sp_dataCount_id, time, getDataCount());
return Arrays.asList(linkStatus, dataCount);
}
public int getMiniminimumTcPacketLength() {
return minimumTcPacketLength;
}
} |
package burlap.oomdp.visualizer;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
/**
* A MultiLayerRenderer is a canvas that will sequentially render a set of render layers, one on top of the other, to the same 2D
* graphics context. Rendering is performed offscreen to a buffered image before being displayed on the screen.
* @author James MacGlashan
*
*/
public class MultiLayerRenderer extends Canvas {
private static final long serialVersionUID = 1L;
/**
* The layers that will be rendered in order from index 0 to n
*/
protected List<RenderLayer> renderLayers;
/**
* the background color of the canvas
*/
protected Color bgColor = Color.white;
/**
* Offscreen image to render to first
*/
protected Image offscreen = null;
/**
* The graphics context of the offscreen image
*/
protected Graphics2D bufferedGraphics = null;
private int lastRenderWidth = 0;
private int lastRenderHeight = 0;
public MultiLayerRenderer(){
this.renderLayers = new ArrayList<RenderLayer>();
}
/**
* Adds the specified {@link RenderLayer} to the end of the render layer ordered list.
* @param l the {@link RenderLayer} to add
*/
public void addRenderLayer(RenderLayer l){
this.renderLayers.add(l);
}
/**
* Inserts a render layer at the specified position
* @param i the position in which the render layer should be inserted
* @param l the render layer to insert
*/
public void insertRenderLayerTo(int i, RenderLayer l){
this.renderLayers.add(i, l);
}
/**
* Removes the render layer at teh specified position.
* @param i the position of the render layer to remove
*/
public void removeRenderLayer(int i){
this.renderLayers.remove(i);
}
/**
* Returns the number of render layers
* @return the number of render layers
*/
public int numRenderLayers(){
return this.renderLayers.size();
}
@Override
public void paint(Graphics g){
this.initializeOffscreen();
this.bufferedGraphics.setColor(bgColor);
this.bufferedGraphics.fill(new Rectangle(this.getWidth(), this.getHeight()));
for(RenderLayer l : this.renderLayers){
l.render(bufferedGraphics, this.getWidth(), this.getHeight());
}
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(offscreen,0,0,this);
}
/**
* Initializes a new offscreen image and context
*/
protected void initializeOffscreen(){
if(this.bufferedGraphics == null || (this.lastRenderWidth != this.getWidth()) && this.lastRenderHeight != this.getHeight()){
this.offscreen = createImage(this.getWidth(), this.getHeight());
this.bufferedGraphics = (Graphics2D)offscreen.getGraphics();
this.lastRenderHeight = this.getHeight();
this.lastRenderWidth = this.getWidth();
}
}
} |
package codeOrchestra.colt.core.ui;
import codeOrchestra.colt.core.ColtException;
import codeOrchestra.colt.core.ColtProjectManager;
import codeOrchestra.colt.core.RecentProjects;
import codeOrchestra.colt.core.errorhandling.ErrorHandler;
import codeOrchestra.colt.core.http.CodeOrchestraRPCHttpServer;
import codeOrchestra.colt.core.http.CodeOrchestraResourcesHttpServer;
import codeOrchestra.colt.core.license.*;
import codeOrchestra.colt.core.loading.LiveCodingHandlerManager;
import codeOrchestra.colt.core.model.monitor.ChangingMonitor;
import codeOrchestra.colt.core.rpc.ColtRemoteServiceServlet;
import codeOrchestra.colt.core.tracker.GAController;
import codeOrchestra.colt.core.ui.dialog.ColtDialogs;
import codeOrchestra.lcs.license.ColtRunningKey;
import com.sun.javafx.css.StyleManager;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import org.controlsfx.control.action.Action;
import org.controlsfx.dialog.Dialog;
import org.scenicview.ScenicView;
import java.io.File;
/**
* @author Alexander Eliseyev
*/
public class ColtApplication extends Application {
private static ColtApplication instance;
private static final int SPLASH_WIDTH = 480;
private static final int SPLASH_HEIGHT = 320;
private Timeline timeline;
private ColtMenuBar menuBar;
public static ColtApplication get() {
return instance;
}
private Stage primaryStage;
private StackPane splashLayout;
private WelcomeScreenStage welcomeScreenStage;
private ProjectStage mainStage;
private Node currentPluginNode;
public static long timeStarted;
@Override
public void start(Stage primaryStage) throws Exception {
instance = this;
this.primaryStage = primaryStage;
StyleManager.getInstance().addUserAgentStylesheet("/codeOrchestra/colt/core/ui/style/main.css");
GAController.getInstance().start(primaryStage);
initSplash();
welcomeScreenStage = new WelcomeScreenStage();
menuBar = new ColtMenuBar();
menuBar.setUseSystemMenuBar(true);
mainStage = new ProjectStage();
mainStage.getRoot().getChildren().add(menuBar);
mainStage.setOnCloseRequest(windowEvent -> {
dispose();
});
showSplash();
timeline = new Timeline(new KeyFrame(new Duration(1000), actionEvent -> {
timeline.stop();
Platform.runLater(this::doAfterUIInit);
}));
timeline.play();
}
private void showSplash() {
Scene splashScene = new Scene(splashLayout);
primaryStage.initStyle(StageStyle.UNDECORATED);
final Rectangle2D bounds = Screen.getPrimary().getBounds();
primaryStage.setScene(splashScene);
primaryStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - SPLASH_WIDTH / 2);
primaryStage.setY(bounds.getMinY() + bounds.getHeight() / 2 - SPLASH_HEIGHT / 2);
primaryStage.show();
}
private void initSplash() {
splashLayout = new StackPane();
String imagePath = getClass().getResource("splash.png").toString();
Image image = new Image(imagePath);
splashLayout.getChildren().add(new ImageView(image));
splashLayout.setEffect(new DropShadow());
}
private void dispose() {
ColtRunningKey.setRunning(false);
ColtProjectManager.getInstance().dispose();
LiveCodingHandlerManager.getInstance().dispose();
CodeOrchestraResourcesHttpServer.getInstance().dispose();
CodeOrchestraRPCHttpServer.getInstance().dispose();
Platform.exit();
}
private void doAfterUIInit() {
// COLT-287
System.setProperty("jsse.enableSNIExtension", "false");
StartupInterceptType startupInterceptType = StartupInterceptor.getInstance().interceptStart();
if (startupInterceptType != StartupInterceptType.START) {
System.exit(1);
}
ColtRunningKey.setRunning(true);
CodeOrchestraResourcesHttpServer.getInstance().init();
CodeOrchestraRPCHttpServer.getInstance().init();
CodeOrchestraRPCHttpServer.getInstance().addServlet(ColtRemoteServiceServlet.getInstance(), "/coltService");
primaryStage.hide();
// Open most recent project
boolean opened = false;
if (RecentProjects.haveRecentProject()) {
for (String recentProjectPath : RecentProjects.getRecentProjectsPaths()) {
File projectFile = new File(recentProjectPath);
if (projectFile.exists()) {
try {
ColtProjectManager.getInstance().load(projectFile.getPath());
opened = true;
break;
} catch (ColtException e) {
// ignore
}
}
}
}
if (!opened) {
showWelcomeScreen();
}
// ScenicView.show(mainStage.getScene());
}
public void closeProject() {
if (mainStage.isShowing()) {
mainStage.hide();
RecentProjects.recentProject(false);
}
}
public void showWelcomeScreen() {
primaryStage = welcomeScreenStage;
primaryStage.show();
}
public Stage getPrimaryStage() {
return primaryStage;
}
public void setPluginPane(Node node) {
if (primaryStage == welcomeScreenStage) {
primaryStage.hide();
}
if (primaryStage != mainStage) {
primaryStage = mainStage;
GAController.getInstance().start(primaryStage);
primaryStage.show();
}
if (currentPluginNode != null) {
mainStage.getRoot().getChildren().remove(currentPluginNode);
}
currentPluginNode = node;
VBox.setVgrow(currentPluginNode, Priority.ALWAYS);
mainStage.getRoot().getChildren().add(node);
}
public static void main(String[] args) {
timeStarted = System.currentTimeMillis();
launch(args);
}
public ColtMenuBar getMenuBar() {
return menuBar;
}
} |
package com.afollestad.silk.cache;
import android.os.Handler;
import android.util.Log;
import com.afollestad.silk.SilkAdapter;
import com.afollestad.silk.fragments.SilkCachedFeedFragment;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Handles caching feeds locally.
*
* @author Aidan Follestad (afollestad)
*/
public final class SilkCacheManager<T extends SilkComparable> {
public interface AddCallback<T> {
public void onAdded(T item);
public void onError(Exception e);
}
public interface UpdateCallback<T> {
public void onUpdated(T item, boolean added);
public void onError(Exception e);
}
public interface WriteCallback<T> {
public void onWrite(List<T> items);
public void onError(Exception e);
}
public interface ReadCallback<T> {
public void onRead(List<T> results);
public void onError(Exception e);
public void onCacheEmpty();
}
public interface RemoveCallback {
public void onRemoved(int index, long itemId);
public void onError(Exception e);
}
/**
* Initializes a new SilkCacheManager.
*
* @param cacheName The name of the cache, must be unique from other feed caches, but must also be valid for being in a file name.
*/
public SilkCacheManager(String cacheName, File cacheDir) {
mHandler = new Handler();
cacheFile = new File(cacheDir, cacheName.toLowerCase() + ".cache");
if (!cacheDir.exists()) cacheDir.mkdirs();
}
public SilkCacheManager(String cacheName, File cacheDir, Handler handler) {
mHandler = handler;
cacheFile = new File(cacheDir, cacheName.toLowerCase() + ".cache");
if (!cacheDir.exists()) cacheDir.mkdirs();
}
private final Handler mHandler;
private final File cacheFile;
private void log(String message) {
Log.d("SilkCacheManager", message);
}
/**
* Writes a single object to the cache, without overwriting previous entries.
*
* @param toAdd the item to add to the cache.
*/
public void add(T toAdd) throws Exception {
List<T> temp = new ArrayList<T>();
temp.add(toAdd);
write(temp, true);
}
/**
* Updates an item in the cache. If it's not found, it's added.
*
* @param toUpdate The item to update, or add.
*/
public boolean update(T toUpdate) throws Exception {
List<T> cache = read();
boolean found = false;
for (int i = 0; i < cache.size(); i++) {
if (cache.get(i).isSameAs(toUpdate)) {
cache.set(i, toUpdate);
found = true;
break;
}
}
if (found) write(cache);
else add(toUpdate);
return found;
}
private void write(List<T> items, boolean append) throws Exception {
if (items == null || items.size() == 0) {
if (cacheFile.exists()) {
log("Adapter for " + cacheFile.getName() + " is empty, deleting file...");
cacheFile.delete();
}
return;
}
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile, append);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
for (T item : items) objectOutputStream.writeObject(item);
objectOutputStream.close();
log("Wrote " + items.size() + " items to " + cacheFile.getName());
}
/**
* Writes an list of items to the cache from the calling thread, overwriting all current entries in the cache.
*/
public void write(List<T> items) throws Exception {
write(items, false);
}
/**
* Reads from the cache file on the calling thread and returns the results.
*/
public List<T> read() throws Exception {
final List<T> results = new ArrayList<T>();
if (cacheFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(cacheFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
while (true) {
try {
final T item = (T) objectInputStream.readObject();
if (item != null) results.add(item);
} catch (EOFException eof) {
break;
}
}
objectInputStream.close();
}
log("Read " + results.size() + " items from " + cacheFile.getName());
return results;
}
/**
* Removes an item from the cache.
*/
public int remove(long itemId) throws Exception {
List<T> cache = read();
if (cache.size() == 0) return -1;
int index = -1;
for (int i = 0; i < cache.size(); i++) {
if (cache.get(i).isSameAs(itemId)) {
cache.remove(i);
index = i;
break;
}
}
write(cache, false);
log("Removed item at index " + index + " from " + cacheFile.getName());
return index;
}
private void runPriorityThread(Runnable runnable) {
Thread t = new Thread(runnable);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
/**
* Writes a single object to the cache from a separate thread, posting results to a callback.
*/
public void addAsync(final T toAdd, final AddCallback callback) throws Exception {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
add(toAdd);
callback.onAdded(toAdd);
} catch (Exception e) {
log("Cache write error: " + e.getMessage());
callback.onError(e);
}
}
});
}
/**
* Updates an item in the cache. If it's not found, it's added. This is done on a separate thread and results are
* posted to a callback.
*/
public void updateAsync(final T toUpdate, final UpdateCallback callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
boolean isAdded = update(toUpdate);
callback.onUpdated(toUpdate, isAdded);
} catch (Exception e) {
log("Cache write error: " + e.getMessage());
callback.onError(e);
}
}
});
}
/**
* Writes a list of items to the cache from a separate thread, overwriting all current entries in the cache.
*/
public void writeAsync(final List<T> items, final WriteCallback callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
write(items, false);
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onWrite(items);
}
});
} catch (final Exception e) {
log("Cache write error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
});
}
/**
* Reads from the cache file on a separate thread and posts results to a callback.
*/
public void readAsync(final ReadCallback callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
if (!cacheFile.exists()) {
log("No cache for " + cacheFile.getName());
callback.onCacheEmpty();
return;
}
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
final List<T> results = read();
mHandler.post(new Runnable() {
@Override
public void run() {
if (results.size() == 0) callback.onCacheEmpty();
else callback.onRead(results);
}
});
} catch (final Exception e) {
log("Cache read error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
});
}
/**
* Reads from the manager's cache file into a {@link SilkAdapter}, and notifies a {@link SilkCachedFeedFragment} when it's loading and done loading.
*
* @param adapter The adapter that items will be added to.
* @param fragment The fragment that will receive loading notifications.
* @param clearIfEmpty Whether or not the adapter will be cleared if the cache is empty.
*/
public void readAsync(final SilkAdapter<T> adapter, final SilkCachedFeedFragment fragment, final boolean clearIfEmpty) {
if (adapter == null || fragment == null)
throw new IllegalArgumentException("The adapter and fragment parameters cannot be null.");
else if (fragment.isLoading()) return;
readAsync(new ReadCallback<T>() {
@Override
public void onRead(List<T> results) {
adapter.clear();
for (T item : results) adapter.add(item);
fragment.setLoadFromCacheComplete(false);
}
@Override
public void onError(Exception e) {
if (adapter.getCount() == 0)
fragment.onCacheEmpty();
fragment.setLoadFromCacheComplete(true);
}
@Override
public void onCacheEmpty() {
if (clearIfEmpty) adapter.clear();
fragment.onCacheEmpty();
fragment.setLoadFromCacheComplete(false);
}
});
}
/**
* Removes an item from the cache, results are posted to a callback.
*/
public void removeAsync(final long itemId, final RemoveCallback callback) {
if (callback == null) throw new IllegalArgumentException("You must specify a callback");
runPriorityThread(new Runnable() {
@Override
public void run() {
try {
final int removeIndex = remove(itemId);
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onRemoved(removeIndex, itemId);
}
});
} catch (final Exception e) {
log("Cache write error: " + e.getMessage());
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
}
}
});
}
} |
package com.backendless.persistence;
import com.backendless.util.JSONUtil;
import weborb.exceptions.AdaptingException;
import weborb.reader.ReferenceCache;
import weborb.types.ICacheableAdaptingType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class JsonDTOAdapter implements ICacheableAdaptingType
{
private String rawJsonString;
public JsonDTOAdapter()
{
}
public JsonDTOAdapter( String rawJsonString )
{
this.rawJsonString = rawJsonString;
}
public String getRawJsonString()
{
return rawJsonString;
}
public void setRawJsonString( String value )
{
this.rawJsonString = value;
}
@Override
public boolean equals( Object o )
{
if( this == o )
return true;
if( !(o instanceof JsonDTO) )
return false;
JsonDTOAdapter jsonDTO = (JsonDTOAdapter) o;
return Objects.equals( rawJsonString, jsonDTO.rawJsonString );
}
@Override
public int hashCode()
{
return Objects.hash( rawJsonString );
}
@Override
public Class getDefaultType()
{
return Map.class;
}
@Override
public Object defaultAdapt()
{
return defaultAdapt( null );
}
@Override
public Object adapt( Type type ) throws AdaptingException
{
return adapt( type, null );
}
@Override
public boolean canAdaptTo( Type type )
{
return true;
}
@Override
public Object defaultAdapt( ReferenceCache referenceCache )
{
try
{
return adapt( HashMap.class, referenceCache );
}
catch( AdaptingException exception )
{
throw new RuntimeException( "unable to adapt JSON value to HashMap" );
}
}
@Override
public Object adapt( Type type, ReferenceCache referenceCache ) throws AdaptingException
{
if( getRawJsonString() == null )
return null;
Object result = JSONUtil.getJsonConverter().readObject( getRawJsonString(), (Class) type );
return result;
}
} |
package com.coderevisited.searching;
public class DuplicateCount
{
public static void main(String[] args)
{
int[] array = new int[]{0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4};
int min = leastIndexBinarySearch(array, 0, array.length - 1, 1);
int max = maxIndexBinarySearch(array, 0, array.length - 1, 1);
System.out.println("min:" + min);
System.out.println("max:" + max);
if (min != -1 && max != -1)
System.out.println(max - min + 1);
else {
System.out.println("Key not found");
}
}
private static int leastIndexBinarySearch(int[] array, int low, int high, int key)
{
while (low <= high) {
int mid = low + (high - low) / 2;
if ((array[mid] == key) && (mid == 0 || array[mid - 1] < key)) {
return mid;
}
if (array[mid] < key) {
low = mid + 1;
} else
high = mid - 1;
}
return -1;
}
private static int maxIndexBinarySearch(int[] array, int low, int high, int key)
{
while (low <= high) {
int mid = low + (high - low) / 2;
if ((array[mid] == key) && (mid == array.length - 1 || array[mid + 1] > key)) {
return mid;
} else if (array[mid] > key) {
high = mid - 1;
} else
low = mid + 1;
}
return -1;
}
} |
package com.edinarobotics.zed.subsystems;
import com.edinarobotics.utils.subsystems.Subsystem1816;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Relay;
public class Collector extends Subsystem1816 {
public final int collectorUpperLimitSwitch;
public final int collectorLowerLimitSwitch;
private Relay leftStar;
private Relay rightStar;
private Relay collectorLifter;
private CollectorDirection collectorDirection;
private CollectorLiftDirection collectorLiftDirection;
private DigitalInput upperLimitSwitch;
private DigitalInput lowerLimitSwitch;
public Collector(int leftStar, int rightStar, int collectorLifter,
int collectorUpperLimitSwitch, int collectorLowerLimitSwitch) {
super("Collector");
this.leftStar = new Relay(leftStar);
this.rightStar = new Relay(rightStar);
this.collectorLifter = new Relay(collectorLifter);
collectorDirection = CollectorDirection.COLLECTOR_STOP;
collectorLiftDirection = CollectorLiftDirection.COLLECTOR_LIFT_STOP;
this.collectorUpperLimitSwitch = collectorUpperLimitSwitch;
this.collectorLowerLimitSwitch = collectorLowerLimitSwitch;
}
/**
* Sets the direction of the collector mechanisms.
* A positive value will set the collector to a forward direction. Forward
* is defined as the direction that will bring discs into the robot.<br/>
* A negative value will set the collector to a backwards direction.<br/>
* A zero value will stop the collector.
* @param direction Sets the collector to the direction as given above.
*/
public void setCollectorDirection(CollectorDirection direction){
this.collectorDirection = direction;
update();
}
public void setCollectorLiftDirection(CollectorLiftDirection direction) {
this.collectorLiftDirection = direction;
update();
}
public CollectorDirection getCollectorDirection() {
return collectorDirection;
}
public CollectorLiftDirection getCollectorLiftDirection() {
return collectorLiftDirection;
}
public void update(){
leftStar.set(collectorDirection.getLeftStarRelayValue());
rightStar.set(collectorDirection.getRightStarRelayValue());
CollectorLiftDirection processLiftDirection = collectorLiftDirection;
if(processLiftDirection.equals(CollectorLiftDirection.COLLECTOR_LIFT_UP) &&
getUpperLimitSwitch()) {
processLiftDirection = CollectorLiftDirection.COLLECTOR_LIFT_STOP;
}
if(processLiftDirection.equals(CollectorLiftDirection.COLLECTOR_LIFT_DOWN) &&
getLowerLimitSwitch()) {
processLiftDirection = CollectorLiftDirection.COLLECTOR_LIFT_STOP;
}
collectorLifter.set(processLiftDirection.getRelayValue());
}
public boolean getUpperLimitSwitch() {
return upperLimitSwitch.get();
}
public boolean getLowerLimitSwitch() {
return lowerLimitSwitch.get();
}
public static class CollectorDirection {
public static final CollectorDirection COLLECTOR_IN = new CollectorDirection((byte)1);
public static final CollectorDirection COLLECTOR_OUT = new CollectorDirection((byte)-1);
public static final CollectorDirection COLLECTOR_STOP = new CollectorDirection((byte)0);
private byte value;
private CollectorDirection(byte value){
this.value = value;
}
protected byte getValue(){
return value;
}
public boolean equals(Object other){
if(other instanceof CollectorDirection){
return ((CollectorDirection)other).getValue() == this.getValue();
}
return false;
}
public int hashCode(){
return new Byte(getValue()).hashCode();
}
public Relay.Value getLeftStarRelayValue(){
if(equals(COLLECTOR_IN)){
return Relay.Value.kForward;
}
else if(equals(COLLECTOR_OUT)){
return Relay.Value.kReverse;
}
return Relay.Value.kOff;
}
public Relay.Value getRightStarRelayValue(){
if(equals(COLLECTOR_IN)){
return Relay.Value.kForward;
}
else if(equals(COLLECTOR_OUT)){
return Relay.Value.kReverse;
}
return Relay.Value.kOff;
}
}
public static class CollectorLiftDirection {
public static final CollectorLiftDirection COLLECTOR_LIFT_UP = new CollectorLiftDirection((byte)1);
public static final CollectorLiftDirection COLLECTOR_LIFT_DOWN = new CollectorLiftDirection((byte)-1);
public static final CollectorLiftDirection COLLECTOR_LIFT_STOP = new CollectorLiftDirection((byte)0);
private byte value;
private CollectorLiftDirection(byte value){
this.value = value;
}
protected byte getValue(){
return value;
}
public boolean equals(Object other){
if(other instanceof CollectorLiftDirection){
return ((CollectorLiftDirection)other).getValue() == this.getValue();
}
return false;
}
public int hashCode(){
return new Byte(getValue()).hashCode();
}
public Relay.Value getRelayValue(){
if(equals(COLLECTOR_LIFT_UP)){
return Relay.Value.kForward;
}
else if(equals(COLLECTOR_LIFT_DOWN)){
return Relay.Value.kReverse;
}
return Relay.Value.kOff;
}
}
} |
package com.github.andlyticsproject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import android.annotation.SuppressLint;
import android.app.Application;
import android.app.backup.BackupManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.github.andlyticsproject.Preferences.Timeframe;
import com.github.andlyticsproject.db.AdmobTable;
import com.github.andlyticsproject.db.AppInfoTable;
import com.github.andlyticsproject.db.AppStatsTable;
import com.github.andlyticsproject.db.CommentsTable;
import com.github.andlyticsproject.db.RevenueSummaryTable;
import com.github.andlyticsproject.model.AdmobStats;
import com.github.andlyticsproject.model.AdmobStatsSummary;
import com.github.andlyticsproject.model.AppInfo;
import com.github.andlyticsproject.model.AppStats;
import com.github.andlyticsproject.model.AppStatsSummary;
import com.github.andlyticsproject.model.Comment;
import com.github.andlyticsproject.model.Revenue;
import com.github.andlyticsproject.model.RevenueSummary;
import com.github.andlyticsproject.util.Utils;
public class ContentAdapter {
private final Context context;
private static ContentAdapter instance;
private BackupManager backupManager;
private ContentAdapter(Context ctx) {
this.context = ctx;
this.backupManager = new BackupManager(ctx);
}
public static synchronized ContentAdapter getInstance(Application appCtx) {
if (instance == null) {
instance = new ContentAdapter(appCtx);
}
return instance;
}
public AdmobStatsSummary getAdmobStats(String siteId, Timeframe currentTimeFrame) {
AdmobStatsSummary admobList = new AdmobStatsSummary();
int limit = Integer.MAX_VALUE;
if (currentTimeFrame.equals(Timeframe.LAST_NINETY_DAYS)) {
limit = 90;
} else if (currentTimeFrame.equals(Timeframe.LAST_THIRTY_DAYS)) {
limit = 30;
} else if (currentTimeFrame.equals(Timeframe.LAST_SEVEN_DAYS)) {
limit = 7;
} else if (currentTimeFrame.equals(Timeframe.LAST_TWO_DAYS)) {
limit = 2;
} else if (currentTimeFrame.equals(Timeframe.LATEST_VALUE)) {
limit = 1;
} else if (currentTimeFrame.equals(Timeframe.MONTH_TO_DATE)) {
limit = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(
AdmobTable.CONTENT_URI,
new String[] {
AdmobTable.KEY_ROWID, AdmobTable.KEY_SITE_ID, AdmobTable.KEY_REQUESTS,
AdmobTable.KEY_HOUSEAD_REQUESTS, AdmobTable.KEY_INTERSTITIAL_REQUESTS,
AdmobTable.KEY_IMPRESSIONS, AdmobTable.KEY_FILL_RATE,
AdmobTable.KEY_HOUSEAD_FILL_RATE, AdmobTable.KEY_OVERALL_FILL_RATE,
AdmobTable.KEY_CLICKS, AdmobTable.KEY_HOUSEAD_CLICKS,
AdmobTable.KEY_CTR, AdmobTable.KEY_ECPM, AdmobTable.KEY_REVENUE,
AdmobTable.KEY_CPC_REVENUE, AdmobTable.KEY_CPM_REVENUE,
AdmobTable.KEY_EXCHANGE_DOWNLOADS, AdmobTable.KEY_DATE
}, AdmobTable.KEY_SITE_ID + "='" + siteId + "'", null,
AdmobTable.KEY_DATE + " desc LIMIT " + limit + ""); // sort
// order ->
// new to
// old
if (cursor.moveToFirst()) {
do {
AdmobStats admob = new AdmobStats();
admob.setSiteId(cursor.getString(cursor.getColumnIndex(AdmobTable.KEY_ROWID)));
admob.setClicks(cursor.getInt(cursor.getColumnIndex(AdmobTable.KEY_CLICKS)));
admob.setCpcRevenue(cursor.getFloat(cursor
.getColumnIndex(AdmobTable.KEY_CPC_REVENUE)));
admob.setCpmRevenue(cursor.getFloat(cursor
.getColumnIndex(AdmobTable.KEY_CPM_REVENUE)));
admob.setCtr(cursor.getFloat(cursor.getColumnIndex(AdmobTable.KEY_CTR)));
admob.setEcpm(cursor.getFloat(cursor.getColumnIndex(AdmobTable.KEY_ECPM)));
admob.setExchangeDownloads(cursor.getInt(cursor
.getColumnIndex(AdmobTable.KEY_EXCHANGE_DOWNLOADS)));
admob.setFillRate(cursor.getFloat(cursor
.getColumnIndex(AdmobTable.KEY_FILL_RATE)));
admob.setHouseAdClicks(cursor.getInt(cursor
.getColumnIndex(AdmobTable.KEY_HOUSEAD_CLICKS)));
admob.setHouseadFillRate(cursor.getFloat(cursor
.getColumnIndex(AdmobTable.KEY_HOUSEAD_FILL_RATE)));
admob.setHouseadRequests(cursor.getInt(cursor
.getColumnIndex(AdmobTable.KEY_HOUSEAD_REQUESTS)));
admob.setImpressions(cursor.getInt(cursor
.getColumnIndex(AdmobTable.KEY_IMPRESSIONS)));
admob.setInterstitialRequests(cursor.getInt(cursor
.getColumnIndex(AdmobTable.KEY_INTERSTITIAL_REQUESTS)));
admob.setOverallFillRate(cursor.getFloat(cursor
.getColumnIndex(AdmobTable.KEY_OVERALL_FILL_RATE)));
admob.setRequests(cursor.getInt(cursor.getColumnIndex(AdmobTable.KEY_REQUESTS)));
admob.setRevenue(cursor.getFloat(cursor.getColumnIndex(AdmobTable.KEY_REVENUE)));
String dateString = cursor
.getString(cursor.getColumnIndex(AdmobTable.KEY_DATE));
admob.setDate(Utils.parseDbDate(dateString.substring(0, 10) + " 12:00:00"));
admobList.addStat(admob);
} while (cursor.moveToNext());
}
cursor.close();
admobList.calculateOverallStats(0, false);
return admobList;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void insertOrUpdateAdmobStats(AdmobStats admob) {
ContentValues value = createAdmobContentValues(admob);
long existingId = getAdmobStatsIdForDate(admob.getDate(), admob.getSiteId());
if (existingId > -1) {
// update
context.getContentResolver().update(AdmobTable.CONTENT_URI, value,
AdmobTable.KEY_ROWID + "=" + existingId, null);
} else {
// insert
context.getContentResolver().insert(AdmobTable.CONTENT_URI, value);
}
backupManager.dataChanged();
}
@SuppressLint("SimpleDateFormat")
private long getAdmobStatsIdForDate(Date date, String siteId) {
long result = -1;
// make sure there is only one entry / day
SimpleDateFormat dateFormatStart = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat dateFormatEnd = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
Cursor mCursor = context.getContentResolver().query(
AdmobTable.CONTENT_URI,
new String[] { AdmobTable.KEY_ROWID, AdmobTable.KEY_DATE },
AdmobTable.KEY_SITE_ID + "='" + siteId + "' and " + AdmobTable.KEY_DATE
+ " BETWEEN '" + dateFormatStart.format(date) + "' and '"
+ dateFormatEnd.format(date) + "'", null, null);
if (mCursor != null && mCursor.moveToFirst()) {
result = mCursor.getInt(mCursor.getColumnIndex(AdmobTable.KEY_ROWID));
}
mCursor.close();
return result;
}
public void bulkInsertAdmobStats(List<AdmobStats> stats) {
List<ContentValues> values = new ArrayList<ContentValues>();
for (AdmobStats admob : stats) {
ContentValues value = createAdmobContentValues(admob);
values.add(value);
}
context.getContentResolver().bulkInsert(AdmobTable.CONTENT_URI,
values.toArray(new ContentValues[values.size()]));
backupManager.dataChanged();
}
private ContentValues createAdmobContentValues(AdmobStats admob) {
ContentValues values = new ContentValues();
values.put(AdmobTable.KEY_CLICKS, admob.getClicks());
values.put(AdmobTable.KEY_CPC_REVENUE, admob.getCpcRevenue());
values.put(AdmobTable.KEY_CPM_REVENUE, admob.getCpmRevenue());
values.put(AdmobTable.KEY_CTR, admob.getCtr());
values.put(AdmobTable.KEY_DATE, Utils.formatDbDate(admob.getDate()));
values.put(AdmobTable.KEY_ECPM, admob.getEcpm());
values.put(AdmobTable.KEY_EXCHANGE_DOWNLOADS, admob.getExchangeDownloads());
values.put(AdmobTable.KEY_FILL_RATE, admob.getFillRate());
values.put(AdmobTable.KEY_HOUSEAD_CLICKS, admob.getHouseAdClicks());
values.put(AdmobTable.KEY_HOUSEAD_FILL_RATE, admob.getHouseadFillRate());
values.put(AdmobTable.KEY_HOUSEAD_REQUESTS, admob.getHouseadRequests());
values.put(AdmobTable.KEY_IMPRESSIONS, admob.getImpressions());
values.put(AdmobTable.KEY_INTERSTITIAL_REQUESTS, admob.getInterstitialRequests());
values.put(AdmobTable.KEY_OVERALL_FILL_RATE, admob.getOverallFillRate());
values.put(AdmobTable.KEY_REQUESTS, admob.getRequests());
values.put(AdmobTable.KEY_REVENUE, admob.getRevenue());
values.put(AdmobTable.KEY_SITE_ID, admob.getSiteId());
return values;
}
public AppStatsDiff insertOrUpdateStats(AppInfo appInfo) {
// do not insert draft apps
if (appInfo == null || appInfo.isDraftOnly()) {
return null;
}
// diff report
AppStats previousStats = getLatestForApp(appInfo.getPackageName());
insertOrUpdateApp(appInfo);
// quickfix
appInfo.setSkipNotification(getSkipNotification(appInfo.getPackageName()));
AppStats downloadInfo = appInfo.getLatestStats();
insertOrUpdateAppStats(downloadInfo, appInfo.getPackageName());
return downloadInfo.createDiff(previousStats, appInfo);
}
public void insertOrUpdateAppStats(AppStats appStats, String packageName) {
ContentValues values = new ContentValues();
values.put(AppStatsTable.KEY_STATS_REQUESTDATE, Utils.formatDbDate(appStats.getDate()));
values.put(AppStatsTable.KEY_STATS_PACKAGENAME, packageName);
values.put(AppStatsTable.KEY_STATS_DOWNLOADS, appStats.getTotalDownloads());
values.put(AppStatsTable.KEY_STATS_INSTALLS, appStats.getActiveInstalls());
values.put(AppStatsTable.KEY_STATS_COMMENTS, appStats.getNumberOfComments());
values.put(AppStatsTable.KEY_STATS_MARKETERANKING, -1);
values.put(AppStatsTable.KEY_STATS_CATEGORYRANKING, -1);
if (appStats.getRating5() != null) {
values.put(AppStatsTable.KEY_STATS_5STARS, appStats.getRating5());
}
if (appStats.getRating4() != null) {
values.put(AppStatsTable.KEY_STATS_4STARS, appStats.getRating4());
}
if (appStats.getRating3() != null) {
values.put(AppStatsTable.KEY_STATS_3STARS, appStats.getRating3());
}
if (appStats.getRating2() != null) {
values.put(AppStatsTable.KEY_STATS_2STARS, appStats.getRating2());
}
if (appStats.getRating1() != null) {
values.put(AppStatsTable.KEY_STATS_1STARS, appStats.getRating1());
}
if (appStats.getVersionCode() != null) {
values.put(AppStatsTable.KEY_STATS_VERSIONCODE, appStats.getVersionCode());
}
if (appStats.getNumberOfErrors() != null) {
values.put(AppStatsTable.KEY_STATS_NUM_ERRORS, appStats.getNumberOfErrors());
}
if (appStats.getTotalRevenue() != null) {
values.put(AppStatsTable.KEY_STATS_TOTAL_REVENUE, appStats.getTotalRevenue()
.getAmount());
values.put(AppStatsTable.KEY_STATS_CURRENCY, appStats.getTotalRevenue()
.getCurrencyCode());
}
context.getContentResolver().insert(AppStatsTable.CONTENT_URI, values);
backupManager.dataChanged();
}
private void insertOrUpdateApp(AppInfo appInfo) {
// do not insert draft apps
if (appInfo == null || appInfo.isDraftOnly()) {
return;
}
ContentValues initialValues = new ContentValues();
initialValues.put(AppInfoTable.KEY_APP_LASTUPDATE,
Utils.formatDbDate(appInfo.getLastUpdate()));
initialValues.put(AppInfoTable.KEY_APP_PACKAGENAME, appInfo.getPackageName());
initialValues.put(AppInfoTable.KEY_APP_ACCOUNT, appInfo.getAccount());
initialValues.put(AppInfoTable.KEY_APP_DEVELOPER_ID, appInfo.getDeveloperId());
initialValues.put(AppInfoTable.KEY_APP_DEVELOPER_NAME, appInfo.getDeveloperName());
initialValues.put(AppInfoTable.KEY_APP_NAME, appInfo.getName());
initialValues.put(AppInfoTable.KEY_APP_ICONURL, appInfo.getIconUrl());
initialValues.put(AppInfoTable.KEY_APP_PUBLISHSTATE, appInfo.getPublishState());
initialValues.put(AppInfoTable.KEY_APP_CATEGORY, -1);
initialValues.put(AppInfoTable.KEY_APP_VERSION_NAME, appInfo.getVersionName());
Uri uri = context.getContentResolver().insert(AppInfoTable.CONTENT_URI, initialValues);
long id = Long.parseLong(uri.getPathSegments().get(1));
appInfo.setId(id);
// XXX here?
RevenueSummary revenue = appInfo.getTotalRevenueSummary();
if (revenue != null) {
ContentValues values = new ContentValues();
values.put(RevenueSummaryTable.TYPE, revenue.getType().ordinal());
values.put(RevenueSummaryTable.CURRENCY, revenue.getCurrency());
values.put(RevenueSummaryTable.LAST_DAY_TOTAL, revenue.getLastDay().getAmount());
values.put(RevenueSummaryTable.LAST_7DAYS_TOTAL, revenue.getLast7Days().getAmount());
values.put(RevenueSummaryTable.LAST_30DAYS_TOTAL, revenue.getLast30Days().getAmount());
values.put(RevenueSummaryTable.OVERALL_TOTAL, revenue.getOverall().getAmount());
values.put(RevenueSummaryTable.APPINFO_ID, appInfo.getId());
if (revenue.getId() == null) {
uri = context.getContentResolver().insert(RevenueSummaryTable.CONTENT_URI, values);
id = Long.parseLong(uri.getPathSegments().get(1));
revenue.setId(id);
} else {
context.getContentResolver().update(RevenueSummaryTable.CONTENT_URI, values,
RevenueSummaryTable.APPINFO_ID + " = ?",
new String[] { Long.toString(revenue.getId()) });
}
}
backupManager.dataChanged();
}
public String getAppName(String packageName) {
if (packageName == null) {
return null;
}
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(AppInfoTable.CONTENT_URI,
new String[] { AppInfoTable.KEY_APP_NAME },
AppInfoTable.KEY_APP_PACKAGENAME + "='" + packageName + "'", null, null);
if (cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndex(AppInfoTable.KEY_APP_NAME));
}
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
// XXX add dev ID filter
public List<String> getPackagesForAccount(String account) {
List<String> result = new ArrayList<String>();
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(AppInfoTable.UNIQUE_PACAKGES_CONTENT_URI,
new String[] { AppInfoTable.KEY_APP_PACKAGENAME },
AppInfoTable.KEY_APP_ACCOUNT + "=?", new String[] { account },
AppInfoTable.KEY_APP_PACKAGENAME);
while (cursor.moveToNext()) {
result.add(cursor.getString(0));
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
// XXX filter by dev ID
public List<AppInfo> getAllAppsLatestStats(String account) {
List<AppInfo> appInfos = new ArrayList<AppInfo>();
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(AppInfoTable.CONTENT_URI,
new String[] { AppInfoTable.KEY_ROWID,
AppInfoTable.KEY_APP_VERSION_NAME,
AppInfoTable.KEY_APP_PACKAGENAME,
AppInfoTable.KEY_APP_LASTUPDATE, AppInfoTable.KEY_APP_NAME,
AppInfoTable.KEY_APP_GHOST,
AppInfoTable.KEY_APP_SKIP_NOTIFICATION,
AppInfoTable.KEY_APP_RATINGS_EXPANDED,
AppInfoTable.KEY_APP_ICONURL,
AppInfoTable.KEY_APP_ADMOB_ACCOUNT,
AppInfoTable.KEY_APP_ADMOB_SITE_ID,
AppInfoTable.KEY_APP_LAST_COMMENTS_UPDATE,
AppInfoTable.KEY_APP_DEVELOPER_ID,
AppInfoTable.KEY_APP_DEVELOPER_NAME },
AppInfoTable.KEY_APP_ACCOUNT + "='" + account + "'", null,
AppInfoTable.KEY_APP_NAME + "");
while (cursor.moveToNext()) {
AppInfo appInfo = new AppInfo();
appInfo.setId(cursor.getLong(cursor.getColumnIndex(AppInfoTable.KEY_ROWID)));
appInfo.setAccount(account);
appInfo.setLastUpdate(Utils.parseDbDate(cursor.getString(cursor
.getColumnIndex(AppInfoTable.KEY_APP_LASTUPDATE))));
appInfo.setPackageName(cursor.getString(cursor
.getColumnIndex(AppInfoTable.KEY_APP_PACKAGENAME)));
appInfo.setName(cursor.getString(cursor.getColumnIndex(AppInfoTable.KEY_APP_NAME)));
appInfo.setGhost(cursor.getInt(cursor.getColumnIndex(AppInfoTable.KEY_APP_GHOST)) == 0 ? false
: true);
appInfo.setSkipNotification(cursor.getInt(cursor
.getColumnIndex(AppInfoTable.KEY_APP_SKIP_NOTIFICATION)) == 0 ? false
: true);
appInfo.setRatingDetailsExpanded(cursor.getInt(cursor
.getColumnIndex(AppInfoTable.KEY_APP_RATINGS_EXPANDED)) == 0 ? false : true);
appInfo.setIconUrl(cursor.getString(cursor
.getColumnIndex(AppInfoTable.KEY_APP_ICONURL)));
appInfo.setVersionName(cursor.getString(cursor
.getColumnIndex(AppInfoTable.KEY_APP_VERSION_NAME)));
int idx = cursor.getColumnIndex(AppInfoTable.KEY_APP_ADMOB_ACCOUNT);
if (!cursor.isNull(idx)) {
appInfo.setAdmobAccount(cursor.getString(idx));
}
idx = cursor.getColumnIndex(AppInfoTable.KEY_APP_ADMOB_SITE_ID);
if (!cursor.isNull(idx)) {
appInfo.setAdmobSiteId(cursor.getString(idx));
}
idx = cursor.getColumnIndex(AppInfoTable.KEY_APP_LAST_COMMENTS_UPDATE);
if (!cursor.isNull(idx)) {
appInfo.setLastCommentsUpdate(new Date(cursor.getLong(idx)));
}
idx = cursor.getColumnIndex(AppInfoTable.KEY_APP_DEVELOPER_ID);
if (!cursor.isNull(idx)) {
appInfo.setDeveloperId(cursor.getString(idx));
}
idx = cursor.getColumnIndex(AppInfoTable.KEY_APP_DEVELOPER_NAME);
if (!cursor.isNull(idx)) {
appInfo.setDeveloperName(cursor.getString(idx));
}
appInfos.add(appInfo);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
for (AppInfo appInfo : appInfos) {
String packageName = appInfo.getPackageName();
AppStatsSummary statsForApp = getStatsForApp(packageName, Timeframe.LAST_TWO_DAYS,
false);
AppStats stats = new AppStats();
if (statsForApp.getStats().size() > 1) {
stats = statsForApp.getStats().get(1);
} else {
if (statsForApp.getStats().size() > 0) {
stats = statsForApp.getStats().get(0);
}
}
stats.init();
appInfo.setLatestStats(stats);
RevenueSummary revenueSummary = getRevenueSummaryForApp(appInfo);
appInfo.setTotalRevenueSummary(revenueSummary);
}
return appInfos;
}
public long setGhost(String account, String packageName, boolean value) {
ContentValues initialValues = new ContentValues();
initialValues.put(AppInfoTable.KEY_APP_GHOST, value == true ? 1 : 0);
long result = -1;
long exisitingId = getAppInfoByPackageName(packageName);
if (exisitingId > -1) {
context.getContentResolver().update(AppInfoTable.CONTENT_URI, initialValues,
AppInfoTable.KEY_ROWID + "=" + exisitingId, null);
result = exisitingId;
backupManager.dataChanged();
}
return result;
}
public long setRatingExpanded(String account, String packageName, boolean value) {
ContentValues initialValues = new ContentValues();
initialValues.put(AppInfoTable.KEY_APP_RATINGS_EXPANDED, value == true ? 1 : 0);
long result = -1;
long exisitingId = getAppInfoByPackageName(packageName);
if (exisitingId > -1) {
context.getContentResolver().update(AppInfoTable.CONTENT_URI, initialValues,
AppInfoTable.KEY_ROWID + "=" + exisitingId, null);
result = exisitingId;
backupManager.dataChanged();
}
return result;
}
private long getAppInfoByPackageName(String packageName) {
long result = -1;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(
AppInfoTable.CONTENT_URI,
new String[] { AppInfoTable.KEY_ROWID, AppInfoTable.KEY_APP_ACCOUNT,
AppInfoTable.KEY_APP_PACKAGENAME },
AppInfoTable.KEY_APP_PACKAGENAME + "='" + packageName + "'", null, null);
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getInt(cursor.getColumnIndex(AppInfoTable.KEY_ROWID));
}
return result;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private boolean getSkipNotification(String packageName) {
boolean result = false;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(
AppInfoTable.CONTENT_URI,
new String[] { AppInfoTable.KEY_APP_SKIP_NOTIFICATION,
AppInfoTable.KEY_APP_ACCOUNT, AppInfoTable.KEY_APP_PACKAGENAME },
AppInfoTable.KEY_APP_PACKAGENAME + "='" + packageName + "'", null, null);
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getInt(cursor
.getColumnIndex(AppInfoTable.KEY_APP_SKIP_NOTIFICATION)) == 0 ? false
: true;
}
return result;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@SuppressLint("SimpleDateFormat")
public AppStatsSummary getStatsForApp(String packageName, Timeframe currentTimeFrame,
Boolean smoothEnabled) {
AppStatsSummary result = new AppStatsSummary();
int limit = Integer.MAX_VALUE;
if (currentTimeFrame.equals(Timeframe.LAST_NINETY_DAYS)) {
limit = 90;
} else if (currentTimeFrame.equals(Timeframe.LAST_THIRTY_DAYS)) {
limit = 30;
} else if (currentTimeFrame.equals(Timeframe.LAST_SEVEN_DAYS)) {
limit = 7;
} else if (currentTimeFrame.equals(Timeframe.LAST_TWO_DAYS)) {
limit = 2;
} else if (currentTimeFrame.equals(Timeframe.LATEST_VALUE)) {
limit = 1;
} else if (currentTimeFrame.equals(Timeframe.MONTH_TO_DATE)) {
limit = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(AppStatsTable.CONTENT_URI,
new String[] { AppStatsTable.KEY_ROWID,
AppStatsTable.KEY_STATS_PACKAGENAME,
AppStatsTable.KEY_STATS_DOWNLOADS,
AppStatsTable.KEY_STATS_INSTALLS,
AppStatsTable.KEY_STATS_COMMENTS,
AppStatsTable.KEY_STATS_MARKETERANKING,
AppStatsTable.KEY_STATS_CATEGORYRANKING,
AppStatsTable.KEY_STATS_5STARS, AppStatsTable.KEY_STATS_4STARS,
AppStatsTable.KEY_STATS_3STARS, AppStatsTable.KEY_STATS_2STARS,
AppStatsTable.KEY_STATS_1STARS,
AppStatsTable.KEY_STATS_REQUESTDATE,
AppStatsTable.KEY_STATS_VERSIONCODE,
AppStatsTable.KEY_STATS_NUM_ERRORS,
AppStatsTable.KEY_STATS_TOTAL_REVENUE,
AppStatsTable.KEY_STATS_CURRENCY },
AppStatsTable.KEY_STATS_PACKAGENAME + "='" + packageName + "'", null,
AppStatsTable.KEY_STATS_REQUESTDATE + " desc LIMIT " + limit + ""); // sort
// order
// new
// old
if (cursor.moveToFirst()) {
do {
AppStats stats = new AppStats();
stats.setActiveInstalls(cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_INSTALLS)));
stats.setTotalDownloads(cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_DOWNLOADS)));
String dateString = cursor.getString(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_REQUESTDATE));
stats.setDate(Utils.parseDbDate(dateString.substring(0, 10) + " 12:00:00"));
stats.setNumberOfComments(cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_COMMENTS)));
stats.setVersionCode(cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_VERSIONCODE)));
stats.setRating(
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_1STARS)),
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_2STARS)),
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_3STARS)),
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_4STARS)),
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_5STARS)));
int idx = cursor.getColumnIndex(AppStatsTable.KEY_STATS_NUM_ERRORS);
if (!cursor.isNull(idx)) {
stats.setNumberOfErrors(cursor.getInt(idx));
}
idx = cursor.getColumnIndex(AppStatsTable.KEY_STATS_TOTAL_REVENUE);
if (!cursor.isNull(idx)) {
double amount = cursor.getDouble(idx);
String currency = cursor.getString(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_CURRENCY));
stats.setTotalRevenue(new Revenue(Revenue.Type.TOTAL, amount, currency));
}
result.addStat(stats);
} while (cursor.moveToNext());
}
cursor.close();
result.calculateOverallStats(limit, smoothEnabled);
return result;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public AppStats getLatestForApp(String packageName) {
AppStats stats = null;
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(AppStatsTable.CONTENT_URI,
new String[] { AppStatsTable.KEY_ROWID,
AppStatsTable.KEY_STATS_PACKAGENAME,
AppStatsTable.KEY_STATS_DOWNLOADS,
AppStatsTable.KEY_STATS_VERSIONCODE,
AppStatsTable.KEY_STATS_INSTALLS,
AppStatsTable.KEY_STATS_COMMENTS,
AppStatsTable.KEY_STATS_MARKETERANKING,
AppStatsTable.KEY_STATS_CATEGORYRANKING,
AppStatsTable.KEY_STATS_5STARS, AppStatsTable.KEY_STATS_4STARS,
AppStatsTable.KEY_STATS_3STARS, AppStatsTable.KEY_STATS_2STARS,
AppStatsTable.KEY_STATS_1STARS,
AppStatsTable.KEY_STATS_REQUESTDATE,
AppStatsTable.KEY_STATS_TOTAL_REVENUE,
AppStatsTable.KEY_STATS_CURRENCY },
AppStatsTable.KEY_STATS_PACKAGENAME + " = ?",
new String[] { packageName },
AppStatsTable.KEY_STATS_REQUESTDATE + " desc limit 1");
if (cursor.moveToFirst()) {
do {
stats = new AppStats();
stats.setActiveInstalls(cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_INSTALLS)));
stats.setTotalDownloads(cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_DOWNLOADS)));
stats.setDate(Utils.parseDbDate(cursor.getString(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_REQUESTDATE))));
stats.setNumberOfComments(cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_COMMENTS)));
stats.setVersionCode(cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_VERSIONCODE)));
stats.setRating(
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_1STARS)),
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_2STARS)),
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_3STARS)),
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_4STARS)),
cursor.getInt(cursor.getColumnIndex(AppStatsTable.KEY_STATS_5STARS)));
int idx = cursor.getColumnIndex(AppStatsTable.KEY_STATS_TOTAL_REVENUE);
if (!cursor.isNull(idx)) {
double amount = cursor.getDouble(idx);
String currency = cursor.getString(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_CURRENCY));
stats.setTotalRevenue(new Revenue(Revenue.Type.TOTAL, amount, currency));
}
stats.init();
} while (cursor.moveToNext());
}
return stats;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public RevenueSummary getRevenueSummaryForApp(AppInfo app) {
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(RevenueSummaryTable.CONTENT_URI,
RevenueSummaryTable.ALL_COLUMNS, RevenueSummaryTable.APPINFO_ID + "=?",
new String[] { Long.toString(app.getId()) }, RevenueSummaryTable.ROWID);
if (cursor.getCount() == 0) {
return null;
}
if (!cursor.moveToLast()) {
return null;
}
int typeIdx = cursor.getInt(cursor.getColumnIndex(RevenueSummaryTable.TYPE));
String currency = cursor.getString(cursor.getColumnIndex(RevenueSummaryTable.CURRENCY));
double lastDay = cursor.getDouble(cursor
.getColumnIndex(RevenueSummaryTable.LAST_DAY_TOTAL));
double last7Days = cursor.getDouble(cursor
.getColumnIndex(RevenueSummaryTable.LAST_7DAYS_TOTAL));
double last30Days = cursor.getDouble(cursor
.getColumnIndex(RevenueSummaryTable.LAST_30DAYS_TOTAL));
double overall = cursor.getDouble(cursor
.getColumnIndex(RevenueSummaryTable.OVERALL_TOTAL));
Revenue.Type type = Revenue.Type.values()[typeIdx];
RevenueSummary result = new RevenueSummary(type, currency, lastDay, last7Days,
last30Days, overall);
return result;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@SuppressLint("SimpleDateFormat")
public Map<Date, Map<Integer, Integer>> getDailyRatings(Date maxDate, String packagename) {
Map<Date, Map<Integer, Integer>> result = new TreeMap<Date, Map<Integer, Integer>>(
new Comparator<Date>() {
// reverse order
@Override
public int compare(Date object1, Date object2) {
return object2.compareTo(object1);
}
});
// make sure there is only one entry / day
SimpleDateFormat dateFormatEnd = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat dateFormatStart = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String queryString = AppStatsTable.KEY_STATS_PACKAGENAME + "='" + packagename + "'";
if (maxDate != null) {
queryString += " and " + AppStatsTable.KEY_STATS_REQUESTDATE + " BETWEEN '"
+ dateFormatStart.format(new Date()) + "' and '"
+ dateFormatEnd.format(maxDate) + "'";
}
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(
AppStatsTable.CONTENT_URI,
new String[] { AppStatsTable.KEY_ROWID, AppStatsTable.KEY_STATS_PACKAGENAME,
AppStatsTable.KEY_STATS_DOWNLOADS, AppStatsTable.KEY_STATS_INSTALLS,
AppStatsTable.KEY_STATS_COMMENTS,
AppStatsTable.KEY_STATS_MARKETERANKING,
AppStatsTable.KEY_STATS_CATEGORYRANKING,
AppStatsTable.KEY_STATS_VERSIONCODE, AppStatsTable.KEY_STATS_5STARS,
AppStatsTable.KEY_STATS_4STARS, AppStatsTable.KEY_STATS_3STARS,
AppStatsTable.KEY_STATS_2STARS, AppStatsTable.KEY_STATS_1STARS,
AppStatsTable.KEY_STATS_REQUESTDATE }, queryString, null,
AppStatsTable.KEY_STATS_REQUESTDATE + " asc");
Integer prev1 = null;
Integer prev2 = null;
Integer prev3 = null;
Integer prev4 = null;
Integer prev5 = null;
if (cursor != null && cursor.moveToFirst()) {
do {
Map<Integer, Integer> ratings = new TreeMap<Integer, Integer>();
int value1 = cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_1STARS));
ratings.put(1, getDiff(prev1, value1));
prev1 = value1;
int value2 = cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_1STARS));
ratings.put(2, getDiff(prev2, value2));
prev2 = value2;
int value3 = cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_3STARS));
ratings.put(3, getDiff(prev3, value3));
prev3 = value3;
int value4 = cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_4STARS));
ratings.put(4, getDiff(prev4, value4));
prev4 = value4;
int value5 = cursor.getInt(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_5STARS));
ratings.put(5, getDiff(prev5, value5));
prev5 = value5;
String dateString = cursor.getString(cursor
.getColumnIndex(AppStatsTable.KEY_STATS_REQUESTDATE));
Date date = Utils.parseDbDate(dateString.substring(0, 10) + " 00:00:00");
result.put(date, ratings);
} while (cursor.moveToNext());
}
return result;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private Integer getDiff(Integer prev1, int value1) {
if (prev1 == null) {
return 0;
} else {
return value1 - prev1;
}
}
public void updateCommentsCache(List<Comment> comments, String packageName) {
// TODO Do not drop the table each time
// clear table
context.getContentResolver().delete(CommentsTable.CONTENT_URI,
CommentsTable.KEY_COMMENT_PACKAGENAME + "='" + packageName + "'", null);
// insert new values
for (Comment comment : comments) {
ContentValues initialValues = new ContentValues();
initialValues.put(CommentsTable.KEY_COMMENT_PACKAGENAME, packageName);
initialValues
.put(CommentsTable.KEY_COMMENT_DATE, Utils.formatDbDate(comment.getDate()));
initialValues.put(CommentsTable.KEY_COMMENT_RATING, comment.getRating());
initialValues.put(CommentsTable.KEY_COMMENT_TEXT, comment.getText());
initialValues.put(CommentsTable.KEY_COMMENT_USER, comment.getUser());
initialValues.put(CommentsTable.KEY_COMMENT_APP_VERSION, comment.getAppVersion());
initialValues.put(CommentsTable.KEY_COMMENT_DEVICE, comment.getDevice());
Comment reply = comment.getReply();
String replyText = null;
String replyDate = null;
if (reply != null) {
replyText = reply.getText();
replyDate = Utils.formatDbDate(reply.getDate());
}
initialValues.put(CommentsTable.KEY_COMMENT_REPLY_TEXT, replyText);
initialValues.put(CommentsTable.KEY_COMMENT_REPLY_DATE, replyDate);
initialValues.put(CommentsTable.KEY_COMMENT_LANGUAGE, comment.getLanguage());
initialValues.put(CommentsTable.KEY_COMMENT_ORIGINAL_TEXT, comment.getOriginalText());
initialValues.put(CommentsTable.KEY_COMMENT_UNIQUE_ID, comment.getUniqueId());
context.getContentResolver().insert(CommentsTable.CONTENT_URI, initialValues);
}
backupManager.dataChanged();
}
public List<Comment> getCommentsFromCache(String packageName) {
List<Comment> result = new ArrayList<Comment>();
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(
CommentsTable.CONTENT_URI,
new String[] { CommentsTable.KEY_COMMENT_DATE,
CommentsTable.KEY_COMMENT_PACKAGENAME,
CommentsTable.KEY_COMMENT_RATING, CommentsTable.KEY_COMMENT_TEXT,
CommentsTable.KEY_COMMENT_USER, CommentsTable.KEY_COMMENT_DEVICE,
CommentsTable.KEY_COMMENT_APP_VERSION,
CommentsTable.KEY_COMMENT_REPLY_TEXT,
CommentsTable.KEY_COMMENT_REPLY_DATE,
CommentsTable.KEY_COMMENT_LANGUAGE,
CommentsTable.KEY_COMMENT_ORIGINAL_TEXT,
CommentsTable.KEY_COMMENT_UNIQUE_ID },
AppInfoTable.KEY_APP_PACKAGENAME + " = ?", new String[] { packageName },
CommentsTable.KEY_COMMENT_DATE + " desc");
if (cursor == null) {
return result;
}
while (cursor.moveToNext()) {
Comment comment = new Comment();
String dateString = cursor.getString(cursor
.getColumnIndex(CommentsTable.KEY_COMMENT_DATE));
comment.setDate(Utils.parseDbDate(dateString));
comment.setUser(cursor.getString(cursor
.getColumnIndex(CommentsTable.KEY_COMMENT_USER)));
comment.setText(cursor.getString(cursor
.getColumnIndex(CommentsTable.KEY_COMMENT_TEXT)));
comment.setDevice(cursor.getString(cursor
.getColumnIndex(CommentsTable.KEY_COMMENT_DEVICE)));
comment.setAppVersion(cursor.getString(cursor
.getColumnIndex(CommentsTable.KEY_COMMENT_APP_VERSION)));
comment.setRating(cursor.getInt(cursor
.getColumnIndex(CommentsTable.KEY_COMMENT_RATING)));
String replyText = cursor.getString(cursor
.getColumnIndex(CommentsTable.KEY_COMMENT_REPLY_TEXT));
if (replyText != null) {
Comment reply = new Comment(true);
reply.setText(replyText);
reply.setDate(Utils.parseDbDate(cursor.getString(cursor
.getColumnIndex(CommentsTable.KEY_COMMENT_REPLY_DATE))));
reply.setOriginalCommentDate(comment.getDate());
comment.setReply(reply);
}
int idx = cursor.getColumnIndex(CommentsTable.KEY_COMMENT_LANGUAGE);
if (!cursor.isNull(idx)) {
comment.setLanguage(cursor.getString(idx));
}
idx = cursor.getColumnIndex(CommentsTable.KEY_COMMENT_ORIGINAL_TEXT);
if (!cursor.isNull(idx)) {
comment.setOriginalText(cursor.getString(idx));
}
idx = cursor.getColumnIndex(CommentsTable.KEY_COMMENT_UNIQUE_ID);
if (!cursor.isNull(idx)) {
comment.setUniqueId(cursor.getString(idx));
}
result.add(comment);
}
if (cursor != null) {
cursor.close();
}
return result;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public long setSkipNotification(String packageName, boolean value) {
ContentValues initialValues = new ContentValues();
initialValues.put(AppInfoTable.KEY_APP_SKIP_NOTIFICATION, value == true ? 1 : 0);
long result = -1;
long exisitingId = getAppInfoByPackageName(packageName);
if (exisitingId > -1) {
context.getContentResolver().update(AppInfoTable.CONTENT_URI, initialValues,
AppInfoTable.KEY_ROWID + "=" + exisitingId, null);
result = exisitingId;
}
return result;
}
} |
package com.github.klondike.java.campfire;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
public class Campfire {
public String subdomain, token;
public String user_id;
public boolean ssl;
public Campfire(String subdomain, String token, boolean ssl) {
this.subdomain = subdomain;
this.token = token;
this.ssl = ssl;
this.user_id = null;
}
public Campfire(String subdomain, String token, boolean ssl, String user_id) {
this.subdomain = subdomain;
this.token = token;
this.ssl = ssl;
this.user_id = user_id;
}
public boolean login() throws CampfireException, JSONException {
HttpResponse response = new CampfireRequest(this).get(mePath());
int statusCode = response.getStatusLine().getStatusCode();
// if API key is wrong, we'll get a 401 status code (HttpStatus.SC_UNAUTHORIZED)
// if it gets a 200, then save the info from the response
if (statusCode == HttpStatus.SC_OK) {
JSONObject user = new JSONObject(CampfireRequest.responseBody(response)).getJSONObject("user");
this.user_id = user.getString("id");
return true;
} else
return false;
}
public static String mePath() {
return "/users/me";
}
public static String roomPath(String room_id) {
return "/room/" + room_id;
}
public static String roomsPath() {
return "/rooms";
}
public static String userPath(String user_id) {
return "/users/" + user_id;
}
public static String joinPath(String room_id) {
return roomPath(room_id) + "/join";
}
public static String speakPath(String room_id) {
return roomPath(room_id) + "/speak";
}
public static String uploadPath(String room_id) {
return roomPath(room_id) + "/uploads";
}
} |
package com.jcwhatever.bukkit.tpregions;
import com.jcwhatever.nucleus.utils.LeashUtils;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.Scheduler;
import com.jcwhatever.nucleus.utils.entity.EntityUtils;
import com.jcwhatever.nucleus.utils.player.PlayerStateSnapshot;
import com.jcwhatever.nucleus.utils.player.PlayerUtils;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
public class Teleporter {
private static final Map<Entity, Void> _crossWorldTeleports = new WeakHashMap<>(10);
/**
* Handles teleporting an entity to a destination.
*
* <p>Teleports on next tick.</p>
*
* <p>Preserves entity velocity.</p>
*
* <p>Loads destination chunk.</p>
*
* <p>Teleports all vehicles/passengers and restores passenger/vehicle relationship
* after teleporting.</p>
*
* @param entity The entity to teleport.
* @param destination The destination location.
*/
public static void teleport(Entity entity, Location destination) {
PreCon.notNull(entity);
PreCon.notNull(destination);
new EntityRelations(getRootEntity(entity)).teleport(destination);
}
/**
* Determine if a non-player entity is currently being teleported cross world.
*
* @param entity The entity to check.
*/
public static boolean isCrossWorldTeleporting(Entity entity) {
PreCon.notNull(entity);
return _crossWorldTeleports.containsKey(entity);
}
/*
* Get the root entity in a passenger/vehicle entity relationship
*/
private static Entity getRootEntity(Entity entity) {
while (entity.getVehicle() != null) {
entity = entity.getVehicle();
}
return entity;
}
/*
* Represents a leash from a player to an entity.
*/
private static class LeashPair {
Player player;
LivingEntity leashed;
LeashPair(Player player, LivingEntity leashed) {
this.player = player;
this.leashed = leashed;
}
}
/*
* Tracks passenger/vehicle relationships and restores them
* after transport.
*/
private static class EntityRelations {
Entity entity;
Vector velocity;
EntityRelations passenger;
EntityRelations(@Nullable Entity entity) {
this.entity = entity;
if (entity != null) {
this.velocity = entity.getVelocity();
this.passenger = new EntityRelations(entity.getPassenger());
}
}
boolean hasPassenger() {
return passenger.entity != null;
}
void mountAll() {
EntityRelations relations = this;
Chunk chunk = relations.entity.getLocation().getChunk();
while (relations.hasPassenger()) {
UUID passengerId = relations.passenger.entity.getUniqueId();
Entity passenger = EntityUtils.getEntityByUUID(chunk, passengerId);
Entity vehicle = EntityUtils.getEntityByUUID(chunk, relations.entity.getUniqueId());
if (passenger != null && vehicle != null)
vehicle.setPassenger(passenger);
relations = relations.passenger;
}
}
void dismountAll() {
EntityRelations relations = this;
while (relations.entity != null) {
relations.entity.eject();
relations = relations.passenger;
}
}
void teleport(final Location destination) {
dismountAll();
Scheduler.runTaskLater(TPRegions.getPlugin(), new Runnable() {
@Override
public void run() {
EntityRelations relations = EntityRelations.this;
boolean isWorldChange = !entity.getWorld().equals(destination.getWorld());
final LinkedList<Entity> entities = new LinkedList<>();
final LinkedList<LeashPair> leashedPairs = new LinkedList<>();
final LinkedList<PlayerStateSnapshot> snapshots = new LinkedList<>();
while (relations.entity != null) {
Entity entity = relations.entity;
if (isWorldChange) {
if (entity instanceof Player) {
snapshots.add(new PlayerStateSnapshot((Player) entity));
} else {
_crossWorldTeleports.put(entity, null);
entities.add(entity);
}
}
// teleport leashed entities
if (entity instanceof Player) {
Collection<Entity> leashed = LeashUtils.getLeashed((Player) entity);
for (Entity leashEntity : leashed) {
leashEntity.teleport(destination);
leashedPairs.add(new LeashPair((Player) entity, (LivingEntity) leashEntity));
}
}
entity.teleport(destination);
relations = relations.passenger;
}
Scheduler.runTaskLater(TPRegions.getPlugin(), 2, new Runnable() {
@Override
public void run() {
if (hasPassenger())
mountAll();
//entity.setVelocity(velocity);
while (!entities.isEmpty()) {
_crossWorldTeleports.remove(entities.remove());
}
// make sure leashes are not broken
while (!leashedPairs.isEmpty()) {
LeashPair pair = leashedPairs.remove();
pair.leashed.setLeashHolder(pair.player);
}
// preserve player game mode and flight
while (!snapshots.isEmpty()) {
PlayerStateSnapshot snapshot = snapshots.remove();
Player player = PlayerUtils.getPlayer(snapshot.getPlayerId());
if (player == null)
continue;
player.setGameMode(snapshot.getGameMode());
player.setFlying(snapshot.isFlying());
player.setAllowFlight(snapshot.isFlightAllowed());
}
}
});
}
});
}
}
} |
package com.lurencun.http.assist;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author :
* @email : chenyoca@gmail.com
* @date : 2012-10-22
* @desc : Executor
*/
public class ThreadPoolManager {
public final static int INALID_REQUEST = -1;
public final static int CORE_POOL_SIZE = 3;
public final static int MAX_POOL_SIZE = CORE_POOL_SIZE * 3;
public final static int KEEP_ALIVE_TIME_IN_S = 3 * 10;
private final static int TASK_SCHEDULE_DELAY = 6 * 1000;
private ConcurrentHashMap<Integer, Future<?>> taskHolder;
private int requestTaskIdPool;
private final ThreadPoolExecutor executor ;
private final Timer cleanNullReferenceDaemon;
{
SynchronousQueue<Runnable> queue = new SynchronousQueue<Runnable>();
executor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME_IN_S, TimeUnit.SECONDS,
queue, new ThreadPoolExecutor.CallerRunsPolicy());
cleanNullReferenceDaemon = new Timer(true);
taskHolder = new ConcurrentHashMap<Integer, Future<?>>();
cleanNullReferenceDaemon.schedule(new TimerTask() {
@Override
public void run() {
Iterator<Map.Entry<Integer, Future<?>>> iter = taskHolder.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Integer, Future<?>> entry = (Map.Entry<Integer, Future<?>>) iter.next();
Future<?> task = entry.getValue();
int key = entry.getKey();
if(task.isDone() || task.isCancelled()){
taskHolder.remove(key);
}
}
}
}, 0,TASK_SCHEDULE_DELAY);
}
/**
*
* @param r Runnable
* @return
*/
public int submit(Runnable r){
int taskId = requestTaskIdPool++;
Future<?> task = executor.submit(r);
taskHolder.put(taskId, task);
return taskId;
}
/**
*
* @param taskId ID
* @param interruptRunning
*/
public void cancel(int taskId,boolean interruptRunning){
if(taskHolder.containsKey(taskId)){
Future<?> task = taskHolder.get(taskId);
if(!task.isDone() && !task.isCancelled()){
task.cancel(interruptRunning);
}
}
}
/**
*
* @param taskId
*/
public void cancel(int taskId){
cancel(taskId,true);
}
public void destory(){
executor.shutdownNow();
}
} |
package com.morninz.ninepinview.widget;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.morninz.ninepinview.R;
public class NinePINView extends View {
private final static String TAG = "NinePINView";
protected final int POINT_COUNT = 9;
protected final int DEFAULT_PADDING = 20;
protected final int DEFAULT_POINT_COLOR = 0xFFFFFFFF;
protected final int DEFAULT_CIRCLE_COLOR = 0xFF66CC99;
protected final int DEFAULT_LINE_COLOR = 0x77FFFFFF;
protected final int DEFAULT_WRONG_COLOR = 0xFFFF0000;
private int mPointColor;
private float mPointSize;
private Paint mPointPaint;
private int mCircleColor;
private float mCircleWidth;
private float mCircleRadius;
private Paint mCirclePaint;
private int mLineColor;
private float mLineWidth;
private Paint mLinePaint;
private int mWrongColor;
private Path[] mWrongPaths = new Path[POINT_COUNT];
private Paint mWrongPaint;
/**
* The correct PIN.
*/
private String mCorrectPIN = "00";
/**
* PIN is consist of points in the drawn shape.
*/
private String mDrawnPIN;
/**
* 9 center points
*/
private Point[] mCenterPoints = new Point[POINT_COUNT];
/**
* The all point have been drawn since last MotionEvent.ACTION_DOWN event
* triggered.
*/
private List<Point> mDrawnPoints = new ArrayList<Point>();
/**
* The last been drawn point.
*/
private Point mLastDrawnPoint = null;
private class Point {
int index;// index of 9 center points
float x;
float y;
@Override
public String toString() {
return "Point [index=" + index + ", x=" + x + ", y=" + y + "]";
}
}
/**
* The current X coordinate of finger
*/
private float mCurrX;
/**
* The current Y coordinate of finger
*/
private float mCurrY;
protected boolean mWillDrawWrongTriangle;
protected OnDrawListener mOnDrawListener;
protected Mode mCurrMode = Mode.MODE_WORK;
public static enum Mode {
/**
* Study correct PIN shape mode.
*/
MODE_STUDY,
/**
* Inspect drawn PIN shape mode.
*/
MODE_WORK
}
public NinePINView(Context context) {
this(context, null);
}
public NinePINView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public NinePINView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.NinePINView);
mPointColor = a.getColor(R.styleable.NinePINView_pointColor,
DEFAULT_POINT_COLOR);
mCircleColor = a.getColor(R.styleable.NinePINView_circleColor,
DEFAULT_CIRCLE_COLOR);
mLineColor = a.getColor(R.styleable.NinePINView_lineColor,
DEFAULT_LINE_COLOR);
mWrongColor = a.getColor(R.styleable.NinePINView_wrongColor,
DEFAULT_WRONG_COLOR);
mPointSize = a.getDimension(R.styleable.NinePINView_pointSize, 8.0f);
mCircleWidth = a
.getDimension(R.styleable.NinePINView_circleWidth, 5.0f);
mLineWidth = a.getDimension(R.styleable.NinePINView_lineWidth, 5.0f);
mCircleRadius = a.getDimension(R.styleable.NinePINView_circleRadius,
40.0f);
a.recycle();
// center point
mPointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPointPaint.setColor(mPointColor);
mPointPaint.setStyle(Style.FILL);
// circle
mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCirclePaint.setColor(mCircleColor);
mCirclePaint.setStrokeWidth(mCircleWidth);
mCirclePaint.setStyle(Style.STROKE);
// connection line
mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mLinePaint.setColor(mLineColor);
mLinePaint.setStrokeWidth(mLineWidth);
mLinePaint.setStyle(Style.FILL);
mLinePaint.setStrokeCap(Cap.ROUND);
mLinePaint.setStrokeJoin(Join.ROUND);
// wrong triangle path
mWrongPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mWrongPaint.setColor(mWrongColor);
mWrongPaint.setStyle(Style.FILL);
setPadding(Math.max(getPaddingLeft(), DEFAULT_PADDING),
Math.max(getPaddingTop(), DEFAULT_PADDING),
Math.max(getPaddingRight(), DEFAULT_PADDING),
Math.max(getPaddingBottom(), DEFAULT_PADDING));
mWillDrawWrongTriangle = false;
}
public int getPointColor() {
return mPointColor;
}
public void setPointColor(int color) {
mPointColor = color;
mPointPaint.setColor(color);
}
public void setCircleColor(int color) {
mCircleColor = color;
mCirclePaint.setColor(color);
}
public void setLineColor(int color) {
mLineColor = color;
mLinePaint.setColor(color);
}
public void setPointSize(int size) {
mPointSize = size;
mPointPaint.setStrokeWidth(size);
}
public void setCircleWidth(int width) {
mCircleWidth = width;
mCirclePaint.setStrokeWidth(width);
}
public void setCircleRadius(int raduis) {
mCircleRadius = raduis;
mCirclePaint.setStrokeWidth(raduis);
}
public void setLineWidth(int width) {
mLineWidth = width;
mLinePaint.setStrokeWidth(width);
}
/**
* Set current work mode of NinePINView.
*
* @param mode
* {@link Mode#MODE_STUDY} or {@link Mode#MODE_WORK}
*/
public void setMode(Mode mode) {
mCurrMode = mode;
}
/**
* Get the current work mode of NinePINView.
*
* @return
*/
public Mode getMode() {
return mCurrMode;
}
/**
*
* @return PIN String has been drawn.
*/
public String getDrawnPIN() {
return mDrawnPIN;
}
public void setCorrectPIN(String pin) {
boolean repeat = false;
for (int i = 0; i < pin.length() - 1; i++) {
for (int j = i + 1; j < pin.length(); j++) {
if (pin.charAt(i) == pin.charAt(j)) {
repeat = true;
break;
}
}
}
boolean match = Pattern.matches("[0-8]{1,9}", pin);
if (repeat || !match) {
throw new IllegalArgumentException(
"The pin must only contains characters '0'-'8' and not be repeat.");
}
mCorrectPIN = pin;
}
public void setOnDrawListener(OnDrawListener listener) {
mOnDrawListener = listener;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
computePointsAndWrongTriangleCoordinate();
}
/**
* Compute the coordinates of 9 center points and wrong triangles.
*/
protected void computePointsAndWrongTriangleCoordinate() {
int drawWidth = getWidth() - getPaddingLeft() - getPaddingRight();
int drawHeight = getHeight() - getPaddingTop() - getPaddingBottom();
float baseX = getPaddingLeft() + mCircleRadius;
float baseY = getPaddingTop() + mCircleRadius;
float gapX = drawWidth / 2.0f - mCircleRadius;
float gapY = drawHeight / 2.0f - mCircleRadius;
float r = mCircleRadius;
for (int i = 0; i < POINT_COUNT; i++) {
// compute center point's coordinate
Point point = new Point();
point.x = baseX + gapX * (i % 3);
point.y = baseY + gapY * (i / 3);
point.index = i;
mCenterPoints[i] = point;
// compute wrong triangle path of this point.
Path path = new Path();
float x1, y1, x2, y2, x3, y3;
x1 = point.x + r;
y1 = point.y;
x2 = point.x + r * (2.0f / 3);
y2 = point.y - r * (1.0f / 3);
x3 = x2;
y3 = point.y + r * (1.0f / 3);
path.moveTo(x1, y1);
path.lineTo(x2, y2);
path.lineTo(x3, y3);
path.lineTo(x1, y1);
path.close();
mWrongPaths[i] = path;
Log.d(TAG, "[ " + x1 + ", " + y1 + " ], " + "[ " + x2 + ", " + y2
+ " ], " + "[ " + x3 + ", " + y3 + " ]");
}
}
@Override
public boolean onTouchEvent(MotionEvent e) {
switch (MotionEventCompat.getActionMasked(e)) {
case MotionEvent.ACTION_DOWN:
onDrawStart();
clearDrawn();
kissSomePoint(e);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
kissSomePoint(e);
invalidate();
break;
case MotionEvent.ACTION_UP:
if (mLastDrawnPoint != null) {
mCurrX = mLastDrawnPoint.x;
mCurrY = mLastDrawnPoint.y;
}
StringBuilder sb = new StringBuilder();
for (Point p : mDrawnPoints) {
sb.append(p.index);
}
mDrawnPIN = sb.toString();
Log.d(TAG, "drawn pin : " + mDrawnPIN + ", correct pin : "
+ mCorrectPIN);
if (mCurrMode == Mode.MODE_STUDY) {
onDrawComplete(true);
clearDrawn();
} else if (mCurrMode == Mode.MODE_WORK) {
if (!mDrawnPIN.equals(mCorrectPIN)) {
mCirclePaint.setColor(mWrongColor);
mWillDrawWrongTriangle = true;
onDrawComplete(false);
} else {
onDrawComplete(true);
}
}
invalidate();
break;
}
return true;
}
/**
* Clear to status before drawn, there are only 9 points in canvas.
*/
protected void clearDrawn() {
mDrawnPoints.clear();
mLastDrawnPoint = null;
mCirclePaint.setColor(mCircleColor);
mWillDrawWrongTriangle = false;
}
/**
* Check whether finger has entered some point's area or not.
*
* @param e
* motion envent.
*/
protected boolean kissSomePoint(MotionEvent e) {
// We just check the one point.
mCurrX = e.getX(0);
mCurrY = e.getY(0);
for (int i = 0; i < POINT_COUNT; i++) {
Point p = mCenterPoints[i];
if (Math.sqrt(Math.pow(mCurrX - p.x, 2) + Math.pow(mCurrY - p.y, 2)) <= mCircleRadius) {
if (!mDrawnPoints.contains(p)) {
Log.d(TAG, "kiss " + p);
// Check the point between last drawn point and kissed
// point, if not drawn, draw it.
// There are two appropriate situations:
// 1. The two points are in corner.
// 2. The connection line of the two points through the
// point 4.
if (mLastDrawnPoint != null) {
if ((isCornerPoint(mLastDrawnPoint) && isCornerPoint(p))
|| (mLastDrawnPoint.index + p.index == 8)) {
int middlePointIndex = (mLastDrawnPoint.index + p.index) / 2;
Point middlePoint = mCenterPoints[middlePointIndex];
if (!mDrawnPoints.contains(middlePoint)) {
mDrawnPoints.add(middlePoint);
}
}
}
mLastDrawnPoint = p;
mDrawnPoints.add(p);
return true;
} else {
// This point has been kissed, don't be greedy!
break;
}
}
}
return false;
}
private boolean isCornerPoint(Point p) {
if (p.index == 0 || p.index == 2 || p.index == 6 || p.index == 8) {
return true;
} else {
return false;
}
}
protected void onDrawStart() {
if (mOnDrawListener != null) {
mOnDrawListener.onDrawStart(this);
} else {
Log.w(TAG,
"You should call NinePINView.setOnDrawCompleteListener() method to set a draw listener.");
}
}
protected void onDrawComplete(boolean correct) {
// XXX: this is not required. The correct PIN should be set by user.
if (mCurrMode == Mode.MODE_STUDY) {
mCorrectPIN = mDrawnPIN;
}
if (mOnDrawListener != null) {
mOnDrawListener.onDrawComplete(this, correct);
} else {
Log.w(TAG,
"You should call NinePINView.setOnDrawCompleteListener() method to set a draw listener.");
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw circles around center points and connection line
int drawnCount = mDrawnPoints.size();
for (int j = 0; j < drawnCount; j++) {
Point p1 = mDrawnPoints.get(j);
canvas.drawCircle(p1.x, p1.y, mCircleRadius, mCirclePaint);
if (j + 1 < drawnCount) {
Point p2 = mDrawnPoints.get(j + 1);
canvas.drawCircle(p2.x, p2.y, mCircleRadius, mCirclePaint);
canvas.drawLine(p1.x, p1.y, p2.x, p2.y, mLinePaint);
if (mWillDrawWrongTriangle) {
// compute the wrong triangle's direction of this point.
float angle = 0.f;
if (p2.y == p1.y) {// x-axis
angle = p2.x > p1.x ? 0.f : 180.f;
} else if (p2.x == p1.x) { // y-axis
angle = p2.y > p1.y ? 90.f : -90.f;
} else {// in quadrants
double tanA = ((double) p2.y - (double) p1.y)
/ ((double) p2.x - (double) p1.x);
// in 1 or 4 quadrant
angle = (float) (Math.atan(tanA) * 180 / Math.PI);
// in 2 or 3 quadrant
if (p2.x < p1.x) {
angle += 180.f;
}
}
Log.d(TAG, "angle " + angle);
canvas.save();
canvas.rotate(angle, p1.x, p1.y);
canvas.drawPath(mWrongPaths[p1.index], mWrongPaint);
canvas.restore();
}
}
}
// draw extra connection line
if (mLastDrawnPoint != null) {
canvas.drawLine(mLastDrawnPoint.x, mLastDrawnPoint.y, mCurrX,
mCurrY, mLinePaint);
}
// draw 9 center points
for (int i = 0; i < POINT_COUNT; i++) {
Point p = mCenterPoints[i];
canvas.drawCircle(p.x, p.y, mPointSize, mPointPaint);
}
}
/**
* Interface definition for a callback to be invoked when finger drawn is
* complete.
*/
public interface OnDrawListener {
/**
* Called when finger begin to draw.
*
* @param ninePINView
* The ninePINView which is being drawing.
*/
public void onDrawStart(NinePINView ninePINView);
/**
* Called when finger draw has been complete.
*
* @param ninePINView
* The ninePINView has been drawn.
* @param correct
* true if shape that has been drawn is correct, false if
* wrong.
*/
public void onDrawComplete(NinePINView ninePINView, boolean correct);
}
} |
package com.namelessmc.java_api;
import com.github.mizosoft.methanol.Methanol;
import com.google.gson.GsonBuilder;
import com.namelessmc.java_api.logger.ApiLogger;
import com.namelessmc.java_api.logger.PrintStreamLogger;
import com.namelessmc.java_api.logger.Slf4jLogger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.ProxySelector;
import java.net.URL;
import java.time.Duration;
import java.util.concurrent.Executor;
public class NamelessApiBuilder {
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(5);
private static final String DEFAULT_USER_AGENT = "Nameless-Java-API";
private static final int DEFAULT_RESPONSE_SIZE_LIMIT = 32*1024*1024;
private final @NonNull URL apiUrl;
private final @NonNull String apiKey;
private final @NonNull GsonBuilder gsonBuilder;
private @Nullable ApiLogger debugLogger = null;
private final Methanol.@NonNull Builder httpClientBuilder;
private int responseSizeLimit = DEFAULT_RESPONSE_SIZE_LIMIT;
NamelessApiBuilder(final @NonNull URL apiUrl,
final @NonNull String apiKey) {
try {
this.apiUrl = apiUrl.toString().endsWith("/") ? apiUrl : new URL(apiUrl + "/");
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
this.apiKey = apiKey;
this.gsonBuilder = new GsonBuilder();
this.gsonBuilder.disableHtmlEscaping();
this.httpClientBuilder = Methanol.newBuilder()
.defaultHeader("Authorization", "Bearer " + this.apiKey)
.userAgent(DEFAULT_USER_AGENT)
.readTimeout(DEFAULT_TIMEOUT)
.requestTimeout(DEFAULT_TIMEOUT)
.connectTimeout(DEFAULT_TIMEOUT)
.autoAcceptEncoding(true);
}
public @NonNull NamelessApiBuilder userAgent(final @NonNull String userAgent) {
this.httpClientBuilder.userAgent(userAgent);
return this;
}
@Deprecated
public @NonNull NamelessApiBuilder debug(final boolean debug) {
if (debug) {
return this.stdErrDebugLogger();
} else {
this.debugLogger = null;
return this;
}
}
public @NonNull NamelessApiBuilder stdErrDebugLogger() {
this.debugLogger = PrintStreamLogger.DEFAULT_INSTANCE;
return this;
}
public @NonNull NamelessApiBuilder slf4jDebugLogger() {
this.debugLogger = Slf4jLogger.DEFAULT_INSTANCE;
return this;
}
public @NonNull NamelessApiBuilder customDebugLogger(final @Nullable ApiLogger debugLogger) {
this.debugLogger = debugLogger;
return this;
}
public @NonNull NamelessApiBuilder timeout(final @NonNull Duration timeout) {
this.httpClientBuilder.readTimeout(timeout)
.requestTimeout(timeout)
.connectTimeout(timeout);
return this;
}
public @NonNull NamelessApiBuilder withProxy(final ProxySelector proxy) {
this.httpClientBuilder.proxy(proxy);
return this;
}
public @NonNull NamelessApiBuilder authenticator(final Authenticator authenticator) {
this.httpClientBuilder.authenticator(authenticator);
return this;
}
public @NonNull NamelessApiBuilder pettyJsonRequests() {
gsonBuilder.setPrettyPrinting();
return this;
}
public @NonNull NamelessApiBuilder responseSizeLimit(int responseSizeLimitBytes) {
this.responseSizeLimit = responseSizeLimitBytes;
return this;
}
public @NonNull NamelessApiBuilder executor(final @NonNull Executor executor) {
this.httpClientBuilder.executor(executor);
return this;
}
public @NonNull NamelessAPI build() {
return new NamelessAPI(
new RequestHandler(
this.apiUrl,
this.httpClientBuilder.build(),
this.gsonBuilder.create(),
this.debugLogger,
this.responseSizeLimit
),
this.apiUrl,
this.apiKey
);
}
} |
package com.neutrinoproject.testrunner.ui;
import com.neutrinoproject.testrunner.TestOutputParser;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Collection;
import java.util.Observable;
import java.util.Observer;
import java.util.stream.Stream;
public class MainForm implements Observer {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton loadTestBinaryButton;
private JTextField testBinaryPathField;
private JButton runAllTestsButton;
private JButton runSelectedButton;
private JButton runFailedButton;
private JButton stopButton;
private JTable testOutputTable;
private JTextArea rawOutputArea;
private JLabel statusLabel;
private JProgressBar progressBar;
private final ProcessRunnerModel model = new ProcessRunnerModel();
public void initForm() {
model.addObserver(this);
mainFrame = new JFrame();
mainFrame.setContentPane(mainPanel);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.setTitle("TestRunner");
mainFrame.setSize(600, 600);
mainFrame.setLocationRelativeTo(null);
// mainFrame.pack();
rawOutputArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, rawOutputArea.getFont().getSize()));
loadTestBinaryButton.addActionListener(this::onLoadTestBinary);
runAllTestsButton.addActionListener(this::onRunAllTests);
stopButton.addActionListener(this::onStop);
}
public void showForm() {
SwingUtilities.invokeLater(() -> mainFrame.setVisible(true));
}
private void onLoadTestBinary(final ActionEvent event) {
final JFileChooser fileChooser = new JFileChooser();
final int returnVal = fileChooser.showOpenDialog(mainFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
final String path = fileChooser.getSelectedFile().getPath();
testBinaryPathField.setText(path);
setLoadingProgress(true);
statusLabel.setText("Loading binary...");
model.startReadingBinary(path);
}
}
private void onRunAllTests(final ActionEvent event) {
setLoadingProgress(true);
statusLabel.setText("Running tests...");
rawOutputArea.setText(null);
model.startAllTests();
}
private void onStop(final ActionEvent event) {
model.stopAllProcesses();
setLoadingProgress(false);
statusLabel.setText("Stopped");
}
private void setLoadingProgress(boolean loading) {
Stream.of(loadTestBinaryButton, runAllTestsButton, runSelectedButton, runFailedButton)
.forEach(b -> b.setEnabled(!loading));
stopButton.setEnabled(loading);
progressBar.setValue(loading ? progressBar.getMinimum() : progressBar.getMaximum());
}
private void onTestCasesLoaded() {
final Collection<TestOutputParser.TestCase> testCases = model.getTestCases();
final String[] columnNames = {"R", "State", "Test Name"};
final DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
for (final TestOutputParser.TestCase testCase : testCases) {
tableModel.addRow(new Object[]{">", "", testCase.name});
for (final String testName : testCase.tests) {
tableModel.addRow(new Object[]{">", "", " " + testName});
}
}
testOutputTable.setModel(tableModel);
testOutputTable.getColumnModel().getColumn(2).setPreferredWidth(400);
testOutputTable.getColumnModel().getColumn(2).setWidth(400);
setLoadingProgress(false);
statusLabel.setText("Binary loaded");
}
private void onOutLine(final String line) {
rawOutputArea.append(line);
rawOutputArea.append("\n");
rawOutputArea.setCaretPosition(rawOutputArea.getDocument().getLength());
}
private void onTestRunFinished() {
setLoadingProgress(false);
statusLabel.setText("Ready");
}
@Override
public void update(final Observable o, final Object arg) {
final ProcessRunnerModel.Event event = (ProcessRunnerModel.Event) arg;
switch (event.type) {
case TEST_CASES_LOADED:
SwingUtilities.invokeLater(this::onTestCasesLoaded);
break;
case OUT_LINE:
SwingUtilities.invokeLater(() -> onOutLine((String) event.data));
break;
case TEST_RUN_FINISHED:
SwingUtilities.invokeLater(this::onTestRunFinished);
break;
case ERROR:
break;
}
}
} |
package com.sbpinvertor.modbus;
import com.sbpinvertor.modbus.master.ModbusMasterASCII;
import com.sbpinvertor.modbus.master.ModbusMasterRTU;
import com.sbpinvertor.modbus.master.ModbusMasterTCP;
import com.sbpinvertor.modbus.serial.SerialParameters;
import com.sbpinvertor.modbus.serial.SerialPort;
final public class ModbusMasterFactory {
private ModbusMasterFactory() {
}
/**
* Creates ModbusMasterRTU instance.
*
* @param device - serial port device name
* @param baudRate - baud rate
* @param dataBits - data bit count
* @param stopBits - stop bit count(1,2)
* @param parity - parity bit(NONE, EVEN, ODD, MARK, SPACE)
* @return ModbusMaster instance if there is no errors, else null
* @see com.sbpinvertor.modbus.serial.SerialPort.Parity
* @see com.sbpinvertor.modbus.serial.SerialPort.BaudRate
* @see ModbusMaster
*/
static public ModbusMaster createModbusMasterRTU(String device, SerialPort.BaudRate baudRate, int dataBits, int stopBits, SerialPort.Parity parity) {
return new ModbusMasterRTU(device, baudRate, dataBits, stopBits, parity);
}
/**
* Creates ModbusMasterRTU instance.
*
* @param sp - a SerialParameters instance.
*
* @return ModbusMaster instance if there is no errors, else null
* @see com.sbpinvertor.modbus.serial.SerialPort.Parity
* @see com.sbpinvertor.modbus.serial.SerialPort.BaudRate
* @see ModbusMaster
* @see SerialParameters
*/
static public ModbusMaster createModbusMasterRTU(SerialParameters sp) {
return new ModbusMasterRTU(sp);
}
/**
* Creates ModbusMasterASCII instance.
*
* @param device - serial port device name
* @param baudRate - baud rate
* @param parity - parity bit(NONE, EVEN, ODD, MARK, SPACE)
* @return ModbusMaster instance if there is no errors, else null
* @see com.sbpinvertor.modbus.serial.SerialPort.Parity
* @see com.sbpinvertor.modbus.serial.SerialPort.BaudRate
* @see ModbusMaster
*/
static public ModbusMaster createModbusMasterASCII(String device, SerialPort.BaudRate baudRate, SerialPort.Parity parity) {
return new ModbusMasterASCII(device, baudRate, parity);
}
/**
* Creates ModbusMasterASCII instance with even parity completion.
*
* @param device - serial port device name
* @param baudRate - baud rate
* @return ModbusMaster instance if there is no errors, else null
* @see com.sbpinvertor.modbus.serial.SerialPort.Parity
* @see com.sbpinvertor.modbus.serial.SerialPort.BaudRate
* @see ModbusMaster
*/
static public ModbusMaster createModbusMasterASCII(String device, SerialPort.BaudRate baudRate) {
return new ModbusMasterASCII(device, baudRate);
}
/**
* Creates ModbusMasterTCP instance.
*
* @param host - ip address of remote slave
* @param keepAlive - whether or not to have socket keep alive turned on.
* @return ModbusMaster instance if there is no errors, else null
* @see ModbusMaster
*/
static public ModbusMaster createModbusMasterTCP(String host, boolean keepAlive) {
return createModbusMasterTCP(host, Modbus.TCP_PORT, keepAlive);
}
/**
* Creates ModbusMasterTCP instance.
*
* @param host - ip address of remote slave
* @return ModbusMaster instance if there is no errors, else null
* @see ModbusMaster
*/
static public ModbusMaster createModbusMasterTCP(String host) {
return createModbusMasterTCP(host, false);
}
/**
* Creates ModbusMasterTCP instance.
*
* @param host - ip address of remote slave
* @param port - tcp port
* @param keepAlive - whether or not to have socket keep alive turned on.
* @return ModbusMaster instance if there is no errors, else null
* @see ModbusMaster
*/
static public ModbusMaster createModbusMasterTCP(String host, int port, boolean keepAlive) {
return new ModbusMasterTCP(host, port, keepAlive);
}
} |
package org.jgroups;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.stack.StateTransferInfo;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.*;
import org.w3c.dom.Element;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
/**
* JChannel is a pure Java implementation of Channel.
* When a JChannel object is instantiated it automatically sets up the
* protocol stack.
* <p>
* <B>Properties</B>
* <P>
* Properties are used to configure a channel, and are accepted in
* several forms; the String form is described here.
* A property string consists of a number of properties separated by
* colons. For example:
* <p>
* <pre>"<prop1>(arg1=val1):<prop2>(arg1=val1;arg2=val2):<prop3>:<propn>"</pre>
* <p>
* Each property relates directly to a protocol layer, which is
* implemented as a Java class. When a protocol stack is to be created
* based on the above property string, the first property becomes the
* bottom-most layer, the second one will be placed on the first, etc.:
* the stack is created from the bottom to the top, as the string is
* parsed from left to right. Each property has to be the name of a
* Java class that resides in the
* {@link org.jgroups.protocols} package.
* <p>
* Note that only the base name has to be given, not the fully specified
* class name (e.g., UDP instead of org.jgroups.protocols.UDP).
* <p>
* Each layer may have 0 or more arguments, which are specified as a
* list of name/value pairs in parentheses directly after the property.
* In the example above, the first protocol layer has 1 argument,
* the second 2, the third none. When a layer is created, these
* properties (if there are any) will be set in a layer by invoking
* the layer's setProperties() method
* <p>
* As an example the property string below instructs JGroups to create
* a JChannel with protocols UDP, PING, FD and GMS:<p>
* <pre>"UDP(mcast_addr=228.10.9.8;mcast_port=5678):PING:FD:GMS"</pre>
* <p>
* The UDP protocol layer is at the bottom of the stack, and it
* should use mcast address 228.10.9.8. and port 5678 rather than
* the default IP multicast address and port. The only other argument
* instructs FD to output debug information while executing.
* Property UDP refers to a class {@link org.jgroups.protocols.UDP},
* which is subsequently loaded and an instance of which is created as protocol layer.
* If any of these classes are not found, an exception will be thrown and
* the construction of the stack will be aborted.
*
* @author Bela Ban
* @version $Id: JChannel.java,v 1.102 2006/10/23 16:11:09 vlada Exp $
*/
public class JChannel extends Channel {
/**
* The default protocol stack used by the default constructor.
*/
public static final String DEFAULT_PROTOCOL_STACK=
"UDP(down_thread=false;mcast_send_buf_size=640000;mcast_port=45566;discard_incompatible_packets=true;" +
"ucast_recv_buf_size=20000000;mcast_addr=228.10.10.10;up_thread=false;loopback=false;" +
"mcast_recv_buf_size=25000000;max_bundle_size=64000;max_bundle_timeout=30;" +
"use_incoming_packet_handler=true;use_outgoing_packet_handler=false;" +
"ucast_send_buf_size=640000;tos=16;enable_bundling=true;ip_ttl=2):" +
"PING(timeout=2000;down_thread=false;num_initial_members=3;up_thread=false):" +
"MERGE2(max_interval=10000;down_thread=false;min_interval=5000;up_thread=false):" +
"FD(timeout=2000;max_tries=3;down_thread=false;up_thread=false):" +
"VERIFY_SUSPECT(timeout=1500;down_thread=false;up_thread=false):" +
"pbcast.NAKACK(max_xmit_size=60000;down_thread=false;use_mcast_xmit=false;gc_lag=0;" +
"discard_delivered_msgs=true;up_thread=false;retransmit_timeout=100,200,300,600,1200,2400,4800):" +
"UNICAST(timeout=300,600,1200,2400,3600;down_thread=false;up_thread=false):" +
"pbcast.STABLE(stability_delay=1000;desired_avg_gossip=50000;max_bytes=400000;down_thread=false;" +
"up_thread=false):" +
"VIEW_SYNC(down_thread=false;avg_send_interval=60000;up_thread=false):" +
"pbcast.GMS(print_local_addr=true;join_timeout=3000;down_thread=false;" +
"join_retry_timeout=2000;up_thread=false;shun=true):" +
"FC(max_credits=2000000;down_thread=false;up_thread=false;min_threshold=0.10):" +
"FRAG2(frag_size=60000;down_thread=false;up_thread=false):" +
"pbcast.STATE_TRANSFER(down_thread=false;up_thread=false)";
static final String FORCE_PROPS="force.properties";
/* the protocol stack configuration string */
private String props=null;
/*the address of this JChannel instance*/
private Address local_addr=null;
/*the channel (also know as group) name*/
private String cluster_name=null; // group name
/*the latest view of the group membership*/
private View my_view=null;
/*the queue that is used to receive messages (events) from the protocol stack*/
private final Queue mq=new Queue();
/*the protocol stack, used to send and receive messages from the protocol stack*/
private ProtocolStack prot_stack=null;
/** Thread responsible for closing a channel and potentially reconnecting to it (e.g., when shunned). */
protected CloserThread closer=null;
/** To wait until a local address has been assigned */
private final Promise local_addr_promise=new Promise();
/** To wait until we have connected successfully */
private final Promise connect_promise=new Promise();
/** To wait until we have been disconnected from the channel */
private final Promise disconnect_promise=new Promise();
private final Promise state_promise=new Promise();
private final Promise flush_unblock_promise=new Promise();
private final Promise flush_promise=new Promise();
/** wait until we have a non-null local_addr */
private long LOCAL_ADDR_TIMEOUT=30000; //=Long.parseLong(System.getProperty("local_addr.timeout", "30000"));
/*if the states is fetched automatically, this is the default timeout, 5 secs*/
private static final long GET_STATE_DEFAULT_TIMEOUT=5000;
/*if FLUSH is used channel waits for UNBLOCK event, this is the default timeout, 10 secs*/
private static final long FLUSH_UNBLOCK_TIMEOUT=10000;
/*flag to indicate whether to receive blocks, if this is set to true, receive_views is set to true*/
private boolean receive_blocks=false;
/*flag to indicate whether to receive local messages
*if this is set to false, the JChannel will not receive messages sent by itself*/
private boolean receive_local_msgs=true;
/*flag to indicate whether the channel will reconnect (reopen) when the exit message is received*/
private boolean auto_reconnect=false;
/*flag t indicate whether the state is supposed to be retrieved after the channel is reconnected
*setting this to true, automatically forces auto_reconnect to true*/
private boolean auto_getstate=false;
/*channel connected flag*/
protected boolean connected=false;
/*channel closed flag*/
protected boolean closed=false; // close() has been called, channel is unusable
/** True if a state transfer protocol is available, false otherwise */
private boolean state_transfer_supported=false; // set by CONFIG event from STATE_TRANSFER protocol
/** True if a flush protocol is available, false otherwise */
private volatile boolean flush_supported=false; // set by CONFIG event from FLUSH protocol
/** Used to maintain additional data across channel disconnects/reconnects. This is a kludge and will be remove
* as soon as JGroups supports logical addresses
*/
private byte[] additional_data=null;
protected final Log log=LogFactory.getLog(getClass());
/** Collect statistics */
protected boolean stats=true;
protected long sent_msgs=0, received_msgs=0, sent_bytes=0, received_bytes=0;
/** Used by subclass to create a JChannel without a protocol stack, don't use as application programmer */
protected JChannel(boolean no_op) {
;
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* specified by the <code>DEFAULT_PROTOCOL_STACK</code> member.
*
* @throws ChannelException if problems occur during the initialization of
* the protocol stack.
*/
public JChannel() throws ChannelException {
this(DEFAULT_PROTOCOL_STACK);
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the specified file.
*
* @param properties a file containing a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(File properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the specified XML element.
*
* @param properties a XML element containing a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(Element properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration indicated by the specified URL.
*
* @param properties a URL pointing to a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(URL properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration based upon the specified properties parameter.
*
* @param properties an old style property string, a string representing a
* system resource containing a JGroups XML configuration,
* a string representing a URL pointing to a JGroups XML
* XML configuration, or a string representing a file name
* that contains a JGroups XML configuration.
*
* @throws ChannelException if problems occur during the configuration and
* initialization of the protocol stack.
*/
public JChannel(String properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the protocol stack configurator parameter.
* <p>
* All of the public constructors of this class eventually delegate to this
* method.
*
* @param configurator a protocol stack configurator containing a JGroups
* protocol stack configuration.
*
* @throws ChannelException if problems occur during the initialization of
* the protocol stack.
*/
protected JChannel(ProtocolStackConfigurator configurator) throws ChannelException {
init(configurator);
}
/**
* Creates a new JChannel with the protocol stack as defined in the properties
* parameter. an example of this parameter is<BR>
* "UDP:PING:FD:STABLE:NAKACK:UNICAST:FRAG:FLUSH:GMS:VIEW_ENFORCER:STATE_TRANSFER:QUEUE"<BR>
* Other examples can be found in the ./conf directory<BR>
* @param properties the protocol stack setup; if null, the default protocol stack will be used.
* The properties can also be a java.net.URL object or a string that is a URL spec.
* The JChannel will validate any URL object and String object to see if they are a URL.
* In case of the parameter being a url, the JChannel will try to load the xml from there.
* In case properties is a org.w3c.dom.Element, the ConfiguratorFactory will parse the
* DOM tree with the element as its root element.
* @deprecated Use the constructors with specific parameter types instead.
*/
public JChannel(Object properties) throws ChannelException {
if (properties == null)
properties = DEFAULT_PROTOCOL_STACK;
ProtocolStackConfigurator c=null;
try {
c=ConfiguratorFactory.getStackConfigurator(properties);
}
catch(Exception x) {
throw new ChannelException("unable to load protocol stack", x);
}
init(c);
}
/**
* Returns the protocol stack.
* Currently used by Debugger.
* Specific to JChannel, therefore
* not visible in Channel
*/
public ProtocolStack getProtocolStack() {
return prot_stack;
}
protected Log getLog() {
return log;
}
/**
* returns the protocol stack configuration in string format.
* an example of this property is<BR>
* "UDP:PING:FD:STABLE:NAKACK:UNICAST:FRAG:FLUSH:GMS:VIEW_ENFORCER:STATE_TRANSFER:QUEUE"
*/
public String getProperties() {
return props;
}
public boolean statsEnabled() {
return stats;
}
public void enableStats(boolean stats) {
this.stats=stats;
}
public void resetStats() {
sent_msgs=received_msgs=sent_bytes=received_bytes=0;
}
public long getSentMessages() {return sent_msgs;}
public long getSentBytes() {return sent_bytes;}
public long getReceivedMessages() {return received_msgs;}
public long getReceivedBytes() {return received_bytes;}
public int getNumberOfTasksInTimer() {return prot_stack != null ? prot_stack.timer.size() : -1;}
public String dumpTimerQueue() {
return prot_stack != null? prot_stack.dumpTimerQueue() : "<n/a";
}
/**
* Returns a pretty-printed form of all the protocols. If include_properties is set,
* the properties for each protocol will also be printed.
*/
public String printProtocolSpec(boolean include_properties) {
return prot_stack != null ? prot_stack.printProtocolSpec(include_properties) : null;
}
/**
* Connects the channel to a group.
* If the channel is already connected, an error message will be printed to the error log.
* If the channel is closed a ChannelClosed exception will be thrown.
* This method starts the protocol stack by calling ProtocolStack.start,
* then it sends an Event.CONNECT event down the stack and waits to receive a CONNECT_OK event.
* Once the CONNECT_OK event arrives from the protocol stack, any channel listeners are notified
* and the channel is considered connected.
*
* @param cluster_name A <code>String</code> denoting the group name. Cannot be null.
* @exception ChannelException The protocol stack cannot be started
* @exception ChannelClosedException The channel is closed and therefore cannot be used any longer.
* A new channel has to be created first.
*/
public synchronized void connect(String cluster_name) throws ChannelException, ChannelClosedException {
/*make sure the channel is not closed*/
checkClosed();
/*if we already are connected, then ignore this*/
if(connected) {
if(log.isTraceEnabled()) log.trace("already connected to " + cluster_name);
return;
}
/*make sure we have a valid channel name*/
if(cluster_name == null) {
if(log.isInfoEnabled()) log.info("cluster_name is null, assuming unicast channel");
}
else
this.cluster_name=cluster_name;
try {
prot_stack.startStack(); // calls start() in all protocols, from top to bottom
}
catch(Throwable e) {
throw new ChannelException("failed to start protocol stack", e);
}
String tmp=Util.getProperty(new String[]{Global.CHANNEL_LOCAL_ADDR_TIMEOUT, "local_addr.timeout"},
null, null, false, "30000");
LOCAL_ADDR_TIMEOUT=Long.parseLong(tmp);
/* Wait LOCAL_ADDR_TIMEOUT milliseconds for local_addr to have a non-null value (set by SET_LOCAL_ADDRESS) */
local_addr=(Address)local_addr_promise.getResult(LOCAL_ADDR_TIMEOUT);
if(local_addr == null) {
log.fatal("local_addr is null; cannot connect");
throw new ChannelException("local_addr is null");
}
/*create a temporary view, assume this channel is the only member and
*is the coordinator*/
Vector t=new Vector(1);
t.addElement(local_addr);
my_view=new View(local_addr, 0, t); // create a dummy view
// only connect if we are not a unicast channel
if(cluster_name != null) {
connect_promise.reset();
if(flush_supported)
flush_unblock_promise.reset();
Event connect_event=new Event(Event.CONNECT, cluster_name);
down(connect_event);
Object res=connect_promise.getResult(); // waits forever until connected (or channel is closed)
if(res != null && res instanceof Exception) { // the JOIN was rejected by the coordinator
throw new ChannelException("connect() failed", (Throwable)res);
}
//if FLUSH is used do not return from connect() until UNBLOCK event is received
boolean singletonMember = my_view != null && my_view.size() == 1;
boolean shouldWaitForUnblock = flush_supported && receive_blocks && !singletonMember && !flush_unblock_promise.hasResult();
if(shouldWaitForUnblock){
try{
flush_unblock_promise.getResultWithTimeout(FLUSH_UNBLOCK_TIMEOUT);
}
catch (TimeoutException te){
if(log.isWarnEnabled())
log.warn("waiting on UNBLOCK after connect timed out");
}
}
}
connected=true;
notifyChannelConnected(this);
}
public synchronized boolean connect(String cluster_name, Address target, String state_id, long timeout) throws ChannelException {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Disconnects the channel if it is connected. If the channel is closed, this operation is ignored<BR>
* Otherwise the following actions happen in the listed order<BR>
* <ol>
* <li> The JChannel sends a DISCONNECT event down the protocol stack<BR>
* <li> Blocks until the channel to receives a DISCONNECT_OK event<BR>
* <li> Sends a STOP_QUEING event down the stack<BR>
* <li> Stops the protocol stack by calling ProtocolStack.stop()<BR>
* <li> Notifies the listener, if the listener is available<BR>
* </ol>
*/
public synchronized void disconnect() {
if(closed) return;
if(connected) {
if(cluster_name != null) {
/* Send down a DISCONNECT event. The DISCONNECT event travels down to the GMS, where a
* DISCONNECT_OK response is generated and sent up the stack. JChannel blocks until a
* DISCONNECT_OK has been received, or until timeout has elapsed.
*/
Event disconnect_event=new Event(Event.DISCONNECT, local_addr);
disconnect_promise.reset();
down(disconnect_event); // DISCONNECT is handled by each layer
disconnect_promise.getResult(); // wait for DISCONNECT_OK
}
// Just in case we use the QUEUE protocol and it is still blocked...
down(new Event(Event.STOP_QUEUEING));
connected=false;
try {
prot_stack.stopStack(); // calls stop() in all protocols, from top to bottom
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
notifyChannelDisconnected(this);
init(); // sets local_addr=null; changed March 18 2003 (bela) -- prevented successful rejoining
}
}
/**
* Destroys the channel.
* After this method has been called, the channel us unusable.<BR>
* This operation will disconnect the channel and close the channel receive queue immediately<BR>
*/
public synchronized void close() {
_close(true, true); // by default disconnect before closing channel and close mq
}
/** Shuts down the channel without disconnecting */
public synchronized void shutdown() {
_close(false, true); // by default disconnect before closing channel and close mq
}
/**
* Opens the channel.
* This does the following actions:
* <ol>
* <li> Resets the receiver queue by calling Queue.reset
* <li> Sets up the protocol stack by calling ProtocolStack.setup
* <li> Sets the closed flag to false
* </ol>
*/
public synchronized void open() throws ChannelException {
if(!closed)
throw new ChannelException("channel is already open");
try {
mq.reset();
prot_stack=new ProtocolStack(this, props);
prot_stack.setup();
closed=false;
}
catch(Exception e) {
throw new ChannelException("failed to open channel" , e);
}
}
/**
* returns true if the Open operation has been called successfully
*/
public boolean isOpen() {
return !closed;
}
/**
* returns true if the Connect operation has been called successfully
*/
public boolean isConnected() {
return connected;
}
public int getNumMessages() {
return mq != null? mq.size() : -1;
}
public String dumpQueue() {
return Util.dumpQueue(mq);
}
/**
* Returns a map of statistics of the various protocols and of the channel itself.
* @return Map<String,Map>. A map where the keys are the protocols ("channel" pseudo key is
* used for the channel itself") and the values are property maps.
*/
public Map dumpStats() {
Map retval=prot_stack.dumpStats();
if(retval != null) {
Map tmp=dumpChannelStats();
if(tmp != null)
retval.put("channel", tmp);
}
return retval;
}
private Map dumpChannelStats() {
Map retval=new HashMap();
retval.put("sent_msgs", new Long(sent_msgs));
retval.put("sent_bytes", new Long(sent_bytes));
retval.put("received_msgs", new Long(received_msgs));
retval.put("received_bytes", new Long(received_bytes));
return retval;
}
/**
* Sends a message through the protocol stack.
* Implements the Transport interface.
*
* @param msg the message to be sent through the protocol stack,
* the destination of the message is specified inside the message itself
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
*/
public void send(Message msg) throws ChannelNotConnectedException, ChannelClosedException {
checkClosed();
checkNotConnected();
if(stats) {
sent_msgs++;
sent_bytes+=msg.getLength();
}
if(msg == null)
throw new NullPointerException("msg is null");
down(new Event(Event.MSG, msg));
}
/**
* creates a new message with the destination address, and the source address
* and the object as the message value
* @param dst - the destination address of the message, null for all members
* @param src - the source address of the message
* @param obj - the value of the message
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
* @see JChannel#send
*/
public void send(Address dst, Address src, Serializable obj) throws ChannelNotConnectedException, ChannelClosedException {
send(new Message(dst, src, obj));
}
/**
* Blocking receive method.
* This method returns the object that was first received by this JChannel and that has not been
* received before. After the object is received, it is removed from the receive queue.<BR>
* If you only want to inspect the object received without removing it from the queue call
* JChannel.peek<BR>
* If no messages are in the receive queue, this method blocks until a message is added or the operation times out<BR>
* By specifying a timeout of 0, the operation blocks forever, or until a message has been received.
* @param timeout the number of milliseconds to wait if the receive queue is empty. 0 means wait forever
* @exception TimeoutException if a timeout occured prior to a new message was received
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
* @see JChannel#peek
*/
public Object receive(long timeout) throws ChannelNotConnectedException, ChannelClosedException, TimeoutException {
checkClosed();
checkNotConnected();
try {
Event evt=(timeout <= 0)? (Event)mq.remove() : (Event)mq.remove(timeout);
Object retval=getEvent(evt);
evt=null;
if(stats) {
if(retval != null && retval instanceof Message) {
received_msgs++;
received_bytes+=((Message)retval).getLength();
}
}
return retval;
}
catch(QueueClosedException queue_closed) {
throw new ChannelClosedException();
}
catch(TimeoutException t) {
throw t;
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
return null;
}
}
/**
* Just peeks at the next message, view or block. Does <em>not</em> install
* new view if view is received<BR>
* Does the same thing as JChannel.receive but doesn't remove the object from the
* receiver queue
*/
public Object peek(long timeout) throws ChannelNotConnectedException, ChannelClosedException, TimeoutException {
checkClosed();
checkNotConnected();
try {
Event evt=(timeout <= 0)? (Event)mq.peek() : (Event)mq.peek(timeout);
Object retval=getEvent(evt);
evt=null;
return retval;
}
catch(QueueClosedException queue_closed) {
if(log.isErrorEnabled()) log.error("exception: " + queue_closed);
return null;
}
catch(TimeoutException t) {
return null;
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
return null;
}
}
/**
* Returns the current view.
* <BR>
* If the channel is not connected or if it is closed it will return null.
* <BR>
* @return returns the current group view, or null if the channel is closed or disconnected
*/
public View getView() {
return closed || !connected ? null : my_view;
}
/**
* returns the local address of the channel
* returns null if the channel is closed
*/
public Address getLocalAddress() {
return closed ? null : local_addr;
}
/**
* returns the name of the channel
* if the channel is not connected or if it is closed it will return null
* @deprecated Use {@link #getClusterName()} instead
*/
public String getChannelName() {
return closed ? null : !connected ? null : cluster_name;
}
public String getClusterName() {
return cluster_name;
}
/**
* Sets a channel option. The options can be one of the following:
* <UL>
* <LI> Channel.BLOCK
* <LI> Channel.LOCAL
* <LI> Channel.AUTO_RECONNECT
* <LI> Channel.AUTO_GETSTATE
* </UL>
* <P>
* There are certain dependencies between the options that you can set,
* I will try to describe them here.
* <P>
* Option: Channel.BLOCK<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true will set setOpt(VIEW, true) and the JChannel will receive BLOCKS and VIEW events<BR>
*<BR>
* Option: LOCAL<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true the JChannel will receive messages that it self sent out.<BR>
*<BR>
* Option: AUTO_RECONNECT<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true and the JChannel will try to reconnect when it is being closed<BR>
*<BR>
* Option: AUTO_GETSTATE<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true, the AUTO_RECONNECT will be set to true and the JChannel will try to get the state after a close and reconnect happens<BR>
* <BR>
*
* @param option the parameter option Channel.VIEW, Channel.SUSPECT, etc
* @param value the value to set for this option
*
*/
public void setOpt(int option, Object value) {
if(closed) {
if(log.isWarnEnabled()) log.warn("channel is closed; option not set !");
return;
}
switch(option) {
case VIEW:
if(log.isWarnEnabled())
log.warn("option VIEW has been deprecated (it is always true now); this option is ignored");
break;
case SUSPECT:
if(log.isWarnEnabled())
log.warn("option SUSPECT has been deprecated (it is always true now); this option is ignored");
break;
case BLOCK:
if(value instanceof Boolean)
receive_blocks=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case GET_STATE_EVENTS:
if(log.isWarnEnabled())
log.warn("option GET_STATE_EVENTS has been deprecated (it is always true now); this option is ignored");
break;
case LOCAL:
if(value instanceof Boolean)
receive_local_msgs=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case AUTO_RECONNECT:
if(value instanceof Boolean)
auto_reconnect=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case AUTO_GETSTATE:
if(value instanceof Boolean) {
auto_getstate=((Boolean)value).booleanValue();
if(auto_getstate)
auto_reconnect=true;
}
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
default:
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) + " not known");
break;
}
}
/**
* returns the value of an option.
* @param option the option you want to see the value for
* @return the object value, in most cases java.lang.Boolean
* @see JChannel#setOpt
*/
public Object getOpt(int option) {
switch(option) {
case VIEW:
return Boolean.TRUE;
case BLOCK:
return receive_blocks ? Boolean.TRUE : Boolean.FALSE;
case SUSPECT:
return Boolean.TRUE;
case AUTO_RECONNECT:
return auto_reconnect ? Boolean.TRUE : Boolean.FALSE;
case AUTO_GETSTATE:
return auto_getstate ? Boolean.TRUE : Boolean.FALSE;
case GET_STATE_EVENTS:
return Boolean.TRUE;
case LOCAL:
return receive_local_msgs ? Boolean.TRUE : Boolean.FALSE;
default:
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) + " not known");
return null;
}
}
/**
* Called to acknowledge a block() (callback in <code>MembershipListener</code> or
* <code>BlockEvent</code> received from call to <code>receive()</code>).
* After sending blockOk(), no messages should be sent until a new view has been received.
* Calling this method on a closed channel has no effect.
*/
public void blockOk() {
down(new Event(Event.BLOCK_OK));
down(new Event(Event.START_QUEUEING));
}
/**
* Retrieves the current group state. Sends GET_STATE event down to STATE_TRANSFER layer.
* Blocks until STATE_TRANSFER sends up a GET_STATE_OK event or until <code>timeout</code>
* milliseconds have elapsed. The argument of GET_STATE_OK should be a single object.
* @param target the target member to receive the state from. if null, state is retrieved from coordinator
* @param timeout the number of milliseconds to wait for the operation to complete successfully. 0 waits until
* the state has been received
* @return true of the state was received, false if the operation timed out
*/
public boolean getState(Address target, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
return getState(target,null,timeout);
}
/**
* Retrieves a substate (or partial state) from the target.
* @param target State provider. If null, coordinator is used
* @param state_id The ID of the substate. If null, the entire state will be transferred
* @param timeout the number of milliseconds to wait for the operation to complete successfully. 0 waits until
* the state has been received
* @return
* @throws ChannelNotConnectedException
* @throws ChannelClosedException
*/
public boolean getState(Address target, String state_id, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
if(target == null)
target=determineCoordinator();
if(target != null && local_addr != null && target.equals(local_addr)) {
if(log.isTraceEnabled())
log.trace("cannot get state from myself (" + target + "): probably the first member");
return false;
}
StateTransferInfo info=new StateTransferInfo(target, state_id, timeout);
boolean rc=_getState(new Event(Event.GET_STATE, info), info);
if(rc == false)
down(new Event(Event.RESUME_STABLE));
return rc;
}
/**
* Retrieves the current group state. Sends GET_STATE event down to STATE_TRANSFER layer.
* Blocks until STATE_TRANSFER sends up a GET_STATE_OK event or until <code>timeout</code>
* milliseconds have elapsed. The argument of GET_STATE_OK should be a vector of objects.
* @param targets - the target members to receive the state from ( an Address list )
* @param timeout - the number of milliseconds to wait for the operation to complete successfully
* @return true of the state was received, false if the operation timed out
* @deprecated Not really needed - we always want to get the state from a single member,
* use {@link #getState(org.jgroups.Address, long)} instead
*/
public boolean getAllStates(Vector targets, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
throw new UnsupportedOperationException("use getState() instead");
}
/**
* Called by the application is response to receiving a <code>getState()</code> object when
* calling <code>receive()</code>.
* When the application receives a getState() message on the receive() method,
* it should call returnState() to reply with the state of the application
* @param state The state of the application as a byte buffer
* (to send over the network).
*/
public void returnState(byte[] state) {
StateTransferInfo info=new StateTransferInfo(null, null, 0L, state);
down(new Event(Event.GET_APPLSTATE_OK, info));
}
/**
* Returns a substate as indicated by state_id
* @param state
* @param state_id
*/
public void returnState(byte[] state, String state_id) {
StateTransferInfo info=new StateTransferInfo(null, state_id, 0L, state);
down(new Event(Event.GET_APPLSTATE_OK, info));
}
/**
* Callback method <BR>
* Called by the ProtocolStack when a message is received.
* It will be added to the message queue from which subsequent
* <code>Receive</code>s will dequeue it.
* @param evt the event carrying the message from the protocol stack
*/
public void up(Event evt) {
int type=evt.getType();
Message msg;
switch(type) {
case Event.MSG:
msg=(Message)evt.getArg();
if(!receive_local_msgs) { // discard local messages (sent by myself to me)
if(local_addr != null && msg.getSrc() != null)
if(local_addr.equals(msg.getSrc()))
return;
}
break;
case Event.VIEW_CHANGE:
View tmp=(View)evt.getArg();
if(tmp instanceof MergeView)
my_view=new View(tmp.getVid(), tmp.getMembers());
else
my_view=tmp;
// crude solution to bug #775120: if we get our first view *before* the CONNECT_OK,
// we simply set the state to connected
/*
* Bela&Vladimir Oct 10th,2006 - we probably do not need this
*
* if(connected == false) {
connected=true;
connect_promise.setResult(null);
}*/
// unblock queueing of messages due to previous BLOCK event:
down(new Event(Event.STOP_QUEUEING));
break;
case Event.CONFIG:
HashMap config=(HashMap)evt.getArg();
if(config != null) {
if(config.containsKey("state_transfer")) {
state_transfer_supported=((Boolean)config.get("state_transfer")).booleanValue();
}
if(config.containsKey("flush_supported")) {
flush_supported=((Boolean)config.get("flush_supported")).booleanValue();
}
}
break;
case Event.CONNECT_OK:
connect_promise.setResult(evt.getArg());
break;
case Event.SUSPEND_OK:
flush_promise.setResult(Boolean.TRUE);
break;
case Event.DISCONNECT_OK:
disconnect_promise.setResult(Boolean.TRUE);
break;
case Event.GET_STATE_OK:
StateTransferInfo info=(StateTransferInfo)evt.getArg();
byte[] state=info.state;
state_promise.setResult(state != null? Boolean.TRUE : Boolean.FALSE);
if(up_handler != null) {
up_handler.up(evt);
return;
}
if(state != null) {
String state_id=info.state_id;
if(receiver != null) {
if(receiver instanceof ExtendedReceiver && state_id!=null)
((ExtendedReceiver)receiver).setState(state_id, state);
else
receiver.setState(state);
}
else {
try {mq.add(new Event(Event.STATE_RECEIVED, info));} catch(Exception e) {}
}
}
break;
case Event.STATE_TRANSFER_INPUTSTREAM:
StateTransferInfo sti=(StateTransferInfo)evt.getArg();
InputStream is=sti.inputStream;
//Oct 13,2006 moved to down() when Event.STATE_TRANSFER_INPUTSTREAM_CLOSED is received
//state_promise.setResult(is != null? Boolean.TRUE : Boolean.FALSE);
if(up_handler != null) {
up_handler.up(evt);
return;
}
if(is != null) {
if(receiver instanceof ExtendedReceiver) {
if(sti.state_id == null)
((ExtendedReceiver)receiver).setState(is);
else
((ExtendedReceiver)receiver).setState(sti.state_id, is);
}
else {
try {
mq.add(new Event(Event.STATE_TRANSFER_INPUTSTREAM, sti));
}
catch(Exception e) {
}
}
}
break;
case Event.SET_LOCAL_ADDRESS:
local_addr_promise.setResult(evt.getArg());
break;
case Event.EXIT:
handleExit(evt);
return; // no need to pass event up; already done in handleExit()
default:
break;
}
// If UpHandler is installed, pass all events to it and return (UpHandler is e.g. a building block)
if(up_handler != null) {
up_handler.up(evt);
if(type == Event.UNBLOCK){
flush_unblock_promise.setResult(Boolean.TRUE);
}
return;
}
switch(type) {
case Event.MSG:
if(receiver != null) {
receiver.receive((Message)evt.getArg());
return;
}
break;
case Event.VIEW_CHANGE:
if(receiver != null) {
receiver.viewAccepted((View)evt.getArg());
return;
}
break;
case Event.SUSPECT:
if(receiver != null) {
receiver.suspect((Address)evt.getArg());
return;
}
break;
case Event.GET_APPLSTATE:
if(receiver != null) {
StateTransferInfo info=(StateTransferInfo)evt.getArg();
byte[] tmp_state;
String state_id=info.state_id;
if(receiver instanceof ExtendedReceiver && state_id!=null) {
tmp_state=((ExtendedReceiver)receiver).getState(state_id);
}
else {
tmp_state=receiver.getState();
}
returnState(tmp_state, state_id);
return;
}
break;
case Event.STATE_TRANSFER_OUTPUTSTREAM:
if(receiver != null) {
StateTransferInfo sti=(StateTransferInfo)evt.getArg();
OutputStream os=sti.outputStream;
if(os != null && receiver instanceof ExtendedReceiver) {
if(sti.state_id == null)
((ExtendedReceiver)receiver).getState(os);
else
((ExtendedReceiver)receiver).getState(sti.state_id, os);
}
return;
}
break;
case Event.BLOCK:
if(!receive_blocks) { // discard if client has not set 'receiving blocks' to 'on'
down(new Event(Event.BLOCK_OK));
down(new Event(Event.START_QUEUEING));
return;
}
if(receiver != null) {
try {
receiver.block();
}
catch(Throwable t) {
if(log.isErrorEnabled())
log.error("failed calling block() on Receiver", t);
}
finally {
blockOk();
}
return;
}
break;
case Event.UNBLOCK:
//discard if client has not set 'receiving blocks' to 'on'
if(!receive_blocks) {
return;
}
if(receiver instanceof ExtendedReceiver) {
try {
((ExtendedReceiver)receiver).unblock();
}
catch(Throwable t) {
if(log.isErrorEnabled())
log.error("failed calling unblock() on Receiver", t);
}
finally{
flush_unblock_promise.setResult(Boolean.TRUE);
}
return;
}
break;
default:
break;
}
if(type == Event.MSG || type == Event.VIEW_CHANGE || type == Event.SUSPECT ||
type == Event.GET_APPLSTATE || type== Event.STATE_TRANSFER_OUTPUTSTREAM
|| type == Event.BLOCK || type == Event.UNBLOCK) {
try {
mq.add(evt);
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception adding event " + evt + " to message queue", e);
}
}
}
/**
* Sends a message through the protocol stack if the stack is available
* @param evt the message to send down, encapsulated in an event
*/
public void down(Event evt) {
if(evt == null) return;
// handle setting of additional data (kludge, will be removed soon)
if(evt.getType() == Event.CONFIG) {
try {
Map m=(Map)evt.getArg();
if(m != null && m.containsKey("additional_data")) {
additional_data=(byte[])m.get("additional_data");
if(local_addr instanceof IpAddress)
((IpAddress)local_addr).setAdditionalData(additional_data);
}
}
catch(Throwable t) {
if(log.isErrorEnabled()) log.error("CONFIG event did not contain a hashmap: " + t);
}
}
if(evt.getType() == Event.STATE_TRANSFER_INPUTSTREAM_CLOSED){
state_promise.setResult(Boolean.TRUE);
}
if(prot_stack != null)
prot_stack.down(evt);
else
if(log.isErrorEnabled()) log.error("no protocol stack available");
}
public String toString(boolean details) {
StringBuffer sb=new StringBuffer();
sb.append("local_addr=").append(local_addr).append('\n');
sb.append("cluster_name=").append(cluster_name).append('\n');
sb.append("my_view=").append(my_view).append('\n');
sb.append("connected=").append(connected).append('\n');
sb.append("closed=").append(closed).append('\n');
if(mq != null)
sb.append("incoming queue size=").append(mq.size()).append('\n');
if(details) {
sb.append("receive_blocks=").append(receive_blocks).append('\n');
sb.append("receive_local_msgs=").append(receive_local_msgs).append('\n');
sb.append("auto_reconnect=").append(auto_reconnect).append('\n');
sb.append("auto_getstate=").append(auto_getstate).append('\n');
sb.append("state_transfer_supported=").append(state_transfer_supported).append('\n');
sb.append("props=").append(props).append('\n');
}
return sb.toString();
}
protected final void init(ProtocolStackConfigurator configurator) throws ChannelException {
if(log.isInfoEnabled())
log.info("JGroups version: " + Version.description);
ConfiguratorFactory.substituteVariables(configurator); // replace vars with system props
props=configurator.getProtocolStackString();
prot_stack=new ProtocolStack(this, props);
try {
prot_stack.setup(); // Setup protocol stack (create layers, queues between them
}
catch(Throwable e) {
throw new ChannelException("unable to setup the protocol stack", e);
}
}
/**
* Initializes all variables. Used after <tt>close()</tt> or <tt>disconnect()</tt>,
* to be ready for new <tt>connect()</tt>
*/
private void init() {
local_addr=null;
cluster_name=null;
my_view=null;
// changed by Bela Sept 25 2003
//if(mq != null && mq.closed())
// mq.reset();
connect_promise.reset();
disconnect_promise.reset();
connected=false;
}
/**
* health check.<BR>
* throws a ChannelNotConnected exception if the channel is not connected
*/
protected void checkNotConnected() throws ChannelNotConnectedException {
if(!connected)
throw new ChannelNotConnectedException();
}
/**
* health check<BR>
* throws a ChannelClosed exception if the channel is closed
*/
protected void checkClosed() throws ChannelClosedException {
if(closed)
throw new ChannelClosedException();
}
/**
* returns the value of the event<BR>
* These objects will be returned<BR>
* <PRE>
* <B>Event Type - Return Type</B>
* Event.MSG - returns a Message object
* Event.VIEW_CHANGE - returns a View object
* Event.SUSPECT - returns a SuspectEvent object
* Event.BLOCK - returns a new BlockEvent object
* Event.GET_APPLSTATE - returns a GetStateEvent object
* Event.STATE_RECEIVED- returns a SetStateEvent object
* Event.Exit - returns an ExitEvent object
* All other - return the actual Event object
* </PRE>
* @param evt - the event of which you want to extract the value
* @return the event value if it matches the select list,
* returns null if the event is null
* returns the event itself if a match (See above) can not be made of the event type
*/
static Object getEvent(Event evt) {
if(evt == null)
return null; // correct ?
switch(evt.getType()) {
case Event.MSG:
return evt.getArg();
case Event.VIEW_CHANGE:
return evt.getArg();
case Event.SUSPECT:
return new SuspectEvent(evt.getArg());
case Event.BLOCK:
return new BlockEvent();
case Event.UNBLOCK:
return new UnblockEvent();
case Event.GET_APPLSTATE:
StateTransferInfo info=(StateTransferInfo)evt.getArg();
return new GetStateEvent(info.target, info.state_id);
case Event.STATE_RECEIVED:
info=(StateTransferInfo)evt.getArg();
return new SetStateEvent(info.state, info.state_id);
case Event.STATE_TRANSFER_OUTPUTSTREAM:
info = (StateTransferInfo)evt.getArg();
return new StreamingGetStateEvent(info.outputStream,info.state_id);
case Event.STATE_TRANSFER_INPUTSTREAM:
info = (StateTransferInfo)evt.getArg();
return new StreamingSetStateEvent(info.inputStream,info.state_id);
case Event.EXIT:
return new ExitEvent();
default:
return evt;
}
}
/**
* Receives the state from the group and modifies the JChannel.state object<br>
* This method initializes the local state variable to null, and then sends the state
* event down the stack. It waits for a GET_STATE_OK event to bounce back
* @param evt the get state event, has to be of type Event.GET_STATE
* @param info Information about the state transfer, e.g. target member and timeout
* @return true of the state was received, false if the operation timed out
*/
private boolean _getState(Event evt, StateTransferInfo info) throws ChannelNotConnectedException, ChannelClosedException {
checkClosed();
checkNotConnected();
if(!state_transfer_supported) {
throw new IllegalStateException("fetching state will fail as state transfer is not supported. "
+ "Add one of the STATE_TRANSFER protocols to your protocol configuration");
}
if(flush_supported)
flush_unblock_promise.reset();
state_promise.reset();
down(evt);
Boolean state_transfer_successfull=(Boolean)state_promise.getResult(info.timeout);
//if FLUSH is used do not return from getState() until UNBLOCK event is received
boolean shouldWaitForUnblock = flush_supported && receive_blocks;
if(shouldWaitForUnblock){
try{
flush_unblock_promise.getResultWithTimeout(FLUSH_UNBLOCK_TIMEOUT);
}
catch (TimeoutException te){
if(log.isWarnEnabled())
log.warn("Waiting on UNBLOCK after getState timed out");
}
}
return state_transfer_successfull != null && state_transfer_successfull.booleanValue();
}
/**
* Disconnects and closes the channel.
* This method does the folloing things
* <ol>
* <li>Calls <code>this.disconnect</code> if the disconnect parameter is true
* <li>Calls <code>Queue.close</code> on mq if the close_mq parameter is true
* <li>Calls <code>ProtocolStack.stop</code> on the protocol stack
* <li>Calls <code>ProtocolStack.destroy</code> on the protocol stack
* <li>Sets the channel closed and channel connected flags to true and false
* <li>Notifies any channel listener of the channel close operation
* </ol>
*/
protected void _close(boolean disconnect, boolean close_mq) {
if(closed)
return;
if(disconnect)
disconnect(); // leave group if connected
if(close_mq) {
try {
if(mq != null)
mq.close(false); // closes and removes all messages
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
}
if(prot_stack != null) {
try {
prot_stack.stopStack();
prot_stack.destroy();
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("failed destroying the protocol stack", e);
}
}
closed=true;
connected=false;
notifyChannelClosed(this);
init(); // sets local_addr=null; changed March 18 2003 (bela) -- prevented successful rejoining
}
public final void closeMessageQueue(boolean flush_entries) {
if(mq != null)
mq.close(flush_entries);
}
/**
* Creates a separate thread to close the protocol stack.
* This is needed because the thread that called JChannel.up() with the EXIT event would
* hang waiting for up() to return, while up() actually tries to kill that very thread.
* This way, we return immediately and allow the thread to terminate.
*/
private void handleExit(Event evt) {
notifyChannelShunned();
if(closer != null && !closer.isAlive())
closer=null;
if(closer == null) {
if(log.isInfoEnabled())
log.info("received an EXIT event, will leave the channel");
closer=new CloserThread(evt);
closer.start();
}
}
boolean startFlush(long timeout) {
if(!flush_supported) {
throw new IllegalStateException("Flush is not supported, add pbcast.FLUSH protocol to your configuration");
}
boolean successfulFlush=false;
down(new Event(Event.SUSPEND));
try {
flush_promise.reset();
flush_promise.getResultWithTimeout(timeout);
successfulFlush=true;
}
catch(TimeoutException e) {
}
return successfulFlush;
}
void stopFlush() {
if(!flush_supported) {
throw new IllegalStateException("Flush is not supported, add pbcast.FLUSH protocol to your configuration");
}
down(new Event(Event.RESUME));
}
Address determineCoordinator() {
Vector mbrs=my_view != null? my_view.getMembers() : null;
if(mbrs == null)
return null;
if(mbrs.size() > 0)
return (Address)mbrs.firstElement();
return null;
}
class CloserThread extends Thread {
final Event evt;
final Thread t=null;
CloserThread(Event evt) {
super(Util.getGlobalThreadGroup(), "CloserThread");
this.evt=evt;
setDaemon(true);
}
public void run() {
try {
String old_cluster_name=cluster_name; // remember because close() will null it
if(log.isInfoEnabled())
log.info("closing the channel");
_close(false, false); // do not disconnect before closing channel, do not close mq (yet !)
if(up_handler != null)
up_handler.up(this.evt);
else {
try {
if(receiver == null)
mq.add(this.evt);
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception: " + ex);
}
}
if(mq != null) {
Util.sleep(500); // give the mq thread a bit of time to deliver EXIT to the application
try {
mq.close(false);
}
catch(Exception ex) {
}
}
if(auto_reconnect) {
try {
if(log.isInfoEnabled()) log.info("reconnecting to group " + old_cluster_name);
open();
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("failure reopening channel: " + ex);
return;
}
try {
if(additional_data != null) {
// send previously set additional_data down the stack - other protocols (e.g. TP) use it
Map m=new HashMap(11);
m.put("additional_data", additional_data);
down(new Event(Event.CONFIG, m));
}
connect(old_cluster_name);
notifyChannelReconnected(local_addr);
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("failure reconnecting to channel: " + ex);
return;
}
}
if(auto_getstate) {
if(log.isInfoEnabled())
log.info("fetching the state (auto_getstate=true)");
boolean rc=JChannel.this.getState(null, GET_STATE_DEFAULT_TIMEOUT);
if(log.isInfoEnabled()) {
if(rc)
log.info("state was retrieved successfully");
else
log.info("state transfer failed");
}
}
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception: " + ex);
}
finally {
closer=null;
}
}
}
} |
package org.mockito;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hamcrest.Matcher;
import org.mockito.internal.matchers.*;
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
import org.mockito.internal.progress.HandyReturnValues;
import org.mockito.internal.progress.MockingProgress;
import org.mockito.internal.progress.ThreadSafeMockingProgress;
/**
* Allow flexible verification or stubbing. See also {@link AdditionalMatchers}.
* <p>
* {@link Mockito} extends Matchers so to get access to all matchers just import Mockito class statically.
* <pre>
* //stubbing using anyInt() argument matcher
* when(mockedList.get(anyInt())).thenReturn("element");
*
* //following prints "element"
* System.out.println(mockedList.get(999));
*
* //you can also verify using argument matcher
* verify(mockedList).get(anyInt());
* </pre>
* Scroll down to see all methods - full list of matchers.
* <p>
* <b>Warning:</b>
* <p>
* If you are using argument matchers, <b>all arguments</b> have to be provided by matchers.
* <p>
* E.g: (example shows verification but the same applies to stubbing):
* <pre>
* verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
* //above is correct - eq() is also an argument matcher
*
* verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
* //above is incorrect - exception will be thrown because third argument is given without argument matcher.
* </pre>
*
* <h1>Custom Argument Matchers</h1>
*
* Use {@link Matchers#argThat} method and pass an instance of hamcrest {@link Matcher}.
* <p>
* Before you start implementing your own custom argument matcher, make sure you check out {@link ArgumentCaptor} api.
* <p>
* So, how to implement your own argument matcher?
* First, you might want to subclass {@link ArgumentMatcher} which is an hamcrest matcher with predefined describeTo() method.
* Default description generated by describeTo() uses <b>decamelized class name</b> - to promote meaningful class names.
* <p>
* Example:
*
* <pre>
* class IsListOfTwoElements extends ArgumentMatcher<List> {
* public boolean matches(Object list) {
* return ((List) list).size() == 2;
* }
* }
*
* List mock = mock(List.class);
*
* when(mock.addAll(argThat(new IsListOfTwoElements()))).thenReturn(true);
*
* mock.addAll(Arrays.asList("one", "two"));
*
* verify(mock).addAll(argThat(new IsListOfTwoElements()));
* </pre>
*
* To keep it readable you may want to extract method, e.g:
* <pre>
* verify(mock).addAll(<b>argThat(new IsListOfTwoElements())</b>);
* //becomes
* verify(mock).addAll(<b>listOfTwoElements()</b>);
* </pre>
*
* <b>Warning:</b> Be reasonable with using complicated argument matching, especially custom argument matchers, as it can make the test less readable.
* Sometimes it's better to implement equals() for arguments that are passed to mocks
* (Mockito naturally uses equals() for argument matching).
* This can make the test cleaner.
* <p>
* Also, <b>sometimes {@link ArgumentCaptor} may be a better fit</b> than custom matcher.
* For example, if custom argument matcher is not likely to be reused
* or you just need it to assert on argument values to complete verification of behavior.
*/
@SuppressWarnings("unchecked")
public class Matchers {
private static MockingProgress mockingProgress = new ThreadSafeMockingProgress();
/**
* any boolean, Boolean or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>false</code>.
*/
public static boolean anyBoolean() {
return reportMatcher(Any.ANY).returnFalse();
}
/**
* any byte, Byte or null
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static byte anyByte() {
return reportMatcher(Any.ANY).returnZero();
}
/**
* any char, Character or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static char anyChar() {
return reportMatcher(Any.ANY).returnChar();
}
/**
* any int, Integer or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static int anyInt() {
return reportMatcher(Any.ANY).returnZero();
}
/**
* any long, Long or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static long anyLong() {
return reportMatcher(Any.ANY).returnZero();
}
/**
* any float, Float or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static float anyFloat() {
return reportMatcher(Any.ANY).returnZero();
}
/**
* any double, Double or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static double anyDouble() {
return reportMatcher(Any.ANY).returnZero();
}
/**
* any short, Short or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>0</code>.
*/
public static short anyShort() {
return reportMatcher(Any.ANY).returnZero();
}
/**
* any Object or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static <T> T anyObject() {
return (T) reportMatcher(Any.ANY).returnNull();
}
//TODO: after 1.8 check out Jay Fields' idea on any() matcher
/**
* Any vararg, meaning any number and values of arguments.
* <p>
* Example:
* <pre>
* //verification:
* mock.foo(1, 2);
* mock.foo(1, 2, 3, 4);
*
* verify(mock, times(2)).foo(anyVararg());
*
* //stubbing:
* when(mock.foo(anyVararg()).thenReturn(100);
*
* //prints 100
* System.out.println(mock.foo(1, 2));
* //also prints 100
* System.out.println(mock.foo(1, 2, 3, 4));
* </pre>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static <T> T anyVararg() {
return (T) reportMatcher(AnyVararg.ANY_VARARG).returnNull();
}
/**
* any kind object, not necessary of the given class.
* The class argument is provided only to avoid casting.
* <p>
* Sometimes looks better than anyObject() - especially when explicit casting is required
* <p>
* Alias to {@link Matchers#anyObject()}
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static <T> T any(Class<T> clazz) {
return (T) anyObject();
}
/**
* any object or null
* <p>
* Shorter alias to {@link Matchers#anyObject()}
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static <T> T any() {
return (T) anyObject();
}
/**
* any String or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty String ("")
*/
public static String anyString() {
return reportMatcher(Any.ANY).returnString();
}
/**
* any List or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty List.
*/
public static List anyList() {
return reportMatcher(Any.ANY).returnList();
}
/**
* generic friendly alias to {@link Matchers#anyList()}.
* It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
* <p>
* any List or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty List.
*/
public static <T> List<T> anyListOf(Class<T> clazz) {
return (List) reportMatcher(Any.ANY).returnList();
}
/**
* any Set or null
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty Set
*/
public static Set anySet() {
return reportMatcher(Any.ANY).returnSet();
}
/**
* generic friendly alias to {@link Matchers#anySet()}.
* It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
* <p>
* any Set or null
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty Set
*/
public static <T> Set<T> anySetOf(Class<T> clazz) {
return (Set) reportMatcher(Any.ANY).returnSet();
}
/**
* any Map or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty Map.
*/
public static Map anyMap() {
return reportMatcher(Any.ANY).returnMap();
}
/**
* any Collection or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty Collection.
*/
public static Collection anyCollection() {
return reportMatcher(Any.ANY).returnList();
}
/**
* generic friendly alias to {@link Matchers#anyCollection()}.
* It's an alternative to @SuppressWarnings("unchecked") to keep code clean of compiler warnings.
* <p>
* any Collection or null.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return empty Collection.
*/
public static <T> Collection<T> anyCollectionOf(Class<T> clazz) {
return (Collection) reportMatcher(Any.ANY).returnList();
}
/**
* Object argument that implements the given class.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param <T>
* the accepted type.
* @param clazz
* the class of the accepted type.
* @return <code>null</code>.
*/
public static <T> T isA(Class<T> clazz) {
return reportMatcher(new InstanceOf(clazz)).<T>returnFor(clazz);
}
/**
* boolean argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>0</code>.
*/
public static boolean eq(boolean value) {
return reportMatcher(new Equals(value)).returnFalse();
}
/**
* byte argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>0</code>.
*/
public static byte eq(byte value) {
return reportMatcher(new Equals(value)).returnZero();
}
/**
* char argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>0</code>.
*/
public static char eq(char value) {
return reportMatcher(new Equals(value)).returnChar();
}
/**
* double argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>0</code>.
*/
public static double eq(double value) {
return reportMatcher(new Equals(value)).returnZero();
}
/**
* float argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>0</code>.
*/
public static float eq(float value) {
return reportMatcher(new Equals(value)).returnZero();
}
/**
* int argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>0</code>.
*/
public static int eq(int value) {
return reportMatcher(new Equals(value)).returnZero();
}
/**
* long argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>0</code>.
*/
public static long eq(long value) {
return reportMatcher(new Equals(value)).returnZero();
}
/**
* short argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>0</code>.
*/
public static short eq(short value) {
return reportMatcher(new Equals(value)).returnZero();
}
/**
* Object argument that is equal to the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @return <code>null</code>.
*/
public static <T> T eq(T value) {
return (T) reportMatcher(new Equals(value)).<T>returnFor(value);
}
/**
* Object argument that is reflection-equal to the given value with support for excluding
* selected fields from a class.
* <p>
* This matcher can be used when equals() is not implemented on compared objects.
* Matcher uses java reflection API to compare fields of wanted and actual object.
* <p>
* Works similarly to EqualsBuilder.reflectionEquals(this, other, exlucdeFields) from
* apache commons library.
* <p>
* <b>Warning</b> The equality check is shallow!
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param value
* the given value.
* @param excludeFields
* fields to exclude, if field does not exist it is ignored.
* @return <code>null</code>.
*/
public static <T> T refEq(T value, String... excludeFields) {
return reportMatcher(new ReflectionEquals(value, excludeFields)).<T>returnNull();
}
/**
* Object argument that is the same as the given value.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param <T>
* the type of the object, it is passed through to prevent casts.
* @param value
* the given value.
* @return <code>null</code>.
*/
public static <T> T same(T value) {
return (T) reportMatcher(new Same(value)).<T>returnFor(value);
}
/**
* null argument.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static Object isNull() {
return reportMatcher(Null.NULL).returnNull();
}
/**
* not null argument.
* <p>
* alias to {@link Matchers#isNotNull()}
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static Object notNull() {
return reportMatcher(NotNull.NOT_NULL).returnNull();
}
/**
* not null argument.
* <p>
* alias to {@link Matchers#notNull()}
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static Object isNotNull() {
return notNull();
}
/**
* String argument that contains the given substring.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param substring
* the substring.
* @return empty String ("").
*/
public static String contains(String substring) {
return reportMatcher(new Contains(substring)).returnString();
}
/**
* String argument that matches the given regular expression.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param regex
* the regular expression.
* @return empty String ("").
*/
public static String matches(String regex) {
return reportMatcher(new Matches(regex)).returnString();
}
/**
* String argument that ends with the given suffix.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param suffix
* the suffix.
* @return empty String ("").
*/
public static String endsWith(String suffix) {
return reportMatcher(new EndsWith(suffix)).returnString();
}
/**
* String argument that starts with the given prefix.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param prefix
* the prefix.
* @return empty String ("").
*/
public static String startsWith(String prefix) {
return reportMatcher(new StartsWith(prefix)).returnString();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link ArgumentMatcher} class
*
* @param matcher decides whether argument matches
* @return <code>null</code>.
*/
public static <T> T argThat(Matcher<T> matcher) {
return reportMatcher(matcher).<T>returnNull();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static char charThat(Matcher<Character> matcher) {
return reportMatcher(matcher).returnChar();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param matcher decides whether argument matches
* @return <code>false</code>.
*/
public static boolean booleanThat(Matcher<Boolean> matcher) {
return reportMatcher(matcher).returnFalse();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static byte byteThat(Matcher<Byte> matcher) {
return reportMatcher(matcher).returnZero();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static short shortThat(Matcher<Short> matcher) {
return reportMatcher(matcher).returnZero();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static int intThat(Matcher<Integer> matcher) {
return reportMatcher(matcher).returnZero();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static long longThat(Matcher<Long> matcher) {
return reportMatcher(matcher).returnZero();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static float floatThat(Matcher<Float> matcher) {
return reportMatcher(matcher).returnZero();
}
/**
* Allows creating custom argument matchers.
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @param matcher decides whether argument matches
* @return <code>0</code>.
*/
public static double doubleThat(Matcher<Double> matcher) {
return reportMatcher(matcher).returnZero();
}
private static HandyReturnValues reportMatcher(Matcher<?> matcher) {
return mockingProgress.getArgumentMatcherStorage().reportMatcher(matcher);
}
} |
package de.lmu.ifi.dbs.algorithm;
import de.lmu.ifi.dbs.data.DatabaseObject;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.database.IndexDatabase;
import de.lmu.ifi.dbs.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.utilities.Util;
import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings;
import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* AbstractAlgorithm sets the values for flags verbose and time. <p/> Any
* Algorithm that makes use of these flags may extend this class. Beware to make
* correct use of parameter settings via optionHandler as commented with
* constructor and methods.
*
* @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>)
*/
public abstract class AbstractAlgorithm<O extends DatabaseObject> implements Algorithm<O>
{
/**
* Holds the class specific debug status.
*/
private static final boolean DEBUG = LoggingConfiguration.DEBUG;
/**
* The logger of this class.
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Flag to allow verbose messages.
*/
public static final String VERBOSE_F = "verbose";
/**
* Description for verbose flag.
*/
public static final String VERBOSE_D = "flag to allow verbose messages while performing the algorithm";
/**
* Flag to assess runtime.
*/
public static final String TIME_F = "time";
/**
* Description for time flag.
*/
public static final String TIME_D = "flag to request output of performance time";
/**
* Map providing a mapping of parameters to their descriptions.
*/
protected Map<String, String> parameterToDescription;
/**
* OptionHandler to handle options. optionHandler should be initialized
* using parameterToDescription in any non-abstract class extending this
* class.
*/
protected OptionHandler optionHandler;
/**
* Property whether verbose messages should be allowed.
*/
private boolean verbose;
/**
* Property whether runtime should be assessed.
*/
private boolean time;
/**
* Holds the currently set parameter array.
*/
private String[] currentParameterArray = new String[0];
/**
* Sets the flags for verbose and time in the parameter map. Any extending
* class should call this constructor, then add further parameters. If any
* non-abstract extending class adds further parameters, it has to finally
* initialize optionHandler like this: <p/> <p/> <p/> <p/>
*
* <pre>
* {
* parameterToDescription.put(YOUR_PARAMETER_NAME+OptionHandler.EXPECTS_VALUE,YOUR_PARAMETER_DESCRIPTION);
* ...
* optionHandler = new OptionHandler(parameterToDescription,yourClass.class.getName());
* }
* </pre>
*/
protected AbstractAlgorithm()
{
parameterToDescription = new Hashtable<String, String>();
parameterToDescription.put(VERBOSE_F, VERBOSE_D);
parameterToDescription.put(TIME_F, TIME_D);
optionHandler = new OptionHandler(parameterToDescription, this.getClass().getName());
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#description()
*/
public String description()
{
return optionHandler.usage("", false);
}
/**
* Sets the values for verbose and time flags. Any extending class should
* call this method first and return the returned array without further
* changes, but after setting further required parameters. <p/> An example
* for overwritting this method taking advantage from the previously (in
* superclasses) defined options would be: <p/> <p/> <p/> <p/>
*
* <pre>
* {
* String[] remainingParameters = super.setParameters(args);
* // set parameters for your class eventually using optionHandler
* <p/>
* ...
* <p/>
* return remainingParameters;
* // or in case of attributes requestingparameters themselves
* // return parameterizableAttribbute.setParameters(remainingParameters);
* }
* </pre>
*
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws ParameterException
{
String[] remainingParameters = optionHandler.grabOptions(args);
verbose = optionHandler.isSet(VERBOSE_F);
time = optionHandler.isSet(TIME_F);
setParameters(args, remainingParameters);
return remainingParameters;
}
/**
* Sets the difference of the first array minus the second array as the
* currently set parameter array.
*
* @param complete
* the complete array
* @param part
* an array that contains only elements of the first array
*/
protected void setParameters(String[] complete, String[] part)
{
currentParameterArray = Util.difference(complete, part);
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#getParameters()
*/
public String[] getParameters()
{
String[] param = new String[currentParameterArray.length];
System.arraycopy(currentParameterArray, 0, param, 0, currentParameterArray.length);
return param;
}
/**
* Returns the parameter setting of the attributes.
*
* @return the parameter setting of the attributes
*/
public List<AttributeSettings> getAttributeSettings()
{
List<AttributeSettings> settings = new ArrayList<AttributeSettings>();
AttributeSettings setting = new AttributeSettings(this);
setting.addSetting(TIME_F, Boolean.toString(isTime()));
setting.addSetting(VERBOSE_F, Boolean.toString(isVerbose()));
settings.add(setting);
return settings;
}
/**
* Returns whether the time should be assessed.
*
* @return whether the time should be assessed
*/
public boolean isTime()
{
return time;
}
/**
* Returns whether verbose messages should be printed while executing the
* algorithm.
*
* @return whether verbose messages should be printed while executing the
* algorithm
*/
public boolean isVerbose()
{
return verbose;
}
/**
* Sets whether the time should be assessed.
*
* @param time
* whether the time should be assessed
*/
public void setTime(boolean time)
{
this.time = time;
}
/**
* Sets whether verbose messages should be printed while executing the
* algorithm.
*
* @param verbose
* whether verbose messages should be printed while executing the
* algorithm
*/
public void setVerbose(boolean verbose)
{
this.verbose = verbose;
}
/**
* Calls the runInTime()-method of extending classes. Measures and prints
* the runtime of this method.
*
* @see Algorithm#run(de.lmu.ifi.dbs.database.Database)
*/
public final void run(Database<O> database) throws IllegalStateException
{
long start = System.currentTimeMillis();
runInTime(database);
long end = System.currentTimeMillis();
if(isTime())
{
long elapsedTime = end - start;
logger.info(this.getClass().getName() + " runtime : " + elapsedTime + " milliseconds.\n");
}
if(database instanceof IndexDatabase && isTime())
{
logger.info(this.getClass().getName() + " I/O-time : " + ((IndexDatabase) database).getIOAccess() + "\n");
}
}
protected abstract void runInTime(Database<O> database) throws IllegalStateException;
} |
package de.lmu.ifi.dbs.algorithm.clustering;
import de.lmu.ifi.dbs.algorithm.Algorithm;
import de.lmu.ifi.dbs.algorithm.DistanceBasedAlgorithm;
import de.lmu.ifi.dbs.algorithm.result.clustering.ClustersPlusNoise;
import de.lmu.ifi.dbs.data.DatabaseObject;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.Distance;
import de.lmu.ifi.dbs.distance.distancefunction.DistanceFunction;
import de.lmu.ifi.dbs.utilities.Description;
import de.lmu.ifi.dbs.utilities.Progress;
import de.lmu.ifi.dbs.utilities.QueryResult;
import de.lmu.ifi.dbs.utilities.optionhandling.*;
import de.lmu.ifi.dbs.utilities.optionhandling.constraints.GlobalDistanceFunctionPatternConstraint;
import de.lmu.ifi.dbs.utilities.optionhandling.constraints.GlobalParameterConstraint;
import de.lmu.ifi.dbs.utilities.optionhandling.constraints.GreaterConstraint;
import java.util.*;
/**
* DBSCAN provides the DBSCAN algorithm.
*
* @author Arthur Zimek
* @param <O> the type of DatabaseObject the algorithm is applied on
* @param <D> the type of Distance used
*/
public class DBSCAN<O extends DatabaseObject, D extends Distance<D>> extends DistanceBasedAlgorithm<O, D> implements Clustering<O> {
"to be considered, must be suitable to " +
"the distance function specified");
/**
* Parameter to specify the maximum radius of the neighborhood to be considered,
* must be suitable to the distance function specified.
* <p>Key: {@code -epsilon} </p>
*/
public static final PatternParameter EPSILON_PARAM = new PatternParameter("epsilon",
"the maximum radius of the neighborhood " +
"to be considered, must be suitable to " +
"the distance function specified");
/**
* Parameter minimum points.
*/
public static final String MINPTS_P = "minpts";
/**
* Description for parameter minimum points.
*/
public static final String MINPTS_D = "threshold for minimum number of points in the epsilon-neighborhood of a point";
/**
* Minimum points.
*/
protected int minpts;
/**
* Holds a list of clusters found.
*/
protected List<List<Integer>> resultList;
/**
* Provides the result of the algorithm.
*/
protected ClustersPlusNoise<O> result;
/**
* Holds a set of noise.
*/
protected Set<Integer> noise;
/**
* Holds a set of processed ids.
*/
protected Set<Integer> processedIDs;
/**
* Sets epsilon and minimum points to the optionhandler additionally to the
* parameters provided by super-classes.
*/
@SuppressWarnings("unchecked")
public DBSCAN() {
super();
// parameter epsilon
optionHandler.put(EPSILON_PARAM);
// global constraint
try {
// noinspection unchecked
GlobalParameterConstraint gpc = new GlobalDistanceFunctionPatternConstraint(EPSILON_PARAM, (ClassParameter<? extends DistanceFunction<?, ?>>) optionHandler.getOption(DISTANCE_FUNCTION_P));
optionHandler.setGlobalParameterConstraint(gpc);
}
catch (UnusedParameterException e) {
verbose("Could not instantiate global parameter constraint concerning parameter " + EPSILON_PARAM.getName() + " and " + DISTANCE_FUNCTION_P + " because parameter " + DISTANCE_FUNCTION_P + " is not specified! " + e.getMessage());
}
optionHandler.put(new IntParameter(MINPTS_P, MINPTS_D, new GreaterConstraint(0)));
}
/**
* Performs the DBSCAN algorithm on the given database.
*
* @see de.lmu.ifi.dbs.algorithm.AbstractAlgorithm#runInTime(de.lmu.ifi.dbs.database.Database)
*/
@Override
protected void runInTime(Database<O> database) throws IllegalStateException {
try {
Progress progress = new Progress("Clustering", database.size());
resultList = new ArrayList<List<Integer>>();
noise = new HashSet<Integer>();
processedIDs = new HashSet<Integer>(database.size());
getDistanceFunction().setDatabase(database, isVerbose(), isTime());
if (isVerbose()) {
verbose("Clustering:");
}
if (database.size() >= minpts) {
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
Integer id = iter.next();
if (!processedIDs.contains(id)) {
expandCluster(database, id, progress);
if (processedIDs.size() == database.size() && noise.size() == 0) {
break;
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
progress(progress, resultList.size());
}
}
}
else {
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
Integer id = iter.next();
noise.add(id);
if (isVerbose()) {
progress.setProcessed(noise.size());
progress(progress, resultList.size());
}
}
}
Integer[][] resultArray = new Integer[resultList.size() + 1][];
int i = 0;
for (Iterator<List<Integer>> resultListIter = resultList.iterator(); resultListIter.hasNext(); i++) {
resultArray[i] = resultListIter.next().toArray(new Integer[0]);
}
resultArray[resultArray.length - 1] = noise.toArray(new Integer[0]);
result = new ClustersPlusNoise<O>(resultArray, database);
if (isVerbose()) {
verbose("");
}
}
catch (UnusedParameterException e) {
throw new IllegalStateException("This should never happen: " + e.getMessage());
}
}
/**
* DBSCAN-function expandCluster. <p/> Border-Objects become members of the
* first possible cluster.
*
* @param database the database on which the algorithm is run
* @param startObjectID potential seed of a new potential cluster
* @param progress the progress object for logging the current status
* @throws de.lmu.ifi.dbs.utilities.optionhandling.UnusedParameterException
* if the parameter setting of parameter epsilon has failed
*/
protected void expandCluster(Database<O> database, Integer startObjectID, Progress progress) throws UnusedParameterException {
List<QueryResult<D>> seeds = database.rangeQuery(startObjectID, EPSILON_PARAM.getValue(), getDistanceFunction());
// startObject is no core-object
if (seeds.size() < minpts) {
noise.add(startObjectID);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
progress(progress, resultList.size());
}
return;
}
// try to expand the cluster
List<Integer> currentCluster = new ArrayList<Integer>();
for (QueryResult<D> seed : seeds) {
Integer nextID = seed.getID();
if (!processedIDs.contains(nextID)) {
currentCluster.add(nextID);
processedIDs.add(nextID);
}
else if (noise.contains(nextID)) {
currentCluster.add(nextID);
noise.remove(nextID);
}
}
seeds.remove(0);
while (seeds.size() > 0) {
Integer o = seeds.remove(0).getID();
List<QueryResult<D>> neighborhood = database.rangeQuery(o, EPSILON_PARAM.getValue(), getDistanceFunction());
if (neighborhood.size() >= minpts) {
for (QueryResult<D> neighbor : neighborhood) {
Integer p = neighbor.getID();
boolean inNoise = noise.contains(p);
boolean unclassified = !processedIDs.contains(p);
if (inNoise || unclassified) {
if (unclassified) {
seeds.add(neighbor);
}
currentCluster.add(p);
processedIDs.add(p);
if (inNoise) {
noise.remove(p);
}
}
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
int numClusters = currentCluster.size() > minpts ? resultList.size() + 1 : resultList.size();
progress(progress, numClusters);
}
if (processedIDs.size() == database.size() && noise.size() == 0) {
break;
}
}
if (currentCluster.size() >= minpts) {
resultList.add(currentCluster);
}
else {
for (Integer id : currentCluster) {
noise.add(id);
}
noise.add(startObjectID);
processedIDs.add(startObjectID);
}
}
/**
* @see Algorithm#getDescription()
*/
public Description getDescription() {
return new Description("DBSCAN", "Density-Based Clustering of Applications with Noise", "Algorithm to find density-connected sets in a database based on the parameters " + MINPTS_P + " and " + EPSILON_PARAM.getName() + " (specifying a volume). " + "These two parameters determine a density threshold for clustering.", "M. Ester, H.-P. Kriegel, J. Sander, and X. Xu: " + "A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise. " + "In Proc. 2nd Int. Conf. on Knowledge Discovery and Data Mining (KDD '96), Portland, OR, 1996.");
}
/**
* Sets the parameters epsilon and minpts additionally to the parameters set
* by the super-class' method. Both epsilon and minpts are required
* parameters.
*
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
@Override
public String[] setParameters(String[] args) throws ParameterException {
String[] remainingParameters = super.setParameters(args);
// minpts
minpts = (Integer) optionHandler.getOptionValue(MINPTS_P);
return remainingParameters;
}
/**
* @see de.lmu.ifi.dbs.algorithm.Algorithm#getResult()
*/
public ClustersPlusNoise<O> getResult() {
return result;
}
public Option<?>[] getOptions() {
return optionHandler.getOptions();
}
} |
package de.tub.citydb.modules.kml.database;
import java.util.HashMap;
import de.tub.citydb.api.log.LogLevel;
import de.tub.citydb.config.project.kmlExporter.DisplayForm;
import de.tub.citydb.log.Logger;
public class Queries {
// GENERIC PURPOSE QUERIES
public static final String GET_IDS =
"SELECT co.id, co.gmlid, co.class_id " +
"FROM CITYOBJECT co " +
"WHERE " +
"(SDO_RELATE(co.envelope, MDSYS.SDO_GEOMETRY(2002, ?, null, MDSYS.SDO_ELEM_INFO_ARRAY(1,2,1), " +
"MDSYS.SDO_ORDINATE_ARRAY(?,?,?,?,?,?)), 'mask=overlapbdydisjoint') ='TRUE') " +
"UNION ALL " +
"SELECT co.id, co.gmlid, co.class_id " +
"FROM CITYOBJECT co " +
"WHERE " +
"(SDO_RELATE(co.envelope, MDSYS.SDO_GEOMETRY(2003, ?, null, MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3), " +
"MDSYS.SDO_ORDINATE_ARRAY(?,?,?,?)), 'mask=inside+coveredby') ='TRUE') " +
"UNION ALL " +
"SELECT co.id, co.gmlid, co.class_id " +
"FROM CITYOBJECT co " +
"WHERE " +
"(SDO_RELATE(co.envelope, MDSYS.SDO_GEOMETRY(2003, ?, null, MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3), " +
"MDSYS.SDO_ORDINATE_ARRAY(?,?,?,?)), 'mask=equal') ='TRUE') " +
"ORDER BY 3"; // ORDER BY co.class_id
public static final String GET_EXTRUDED_HEIGHT =
"SELECT " + // "b.measured_height, " +
"SDO_GEOM.SDO_MAX_MBR_ORDINATE(co.envelope, 3) - SDO_GEOM.SDO_MIN_MBR_ORDINATE(co.envelope, 3) AS envelope_measured_height " +
"FROM CITYOBJECT co " + // ", BUILDING b " +
"WHERE " +
"co.id = ?"; // + " AND b.building_root_id = co.id";
public static final String GET_STRVAL_GENERICATTRIB_FROM_ID =
"SELECT coga.strval " +
"FROM CITYOBJECT_GENERICATTRIB coga " +
"WHERE coga.cityobject_id = ? AND coga.attrname = ? ";
public static final String GET_ID_FROM_GMLID =
"SELECT id FROM CITYOBJECT WHERE gmlid = ?";
public static final String GET_ID_AND_OBJECTCLASS_FROM_GMLID =
"SELECT id, class_id FROM CITYOBJECT WHERE gmlid = ?";
public static final String GET_GMLID_AND_OBJECTCLASS_FROM_ID =
"SELECT gmlid, class_id FROM CITYOBJECT WHERE id = ?";
public static final String INSERT_GE_ZOFFSET =
"INSERT INTO CITYOBJECT_GENERICATTRIB (ID, ATTRNAME, DATATYPE, STRVAL, CITYOBJECT_ID) " +
"VALUES (CITYOBJECT_GENERICATT_SEQ.NEXTVAL, ?, 1, ?, ?)";
public static final String TRANSFORM_GEOMETRY_TO_WGS84 =
"SELECT SDO_CS.TRANSFORM(?, 4326) FROM DUAL";
public static final String TRANSFORM_GEOMETRY_TO_WGS84_3D =
"SELECT SDO_CS.TRANSFORM(?, 4329) FROM DUAL";
public static final String GET_ENVELOPE_IN_WGS84_FROM_ID =
"SELECT SDO_CS.TRANSFORM(co.envelope, 4326) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_IN_WGS84_3D_FROM_ID =
"SELECT SDO_CS.TRANSFORM(co.envelope, 4329) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_CENTROID_IN_WGS84_FROM_ID =
"SELECT SDO_CS.TRANSFORM(SDO_GEOM.SDO_CENTROID(co.envelope, 0.001), 4326) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_CENTROID_IN_WGS84_3D_FROM_ID =
"SELECT SDO_CS.TRANSFORM(SDO_GEOM.SDO_CENTROID(co.envelope, 0.001), 4329) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_CENTROID_LAT_IN_WGS84_FROM_ID =
"SELECT v.Y FROM TABLE(" +
"SELECT SDO_UTIL.GETVERTICES(SDO_CS.TRANSFORM(SDO_GEOM.SDO_CENTROID(co.envelope, 0.001), 4326)) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?) v";
public static final String GET_CENTROID_LAT_IN_WGS84_3D_FROM_ID =
"SELECT v.Y FROM TABLE(" +
"SELECT SDO_UTIL.GETVERTICES(SDO_CS.TRANSFORM(SDO_GEOM.SDO_CENTROID(co.envelope, 0.001), 4329)) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?) v";
public static final String GET_CENTROID_LON_IN_WGS84_FROM_ID =
"SELECT v.X FROM TABLE(" +
"SELECT SDO_UTIL.GETVERTICES(SDO_CS.TRANSFORM(SDO_GEOM.SDO_CENTROID(co.envelope, 0.001), 4326)) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?) v";
public static final String GET_CENTROID_LON_IN_WGS84_3D_FROM_ID =
"SELECT v.X FROM TABLE(" +
"SELECT SDO_UTIL.GETVERTICES(SDO_CS.TRANSFORM(SDO_GEOM.SDO_CENTROID(co.envelope, 0.001), 4329)) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?) v";
public static final String GET_ENVELOPE_LAT_MIN_IN_WGS84_FROM_ID =
"SELECT SDO_GEOM.SDO_MIN_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4326), 2) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_LAT_MIN_IN_WGS84_3D_FROM_ID =
"SELECT SDO_GEOM.SDO_MIN_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4329), 2) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_LAT_MAX_IN_WGS84_FROM_ID =
"SELECT SDO_GEOM.SDO_MAX_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4326), 2) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_LAT_MAX_IN_WGS84_3D_FROM_ID =
"SELECT SDO_GEOM.SDO_MAX_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4329), 2) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_LON_MIN_IN_WGS84_FROM_ID =
"SELECT SDO_GEOM.SDO_MIN_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4326), 1) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_LON_MIN_IN_WGS84_3D_FROM_ID =
"SELECT SDO_GEOM.SDO_MIN_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4329), 1) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_LON_MAX_IN_WGS84_FROM_ID =
"SELECT SDO_GEOM.SDO_MAX_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4326), 1) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_LON_MAX_IN_WGS84_3D_FROM_ID =
"SELECT SDO_GEOM.SDO_MAX_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4329), 1) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_HEIGHT_MIN_IN_WGS84_FROM_ID =
"SELECT SDO_GEOM.SDO_MIN_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4326), 3) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_HEIGHT_MIN_IN_WGS84_3D_FROM_ID =
"SELECT SDO_GEOM.SDO_MIN_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4329), 3) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_HEIGHT_MAX_IN_WGS84_FROM_ID =
"SELECT SDO_GEOM.SDO_MAX_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4326), 3) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
public static final String GET_ENVELOPE_HEIGHT_MAX_IN_WGS84_3D_FROM_ID =
"SELECT SDO_GEOM.SDO_MAX_MBR_ORDINATE(SDO_CS.TRANSFORM(co.envelope, 4329), 3) " +
"FROM CITYOBJECT co " +
"WHERE co.id = ?";
// BUILDING QUERIES
public static final String BUILDING_PARTS_FROM_BUILDING =
"SELECT id FROM BUILDING WHERE building_root_id = ?";
private static final String BUILDING_PART_FOOTPRINT_LOD4 =
"SELECT sg.geometry " +
"FROM SURFACE_GEOMETRY sg, THEMATIC_SURFACE ts " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.type = 'GroundSurface' " +
"AND sg.root_id = ts.lod4_multi_surface_id " +
"AND sg.geometry IS NOT NULL ";
// "ORDER BY ts.building_id";
private static final String BUILDING_PART_COLLADA_LOD4_ROOT_IDS =
"SELECT ts.lod4_multi_surface_id " +
"FROM THEMATIC_SURFACE ts " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.lod4_multi_surface_id IS NOT NULL " +
"UNION " +
/*
"SELECT r.lod4_geometry_id " +
"FROM ROOM r " +
"WHERE " +
"r.building_id = ? " +
"AND r.lod4_geometry_id IS NOT NULL " +
*/
"SELECT ts.lod4_multi_surface_id " +
"FROM ROOM r, THEMATIC_SURFACE ts " +
"WHERE " +
"r.building_id = ? " +
"AND ts.room_id = r.id " +
"AND ts.lod4_multi_surface_id IS NOT NULL " +
"UNION " +
"SELECT bf.lod4_geometry_id " +
"FROM ROOM r, BUILDING_FURNITURE bf " +
"WHERE " +
"r.building_id = ? " +
"AND bf.room_id = r.id " +
"AND bf.lod4_geometry_id IS NOT NULL " +
"UNION " +
"SELECT bi.lod4_geometry_id " +
"FROM ROOM r, BUILDING_INSTALLATION bi " +
"WHERE " +
"r.building_id = ? " +
"AND bi.room_id = r.id " +
"AND bi.lod4_geometry_id IS NOT NULL " +
"UNION " +
"SELECT o.lod4_multi_surface_id " +
"FROM THEMATIC_SURFACE ts, OPENING_TO_THEM_SURFACE o2ts, OPENING o " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.lod4_multi_surface_id IS NOT NULL " +
"AND o2ts.thematic_surface_id = ts.id " +
"AND o.id = o2ts.opening_id " +
"UNION " +
"SELECT b.lod4_geometry_id " +
"FROM BUILDING b LEFT JOIN THEMATIC_SURFACE ts ON ts.building_id = b.id " +
"WHERE " +
"b.id = ? " +
"AND b.lod4_geometry_id IS NOT NULL " +
"AND ts.lod4_multi_surface_id IS NULL";
private static final String BUILDING_PART_GEOMETRY_LOD4 =
"SELECT sg.geometry, ts.type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"LEFT JOIN THEMATIC_SURFACE ts ON ts.lod4_multi_surface_id = sg.root_id " +
"WHERE " +
"sg.geometry IS NOT NULL " +
"AND sg.root_id IN (" + BUILDING_PART_COLLADA_LOD4_ROOT_IDS + ")";
private static final String BUILDING_PART_FOOTPRINT_LOD3 =
"SELECT sg.geometry " +
"FROM SURFACE_GEOMETRY sg, THEMATIC_SURFACE ts " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.type = 'GroundSurface' " +
"AND sg.root_id = ts.lod3_multi_surface_id " +
"AND sg.geometry IS NOT NULL ";
// "ORDER BY ts.building_id";
private static final String BUILDING_PART_COLLADA_LOD3_ROOT_IDS =
"SELECT ts.lod3_multi_surface_id " +
"FROM THEMATIC_SURFACE ts " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.lod3_multi_surface_id IS NOT NULL " +
"UNION " +
"SELECT bi.lod3_geometry_id " +
"FROM BUILDING_INSTALLATION bi " +
"WHERE " +
"bi.building_id = ? " +
"AND bi.lod3_geometry_id IS NOT NULL " +
"UNION " +
"SELECT o.lod3_multi_surface_id " +
"FROM THEMATIC_SURFACE ts, OPENING_TO_THEM_SURFACE o2ts, OPENING o " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.lod3_multi_surface_id IS NOT NULL " +
"AND o2ts.thematic_surface_id = ts.id " +
"AND o.id = o2ts.opening_id " +
"UNION " +
"SELECT b.lod3_geometry_id " +
"FROM BUILDING b LEFT JOIN THEMATIC_SURFACE ts ON ts.building_id = b.id " +
"WHERE " +
"b.id = ? " +
"AND b.lod3_geometry_id IS NOT NULL " +
"AND ts.lod3_multi_surface_id IS NULL";
private static final String BUILDING_PART_GEOMETRY_LOD3 =
"SELECT sg.geometry, ts.type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"LEFT JOIN THEMATIC_SURFACE ts ON ts.lod3_multi_surface_id = sg.root_id " +
"WHERE " +
"sg.geometry IS NOT NULL " +
"AND sg.root_id IN (" + BUILDING_PART_COLLADA_LOD3_ROOT_IDS + ")";
private static final String BUILDING_PART_COLLADA_LOD2_ROOT_IDS =
"SELECT ts.lod2_multi_surface_id " +
"FROM THEMATIC_SURFACE ts " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.lod2_multi_surface_id IS NOT NULL " +
"UNION " +
"SELECT bi.lod2_geometry_id " +
"FROM BUILDING_INSTALLATION bi " +
"WHERE " +
"bi.building_id = ? " +
"AND bi.lod2_geometry_id IS NOT NULL " +
"UNION " +
"SELECT b.lod2_geometry_id " +
"FROM BUILDING b LEFT JOIN THEMATIC_SURFACE ts ON ts.building_id = b.id " +
"WHERE " +
"b.id = ? " +
"AND b.lod2_geometry_id IS NOT NULL " +
"AND ts.lod2_multi_surface_id IS NULL";
private static final String BUILDING_PART_COLLADA_LOD1_ROOT_IDS =
"SELECT b.lod1_geometry_id " +
"FROM BUILDING b " +
"WHERE " +
"b.id = ? " +
"AND b.lod1_geometry_id IS NOT NULL";
private static final String COLLADA_GEOMETRY_AND_APPEARANCE_FROM_ROOT_ID_0 =
"SELECT sg.geometry, sg.id, sg.parent_id, sd.type, " +
"sd.x3d_shininess, sd.x3d_transparency, sd.x3d_ambient_intensity, sd.x3d_specular_color, sd.x3d_diffuse_color, sd.x3d_emissive_color, sd.x3d_is_smooth, " +
"sd.tex_image_uri, sd.tex_image, tp.texture_coordinates, a.theme " +
"FROM SURFACE_GEOMETRY sg " +
"LEFT JOIN TEXTUREPARAM tp ON tp.surface_geometry_id = sg.id " +
"LEFT JOIN SURFACE_DATA sd ON sd.id = tp.surface_data_id " +
"LEFT JOIN APPEAR_TO_SURFACE_DATA a2sd ON a2sd.surface_data_id = sd.id " +
"LEFT JOIN APPEARANCE a ON a2sd.appearance_id = a.id " +
"WHERE " +
"sg.root_id = ? ";
// "AND (a.theme = ? OR a.theme IS NULL) " +
// "ORDER BY sg.parent_id ASC"; // own root surfaces first
public static final String[] COLLADA_GEOMETRY_AND_APPEARANCE_FROM_ROOT_ID = new String[] {
COLLADA_GEOMETRY_AND_APPEARANCE_FROM_ROOT_ID_0 + "AND sg.geometry IS NULL ORDER BY sg.id", // parents
COLLADA_GEOMETRY_AND_APPEARANCE_FROM_ROOT_ID_0 + "AND sg.geometry IS NOT NULL" // elementary surfaces
};
private static final String BUILDING_PART_GEOMETRY_LOD2 =
"SELECT sg.geometry, ts.type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"LEFT JOIN THEMATIC_SURFACE ts ON ts.lod2_multi_surface_id = sg.root_id " +
"WHERE " +
"sg.geometry IS NOT NULL " +
"AND sg.root_id IN (" + BUILDING_PART_COLLADA_LOD2_ROOT_IDS + ")";
private static final String BUILDING_PART_FOOTPRINT_LOD2 =
"SELECT sg.geometry " +
"FROM SURFACE_GEOMETRY sg, THEMATIC_SURFACE ts " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.type = 'GroundSurface' " +
"AND sg.root_id = ts.lod2_multi_surface_id " +
"AND sg.geometry IS NOT NULL " +
"ORDER BY ts.building_id";
private static final String BUILDING_PART_GEOMETRY_LOD1 =
"SELECT sg.geometry, NULL as type, sg.id " +
"FROM SURFACE_GEOMETRY sg, BUILDING b " +
"WHERE " +
"b.id = ? " +
"AND sg.root_id = b.lod1_geometry_id " +
"AND sg.geometry IS NOT NULL ";
// "ORDER BY b.id";
private static final String BUILDING_PART_GEOMETRY_HIGHLIGHTING_LOD1 =
"SELECT sg.geometry, sg.id " +
"FROM SURFACE_GEOMETRY sg, BUILDING b " +
"WHERE " +
"b.id = ? " +
"AND sg.root_id = b.lod1_geometry_id " +
"AND sg.geometry IS NOT NULL ";
private static final String BUILDING_PART_GEOMETRY_HIGHLIGHTING_LOD2 =
"SELECT sg.geometry, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE " +
"sg.geometry IS NOT NULL " +
"AND sg.root_id IN (" + BUILDING_PART_COLLADA_LOD2_ROOT_IDS + ")";
private static final String BUILDING_PART_GEOMETRY_HIGHLIGHTING_LOD3 =
"SELECT sg.geometry, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE " +
"sg.geometry IS NOT NULL " +
"AND sg.root_id IN (" + BUILDING_PART_COLLADA_LOD3_ROOT_IDS + ")";
private static final String BUILDING_PART_GEOMETRY_HIGHLIGHTING_LOD4 =
"SELECT sg.geometry, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE " +
"sg.geometry IS NOT NULL " +
"AND sg.root_id IN (" +
"SELECT ts.lod4_multi_surface_id " +
"FROM THEMATIC_SURFACE ts " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.lod4_multi_surface_id IS NOT NULL " +
"UNION " +
"SELECT o.lod4_multi_surface_id " +
"FROM THEMATIC_SURFACE ts, OPENING_TO_THEM_SURFACE o2ts, OPENING o " +
"WHERE " +
"ts.building_id = ? " +
"AND ts.lod4_multi_surface_id IS NOT NULL " +
"AND o2ts.thematic_surface_id = ts.id " +
"AND o.id = o2ts.opening_id " +
"UNION " +
"SELECT b.lod4_geometry_id " +
"FROM BUILDING b LEFT JOIN THEMATIC_SURFACE ts ON ts.building_id = b.id " +
"WHERE " +
"b.id = ? " +
"AND b.lod4_geometry_id IS NOT NULL " +
"AND ts.lod4_multi_surface_id IS NULL)";
private static final String BUILDING_PART_GET_AGGREGATE_GEOMETRIES_FOR_LOD2_OR_HIGHER =
"SELECT sdo_aggr_union(mdsys.sdoaggrtype(aggr_geom, <TOLERANCE>)) aggr_geom " +
"FROM (SELECT sdo_aggr_union(mdsys.sdoaggrtype(aggr_geom, <TOLERANCE>)) aggr_geom " +
"FROM (SELECT sdo_aggr_union(mdsys.sdoaggrtype(aggr_geom, <TOLERANCE>)) aggr_geom " +
"FROM (SELECT sdo_aggr_union(mdsys.sdoaggrtype(simple_geom, <TOLERANCE>)) aggr_geom " +
"FROM (" +
"SELECT * FROM (" +
"SELECT * FROM (" +
"SELECT geodb_util.to_2d(sg.geometry, <2D_SRID>) AS simple_geom " +
// "SELECT geodb_util.to_2d(sg.geometry, <2D_SRID>) AS simple_geom " +
// "SELECT geodb_util.to_2d(sg.geometry, (select srid from database_srs)) AS simple_geom " +
// "SELECT sg.geometry AS simple_geom " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE " +
"sg.root_id IN( " +
"SELECT b.lod<LoD>_geometry_id " +
"FROM BUILDING b " +
"WHERE "+
"b.id = ? " +
"AND b.lod<LoD>_geometry_id IS NOT NULL " +
"UNION " +
"SELECT ts.lod<LoD>_multi_surface_id " +
"FROM THEMATIC_SURFACE ts " +
"WHERE "+
"ts.building_id = ? " +
"AND ts.lod<LoD>_multi_surface_id IS NOT NULL "+
") " +
"AND sg.geometry IS NOT NULL" +
") WHERE sdo_geom.validate_geometry(simple_geom, <TOLERANCE>) = 'TRUE'" +
") WHERE sdo_geom.sdo_area(simple_geom, <TOLERANCE>) > <TOLERANCE>" +
") " +
"GROUP BY mod(rownum, <GROUP_BY_1>) " +
") " +
"GROUP BY mod (rownum, <GROUP_BY_2>) " +
") " +
"GROUP BY mod (rownum, <GROUP_BY_3>) " +
")";
private static final String BUILDING_PART_GET_AGGREGATE_GEOMETRIES_FOR_LOD1 =
"SELECT sdo_aggr_union(mdsys.sdoaggrtype(aggr_geom, <TOLERANCE>)) aggr_geom " +
"FROM (SELECT sdo_aggr_union(mdsys.sdoaggrtype(aggr_geom, <TOLERANCE>)) aggr_geom " +
"FROM (SELECT sdo_aggr_union(mdsys.sdoaggrtype(aggr_geom, <TOLERANCE>)) aggr_geom " +
"FROM (SELECT sdo_aggr_union(mdsys.sdoaggrtype(simple_geom, <TOLERANCE>)) aggr_geom " +
"FROM (" +
"SELECT * FROM (" +
"SELECT * FROM (" +
"SELECT geodb_util.to_2d(sg.geometry, <2D_SRID>) AS simple_geom " +
// "SELECT geodb_util.to_2d(sg.geometry, <2D_SRID>) AS simple_geom " +
// "SELECT geodb_util.to_2d(sg.geometry, (select srid from database_srs)) AS simple_geom " +
// "SELECT sg.geometry AS simple_geom " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE " +
"sg.root_id IN( " +
"SELECT b.lod<LoD>_geometry_id " +
"FROM BUILDING b " +
"WHERE "+
"b.id = ? " +
"AND b.lod<LoD>_geometry_id IS NOT NULL " +
") " +
"AND sg.geometry IS NOT NULL" +
") WHERE sdo_geom.validate_geometry(simple_geom, <TOLERANCE>) = 'TRUE'" +
") WHERE sdo_geom.sdo_area(simple_geom, <TOLERANCE>) > <TOLERANCE>" +
") " +
"GROUP BY mod(rownum, <GROUP_BY_1>) " +
") " +
"GROUP BY mod (rownum, <GROUP_BY_2>) " +
") " +
"GROUP BY mod (rownum, <GROUP_BY_3>) " +
")";
public static String getBuildingPartAggregateGeometries (double tolerance,
int srid2D,
int lodToExportFrom,
double groupBy1,
double groupBy2,
double groupBy3) {
if (lodToExportFrom > 1) {
return BUILDING_PART_GET_AGGREGATE_GEOMETRIES_FOR_LOD2_OR_HIGHER.replace("<TOLERANCE>", String.valueOf(tolerance))
.replace("<2D_SRID>", String.valueOf(srid2D))
.replace("<LoD>", String.valueOf(lodToExportFrom))
.replace("<GROUP_BY_1>", String.valueOf(groupBy1))
.replace("<GROUP_BY_2>", String.valueOf(groupBy2))
.replace("<GROUP_BY_3>", String.valueOf(groupBy3));
}
// else
return BUILDING_PART_GET_AGGREGATE_GEOMETRIES_FOR_LOD1.replace("<TOLERANCE>", String.valueOf(tolerance))
.replace("<2D_SRID>", String.valueOf(srid2D))
.replace("<LoD>", String.valueOf(lodToExportFrom))
.replace("<GROUP_BY_1>", String.valueOf(groupBy1))
.replace("<GROUP_BY_2>", String.valueOf(groupBy2))
.replace("<GROUP_BY_3>", String.valueOf(groupBy3));
}
private static final String BUILDING_PART_FOOTPRINT_LOD1 =
BUILDING_PART_GET_AGGREGATE_GEOMETRIES_FOR_LOD1.replace("<TOLERANCE>", "0.001")
.replace("<2D_SRID>", "(SELECT SRID FROM DATABASE_SRS)")
.replace("<LoD>", "1")
.replace("<GROUP_BY_1>", "256")
.replace("<GROUP_BY_2>", "64")
.replace("<GROUP_BY_3>", "16");
private static final HashMap<Integer, String> buildingPartQueriesLod4 = new HashMap<Integer, String>();
static {
buildingPartQueriesLod4.put(DisplayForm.FOOTPRINT, BUILDING_PART_FOOTPRINT_LOD4);
buildingPartQueriesLod4.put(DisplayForm.EXTRUDED, BUILDING_PART_FOOTPRINT_LOD4);
buildingPartQueriesLod4.put(DisplayForm.GEOMETRY, BUILDING_PART_GEOMETRY_LOD4);
buildingPartQueriesLod4.put(DisplayForm.COLLADA, BUILDING_PART_COLLADA_LOD4_ROOT_IDS);
}
private static final HashMap<Integer, String> buildingPartQueriesLod3 = new HashMap<Integer, String>();
static {
buildingPartQueriesLod3.put(DisplayForm.FOOTPRINT, BUILDING_PART_FOOTPRINT_LOD3);
buildingPartQueriesLod3.put(DisplayForm.EXTRUDED, BUILDING_PART_FOOTPRINT_LOD3);
buildingPartQueriesLod3.put(DisplayForm.GEOMETRY, BUILDING_PART_GEOMETRY_LOD3);
buildingPartQueriesLod3.put(DisplayForm.COLLADA, BUILDING_PART_COLLADA_LOD3_ROOT_IDS);
}
private static final HashMap<Integer, String> buildingPartQueriesLod2 = new HashMap<Integer, String>();
static {
buildingPartQueriesLod2.put(DisplayForm.FOOTPRINT, BUILDING_PART_FOOTPRINT_LOD2);
buildingPartQueriesLod2.put(DisplayForm.EXTRUDED, BUILDING_PART_FOOTPRINT_LOD2);
buildingPartQueriesLod2.put(DisplayForm.GEOMETRY, BUILDING_PART_GEOMETRY_LOD2);
buildingPartQueriesLod2.put(DisplayForm.COLLADA, BUILDING_PART_COLLADA_LOD2_ROOT_IDS);
}
private static final HashMap<Integer, String> buildingPartQueriesLod1 = new HashMap<Integer, String>();
static {
buildingPartQueriesLod1.put(DisplayForm.FOOTPRINT, BUILDING_PART_FOOTPRINT_LOD1);
buildingPartQueriesLod1.put(DisplayForm.EXTRUDED, BUILDING_PART_FOOTPRINT_LOD1);
buildingPartQueriesLod1.put(DisplayForm.GEOMETRY, BUILDING_PART_GEOMETRY_LOD1);
buildingPartQueriesLod1.put(DisplayForm.COLLADA, BUILDING_PART_COLLADA_LOD1_ROOT_IDS);
}
public static String getBuildingPartQuery (int lodToExportFrom, DisplayForm displayForm) {
String query = null;
switch (lodToExportFrom) {
case 1:
query = buildingPartQueriesLod1.get(displayForm.getForm());
break;
case 2:
query = buildingPartQueriesLod2.get(displayForm.getForm());
break;
case 3:
query = buildingPartQueriesLod3.get(displayForm.getForm());
break;
case 4:
query = buildingPartQueriesLod4.get(displayForm.getForm());
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No BuildingPart query found for LoD" + lodToExportFrom);
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query;
}
public static String getBuildingPartHighlightingQuery (int lodToExportFrom) {
String query = null;
switch (lodToExportFrom) {
case 1:
query = BUILDING_PART_GEOMETRY_HIGHLIGHTING_LOD1;
break;
case 2:
query = BUILDING_PART_GEOMETRY_HIGHLIGHTING_LOD2;
break;
case 3:
query = BUILDING_PART_GEOMETRY_HIGHLIGHTING_LOD3;
break;
case 4:
query = BUILDING_PART_GEOMETRY_HIGHLIGHTING_LOD4;
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No BuildingPart highlighting query found for LoD" + lodToExportFrom);
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query;
}
// CITY OBJECT GROUP QUERIES
public static final String CITYOBJECTGROUP_FOOTPRINT =
"SELECT sg.geometry " +
"FROM SURFACE_GEOMETRY sg, CITYOBJECTGROUP cog " +
"WHERE " +
"cog.id = ? " +
"AND sg.root_id = cog.surface_geometry_id " +
"AND sg.geometry IS NOT NULL ";
public static final String CITYOBJECTGROUP_MEMBERS =
"SELECT co.id, co.gmlid, co.class_id " +
"FROM CITYOBJECT co " +
"WHERE co.ID IN (SELECT g2co.cityobject_id "+
"FROM GROUP_TO_CITYOBJECT g2co "+
"WHERE g2co.cityobjectgroup_id = ?) " +
"ORDER BY co.class_id";
public static final String CITYOBJECTGROUP_MEMBERS_IN_BBOX =
"SELECT co.id, co.gmlid, co.class_id " +
"FROM CITYOBJECT co " +
"WHERE co.ID IN (SELECT g2co.cityobject_id "+
"FROM GROUP_TO_CITYOBJECT g2co "+
"WHERE g2co.cityobjectgroup_id = ?) " +
"AND (SDO_RELATE(co.envelope, MDSYS.SDO_GEOMETRY(2002, ?, null, MDSYS.SDO_ELEM_INFO_ARRAY(1,2,1), " +
"MDSYS.SDO_ORDINATE_ARRAY(?,?,?,?,?,?)), 'mask=overlapbdydisjoint') ='TRUE') " +
"UNION ALL " +
"SELECT co.id, co.gmlid, co.class_id " +
"FROM CITYOBJECT co " +
"WHERE co.ID IN (SELECT g2co.cityobject_id "+
"FROM GROUP_TO_CITYOBJECT g2co "+
"WHERE g2co.cityobjectgroup_id = ?) " +
"AND (SDO_RELATE(co.envelope, MDSYS.SDO_GEOMETRY(2003, ?, null, MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3), " +
"MDSYS.SDO_ORDINATE_ARRAY(?,?,?,?)), 'mask=inside+coveredby') ='TRUE') " +
"UNION ALL " +
"SELECT co.id, co.gmlid, co.class_id " +
"FROM CITYOBJECT co " +
"WHERE co.ID IN (SELECT g2co.cityobject_id "+
"FROM GROUP_TO_CITYOBJECT g2co "+
"WHERE g2co.cityobjectgroup_id = ?) " +
"AND (SDO_RELATE(co.envelope, MDSYS.SDO_GEOMETRY(2003, ?, null, MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,3), " +
"MDSYS.SDO_ORDINATE_ARRAY(?,?,?,?)), 'mask=equal') ='TRUE') " +
"ORDER BY 3"; // ORDER BY co.class_id
// SOLITARY VEGETATION OBJECT QUERIES
private static final String SOLITARY_VEGETATION_OBJECT_BASIS_DATA =
"SELECT ig.relative_geometry_id, svo.lod<LoD>_implicit_ref_point, " +
"svo.lod<LoD>_implicit_transformation, svo.lod<LoD>_geometry_id " +
"FROM SOLITARY_VEGETAT_OBJECT svo " +
"LEFT JOIN IMPLICIT_GEOMETRY ig ON ig.id = svo.lod<LoD>_implicit_rep_id " +
"WHERE svo.id = ?";
public static String getSolitaryVegetationObjectBasisData (int lodToExportFrom) {
return SOLITARY_VEGETATION_OBJECT_BASIS_DATA.replace("<LoD>", String.valueOf(lodToExportFrom));
}
private static final String SOLITARY_VEGETATION_OBJECT_FOOTPRINT_EXTRUDED_GEOMETRY =
"SELECT sg.geometry, 'Vegetation' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id = ? " +
"AND sg.geometry IS NOT NULL";
private static final String SOLITARY_VEGETATION_OBJECT_COLLADA_ROOT_IDS =
"SELECT ? FROM DUAL "; // dummy
public static String getSolitaryVegetationObjectGeometryContents (DisplayForm displayForm) {
String query = null;
switch (displayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
case DisplayForm.GEOMETRY:
query = SOLITARY_VEGETATION_OBJECT_FOOTPRINT_EXTRUDED_GEOMETRY;
break;
case DisplayForm.COLLADA:
query = SOLITARY_VEGETATION_OBJECT_COLLADA_ROOT_IDS;
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No solitary vegetation object query found");
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query;
}
private static final String SOLITARY_VEGETATION_OBJECT_GEOMETRY_HIGHLIGHTING =
"SELECT sg.geometry, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id IN ( " +
"SELECT ig.relative_geometry_id " +
"FROM SOLITARY_VEGETAT_OBJECT svo, IMPLICIT_GEOMETRY ig " +
"WHERE svo.id = ? " +
"AND ig.id = svo.lod<LoD>_implicit_rep_id " +
"UNION " +
"SELECT svo.lod<LoD>_geometry_id " +
"FROM SOLITARY_VEGETAT_OBJECT svo " +
"WHERE svo.id = ?) " +
"AND sg.geometry IS NOT NULL";
public static String getSolitaryVegetationObjectHighlightingQuery (int lodToExportFrom) {
return SOLITARY_VEGETATION_OBJECT_GEOMETRY_HIGHLIGHTING.replace("<LoD>", String.valueOf(lodToExportFrom));
}
// PLANT COVER QUERIES
private static final String PLANT_COVER_FOOTPRINT_EXTRUDED_GEOMETRY =
"SELECT sg.geometry, 'Vegetation' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg, PLANT_COVER pc " +
"WHERE pc.id = ? " +
"AND sg.root_id = pc.lod<LoD>_geometry_id " +
"AND sg.geometry IS NOT NULL";
private static final String PLANT_COVER_COLLADA_ROOT_IDS =
"SELECT pc.lod<LoD>_geometry_id " +
"FROM PLANT_COVER pc " +
"WHERE pc.id = ?";
public static String getPlantCoverQuery (int lodToExportFrom, DisplayForm displayForm) {
String query = null;
switch (displayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
case DisplayForm.GEOMETRY:
query = PLANT_COVER_FOOTPRINT_EXTRUDED_GEOMETRY;
break;
case DisplayForm.COLLADA:
query = PLANT_COVER_COLLADA_ROOT_IDS;
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No plant cover object query found");
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query.replace("<LoD>", String.valueOf(lodToExportFrom));
}
public static String getPlantCoverHighlightingQuery (int lodToExportFrom) {
return PLANT_COVER_FOOTPRINT_EXTRUDED_GEOMETRY.replace("<LoD>", String.valueOf(lodToExportFrom));
}
// GENERIC CITY OBJECT QUERIES
private static final String GENERIC_CITYOBJECT_BASIS_DATA =
"SELECT ig.relative_geometry_id, gco.lod<LoD>_implicit_ref_point, " +
"gco.lod<LoD>_implicit_transformation, gco.lod<LoD>_geometry_id " +
"FROM GENERIC_CITYOBJECT gco " +
"LEFT JOIN IMPLICIT_GEOMETRY ig ON ig.id = gco.lod<LoD>_implicit_rep_id " +
"WHERE gco.id = ?";
public static String getGenericCityObjectBasisData (int lodToExportFrom) {
return GENERIC_CITYOBJECT_BASIS_DATA.replace("<LoD>", String.valueOf(lodToExportFrom));
}
private static final String GENERIC_CITYOBJECT_FOOTPRINT_EXTRUDED_GEOMETRY =
"SELECT sg.geometry, 'Generic' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id = ? " +
"AND sg.geometry IS NOT NULL";
private static final String GENERIC_CITYOBJECT_COLLADA_ROOT_IDS =
"SELECT ? FROM DUAL "; // dummy
public static String getGenericCityObjectGeometryContents (DisplayForm displayForm) {
String query = null;
switch (displayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
case DisplayForm.GEOMETRY:
query = GENERIC_CITYOBJECT_FOOTPRINT_EXTRUDED_GEOMETRY;
break;
case DisplayForm.COLLADA:
query = GENERIC_CITYOBJECT_COLLADA_ROOT_IDS;
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No GenericCityObject query found");
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query;
}
private static final String GENERIC_CITYOBJECT_GEOMETRY_HIGHLIGHTING =
"SELECT sg.geometry, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id IN ( " +
"SELECT ig.relative_geometry_id " +
"FROM GENERIC_CITYOBJECT gco, IMPLICIT_GEOMETRY ig " +
"WHERE gco.id = ? " +
"AND ig.id = gco.lod<LoD>_implicit_rep_id " +
"UNION " +
"SELECT gco.lod<LoD>_geometry_id " +
"FROM GENERIC_CITYOBJECT gco " +
"WHERE gco.id = ?) " +
"AND sg.geometry IS NOT NULL";
public static String getGenericCityObjectHighlightingQuery (int lodToExportFrom) {
return GENERIC_CITYOBJECT_GEOMETRY_HIGHLIGHTING.replace("<LoD>", String.valueOf(lodToExportFrom));
}
// CITY FURNITURE QUERIES
private static final String CITY_FURNITURE_BASIS_DATA =
"SELECT ig.relative_geometry_id, cf.lod<LoD>_implicit_ref_point, " +
"cf.lod<LoD>_implicit_transformation, cf.lod<LoD>_geometry_id " +
"FROM CITY_FURNITURE cf " +
"LEFT JOIN IMPLICIT_GEOMETRY ig ON ig.id = cf.lod<LoD>_implicit_rep_id " +
"WHERE cf.id = ?";
public static String getCityFurnitureBasisData (int lodToExportFrom) {
return CITY_FURNITURE_BASIS_DATA.replace("<LoD>", String.valueOf(lodToExportFrom));
}
private static final String CITY_FURNITURE_FOOTPRINT_EXTRUDED_GEOMETRY =
"SELECT sg.geometry, 'Furniture' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id = ? " +
"AND sg.geometry IS NOT NULL";
private static final String CITY_FURNITURE_COLLADA_ROOT_IDS =
"SELECT ? FROM DUAL "; // dummy
public static String getCityFurnitureGeometryContents (DisplayForm displayForm) {
String query = null;
switch (displayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
case DisplayForm.GEOMETRY:
query = CITY_FURNITURE_FOOTPRINT_EXTRUDED_GEOMETRY;
break;
case DisplayForm.COLLADA:
query = CITY_FURNITURE_COLLADA_ROOT_IDS;
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No city furniture query found");
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query;
}
private static final String CITY_FURNITURE_GEOMETRY_HIGHLIGHTING =
"SELECT sg.geometry, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id IN ( " +
"SELECT ig.relative_geometry_id " +
"FROM CITY_FURNITURE cf, IMPLICIT_GEOMETRY ig " +
"WHERE cf.id = ? " +
"AND ig.id = cf.lod<LoD>_implicit_rep_id " +
"UNION " +
"SELECT cf.lod<LoD>_geometry_id " +
"FROM CITY_FURNITURE cf " +
"WHERE cf.id = ?) " +
"AND sg.geometry IS NOT NULL";
public static String getCityFurnitureHighlightingQuery (int lodToExportFrom) {
return CITY_FURNITURE_GEOMETRY_HIGHLIGHTING.replace("<LoD>", String.valueOf(lodToExportFrom));
}
// WATER BODY QUERIES
private static final String WATERBODY_LOD1_ROOT_IDS =
"SELECT wb.lod<LoD>_solid_id " +
"FROM WATERBODY wb " +
"WHERE wb.id = ? " +
"AND wb.lod<LoD>_solid_id IS NOT NULL";
private static final String WATERBODY_ROOT_IDS =
WATERBODY_LOD1_ROOT_IDS +
" UNION " +
"SELECT wbs.lod<LoD>_surface_id " + // min lod value here is 2
"FROM WATERBOD_TO_WATERBND_SRF wb2wbs, WATERBOUNDARY_SURFACE wbs " +
"WHERE wb2wbs.waterbody_id = ? " +
"AND wbs.id = wb2wbs.waterboundary_surface_id " +
"AND wbs.lod<LoD>_surface_id IS NOT NULL";
private static final String WATERBODY_FOOTPRINT_EXTRUDED_GEOMETRY =
"SELECT sg.geometry, 'Water' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id IN (" + WATERBODY_ROOT_IDS +
") AND sg.geometry IS NOT NULL";
private static final String WATERBODY_FOOTPRINT_EXTRUDED_GEOMETRY_LOD1 =
"SELECT sg.geometry, 'Water' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id IN (" +
"SELECT wb.lod1_solid_id " +
"FROM WATERBODY wb " +
"WHERE wb.id = ? " +
"UNION " +
"SELECT wb.lod1_multi_surface_id " +
"FROM WATERBODY wb " +
"WHERE wb.id = ? " +
") AND sg.geometry IS NOT NULL " +
"UNION " +
"SELECT wb.lod1_multi_curve " +
"FROM WATERBODY wb " +
"WHERE wb.id = ? ";
private static final String WATERBODY_FOOTPRINT_LOD0 =
"SELECT sg.geometry, 'Water' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg, WATERBODY wb " +
"WHERE wb.id = ? "+
"AND sg.root_id = wb.lod0_multi_surface_id " +
"AND sg.geometry IS NOT NULL " +
"UNION " +
"SELECT wb.lod0_multi_curve, 'Water' as type, -1 " +
"FROM WATERBODY wb " +
"WHERE wb.id = ? " +
"AND wb.lod0_multi_curve IS NOT NULL";
public static String getWaterBodyQuery (int lodToExportFrom, DisplayForm displayForm) {
String query = null;
switch (displayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
case DisplayForm.GEOMETRY:
if (lodToExportFrom > 1) {
query = WATERBODY_FOOTPRINT_EXTRUDED_GEOMETRY;
}
else if (lodToExportFrom == 1) {
query = WATERBODY_FOOTPRINT_EXTRUDED_GEOMETRY_LOD1;
}
else {
query = WATERBODY_FOOTPRINT_LOD0;
}
break;
case DisplayForm.COLLADA:
if (lodToExportFrom == 1) {
query = WATERBODY_LOD1_ROOT_IDS;
}
else {
query = WATERBODY_ROOT_IDS;
}
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No water body object query found");
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query.replace("<LoD>", String.valueOf(lodToExportFrom));
}
public static String getWaterBodyHighlightingQuery (int lodToExportFrom) {
String query = null;
if (lodToExportFrom > 1) {
query = WATERBODY_FOOTPRINT_EXTRUDED_GEOMETRY;
}
else if (lodToExportFrom == 1) {
query = WATERBODY_FOOTPRINT_EXTRUDED_GEOMETRY_LOD1;
}
else {
query = WATERBODY_FOOTPRINT_LOD0;
}
return query.replace("<LoD>", String.valueOf(lodToExportFrom));
}
// LAND USE QUERIES
private static final String LAND_USE_FOOTPRINT_EXTRUDED_GEOMETRY =
"SELECT sg.geometry, 'LandUse' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg, LAND_USE lu " +
"WHERE lu.id = ? " +
"AND sg.root_id = lu.lod<LoD>_multi_surface_id " +
"AND sg.geometry IS NOT NULL";
private static final String LAND_USE_COLLADA_ROOT_IDS =
"SELECT lu.lod<LoD>_multi_surface_id " +
"FROM LAND_USE lu " +
"WHERE lu.id = ? " +
"AND lu.lod<LoD>_multi_surface_id IS NOT NULL";
public static String getLandUseQuery (int lodToExportFrom, DisplayForm displayForm) {
String query = null;
switch (displayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
case DisplayForm.GEOMETRY:
query = LAND_USE_FOOTPRINT_EXTRUDED_GEOMETRY;
break;
case DisplayForm.COLLADA:
query = LAND_USE_COLLADA_ROOT_IDS;
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No land use object query found");
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query.replace("<LoD>", String.valueOf(lodToExportFrom));
}
public static String getLandUseHighlightingQuery (int lodToExportFrom) {
return LAND_USE_FOOTPRINT_EXTRUDED_GEOMETRY.replace("<LoD>", String.valueOf(lodToExportFrom));
}
// TRANSPORTATION QUERIES
private static final String TRANSPORTATION_COMPLEX_LOD1_ROOT_IDS =
"SELECT tc.lod<LoD>_multi_surface_id " +
"FROM TRANSPORTATION_COMPLEX tc " +
"WHERE tc.id = ? " +
"AND tc.lod<LoD>_multi_surface_id IS NOT NULL";
private static final String TRANSPORTATION_COMPLEX_ROOT_IDS =
TRANSPORTATION_COMPLEX_LOD1_ROOT_IDS +
" UNION " +
"SELECT ta.lod<LoD>_multi_surface_id " + // min lod value here is 2
"FROM TRAFFIC_AREA ta " +
"WHERE ta.transportation_complex_id = ? " +
"AND ta.lod<LoD>_multi_surface_id IS NOT NULL";
private static final String TRANSPORTATION_COMPLEX_FOOTPRINT_EXTRUDED_GEOMETRY =
"SELECT sg.geometry, 'Transportation' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id IN (" + TRANSPORTATION_COMPLEX_ROOT_IDS +
") AND sg.geometry IS NOT NULL";
private static final String TRANSPORTATION_COMPLEX_FOOTPRINT_EXTRUDED_GEOMETRY_LOD1 =
"SELECT sg.geometry, 'Transportation' as type, sg.id " +
"FROM SURFACE_GEOMETRY sg " +
"WHERE sg.root_id IN (" +
"SELECT tc.lod1_multi_surface_id " +
"FROM TRANSPORTATION_COMPLEX tc " +
"WHERE tc.id = ? " +
"AND tc.lod1_multi_surface_id IS NOT NULL" +
") AND sg.geometry IS NOT NULL";
private static final String TRANSPORTATION_COMPLEX_FOOTPRINT_LOD0 =
"SELECT tc.lod0_network " +
"FROM TRANSPORTATION_COMPLEX tc " +
"WHERE tc.id = ? " +
"AND tc.lod0_network IS NOT NULL";
public static String getTransportationQuery (int lodToExportFrom, DisplayForm displayForm) {
String query = null;
switch (displayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
case DisplayForm.GEOMETRY:
switch (lodToExportFrom) {
case 2:
case 3:
case 4:
query = TRANSPORTATION_COMPLEX_FOOTPRINT_EXTRUDED_GEOMETRY;
break;
case 1:
query = TRANSPORTATION_COMPLEX_FOOTPRINT_EXTRUDED_GEOMETRY_LOD1;
break;
case 0:
query = TRANSPORTATION_COMPLEX_FOOTPRINT_LOD0;
break;
}
break;
case DisplayForm.COLLADA:
if (lodToExportFrom == 1) {
query = TRANSPORTATION_COMPLEX_LOD1_ROOT_IDS;
}
else {
query = TRANSPORTATION_COMPLEX_ROOT_IDS;
}
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No transportation object query found");
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query.replace("<LoD>", String.valueOf(lodToExportFrom));
}
public static String getTransportationHighlightingQuery (int lodToExportFrom) {
String query = null;
if (lodToExportFrom > 1) {
query = TRANSPORTATION_COMPLEX_FOOTPRINT_EXTRUDED_GEOMETRY;
}
else if (lodToExportFrom == 1) {
query = TRANSPORTATION_COMPLEX_FOOTPRINT_EXTRUDED_GEOMETRY_LOD1;
}
else {
query = TRANSPORTATION_COMPLEX_FOOTPRINT_LOD0;
}
return query.replace("<LoD>", String.valueOf(lodToExportFrom));
}
// RELIEF QUERIES
public static final int RELIEF_TIN_QUERY = 0;
private static final String RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN =
"SELECT sg.geometry, 'Relief' as type, sg.id " +
"FROM RELIEF_FEATURE rf, RELIEF_FEAT_TO_REL_COMP rf2rc, TIN_RELIEF tr, SURFACE_GEOMETRY sg " +
"WHERE rf.id = ? " +
"AND rf.lod = <LoD> " +
"AND rf2rc.relief_feature_id = rf.id " +
"AND tr.id = rf2rc.relief_component_id " +
"AND sg.root_id = tr.surface_geometry_id " +
"AND sg.geometry IS NOT NULL";
public static final int RELIEF_TIN_BREAK_LINES_QUERY = 1;
private static final String RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN_BREAK_LINES =
"SELECT tr.break_lines, 'Relief' as type, -1 " +
"FROM RELIEF_FEATURE rf, RELIEF_FEAT_TO_REL_COMP rf2rc, TIN_RELIEF tr " +
"WHERE rf.id = ? " +
"AND rf.lod = <LoD> " +
"AND rf2rc.relief_feature_id = rf.id " +
"AND tr.id = rf2rc.relief_component_id " +
"AND tr.break_lines IS NOT NULL";
public static final int RELIEF_TIN_STOP_LINES_QUERY = 2;
private static final String RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN_STOP_LINES =
"SELECT tr.stop_lines, 'Relief' as type, -1 " +
"FROM RELIEF_FEATURE rf, RELIEF_FEAT_TO_REL_COMP rf2rc, TIN_RELIEF tr " +
"WHERE rf.id = ? " +
"AND rf.lod = <LoD> " +
"AND rf2rc.relief_feature_id = rf.id " +
"AND tr.id = rf2rc.relief_component_id " +
"AND tr.stop_lines IS NOT NULL";
/*
public static final int RELIEF_TIN_CONTROL_POINTS_QUERY = 2;
private static final String RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN_CONTROL_POINTS =
"SELECT tr.control_points, 'Relief' as type, -1 " +
"FROM RELIEF_FEATURE rf, RELIEF_FEAT_TO_REL_COMP rf2rc, TIN_RELIEF tr " +
"WHERE rf.id = ? " +
"AND rf.lod = <LoD> " +
"AND rf2rc.relief_feature_id = rf.id " +
"AND tr.id = rf2rc.relief_component_id";
*/
public static final int RELIEF_BREAK_BREAK_LINES_QUERY = 3;
private static final String RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_BREAK_BREAK_LINES =
"SELECT br.break_lines, 'Relief' as type, -1 " +
"FROM RELIEF_FEATURE rf, RELIEF_FEAT_TO_REL_COMP rf2rc, BREAKLINE_RELIEF br " +
"WHERE rf.id = ? " +
"AND rf.lod = <LoD> " +
"AND rf2rc.relief_feature_id = rf.id " +
"AND br.id = rf2rc.relief_component_id " +
"AND br.break_lines IS NOT NULL";
public static final int RELIEF_BREAK_RIDGE_OR_VALLEY_LINES_QUERY = 4;
private static final String RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_BREAK_RIDGE_OR_VALLEY_LINES =
"SELECT br.ridge_or_valley_lines, 'Relief' as type, -1 " +
"FROM RELIEF_FEATURE rf, RELIEF_FEAT_TO_REL_COMP rf2rc, BREAKLINE_RELIEF br " +
"WHERE rf.id = ? " +
"AND rf.lod = <LoD> " +
"AND rf2rc.relief_feature_id = rf.id " +
"AND br.id = rf2rc.relief_component_id " +
"AND br.ridge_or_valley_lines IS NOT NULL";
/*
public static final int RELIEF_MASSPOINT_QUERY = 4;
private static final String RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_MASSPOINT =
"SELECT mr.relief_points, 'Relief' as type, -1 " +
"FROM RELIEF_FEATURE rf, RELIEF_FEAT_TO_REL_COMP rf2rc, MASSPOINT_RELIEF mr " +
"WHERE rf.id = ? " +
"AND rf.lod = <LoD> " +
"AND rf2rc.relief_feature_id = rf.id " +
"AND mr.id = rf2rc.relief_component_id";
*/
private static final String RELIEF_COLLADA_ROOT_IDS =
"SELECT tr.surface_geometry_id " +
"FROM RELIEF_FEATURE rf, RELIEF_FEAT_TO_REL_COMP rf2rc, TIN_RELIEF tr " +
"WHERE rf.id = ? " +
"AND rf.lod = <LoD> " +
"AND rf2rc.relief_feature_id = rf.id " +
"AND tr.id = rf2rc.relief_component_id";
public static String getReliefQuery (int lodToExportFrom, DisplayForm displayForm, int queryNumber) {
String query = null;
switch (queryNumber) {
case RELIEF_TIN_QUERY:
switch (displayForm.getForm()) {
case DisplayForm.FOOTPRINT:
case DisplayForm.EXTRUDED:
case DisplayForm.GEOMETRY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN;
break;
case DisplayForm.COLLADA:
query = RELIEF_COLLADA_ROOT_IDS;
break;
}
break;
case RELIEF_TIN_BREAK_LINES_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN_BREAK_LINES;
break;
case RELIEF_TIN_STOP_LINES_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN_STOP_LINES;
break;
case RELIEF_BREAK_BREAK_LINES_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_BREAK_BREAK_LINES;
break;
case RELIEF_BREAK_RIDGE_OR_VALLEY_LINES_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_BREAK_RIDGE_OR_VALLEY_LINES;
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No relief object query found");
}
// Logger.getInstance().log(LogLevelType.DEBUG, query);
return query.replace("<LoD>", String.valueOf(lodToExportFrom));
}
public static String getReliefHighlightingQuery (int lodToExportFrom, int queryNumber) {
String query = null;
switch (queryNumber) {
case RELIEF_TIN_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN;
break;
case RELIEF_TIN_BREAK_LINES_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN_BREAK_LINES;
break;
case RELIEF_TIN_STOP_LINES_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_TIN_STOP_LINES;
break;
case RELIEF_BREAK_BREAK_LINES_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_BREAK_BREAK_LINES;
break;
case RELIEF_BREAK_RIDGE_OR_VALLEY_LINES_QUERY:
query = RELIEF_FOOTPRINT_EXTRUDED_GEOMETRY_BREAK_RIDGE_OR_VALLEY_LINES;
break;
default:
Logger.getInstance().log(LogLevel.INFO, "No relief object query found");
}
return query.replace("<LoD>", String.valueOf(lodToExportFrom));
}
} |
package dr.app.beauti.generator;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.enumTypes.StartingTreeType;
import dr.app.beauti.enumTypes.TreePriorParameterizationType;
import dr.app.beauti.enumTypes.TreePriorType;
import dr.app.beauti.options.*;
import dr.app.beauti.util.XMLWriter;
import dr.evolution.util.Units;
import dr.evomodel.coalescent.*;
import dr.evomodel.speciation.BirthDeathGernhard08Model;
import dr.evomodel.speciation.SpeciationLikelihood;
import dr.evomodel.speciation.SpeciesBindings;
import dr.evomodel.speciation.YuleModel;
import dr.evomodel.tree.TreeModel;
import dr.evomodelxml.BirthDeathModelParser;
import dr.evomodelxml.CSVExporterParser;
import dr.evomodelxml.YuleModelParser;
import dr.inference.distribution.ExponentialDistributionModel;
import dr.inference.distribution.ExponentialMarkovModel;
import dr.inference.distribution.MixedDistributionLikelihood;
import dr.inference.model.BooleanLikelihood;
import dr.inference.model.ParameterParser;
import dr.inference.model.SumStatistic;
import dr.inference.model.TestStatistic;
import dr.inferencexml.DistributionModelParser;
import dr.inferencexml.ExponentialMarkovModelParser;
import dr.util.Attribute;
import dr.xml.XMLParser;
/**
* @author Alexei Drummond
*/
public class TreePriorGenerator extends Generator {
public TreePriorGenerator(BeautiOptions options, ComponentFactory[] components) {
super(options, components);
}
// void writeTreePrior(PartitionTreePrior prior, PartitionTreeModel model, XMLWriter writer) { // for species, partitionName.treeModel
// setModelPrefix(prior.getPrefix()); // only has prefix, if (options.getPartitionTreePriors().size() > 1)
// writePriorLikelihood(prior, model, writer);
/**
* Write a tree prior (coalescent or speciational) model
*
* @param prior the partition tree prior
* @param writer the writer
*/
void writeTreePriorModel(PartitionTreePrior prior, XMLWriter writer) {
setModelPrefix(prior.getPrefix()); // only has prefix, if (options.getPartitionTreePriors().size() > 1)
String initialPopSize = null;
TreePriorType nodeHeightPrior = prior.getNodeHeightPrior();
Units.Type units = options.units;
TreePriorParameterizationType parameterization = prior.getParameterization();
switch (nodeHeightPrior) {
case CONSTANT:
writer.writeComment("A prior assumption that the population size has remained constant");
writer.writeComment("throughout the time spanned by the genealogy.");
writer.writeOpenTag(
ConstantPopulationModel.CONSTANT_POPULATION_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "constant"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
}
);
writer.writeOpenTag(ConstantPopulationModel.POPULATION_SIZE);
writeParameter("constant.popSize", prior, writer);
writer.writeCloseTag(ConstantPopulationModel.POPULATION_SIZE);
writer.writeCloseTag(ConstantPopulationModel.CONSTANT_POPULATION_MODEL);
break;
case EXPONENTIAL:
// generate an exponential prior tree
writer.writeComment("A prior assumption that the population size has grown exponentially");
writer.writeComment("throughout the time spanned by the genealogy.");
writer.writeOpenTag(
ExponentialGrowthModel.EXPONENTIAL_GROWTH_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "exponential"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
}
);
// write pop size socket
writer.writeOpenTag(ExponentialGrowthModel.POPULATION_SIZE);
writeParameter("exponential.popSize", prior, writer);
writer.writeCloseTag(ExponentialGrowthModel.POPULATION_SIZE);
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
// write growth rate socket
writer.writeOpenTag(ExponentialGrowthModel.GROWTH_RATE);
writeParameter("exponential.growthRate", prior, writer);
writer.writeCloseTag(ExponentialGrowthModel.GROWTH_RATE);
} else {
// write doubling time socket
writer.writeOpenTag(ExponentialGrowthModel.DOUBLING_TIME);
writeParameter("exponential.doublingTime", prior, writer);
writer.writeCloseTag(ExponentialGrowthModel.DOUBLING_TIME);
}
writer.writeCloseTag(ExponentialGrowthModel.EXPONENTIAL_GROWTH_MODEL);
break;
case LOGISTIC:
// generate an exponential prior tree
writer.writeComment("A prior assumption that the population size has grown logistically");
writer.writeComment("throughout the time spanned by the genealogy.");
writer.writeOpenTag(
LogisticGrowthModel.LOGISTIC_GROWTH_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "logistic"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
}
);
// write pop size socket
writer.writeOpenTag(LogisticGrowthModel.POPULATION_SIZE);
writeParameter("logistic.popSize", prior, writer);
writer.writeCloseTag(LogisticGrowthModel.POPULATION_SIZE);
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
// write growth rate socket
writer.writeOpenTag(LogisticGrowthModel.GROWTH_RATE);
writeParameter("logistic.growthRate", prior, writer);
writer.writeCloseTag(LogisticGrowthModel.GROWTH_RATE);
} else {
// write doubling time socket
writer.writeOpenTag(LogisticGrowthModel.DOUBLING_TIME);
writeParameter("logistic.doublingTime", prior, writer);
writer.writeCloseTag(LogisticGrowthModel.DOUBLING_TIME);
}
// write logistic t50 socket
writer.writeOpenTag(LogisticGrowthModel.TIME_50);
// if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN
// || options.clockModelOptions.getRateOptionClockModel() == FixRateType.RELATIVE_TO) {
// writer.writeComment("No calibration");
writer.writeComment("logistic.t50 initial always has to < treeRootHeight initial");
dr.app.beauti.options.Parameter priorPara = prior.getParameter("logistic.t50");
double initRootHeight;
if (options.isShareSameTreePrior()) {
initRootHeight = priorPara.initial;
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
double tmpRootHeight = tree.getParameter("treeModel.rootHeight").initial;
if (initRootHeight > tmpRootHeight) { // take min
initRootHeight = tmpRootHeight;
}
}
} else {
initRootHeight = prior.getTreeModel().getParameter("treeModel.rootHeight").initial;
}
// logistic.t50 initial always has to < treeRootHeight initial
if (priorPara.initial >= initRootHeight) {
priorPara.initial = initRootHeight / 2; // tree prior.initial has to < treeRootHeight.initial
}
// } else {
// writer.writeComment("Has calibration");
// //TODO
writeParameter("logistic.t50", prior, writer);
writer.writeCloseTag(LogisticGrowthModel.TIME_50);
writer.writeCloseTag(LogisticGrowthModel.LOGISTIC_GROWTH_MODEL);
initialPopSize = "logistic.popSize";
break;
case EXPANSION:
// generate an exponential prior tree
writer.writeComment("A prior assumption that the population size has grown exponentially");
writer.writeComment("from some ancestral population size in the past.");
writer.writeOpenTag(
ExpansionModel.EXPANSION_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "expansion"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
}
);
// write pop size socket
writeParameter(ExpansionModel.POPULATION_SIZE, "expansion.popSize", prior, writer);
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
// write growth rate socket
writeParameter(ExpansionModel.GROWTH_RATE, "expansion.growthRate", prior, writer);
} else {
// write doubling time socket
writeParameter(ExpansionModel.DOUBLING_TIME, "expansion.doublingTime", prior, writer);
}
// write ancestral proportion socket
writeParameter(ExpansionModel.ANCESTRAL_POPULATION_PROPORTION, "expansion.ancestralProportion", prior, writer);
writer.writeCloseTag(ExpansionModel.EXPANSION_MODEL);
initialPopSize = "expansion.popSize";
break;
case YULE:
writer.writeComment("A prior on the distribution node heights defined given");
writer.writeComment("a Yule speciation process (a pure birth process).");
writer.writeOpenTag(
YuleModel.YULE_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "yule"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(units))
}
);
writeParameter(YuleModelParser.BIRTH_RATE, "yule.birthRate", prior, writer);
writer.writeCloseTag(YuleModel.YULE_MODEL);
break;
case BIRTH_DEATH:
writer.writeComment("A prior on the distribution node heights defined given");
writer.writeComment("a Birth-Death speciation process (Gernhard 2008).");
writer.writeOpenTag(
BirthDeathGernhard08Model.BIRTH_DEATH_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "birthDeath"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(units))
}
);
writeParameter(BirthDeathModelParser.BIRTHDIFF_RATE, BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME, prior, writer);
writeParameter(BirthDeathModelParser.RELATIVE_DEATH_RATE, BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME, prior, writer);
writer.writeCloseTag(BirthDeathGernhard08Model.BIRTH_DEATH_MODEL);
break;
case SPECIES_BIRTH_DEATH:
case SPECIES_YULE:
writer.writeComment("A prior assumption that the population size has remained constant");
writer.writeComment("throughout the time spanned by the genealogy.");
writer.writeOpenTag(
ConstantPopulationModel.CONSTANT_POPULATION_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "constant"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
}
);
// initial value for pop mean is the same as what used to be the value for the population size
Parameter para = options.starBEASTOptions.getParameter(TraitGuesser.Traits.TRAIT_SPECIES + "." + options.starBEASTOptions.POP_MEAN);
prior.getParameter("constant.popSize").initial = para.initial;
writer.writeOpenTag(ConstantPopulationModel.POPULATION_SIZE);
writeParameter("constant.popSize", prior, writer);
writer.writeCloseTag(ConstantPopulationModel.POPULATION_SIZE);
writer.writeCloseTag(ConstantPopulationModel.CONSTANT_POPULATION_MODEL);
break;
}
if ((!options.starBEASTOptions.isSpeciesAnalysis()) && nodeHeightPrior != TreePriorType.CONSTANT && nodeHeightPrior != TreePriorType.EXPONENTIAL) {
// If the node height prior is not one of these two then we need to simulate a
// random starting tree under a constant size coalescent.
writer.writeComment("This is a simple constant population size coalescent model");
writer.writeComment("that is used to generate an initial tree for the chain.");
writer.writeOpenTag(
ConstantPopulationModel.CONSTANT_POPULATION_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "initialDemo"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(units))
}
);
writer.writeOpenTag(ConstantPopulationModel.POPULATION_SIZE);
if (initialPopSize != null) {
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + initialPopSize);
} else {
writeParameter(modelPrefix + "initialDemo.popSize", 1, 100.0, Double.NaN, Double.NaN, writer);
}
writer.writeCloseTag(ConstantPopulationModel.POPULATION_SIZE);
writer.writeCloseTag(ConstantPopulationModel.CONSTANT_POPULATION_MODEL);
}
}
/**
* Write the prior on node heights (coalescent or speciational models)
*
* @param prior the partition tree prior
* @param model PartitionTreeModel
* @param writer the writer
*/
void writePriorLikelihood (PartitionTreePrior prior, PartitionTreeModel model, XMLWriter writer) {
//tree model prefix
setModelPrefix(model.getPrefix()); // only has prefix, if (options.getPartitionTreePriors().size() > 1)
String priorPrefix = prior.getPrefix();
TreePriorType treePrior = prior.getNodeHeightPrior();
switch (treePrior) {
case YULE:
case BIRTH_DEATH:
// generate a speciational process
writer.writeComment("Generate a speciation likelihood for Yule or Birth Death");
writer.writeOpenTag(
SpeciationLikelihood.SPECIATION_LIKELIHOOD,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "speciation")
}
);
// write pop size socket
writer.writeOpenTag(SpeciationLikelihood.MODEL);
writeNodeHeightPriorModelRef(prior, writer);
writer.writeCloseTag(SpeciationLikelihood.MODEL);
writer.writeOpenTag(SpeciationLikelihood.TREE);
writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL);
writer.writeCloseTag(SpeciationLikelihood.TREE);
writer.writeCloseTag(SpeciationLikelihood.SPECIATION_LIKELIHOOD);
break;
case LOGISTIC:
writer.writeComment("Generate a boolean likelihood for Coalescent: Logistic Growth");
writer.writeOpenTag(
BooleanLikelihood.BOOLEAN_LIKELIHOOD,
new Attribute[]{new Attribute.Default<String>(XMLParser.ID, modelPrefix + "booleanLikelihood1")}
);
writer.writeOpenTag(
TestStatistic.TEST_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "test1"),
new Attribute.Default<String>("name", "test1")
}
);
writer.writeIDref(ParameterParser.PARAMETER, priorPrefix + "logistic.t50"); //TODO correct?
writer.writeOpenTag("lessThan");
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "treeModel.rootHeight");
writer.writeCloseTag("lessThan");
writer.writeCloseTag(TestStatistic.TEST_STATISTIC);
writer.writeCloseTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
writer.writeOpenTag(
CoalescentLikelihood.COALESCENT_LIKELIHOOD,
new Attribute[]{new Attribute.Default<String>(XMLParser.ID, modelPrefix + COALESCENT)}
);
writer.writeOpenTag(CoalescentLikelihood.MODEL);
writeNodeHeightPriorModelRef(prior, writer);
writer.writeCloseTag(CoalescentLikelihood.MODEL);
writer.writeOpenTag(CoalescentLikelihood.POPULATION_TREE);
writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL);
writer.writeCloseTag(CoalescentLikelihood.POPULATION_TREE);
writer.writeCloseTag(CoalescentLikelihood.COALESCENT_LIKELIHOOD);
break;
case SKYLINE:
// generate a Bayesian skyline plot
writer.writeComment("Generate a generalizedSkyLineLikelihood for Bayesian Skyline");
writer.writeOpenTag(
BayesianSkylineLikelihood.SKYLINE_LIKELIHOOD,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "skyline"),
new Attribute.Default<String>("linear",
prior.getSkylineModel() == TreePriorParameterizationType.LINEAR_SKYLINE ? "true" : "false")
}
);
// write pop size socket
writer.writeOpenTag(BayesianSkylineLikelihood.POPULATION_SIZES);
if (prior.getSkylineModel() == TreePriorParameterizationType.LINEAR_SKYLINE) {
writeParameter(prior.getParameter("skyline.popSize"), prior.getSkylineGroupCount() + 1, writer);
} else {
writeParameter(prior.getParameter("skyline.popSize"), prior.getSkylineGroupCount(), writer);
}
writer.writeCloseTag(BayesianSkylineLikelihood.POPULATION_SIZES);
// write group size socket
writer.writeOpenTag(BayesianSkylineLikelihood.GROUP_SIZES);
writeParameter(prior.getParameter("skyline.groupSize"), prior.getSkylineGroupCount(), writer);
writer.writeCloseTag(BayesianSkylineLikelihood.GROUP_SIZES);
writer.writeOpenTag(CoalescentLikelihood.POPULATION_TREE);
writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL);
writer.writeCloseTag(CoalescentLikelihood.POPULATION_TREE);
writer.writeCloseTag(BayesianSkylineLikelihood.SKYLINE_LIKELIHOOD);
writer.writeText("");
writeExponentialMarkovLikelihood(writer);
break;
case EXTENDED_SKYLINE:
// different format
break;
case GMRF_SKYRIDE:
writer.writeComment("Generate a gmrfSkyrideLikelihood for GMRF Bayesian Skyride process");
writer.writeOpenTag(
GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "skyride"),
new Attribute.Default<String>(GMRFSkyrideLikelihood.TIME_AWARE_SMOOTHING,
prior.getSkyrideSmoothing() == TreePriorParameterizationType.TIME_AWARE_SKYRIDE ? "true" : "false"),
new Attribute.Default<String>(GMRFSkyrideLikelihood.RANDOMIZE_TREE,
//TODO For GMRF, tree model/tree prior combination not implemented by BEAST yet. The validation is in BeastGenerator.checkOptions()
prior.getTreeModel().getStartingTreeType() == StartingTreeType.UPGMA ? "true" : "false"),
}
);
int skyrideIntervalCount = options.taxonList.getTaxonCount() - 1;
writer.writeOpenTag(GMRFSkyrideLikelihood.POPULATION_PARAMETER);
writeParameter(prior.getParameter("skyride.popSize"), skyrideIntervalCount, writer);
writer.writeCloseTag(GMRFSkyrideLikelihood.POPULATION_PARAMETER);
writer.writeOpenTag(GMRFSkyrideLikelihood.GROUP_SIZES);
writeParameter(prior.getParameter("skyride.groupSize"), skyrideIntervalCount, writer);
writer.writeCloseTag(GMRFSkyrideLikelihood.GROUP_SIZES);
writer.writeOpenTag(GMRFSkyrideLikelihood.PRECISION_PARAMETER);
writeParameter(prior.getParameter("skyride.precision"), 1, writer);
writer.writeCloseTag(GMRFSkyrideLikelihood.PRECISION_PARAMETER);
writer.writeOpenTag(GMRFSkyrideLikelihood.POPULATION_TREE);
writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL);
writer.writeCloseTag(GMRFSkyrideLikelihood.POPULATION_TREE);
writer.writeCloseTag(GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD);
break;
case SPECIES_YULE:
case SPECIES_BIRTH_DEATH:
break;
default:
// generate a coalescent process
writer.writeComment("Generate a coalescent likelihood");
writer.writeOpenTag(
CoalescentLikelihood.COALESCENT_LIKELIHOOD,
new Attribute[]{new Attribute.Default<String>(XMLParser.ID, modelPrefix + COALESCENT)}
);
writer.writeOpenTag(CoalescentLikelihood.MODEL);
writeNodeHeightPriorModelRef(prior, writer);
writer.writeCloseTag(CoalescentLikelihood.MODEL);
writer.writeOpenTag(CoalescentLikelihood.POPULATION_TREE);
writer.writeIDref(TreeModel.TREE_MODEL, modelPrefix + TreeModel.TREE_MODEL);
writer.writeCloseTag(CoalescentLikelihood.POPULATION_TREE);
writer.writeCloseTag(CoalescentLikelihood.COALESCENT_LIKELIHOOD);
}
}
void writeNodeHeightPriorModelRef(PartitionTreePrior prior, XMLWriter writer) {
TreePriorType treePrior = prior.getNodeHeightPrior();
String priorPrefix = prior.getPrefix();
switch (treePrior) {
case CONSTANT:
case SPECIES_YULE:
case SPECIES_BIRTH_DEATH:
writer.writeIDref(ConstantPopulationModel.CONSTANT_POPULATION_MODEL, priorPrefix + "constant");
break;
case EXPONENTIAL:
writer.writeIDref(ExponentialGrowthModel.EXPONENTIAL_GROWTH_MODEL, priorPrefix + "exponential");
break;
case LOGISTIC:
writer.writeIDref(LogisticGrowthModel.LOGISTIC_GROWTH_MODEL, priorPrefix + "logistic");
break;
case EXPANSION:
writer.writeIDref(ExpansionModel.EXPANSION_MODEL, priorPrefix + "expansion");
break;
case SKYLINE:
writer.writeIDref(BayesianSkylineLikelihood.SKYLINE_LIKELIHOOD, priorPrefix + "skyline");
break;
case GMRF_SKYRIDE:
writer.writeIDref(GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD, priorPrefix + "skyride");
break;
case YULE:
writer.writeIDref(YuleModel.YULE_MODEL, priorPrefix + "yule");
break;
case BIRTH_DEATH:
writer.writeIDref(BirthDeathGernhard08Model.BIRTH_DEATH_MODEL, priorPrefix + "birthDeath");
break;
default:
throw new RuntimeException("No tree prior has been specified so cannot refer to it");
}
}
void writeEBSPVariableDemographic(PartitionTreePrior prior, XMLWriter writer) {
if (prior.getNodeHeightPrior() == TreePriorType.EXTENDED_SKYLINE) {
setModelPrefix(prior.getPrefix());
final String tagName = VariableDemographicModel.PARSER.getParserName();
writer.writeComment("Generate a variableDemographic for extended Bayesian skyline process");
writer.writeOpenTag(tagName, new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + VariableDemographicModel.demoElementName),
new Attribute.Default<String>(VariableDemographicModel.TYPE, prior.getExtendedSkylineModel().toString()),
// use midpoint by default (todo) would be nice to have a user 'tickable' option
new Attribute.Default<String>(VariableDemographicModel.USE_MIDPOINTS, "true")
}
);
// Parameter popSize = prior.getParameter(VariableDemographicModel.demoElementName + ".popSize");
// Parameter populationMean = prior.getParameter(VariableDemographicModel.demoElementName + ".populationMean");
// popSize.initial = populationMean.initial;
writer.writeOpenTag(VariableDemographicModel.POPULATION_SIZES);
// writer.writeComment("popSize value = populationMean value");
writer.writeTag(ParameterParser.PARAMETER,
new Attribute.Default<String>(XMLParser.ID, modelPrefix + VariableDemographicModel.demoElementName + ".popSize"), true);
// writeParameter(popSize, -1, writer);
writer.writeCloseTag(VariableDemographicModel.POPULATION_SIZES);
writer.writeOpenTag(VariableDemographicModel.INDICATOR_PARAMETER);
writeParameter(prior.getParameter(VariableDemographicModel.demoElementName + ".indicators"), -1, writer); // not need dimension
writer.writeCloseTag(VariableDemographicModel.INDICATOR_PARAMETER);
writer.writeOpenTag(VariableDemographicModel.POPULATION_TREES);
if (options.isShareSameTreePrior()) {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeOpenTag(VariableDemographicModel.POP_TREE, new Attribute[]{
new Attribute.Default<String>(SpeciesBindings.PLOIDY, Double.toString(model.getPloidyType().getValue()))
}
);
writer.writeIDref(TreeModel.TREE_MODEL, model.getPrefix() + TreeModel.TREE_MODEL);
writer.writeCloseTag(VariableDemographicModel.POP_TREE);
}
} else {//TODO correct for not sharing same prior?
writer.writeOpenTag(VariableDemographicModel.POP_TREE, new Attribute[]{
new Attribute.Default<String>(SpeciesBindings.PLOIDY, Double.toString(prior.getTreeModel().getPloidyType().getValue()))
}
);
writer.writeIDref(TreeModel.TREE_MODEL, prior.getTreeModel().getPrefix() + TreeModel.TREE_MODEL);
writer.writeCloseTag(VariableDemographicModel.POP_TREE);
}
writer.writeCloseTag(VariableDemographicModel.POPULATION_TREES);
writer.writeCloseTag(tagName);
writer.writeOpenTag(CoalescentLikelihood.COALESCENT_LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, modelPrefix + COALESCENT));
writer.writeOpenTag(CoalescentLikelihood.MODEL);
writer.writeIDref(tagName, modelPrefix + VariableDemographicModel.demoElementName);
writer.writeCloseTag(CoalescentLikelihood.MODEL);
writer.writeComment("Take population Tree from demographic");
writer.writeCloseTag(CoalescentLikelihood.COALESCENT_LIKELIHOOD);
writer.writeOpenTag(SumStatistic.SUM_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + VariableDemographicModel.demoElementName + ".populationSizeChanges"),
new Attribute.Default<String>("elementwise", "true")
});
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + VariableDemographicModel.demoElementName + ".indicators");
writer.writeCloseTag(SumStatistic.SUM_STATISTIC);
writer.writeOpenTag(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + VariableDemographicModel.demoElementName + ".populationMeanDist")
//,new Attribute.Default<String>("elementwise", "true")
});
writer.writeOpenTag(DistributionModelParser.MEAN);
writer.writeComment("prefer populationMean value = 1");
Parameter populationMean = prior.getParameter(VariableDemographicModel.demoElementName + ".populationMean");
writer.writeTag(ParameterParser.PARAMETER,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + VariableDemographicModel.demoElementName + ".populationMean"),
new Attribute.Default<String>(ParameterParser.VALUE, Double.toString(populationMean.initial))}, true);
writer.writeCloseTag(DistributionModelParser.MEAN);
writer.writeCloseTag(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL);
}
}
void writeParameterLog(PartitionTreePrior prior, XMLWriter writer) {
setModelPrefix(prior.getPrefix());
switch (prior.getNodeHeightPrior()) {
case CONSTANT:
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "constant.popSize");
break;
case EXPONENTIAL:
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "exponential.popSize");
if (prior.getParameterization() == TreePriorParameterizationType.GROWTH_RATE) {
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "exponential.growthRate");
} else {
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "exponential.doublingTime");
}
break;
case LOGISTIC:
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "logistic.popSize");
if (prior.getParameterization() == TreePriorParameterizationType.GROWTH_RATE) {
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "logistic.growthRate");
} else {
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "logistic.doublingTime");
}
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "logistic.t50");
break;
case EXPANSION:
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "expansion.popSize");
if (prior.getParameterization() == TreePriorParameterizationType.GROWTH_RATE) {
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "expansion.growthRate");
} else {
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "expansion.doublingTime");
}
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "expansion.ancestralProportion");
break;
case SKYLINE:
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "skyline.popSize");
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "skyline.groupSize");
break;
case EXTENDED_SKYLINE:
writeSumStatisticColumn(writer, "demographic.populationSizeChanges", "popSize_changes");
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "demographic.populationMean");
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "demographic.popSize");
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "demographic.indicators");
break;
case GMRF_SKYRIDE:
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "skyride.precision");
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "skyride.popSize");
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "skyride.groupSize");
break;
case YULE:
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "yule.birthRate");
break;
case BIRTH_DEATH:
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME);
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME);
break;
case SPECIES_YULE:
case SPECIES_BIRTH_DEATH:
break;
default:
throw new RuntimeException("No tree prior has been specified so cannot refer to it");
}
}
void writeEBSPAnalysisToCSVfile(PartitionTreePrior prior, XMLWriter writer) {
setModelPrefix(prior.getPrefix());
String logFileName = options.logFileName;
if (prior.getNodeHeightPrior() == TreePriorType.EXTENDED_SKYLINE) {
writer.writeOpenTag(EBSPAnalysis.VD_ANALYSIS, new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, modelPrefix + "demographic.analysis"),
new Attribute.Default<Double>(EBSPAnalysis.BURN_IN, 0.1),
new Attribute.Default<Boolean>(VariableDemographicModel.USE_MIDPOINTS, true)}
);
writer.writeOpenTag(EBSPAnalysis.LOG_FILE_NAME);
writer.writeText(logFileName);
writer.writeCloseTag(EBSPAnalysis.LOG_FILE_NAME);
writer.writeOpenTag(EBSPAnalysis.TREE_FILE_NAMES);
for (String treeFN : options.treeFileName) {
writer.writeOpenTag(EBSPAnalysis.TREE_LOG);
writer.writeText(treeFN);
writer.writeCloseTag(EBSPAnalysis.TREE_LOG);
}
writer.writeCloseTag(EBSPAnalysis.TREE_FILE_NAMES);
writer.writeOpenTag(EBSPAnalysis.MODEL_TYPE);
writer.writeText(prior.getExtendedSkylineModel().toString());
writer.writeCloseTag(EBSPAnalysis.MODEL_TYPE);
writer.writeOpenTag(EBSPAnalysis.POPULATION_FIRST_COLUMN);
writer.writeText(VariableDemographicModel.demoElementName + ".popSize1");
writer.writeCloseTag(EBSPAnalysis.POPULATION_FIRST_COLUMN);
writer.writeOpenTag(EBSPAnalysis.INDICATORS_FIRST_COLUMN);
writer.writeText(VariableDemographicModel.demoElementName + ".indicators1");
writer.writeCloseTag(EBSPAnalysis.INDICATORS_FIRST_COLUMN);
writer.writeCloseTag(EBSPAnalysis.VD_ANALYSIS);
writer.writeOpenTag(CSVExporterParser.CSV_EXPORT,
new Attribute[]{
new Attribute.Default<String>(CSVExporterParser.FILE_NAME,
logFileName.subSequence(0, logFileName.length() - 4) + ".csv"), //.log
new Attribute.Default<String>(CSVExporterParser.SEPARATOR, ",")
});
writer.writeOpenTag(CSVExporterParser.COLUMNS);
writer.writeIDref(EBSPAnalysis.VD_ANALYSIS, modelPrefix + "demographic.analysis");
writer.writeCloseTag(CSVExporterParser.COLUMNS);
writer.writeCloseTag(CSVExporterParser.CSV_EXPORT);
}
}
private void writeExponentialMarkovLikelihood(XMLWriter writer) {
writer.writeOpenTag(
ExponentialMarkovModel.EXPONENTIAL_MARKOV_MODEL,
new Attribute[]{new Attribute.Default<String>(XMLParser.ID, modelPrefix + "eml1"),
new Attribute.Default<String>("jeffreys", "true")}
);
writer.writeOpenTag(ExponentialMarkovModelParser.CHAIN_PARAMETER);
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "skyline.popSize");
writer.writeCloseTag(ExponentialMarkovModelParser.CHAIN_PARAMETER);
writer.writeCloseTag(ExponentialMarkovModel.EXPONENTIAL_MARKOV_MODEL);
}
public void writePriorLikelihoodReferenceLog(PartitionTreePrior prior, PartitionTreeModel model, XMLWriter writer) {
//tree model prefix
setModelPrefix(model.getPrefix()); // only has prefix, if (options.getPartitionTreePriors().size() > 1)
switch (prior.getNodeHeightPrior()) {
case YULE:
case BIRTH_DEATH:
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, modelPrefix + "speciation");
break;
case SKYLINE:
writer.writeIDref(BayesianSkylineLikelihood.SKYLINE_LIKELIHOOD, modelPrefix + "skyline");
// writer.writeIDref(ExponentialMarkovModel.EXPONENTIAL_MARKOV_MODEL, modelPrefix + "eml1");
break;
case GMRF_SKYRIDE:
writer.writeIDref(GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD, modelPrefix + "skyride");
break;
case LOGISTIC:
// writer.writeIDref(BooleanLikelihood.BOOLEAN_LIKELIHOOD, modelPrefix + "booleanLikelihood1");
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, modelPrefix + COALESCENT);
break;
case EXTENDED_SKYLINE:
// only 1 coalescent, so write it separately after this method
case SPECIES_YULE:
case SPECIES_BIRTH_DEATH:
// do not need
break;
default:
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, modelPrefix + COALESCENT);
}
}
// id is written in writePriorLikelihood (PartitionTreePrior prior, PartitionTreeModel model, XMLWriter writer)
public void writePriorLikelihoodReference(PartitionTreePrior prior, PartitionTreeModel model, XMLWriter writer) {
//tree model prefix
setModelPrefix(model.getPrefix()); // only has prefix, if (options.getPartitionTreePriors().size() > 1)
switch (prior.getNodeHeightPrior()) {
case YULE:
case BIRTH_DEATH:
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, modelPrefix + "speciation");
break;
case SKYLINE:
writer.writeIDref(BayesianSkylineLikelihood.SKYLINE_LIKELIHOOD, modelPrefix + "skyline");
writer.writeIDref(ExponentialMarkovModel.EXPONENTIAL_MARKOV_MODEL, modelPrefix + "eml1");
break;
case GMRF_SKYRIDE:
writer.writeIDref(GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD, modelPrefix + "skyride");
break;
case LOGISTIC:
writer.writeIDref(BooleanLikelihood.BOOLEAN_LIKELIHOOD, modelPrefix + "booleanLikelihood1");
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, modelPrefix + COALESCENT);
break;
case EXTENDED_SKYLINE:
// only 1 coalescent, so write it in writeEBSPVariableDemographicReference
case SPECIES_YULE:
case SPECIES_BIRTH_DEATH:
// do not need
break;
default:
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, modelPrefix + COALESCENT);
}
}
public void writeEBSPVariableDemographicReference(PartitionTreePrior prior, XMLWriter writer) {
setModelPrefix(prior.getPrefix());
//TODO: make suitable for *BEAST
if (prior.getNodeHeightPrior() == TreePriorType.EXTENDED_SKYLINE) {
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, modelPrefix + COALESCENT); // only 1 coalescent
writer.writeOpenTag(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD);
writer.writeOpenTag(MixedDistributionLikelihood.DISTRIBUTION0);
writer.writeIDref(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL, modelPrefix + "demographic.populationMeanDist");
writer.writeCloseTag(MixedDistributionLikelihood.DISTRIBUTION0);
writer.writeOpenTag(MixedDistributionLikelihood.DISTRIBUTION1);
writer.writeIDref(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL, modelPrefix + "demographic.populationMeanDist");
writer.writeCloseTag(MixedDistributionLikelihood.DISTRIBUTION1);
writer.writeOpenTag(MixedDistributionLikelihood.DATA);
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "demographic.popSize");
writer.writeCloseTag(MixedDistributionLikelihood.DATA);
writer.writeOpenTag(MixedDistributionLikelihood.INDICATORS);
writer.writeIDref(ParameterParser.PARAMETER, modelPrefix + "demographic.indicators");
writer.writeCloseTag(MixedDistributionLikelihood.INDICATORS);
writer.writeCloseTag(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD);
}
}
} |
package dr.inference.operators.hmc;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.inference.operators.CoercionMode;
import dr.inference.operators.GeneralOperator;
import dr.inference.operators.GibbsOperator;
import dr.math.MathUtils;
import dr.util.Transform;
import java.util.Arrays;
/**
* @author Marc A. Suchard
* @author Zhenyu Zhang
*/
public class NoUTurnOperator extends HamiltonianMonteCarloOperator implements GeneralOperator, GibbsOperator {
private final int dim = gradientProvider.getDimension();
private class Options { //TODO: these values might be adjusted for dual averaging.
private double kappa = 0.75;
private double t0 = 10.0;
private double gamma = 0.05;
private double targetAcceptRate = 0.9;
private double logProbErrorTol = 100.0;
private double muFactor = 10.0;
private int findMax = 100;
private int maxHeight = 10;
private int adaptLength = 1000;
}
// TODO Magic numbers; pass as options
private final Options options = new Options();
public NoUTurnOperator(CoercionMode mode, double weight, GradientWrtParameterProvider gradientProvider,
Parameter parameter, Transform transform, double stepSize, int nSteps, double drawVariance) {
super(mode, weight, gradientProvider, parameter, transform, stepSize, nSteps, drawVariance, 0.0);
}
@Override
protected InstabilityHandler getDefaultInstabilityHandler() {
return InstabilityHandler.IGNORE;
}
private class StepSize {
final double initialStepSize;
double stepSize;
double logStepSize;
double averageLogStepSize;
double h;
double mu;
private StepSize(double initialStepSize) {
this.initialStepSize = initialStepSize;
this.stepSize = initialStepSize;
this.logStepSize = Math.log(stepSize);
this.averageLogStepSize = 0;
this.h = 0;
this.mu = Math.log(options.muFactor * initialStepSize);
}
private void update(long m, double cumAcceptProb, double numAcceptProbStates, Options options) {
if (m <= options.adaptLength) {
h = (1 - 1 / (m + options.t0)) * h + 1 / (m + options.t0) * (options.targetAcceptRate - (cumAcceptProb / numAcceptProbStates));
logStepSize = mu - Math.sqrt(m) / options.gamma * h;
averageLogStepSize = Math.pow(m, -options.kappa) * logStepSize +
(1 - Math.pow(m, -options.kappa)) * averageLogStepSize;
stepSize = Math.exp(logStepSize);
}
}
}
private StepSize stepSizeInformation;
@Override
public String getOperatorName() {
return "No-UTurn-Sampler operator";
}
@Override
public double doOperation(Likelihood likelihood) {
final double[] initialPosition = leapFrogEngine.getInitialPosition();
final double initialLogLikelihood = gradientProvider.getLikelihood().getLogLikelihood();
if (stepSizeInformation == null) {
stepSizeInformation = findReasonableStepSize(initialPosition);
final double testLogLikelihood = gradientProvider.getLikelihood().getLogLikelihood();
assert (testLogLikelihood == initialLogLikelihood);
assert (Arrays.equals(leapFrogEngine.getInitialPosition(), initialPosition));
}
double[] position = takeOneStep(getCount() + 1, initialPosition);
leapFrogEngine.setParameter(position);
return 0.0;
}
private double[] takeOneStep(long m, double[] initialPosition) {
double[] endPosition = Arrays.copyOf(initialPosition, initialPosition.length);
final double[] initialMomentum = drawInitialMomentum(drawDistribution, dim);
final double initialJointDensity = getJointProbability(gradientProvider, initialMomentum);
double logSliceU = Math.log(MathUtils.nextDouble()) + initialJointDensity;
TreeState trajectoryTree = new TreeState(initialPosition, initialMomentum, 1, true);
// Trajectory of Hamiltonian dynamics endowed with a binary tree structure.
int height = 0;
while (trajectoryTree.flagContinue) {
double[] tmp = updateTrajectoryTree(trajectoryTree, height, logSliceU, initialJointDensity);
if (tmp != null) {
endPosition = tmp;
}
height++;
if (height > options.maxHeight) {
throw new RuntimeException("Reach maximum tree height"); // TODO Handle more gracefully
}
}
stepSizeInformation.update(m, trajectoryTree.cumAcceptProb, trajectoryTree.numAcceptProbStates, options);
return endPosition;
}
private double[] updateTrajectoryTree(TreeState trajectoryTree, int delpth, double logSliceU, double initialJointDensity) {
double[] endPosition = null;
final double uniform1 = MathUtils.nextDouble();
int direction = (uniform1 < 0.5) ? -1 : 1;
TreeState nextTrajectoryTree = buildTree(
trajectoryTree.getPosition(direction), trajectoryTree.getMomentum(direction),
direction, logSliceU, delpth, stepSizeInformation.stepSize, initialJointDensity);
trajectoryTree.mergeNextTree(nextTrajectoryTree, direction);
if (nextTrajectoryTree.flagContinue) {
final double uniform = MathUtils.nextDouble();
final double acceptProb = (double) nextTrajectoryTree.numNodes / (double) trajectoryTree.numNodes;
if (uniform < acceptProb) {
endPosition = nextTrajectoryTree.getSample();
}
}
return endPosition;
}
private TreeState buildTree(double[] position, double[] momentum, int direction,
double logSliceU, int height, double stepSize, double initialJointDensity) {
if (height == 0) {
return buildBaseCase(position, momentum, direction, logSliceU, stepSize, initialJointDensity);
} else {
return buildRecursiveCase(position, momentum, direction, logSliceU, height, stepSize, initialJointDensity);
}
}
private void handleInstability() {
throw new RuntimeException("Numerical instability; need to handle"); // TODO
}
private TreeState buildBaseCase(double[] inPosition, double[] inMomentum, int direction,
double logSliceU, double stepSize, double initialJointDensity) {
// Make deep copy of position and momentum
double[] position = Arrays.copyOf(inPosition, inPosition.length);
double[] momentum = Arrays.copyOf(inMomentum, inMomentum.length);
leapFrogEngine.setParameter(position);
// "one frog jump!"
try {
doLeap(position, momentum, direction * stepSize);
} catch (NumericInstabilityException e) {
handleInstability();
}
double logJointProbAfter = getJointProbability(gradientProvider, momentum);
final int numNodes = (logSliceU <= logJointProbAfter ? 1 : 0);
final boolean flagContinue = (logSliceU < options.logProbErrorTol + logJointProbAfter);
// Values for dual-averaging
final double acceptProb = Math.min(1.0, Math.exp(logJointProbAfter - initialJointDensity));
final int numAcceptProbStates = 1;
leapFrogEngine.setParameter(inPosition);
return new TreeState(position, momentum, numNodes, flagContinue, acceptProb, numAcceptProbStates);
}
private TreeState buildRecursiveCase(double[] inPosition, double[] inMomentum, int direction,
double logSliceU, int height, double stepSize, double initialJointDensity) {
TreeState subtree = buildTree(inPosition, inMomentum, direction, logSliceU,
height - 1, // Recursion
stepSize, initialJointDensity);
if (subtree.flagContinue) {
TreeState nextSubtree = buildTree(subtree.getPosition(direction), subtree.getMomentum(direction), direction,
logSliceU, height - 1, stepSizeInformation.stepSize, initialJointDensity);
subtree.mergeNextTree(nextSubtree);
}
return subtree;
}
private void doLeap(final double[] position,
final double[] momentum,
final double stepSize) throws NumericInstabilityException {
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), stepSize / 2);
leapFrogEngine.updatePosition(position, momentum, stepSize, 1.0);
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), stepSize / 2);
}
private StepSize findReasonableStepSize(double[] initialPosition) {
double stepSize = 1;
double[] momentum = drawInitialMomentum(drawDistribution, dim);
int count = 1;
double[] position = Arrays.copyOf(initialPosition, dim);
double probBefore = getJointProbability(gradientProvider, momentum);
try {
doLeap(position, momentum, stepSize);
} catch (NumericInstabilityException e) {
handleInstability();
}
double probAfter = getJointProbability(gradientProvider, momentum);
double a = ((probAfter - probBefore) > Math.log(0.5) ? 1 : -1);
double probRatio = Math.exp(probAfter - probBefore);
while (Math.pow(probRatio, a) > Math.pow(2, -a)) {
probBefore = probAfter;
//"one frog jump!"
try {
doLeap(position, momentum, stepSize);
} catch (NumericInstabilityException e) {
handleInstability();
}
probAfter = getJointProbability(gradientProvider, momentum);
probRatio = Math.exp(probAfter - probBefore);
stepSize = Math.pow(2, a) * stepSize;
count++;
if (count > options.findMax) {
throw new RuntimeException("Cannot find a reasonable step-size in " + options.findMax + " iterations");
}
}
leapFrogEngine.setParameter(initialPosition);
return new StepSize(stepSize);
}
private static boolean computeStopCriterion(boolean flagContinue, TreeState state) {
return computeStopCriterion(flagContinue,
state.getPosition(1), state.getPosition(-1),
state.getMomentum(1), state.getMomentum(-1));
}
private static boolean computeStopCriterion(boolean flagContinue,
double[] positionPlus, double[] positionMinus,
double[] momentumPlus, double[] momentumMinus) {
double[] positionDifference = subtractArray(positionPlus, positionMinus);
return flagContinue &&
getDotProduct(positionDifference, momentumMinus) >= 0 &&
getDotProduct(positionDifference, momentumPlus) >= 0;
}
private static double getDotProduct(double[] x, double[] y) {
assert (x.length == y.length);
final int dim = x.length;
double total = 0.0;
for (int i = 0; i < dim; i++) {
total += x[i] * y[i];
}
return total;
}
private static double[] subtractArray(double[] a, double[] b) {
assert (a.length == b.length);
final int dim = a.length;
double result[] = new double[dim];
for (int i = 0; i < dim; i++) {
result[i] = a[i] - b[i];
}
return result;
}
private double getJointProbability(GradientWrtParameterProvider gradientProvider, double[] momentum) {
assert (gradientProvider != null);
assert (momentum != null);
return gradientProvider.getLikelihood().getLogLikelihood() - getScaledDotProduct(momentum, 1.0)
- leapFrogEngine.getParameterLogJacobian();
}
private class TreeState {
private TreeState(double[] position, double[] moment,
int numNodes, boolean flagContinue) {
this(position, moment, numNodes, flagContinue, 0.0, 0);
}
private TreeState(double[] position, double[] moment,
int numNodes, boolean flagContinue,
double acceptProb, int numAcceptProbStates) {
this.position = new double[3][];
this.momentum = new double[3][];
for (int i = 0; i < 3; ++i) {
this.position[i] = position;
this.momentum[i] = moment;
}
// Recursion variables
this.numNodes = numNodes;
this.flagContinue = flagContinue;
// Dual-averaging variables
this.cumAcceptProb = acceptProb;
this.numAcceptProbStates = numAcceptProbStates;
}
private double[] getPosition(int direction) {
return position[getIndex(direction)];
}
private double[] getMomentum(int direction) {
return momentum[getIndex(direction)];
}
private double[] getSample() {
/*
Returns a state chosen uniformly from the acceptable states along a hamiltonian dyanmics trajectory tree.
The sample is updated recursively while building trees.
*/
return this.position[getIndex(0)];
}
private void setPosition(int direction, double[] position) {
this.position[getIndex(direction)] = position;
}
private void setMomentum(int direction, double[] momentum) {
this.momentum[getIndex(direction)] = momentum;
}
private void setSample(double[] position) { this.setPosition(0, position); }
private int getIndex(int direction) { // valid directions: -1, 0, +1
assert (direction >= -1 && direction <= 1);
return direction + 1;
}
private void mergeNextTree(TreeState nextTree, int direction) {
this.setPosition(direction, nextTree.getPosition(direction));
this.setMomentum(direction, nextTree.getMomentum(direction));
this.updateSample(nextTree);
this.numNodes += nextTree.numNodes;
this.flagContinue = computeStopCriterion(nextTree.flagContinue, this);
this.cumAcceptProb += nextTree.cumAcceptProb;
this.numAcceptProbStates += nextTree.numAcceptProbStates;
}
private void updateSample(TreeState nextTree) {
double uniform = MathUtils.nextDouble();
if (nextTree.numNodes > 0
&& uniform < ((double) nextTree.numNodes / (double) (this.numNodes + nextTree.numNodes))) {
this.setSample(nextTree.getSample());
}
}
final private double[][] position;
final private double[][] momentum;
private int numNodes;
private boolean flagContinue;
private double cumAcceptProb;
private int numAcceptProbStates;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.