answer
stringlengths
17
10.2M
package com.gmail.nossr50.skills; import java.text.DecimalFormat; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.gmail.nossr50.commands.CommandHelper; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.utilities.SkillTools; import com.gmail.nossr50.skills.utilities.SkillType; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Users; public abstract class SkillCommand implements CommandExecutor { private SkillType skill; private String skillString; protected Player player; protected PlayerProfile profile; protected float skillValue; protected boolean isLucky; protected boolean hasEndurance; protected DecimalFormat percent = new DecimalFormat("##0.00%"); protected DecimalFormat decimal = new DecimalFormat("##0.00"); public SkillCommand(SkillType skill) { this.skill = skill; this.skillString = Misc.getCapitalized(skill.toString()); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (CommandHelper.noConsoleUsage(sender)) { return true; } player = (Player) sender; profile = Users.getProfile(player); if (profile == null) { sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist")); return true; } skillValue = profile.getSkillLevel(skill); isLucky = Permissions.lucky(player, skill); hasEndurance = (Permissions.activationTwelve(player) || Permissions.activationEight(player) || Permissions.activationFour(player)); dataCalculations(); permissionsCheck(); player.sendMessage(LocaleLoader.getString("Skills.Header", new Object[] { LocaleLoader.getString(skillString + ".SkillName") })); if (!skill.isChildSkill()) { player.sendMessage(LocaleLoader.getString("Commands.XPGain", new Object[] { LocaleLoader.getString("Commands.XPGain." + skillString) })); player.sendMessage(LocaleLoader.getString("Effects.Level", new Object[] { profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), profile.getXpToLevel(skill) })); } if (effectsHeaderPermissions()) { player.sendMessage(LocaleLoader.getString("Skills.Header", new Object[] { LocaleLoader.getString("Effects.Effects") })); } effectsDisplay(); if (statsHeaderPermissions()) { player.sendMessage(LocaleLoader.getString("Skills.Header", new Object[] { LocaleLoader.getString("Commands.Stats.Self") })); } statsDisplay(); SkillGuide.grabGuidePageForSkill(skill, player, args); return true; } protected String calculateRank(int maxLevel, int rankChangeLevel) { if (skillValue >= maxLevel) { return String.valueOf(maxLevel / rankChangeLevel); } return String.valueOf((int) (skillValue / rankChangeLevel)); } protected String[] calculateAbilityDisplayValues(double chance) { if (isLucky) { double luckyChance = chance * 1.3333D; if (luckyChance >= 100D) { return new String[] { percent.format(chance / 100.0D), percent.format(1.0D) }; } return new String[] { percent.format(chance / 100.0D), percent.format(luckyChance / 100.0D) }; } return new String[] { percent.format(chance / 100.0D), null }; } protected String[] calculateAbilityDisplayValues(int maxBonusLevel, double maxChance) { double abilityChance; if (skillValue >= maxBonusLevel) { abilityChance = maxChance; } else { abilityChance = (maxChance / maxBonusLevel) * skillValue; } if (isLucky) { double luckyChance = abilityChance * 1.3333D; if (luckyChance >= 100D) { return new String[] { percent.format(abilityChance / 100.0D), percent.format(1.0D) }; } return new String[] { percent.format(abilityChance / 100.0D), percent.format(luckyChance / 100.0D) }; } return new String[] { percent.format(abilityChance / 100.0D), null }; } protected String[] calculateLengthDisplayValues() { int maxLength = skill.getAbility().getMaxTicks(); int length = 2 + (int) (skillValue / Misc.abilityLengthIncreaseLevel); int enduranceLength = 0; if (Permissions.activationTwelve(player)) { enduranceLength = length + 12; } else if (Permissions.activationEight(player)) { enduranceLength = length + 8; } else if (Permissions.activationFour(player)) { enduranceLength = length + 4; } if (maxLength != 0) { if (length > maxLength) { length = maxLength; } if (enduranceLength > maxLength) { enduranceLength = maxLength; } } return new String[] { String.valueOf(length), String.valueOf(enduranceLength) }; } protected void luckyEffectsDisplay() { if (isLucky) { String perkPrefix = LocaleLoader.getString("MOTD.PerksPrefix"); player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Perks.lucky.name"), LocaleLoader.getString("Perks.lucky.desc", new Object[] { SkillTools.localizeSkillName(skill) }) })); } } protected abstract void dataCalculations(); protected abstract void permissionsCheck(); protected abstract boolean effectsHeaderPermissions(); protected abstract void effectsDisplay(); protected abstract boolean statsHeaderPermissions(); protected abstract void statsDisplay(); }
package com.bedrock.padder.activity; import android.annotation.TargetApi; import android.app.Activity; import android.content.DialogInterface; import android.content.SharedPreferences; import android.media.AudioManager; import android.media.SoundPool; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.bedrock.padder.R; import com.bedrock.padder.fragment.AboutFragment; import com.bedrock.padder.fragment.SettingsFragment; import com.bedrock.padder.helper.AdmobHelper; import com.bedrock.padder.helper.AnimateHelper; import com.bedrock.padder.helper.FabHelper; import com.bedrock.padder.helper.FileHelper; import com.bedrock.padder.helper.IntentHelper; import com.bedrock.padder.helper.SoundHelper; import com.bedrock.padder.helper.ToolbarHelper; import com.bedrock.padder.helper.TutorialHelper; import com.bedrock.padder.helper.WindowHelper; import com.bedrock.padder.model.FirebaseMetadata; import com.bedrock.padder.model.about.About; import com.bedrock.padder.model.about.Bio; import com.bedrock.padder.model.about.Detail; import com.bedrock.padder.model.about.Item; import com.bedrock.padder.model.app.theme.ColorData; import com.bedrock.padder.model.preset.Music; import com.bedrock.padder.model.preset.Preset; import com.google.gson.Gson; import java.io.File; import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt; import static com.bedrock.padder.helper.FirebaseHelper.PROJECT_LOCATION_PRESETS; import static com.bedrock.padder.helper.WindowHelper.APPLICATION_ID; @TargetApi(14) @SuppressWarnings("deprecation") public class MainActivity extends AppCompatActivity implements AboutFragment.OnFragmentInteractionListener, SettingsFragment.OnFragmentInteractionListener { final AppCompatActivity a = this; final String qs = "quickstart"; public static final String TAG = "MainActivity"; public boolean tgl1 = false; public boolean tgl2 = false; public boolean tgl3 = false; public boolean tgl4 = false; public boolean tgl5 = false; public boolean tgl6 = false; public boolean tgl7 = false; public boolean tgl8 = false; private SharedPreferences prefs = null; int currentVersionCode; int themeColor = R.color.hello; int color = R.color.cyan_400; private MaterialDialog PresetDialog; int toggleSoundId = 0; int togglePatternId = 0; private AnimateHelper anim = new AnimateHelper(); private SoundHelper sound = new SoundHelper(); private WindowHelper w = new WindowHelper(); private FabHelper fab = new FabHelper(); private ToolbarHelper toolbar = new ToolbarHelper(); private TutorialHelper tut = new TutorialHelper(); private IntentHelper intent = new IntentHelper(); private AdmobHelper ad = new AdmobHelper(); private FileHelper file = new FileHelper(); private boolean doubleBackToExitPressedOnce = false; private boolean isToolbarVisible = false; private boolean isSettingsFromMenu = false; public static boolean isPresetLoading = false; public static boolean isPresetVisible = false; public static boolean isPresetChanged = false; public static boolean isTutorialVisible = false; public static boolean isAboutVisible = false; public static boolean isSettingVisible = false; public static boolean isDeckShouldCleared = false; public static final String PRESET_KEY = "savedPreset"; private int circularRevealDuration = 400; private int fadeAnimDuration = 200; private MaterialTapTargetPrompt promptToggle; private MaterialTapTargetPrompt promptButton; private MaterialTapTargetPrompt promptSwipe; private MaterialTapTargetPrompt promptLoop; private MaterialTapTargetPrompt promptPattern; private MaterialTapTargetPrompt promptFab; private MaterialTapTargetPrompt promptPreset; private MaterialTapTargetPrompt promptInfo; private MaterialTapTargetPrompt promptTutorial; // TODO SET ON INTENT private Gson gson = new Gson(); public static Preset preset; public static Preset currentPreset = null; // TODO TAP launch //IabHelper mHelper; //IabBroadcastReceiver mBroadcastReceiver; // Used for circularReveal // End two is for settings coordination public static int coord[] = {0, 0, 0, 0}; public static void largeLog(String tag, String content) { if (content.length() > 4000) { Log.d(tag, content.substring(0, 4000)); largeLog(tag, content.substring(4000)); } else { Log.d(tag, content); } } private void quickmove() { // TODO this is a dev only function intent.intent(a, "activity.PresetStoreActivity"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); makeJson(); // TODO IAP launch //String base64EncodePublicKey = constructBase64Key(); //mHelper = new IabHelper(this, base64EncodePublicKey); //mHelper.enableDebugLogging(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. //Log.d(TAG, "Starting setup."); //mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { // public void onIabSetupFinished(IabResult result) { // Log.d(TAG, "Setup finished."); // if (!result.isSuccess()) { // // Oh noes, there was a problem. // complain("Problem setting up in-app billing: " + result); // return; // // Have we been disposed of in the meantime? If so, quit. // if (mHelper == null) return; // // Important: Dynamically register for broadcast messages about updated purchases. // // We register the receiver here instead of as a <receiver> in the Manifest // // because we always call getPurchases() at startup, so therefore we can ignore // // any broadcasts sent while the app isn't running. // // Note: registering this listener in an Activity is a bad idea, but is done here // // because this is a SAMPLE. Regardless, the receiver must be registered after // // IabHelper is setup, but before first call to getPurchases(). // mBroadcastReceiver = new IabBroadcastReceiver(MainActivity.this); // IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION); // registerReceiver(mBroadcastReceiver, broadcastFilter); // // IAB is fully set up. Now, let's get an inventory of stuff we own. // //Log.d(TAG, "Setup successful. Querying inventory."); // //try { // // mHelper.queryInventoryAsync(mGotInventoryListener); // //} catch (IabAsyncInProgressException e) { // // complain("Error querying inventory. Another async operation in progress."); // sharedPrefs Log.d(TAG, "Sharedprefs initialized"); prefs = this.getSharedPreferences(APPLICATION_ID, MODE_PRIVATE); if (getSavedPreset() != null) { try { currentPreset = gson.fromJson(file.getStringFromFile(getCurrentPresetLocation() + "/about/json.txt"), Preset.class); } catch (Exception e) { // corrupted preset } } else { } // for quickstart test //prefs.edit().putInt(qs, 0).apply(); if (prefs.getBoolean("welcome", true)) { prefs.edit().putBoolean("welcome", false).apply(); } color = prefs.getInt("color", R.color.cyan_400); toolbar.setActionBar(this); toolbar.setStatusBarTint(this); if (prefs.getString("colorData", null) == null) { // First run colorData json set ColorData placeHolderColorData = new ColorData(color); String colorDataJson = gson.toJson(placeHolderColorData); prefs.edit().putString("colorData", colorDataJson).apply(); Log.d("ColorData pref", prefs.getString("colorData", null)); } a.setVolumeControlStream(AudioManager.STREAM_MUSIC); // Set UI clearToggleButton(); setFab(); setToolbar(); setPresetInfo(); setToggleButton(R.color.colorAccent); enterAnim(); loadPreset(400); setButtonLayout(); // Request ads ad.requestLoadNativeAd(ad.getNativeAdView(R.id.adView_main, a)); // Set transparent nav bar w.setStatusBar(R.color.transparent, a); w.setNavigationBar(R.color.transparent, a); //ab.setStatusHeight(a); clearDeck(a); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.actionbar_item, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_about: intent.intentWithExtra(a, "activity.AboutActivity", "about", "tapad", 0); break; case R.id.action_settings: Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { showSettingsFragment(a); isSettingsFromMenu = true; } }, 400); break; case R.id.action_help: intent.intent(a, "activity.HelpActivity"); break; // TODO this is a dev only function case R.id.quickmove: quickmove(); break; } return super.onOptionsItemSelected(item); } @Override public void onFragmentInteraction(Uri uri){ // leave it empty // used for fragments } @Override public void onBackPressed() { Log.i("BackPressed", "isAboutVisible " + String.valueOf(isAboutVisible)); Log.i("BackPressed", "isSettingVisible " + String.valueOf(isSettingVisible)); if (isToolbarVisible == true) { if (prefs.getInt(qs, 0) > 0 && isAboutVisible == false && isSettingVisible == false) { Log.i("BackPressed", String.valueOf(prefs.getInt(qs, 0))); Log.i("BackPressed", "Quickstart tap target prompt is visible, backpress ignored."); } else { // new structure if (isAboutVisible && isSettingVisible) { // Setting is visible above about closeSettings(); } else if (isSettingVisible) { // Setting visible alone closeSettings(); } else if (isAboutVisible) { // About visible alone closeAbout(); } else { // Toolbar visible alone closeToolbar(a); } } } else if (isSettingVisible == true) { // Setting is visible above about closeSettings(); } else { if (prefs.getInt(qs, 0) > 0) { Log.i("BackPressed", "Tutorial prompt is visible, backpress ignored."); } else { Log.d("BackPressed", "Down"); if (doubleBackToExitPressedOnce) { super.onBackPressed(); finish(); } doubleBackToExitPressedOnce = true; Toast.makeText(this, R.string.confirm_exit, Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; } }, 2000); } } } public void onWindowFocusChanged(boolean hasFocus) { Log.i("MainActivity", "onWindowFocusChanged"); sound.soundAllStop(); int tutorial[] = { R.id.btn00_tutorial, R.id.tgl1_tutorial, R.id.tgl2_tutorial, R.id.tgl3_tutorial, R.id.tgl4_tutorial, R.id.tgl5_tutorial, R.id.tgl6_tutorial, R.id.tgl7_tutorial, R.id.tgl8_tutorial, R.id.btn11_tutorial, R.id.btn12_tutorial, R.id.btn13_tutorial, R.id.btn14_tutorial, R.id.btn21_tutorial, R.id.btn22_tutorial, R.id.btn23_tutorial, R.id.btn24_tutorial, R.id.btn31_tutorial, R.id.btn32_tutorial, R.id.btn33_tutorial, R.id.btn34_tutorial, R.id.btn41_tutorial, R.id.btn42_tutorial, R.id.btn43_tutorial, R.id.btn44_tutorial}; for (int i = 0; i < tutorial.length; i++) { w.setInvisible(tutorial[i], 10, a); } color = prefs.getInt("color", R.color.cyan_400); if (isPresetVisible) { if (!isAboutVisible && !isSettingVisible) { // preset store visible closePresetStore(); } isPresetVisible = false; } clearToggleButton(); super.onWindowFocusChanged(hasFocus); } @Override public void onPause() { ad.pauseNativeAdView(R.id.adView_main, a); super.onPause(); } @Override public void onResume() { super.onResume(); if (isTutorialVisible == true) { tut.tutorialStop(a); } Log.d("MainActivity", "onResume"); sound.soundAllStop(); int tutorial[] = { R.id.btn00_tutorial, R.id.tgl1_tutorial, R.id.tgl2_tutorial, R.id.tgl3_tutorial, R.id.tgl4_tutorial, R.id.tgl5_tutorial, R.id.tgl6_tutorial, R.id.tgl7_tutorial, R.id.tgl8_tutorial, R.id.btn11_tutorial, R.id.btn12_tutorial, R.id.btn13_tutorial, R.id.btn14_tutorial, R.id.btn21_tutorial, R.id.btn22_tutorial, R.id.btn23_tutorial, R.id.btn24_tutorial, R.id.btn31_tutorial, R.id.btn32_tutorial, R.id.btn33_tutorial, R.id.btn34_tutorial, R.id.btn41_tutorial, R.id.btn42_tutorial, R.id.btn43_tutorial, R.id.btn44_tutorial}; for (int i = 0; i < tutorial.length; i++) { w.setInvisible(tutorial[i], 10, a); } ad.resumeNativeAdView(R.id.adView_main, a); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); sound.soundAllStop(); sound.cancelLoading(); ad.destroyNativeAdView(R.id.adView_main, a); super.onDestroy(); } private void showAboutFragment() { getSupportFragmentManager() .beginTransaction() .add(R.id.fragment_about_container, new AboutFragment()) .commit(); WindowHelper w = new WindowHelper(); w.getView(R.id.fragment_about_container, a).setVisibility(View.VISIBLE); setAboutVisible(true); w.setRecentColor(R.string.about, 0, themeColor, a); } public static void showSettingsFragment(AppCompatActivity a) { a.getSupportFragmentManager() .beginTransaction() .add(R.id.fragment_settings_container, new SettingsFragment()) .commit(); WindowHelper w = new WindowHelper(); w.getView(R.id.fragment_settings_container, a).setVisibility(View.VISIBLE); setSettingVisible(true); w.setRecentColor(R.string.settings, 0, R.color.colorAccent, a); } // TODO iap launch // IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { // public void onQueryInventoryFinished(IabResult result, Inventory inventory) { // Log.d(TAG, "Query inventory finished."); // // Have we been disposed of in the meantime? If so, quit. // if (mHelper == null) return; // // Is it a failure? // if (result.isFailure()) { // complain("Failed to query inventory: " + result); // return; // Log.d(TAG, "Query inventory was successful."); // Log.d(TAG, "Initial inventory query finished; enabling main UI."); // @NonNull // private String constructBase64Key() { // // TODO work on iap processes // String encodedString = getResources().getString(R.string.base64_rsa_key); // int base64Length = encodedString.length(); // char[] encodedStringArray = encodedString.toCharArray(); // char temp; // for(int i = 0; i < base64Length / 2; i++) { // if (i % 2 == 0) { // temp = encodedStringArray[i]; // encodedStringArray[i] = encodedStringArray[base64Length - 1 - i]; // encodedStringArray[base64Length - 1 - i] = temp; // return String.valueOf(encodedStringArray); // private void complain(String message) { // alert("Error: " + message); // private void alert(String message) { // AlertDialog.Builder bld = new AlertDialog.Builder(this); // bld.setMessage(message); // bld.setNeutralButton("OK", null); // Log.d(TAG, "Showing alert dialog: " + message); // bld.create().show(); private void enterAnim() { anim.fadeIn(R.id.actionbar_layout, 0, 200, "background", a); anim.fadeIn(R.id.actionbar_image, 200, 200, "image", a); isPresetLoading = true; } private void setButtonLayout() { int screenWidthPx = (int)(w.getWindowWidthPx(a) * (0.8)); int marginPx = w.getWindowWidthPx(a) / 160; int newWidthPx; int newHeightPx; int buttons[][] = { // first row is root view {R.id.ver0, R.id.tgl1, R.id.tgl2, R.id.tgl3, R.id.tgl4, R.id.btn00}, {R.id.ver1, R.id.btn11, R.id.btn12, R.id.btn13, R.id.btn14, R.id.tgl5}, {R.id.ver2, R.id.btn21, R.id.btn22, R.id.btn23, R.id.btn24, R.id.tgl6}, {R.id.ver3, R.id.btn31, R.id.btn32, R.id.btn33, R.id.btn34, R.id.tgl7}, {R.id.ver4, R.id.btn41, R.id.btn42, R.id.btn43, R.id.btn44, R.id.tgl8}, }; int tutorialButtons[][] = { // first row is root view {R.id.ver0_tutorial, R.id.tgl1_tutorial, R.id.tgl2_tutorial, R.id.tgl3_tutorial, R.id.tgl4_tutorial, R.id.btn00_tutorial}, {R.id.ver1_tutorial, R.id.btn11_tutorial, R.id.btn12_tutorial, R.id.btn13_tutorial, R.id.btn14_tutorial, R.id.tgl5_tutorial}, {R.id.ver2_tutorial, R.id.btn21_tutorial, R.id.btn22_tutorial, R.id.btn23_tutorial, R.id.btn24_tutorial, R.id.tgl6_tutorial}, {R.id.ver3_tutorial, R.id.btn31_tutorial, R.id.btn32_tutorial, R.id.btn33_tutorial, R.id.btn34_tutorial, R.id.tgl7_tutorial}, {R.id.ver4_tutorial, R.id.btn41_tutorial, R.id.btn42_tutorial, R.id.btn43_tutorial, R.id.btn44_tutorial, R.id.tgl8_tutorial}, }; for (int i = 0; i < 5; i++) { if (i == 0) { newHeightPx = screenWidthPx / 9; } else { newHeightPx = (screenWidthPx / 9) * 2; } for (int j = 0; j < 6; j++) { if (j == 0) { resizeView(tutorialButtons[i][j], 0, newHeightPx); resizeView(buttons[i][j], 0, newHeightPx); } else if (j == 5) { newWidthPx = screenWidthPx / 9; resizeView(tutorialButtons[i][j], newWidthPx, newHeightPx); resizeView(buttons[i][j], newWidthPx - (marginPx * 2), newHeightPx - (marginPx * 2)); w.setMarginLinearPX(buttons[i][j], marginPx, marginPx, marginPx, marginPx, a); if (i != 0) { w.getTextView(buttons[i][j], a).setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) (newWidthPx / 3)); } } else { newWidthPx = (screenWidthPx / 9) * 2; resizeView(tutorialButtons[i][j], newWidthPx, newHeightPx); resizeView(buttons[i][j], newWidthPx - (marginPx * 2), newHeightPx - (marginPx * 2)); w.setMarginLinearPX(buttons[i][j], marginPx, marginPx, marginPx, marginPx, a); if (i == 0) { w.getTextView(buttons[i][j], a).setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) (newHeightPx / 3)); } } } } } private void resizeView(int viewId, int newWidth, int newHeight) { View view = a.findViewById(viewId); Log.d("resizeView", "width " + newWidth + " X height " + newHeight); if (newHeight > 0) { view.getLayoutParams().height = newHeight; } if (newWidth > 0) { view.getLayoutParams().width = newWidth; } view.setLayoutParams(view.getLayoutParams()); } public void setQuickstart(final Activity activity) { final SharedPreferences pref = activity.getSharedPreferences(APPLICATION_ID, MODE_PRIVATE); try { currentVersionCode = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode; Log.i("versionCode", "versionCode retrieved = " + String.valueOf(currentVersionCode)); } catch (android.content.pm.PackageManager.NameNotFoundException e) { // handle exception currentVersionCode = -1; Log.e("NameNotFound", "NNFE, currentVersionCode = -1"); } try { Log.d("VersionCode", "sharedPrefs versionCode = " + String.valueOf(pref.getInt("versionCode", -1)) + " , currentVersionCode = " + String.valueOf(currentVersionCode)); Log.d("VersionCode", "Updated, show changelog"); if (currentVersionCode > pref.getInt("versionCode", -1)) { // new app and updates new MaterialDialog.Builder(activity) .title(w.getStringId("info_tapad_info_changelog")) .content(w.getStringId("info_tapad_info_changelog_text")) .contentColorRes(R.color.dark_primary) .positiveText(R.string.dialog_close) .positiveColorRes(R.color.colorAccent) .dismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { // Dialog if (pref.getInt(qs, 0) == 0) { closeToolbar(activity); new MaterialDialog.Builder(activity) .title(R.string.dialog_quickstart_welcome_title) .content(R.string.dialog_quickstart_welcome_text) .positiveText(R.string.dialog_quickstart_welcome_positive) .positiveColorRes(R.color.colorAccent) .negativeText(R.string.dialog_quickstart_welcome_negative) .negativeColorRes(R.color.dark_secondary) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { pref.edit().putInt(qs, 0).apply(); Log.i("sharedPrefs", "quickstart edited to 0"); } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { pref.edit().putInt(qs, -1).apply(); Log.i("sharedPrefs", "quickstart edited to -1"); } }) .dismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { if (pref.getInt(qs, 0) == 0) { Log.i("setQuickstart", "Quickstart started"); if (promptFab != null) { return; } promptToggle = new MaterialTapTargetPrompt.Builder(activity) .setTarget(activity.findViewById(R.id.tgl1)) .setPrimaryText(R.string.dialog_tap_target_toggle_primary) .setSecondaryText(R.string.dialog_tap_target_toggle_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setAutoDismiss(false) .setAutoFinish(false) .setFocalColourFromRes(R.color.white) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptToggle.finish(); promptToggle = null; pref.edit().putInt(qs, 1).apply(); Log.i("sharedPrefs", "quickstart edited to 1"); } } @Override public void onHidePromptComplete() { promptButton = new MaterialTapTargetPrompt.Builder(activity) .setTarget(activity.findViewById(R.id.btn31)) .setPrimaryText(R.string.dialog_tap_target_button_primary) .setSecondaryText(R.string.dialog_tap_target_button_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setAutoDismiss(false) .setAutoFinish(false) .setFocalColourFromRes(R.color.white) .setFocalRadius((float) w.convertDPtoPX(80, activity)) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptButton.finish(); promptButton = null; pref.edit().putInt(qs, 3).apply(); Log.i("sharedPrefs", "quickstart edited to 3"); } } @Override public void onHidePromptComplete() { promptSwipe = new MaterialTapTargetPrompt.Builder(activity) .setTarget(activity.findViewById(R.id.btn23)) .setPrimaryText(R.string.dialog_tap_target_swipe_primary) .setSecondaryText(R.string.dialog_tap_target_swipe_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setAutoDismiss(false) .setAutoFinish(false) .setFocalColourFromRes(R.color.white) .setFocalRadius((float) w.convertDPtoPX(80, activity)) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptSwipe.finish(); promptSwipe = null; pref.edit().putInt(qs, 4).apply(); Log.i("sharedPrefs", "quickstart edited to 4"); } } @Override public void onHidePromptComplete() { promptLoop = new MaterialTapTargetPrompt.Builder(activity) .setTarget(activity.findViewById(R.id.btn42)) .setPrimaryText(R.string.dialog_tap_target_loop_primary) .setSecondaryText(R.string.dialog_tap_target_loop_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setAutoDismiss(false) .setAutoFinish(false) .setFocalColourFromRes(R.color.white) .setFocalRadius((float) w.convertDPtoPX(80, activity)) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptLoop.finish(); promptLoop = null; pref.edit().putInt(qs, 5).apply(); Log.i("sharedPrefs", "quickstart edited to 5"); } } @Override public void onHidePromptComplete() { promptPattern = new MaterialTapTargetPrompt.Builder(activity) .setTarget(activity.findViewById(R.id.tgl7)) .setPrimaryText(R.string.dialog_tap_target_pattern_primary) .setSecondaryText(R.string.dialog_tap_target_pattern_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setAutoDismiss(false) .setAutoFinish(false) .setFocalColourFromRes(R.color.white) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptPattern.finish(); promptPattern = null; pref.edit().putInt(qs, 5).apply(); Log.i("sharedPrefs", "quickstart edited to 5"); } } @Override public void onHidePromptComplete() { promptFab = new MaterialTapTargetPrompt.Builder(activity) .setTarget(activity.findViewById(R.id.fab)) .setPrimaryText(R.string.dialog_tap_target_fab_primary) .setSecondaryText(R.string.dialog_tap_target_fab_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setAutoDismiss(false) .setAutoFinish(false) .setFocalColourFromRes(R.color.white) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptFab.finish(); promptFab = null; pref.edit().putInt(qs, 6).apply(); Log.i("sharedPrefs", "quickstart edited to 6"); } } @Override public void onHidePromptComplete() { promptPreset = new MaterialTapTargetPrompt.Builder(activity) .setTarget(activity.findViewById(R.id.toolbar_preset)) .setPrimaryText(R.string.dialog_tap_target_preset_primary) .setSecondaryText(R.string.dialog_tap_target_preset_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setAutoDismiss(false) .setAutoFinish(false) .setFocalColourFromRes(R.color.blue_500) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptPreset.finish(); promptPreset = null; pref.edit().putInt(qs, 7).apply(); Log.i("sharedPrefs", "quickstart edited to 7"); } } @Override public void onHidePromptComplete() { } }) .show(); } }) .show(); } }) .show(); } }) .show(); } }) .show(); } }) .show(); } }) .show(); } else { Log.i("setQuickstart", "Quickstart canceled"); pref.edit().putInt(qs, -1).apply(); } } }) .show(); } pref.edit().putInt("versionCode", currentVersionCode).apply(); // Change this Log.d("VersionCode", "putInt " + String.valueOf(pref.getInt("versionCode", -1))); } }) .show(); } } catch (Exception e) { Log.e("QuickstartException", e.getMessage()); } } private void setFab() { fab.setFab(a); fab.setFabIcon(R.drawable.ic_info_white, a); fab.showFab(); fab.setFabOnClickListener(new Runnable() { @Override public void run() { if (isToolbarVisible == false) { fab.hideFab(0, 200); anim.fadeIn(R.id.toolbar, 200, 100, "toolbarIn", a); if (prefs.getInt(qs, 0) == 7) { Log.i("setQuickstart", "Quickstart started"); if (promptInfo != null) { return; } promptInfo = new MaterialTapTargetPrompt.Builder(a) .setTarget(a.findViewById(R.id.toolbar_info)) .setPrimaryText(R.string.dialog_tap_target_info_primary) .setSecondaryText(R.string.dialog_tap_target_info_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setFocalColourFromRes(R.color.blue_500) .setAutoDismiss(false) .setAutoFinish(false) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptInfo.finish(); promptInfo = null; prefs.edit().putInt(qs, 8).apply(); Log.i("sharedPrefs", "quickstart edited to 8"); } } @Override public void onHidePromptComplete() { } }) .show(); } isToolbarVisible = true; } } }); // set bottom margin w.setMarginRelativePX(R.id.fab, 0, 0, w.convertDPtoPX(20, a), w.getNavigationBarFromPrefs(a) + w.convertDPtoPX(20, a), a); } private void setToolbar() { // set bottom margin w.setMarginRelativePX(R.id.toolbar, 0, 0, 0, w.getNavigationBarFromPrefs(a), a); View info = findViewById(R.id.toolbar_info); View tutorial = findViewById(R.id.toolbar_tutorial); View preset = findViewById(R.id.toolbar_preset); View settings = findViewById(R.id.toolbar_settings); assert info != null; info.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { coord[0] = (int) event.getRawX(); coord[1] = (int) event.getRawY(); return false; } }); info.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isAboutVisible == false) { anim.circularRevealInPx(R.id.placeholder, coord[0], coord[1], 0, (int) Math.hypot(coord[0], coord[1]) + 200, new AccelerateDecelerateInterpolator(), circularRevealDuration, 0, a); Handler about = new Handler(); about.postDelayed(new Runnable() { @Override public void run() { showAboutFragment(); } }, circularRevealDuration); anim.fadeOut(R.id.placeholder, circularRevealDuration, fadeAnimDuration, a); isAboutVisible = true; } } }); assert preset != null; preset.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { coord[0] = (int) event.getRawX(); coord[1] = (int) event.getRawY(); return false; } }); preset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isPresetVisible == false) { anim.circularRevealInPx(R.id.placeholder, coord[0], coord[1], 0, (int) Math.hypot(coord[0], coord[1]) + 200, new AccelerateDecelerateInterpolator(), circularRevealDuration, 0, a); intent.intent(a, "activity.PresetStoreActivity", circularRevealDuration); } } }); assert tutorial != null; tutorial.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { coord[0] = (int) event.getRawX(); coord[1] = (int) event.getRawY(); return false; } }); tutorial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("isTutVisible", String.valueOf(isTutorialVisible)); if (isTutorialVisible == false) { toggleTutorial(); isTutorialVisible = true; } } }); assert settings != null; settings.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { coord[2] = (int) event.getRawX(); coord[3] = (int) event.getRawY(); return false; } }); settings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isSettingVisible == false) { w.setRecentColor(R.string.settings, 0, R.color.colorAccent, a); anim.circularRevealInPx(R.id.placeholder, coord[2], coord[3], 0, (int) Math.hypot(coord[2], coord[3]) + 200, new AccelerateDecelerateInterpolator(), circularRevealDuration, 0, a); Handler about = new Handler(); about.postDelayed(new Runnable() { @Override public void run() { showSettingsFragment(a); } }, circularRevealDuration); anim.fadeOut(R.id.placeholder, circularRevealDuration, fadeAnimDuration, a); setSettingVisible(true); } } }); } private void closeToolbar(Activity activity) { anim.fadeOut(R.id.toolbar, 0, 100, activity); fab.showFab(100, 200); isToolbarVisible = false; } private void closeAbout() { Log.d("closeAbout", "triggered"); anim.circularRevealInPx(R.id.placeholder, coord[0], coord[1], (int) Math.hypot(coord[0], coord[1]) + 200, 0, new AccelerateDecelerateInterpolator(), circularRevealDuration, fadeAnimDuration, a); anim.fadeIn(R.id.placeholder, 0, fadeAnimDuration, "aboutOut", a); setAboutVisible(false); Handler closeAbout = new Handler(); closeAbout.postDelayed(new Runnable() { @Override public void run() { setPresetInfo(); w.getView(R.id.fragment_about_container, a).setVisibility(View.GONE); } }, fadeAnimDuration); // Firstrun tutorial if (prefs.getInt(qs, 0) == 8) { promptPreset = new MaterialTapTargetPrompt.Builder(a) .setTarget(a.findViewById(R.id.toolbar_preset)) .setPrimaryText(R.string.dialog_tap_target_preset_primary) .setSecondaryText(R.string.dialog_tap_target_preset_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setFocalColourFromRes(R.color.blue_500) .setAutoDismiss(false) .setAutoFinish(false) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptPreset.finish(); promptPreset = null; prefs.edit().putInt(qs, 9).apply(); Log.i("sharedPrefs", "quickstart edited to 9"); } } @Override public void onHidePromptComplete() { // idk why is this here //isTutorialVisible = false; } }) .show(); } // reset the touch coords coord[0] = 0; coord[1] = 0; } public void toggleTutorial() { if (currentPreset != null) { if (!isPresetLoading) { String tutorialText = currentPreset.getAbout().getTutorialLink(); if (tutorialText == null || tutorialText.equals("null")) { tutorialText = w.getStringFromId("dialog_tutorial_text_error", a); } else { tutorialText = currentPreset.getAbout().getTutorialLink(); } new MaterialDialog.Builder(a) .title(R.string.dialog_tutorial_title) .content(tutorialText) .neutralText(R.string.dialog_close) .dismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { isTutorialVisible = false; } }) .show(); } else { // still loading preset Toast.makeText(a, R.string.tutorial_loading, Toast.LENGTH_LONG).show(); isTutorialVisible = false; } } else { // no preset Toast.makeText(a, R.string.tutorial_no_preset, Toast.LENGTH_LONG).show(); isTutorialVisible = false; } } private void closeSettings() { Log.d("closeSettings", "triggered"); if (isToolbarVisible && !isSettingsFromMenu) { anim.circularRevealInPx(R.id.placeholder, coord[2], coord[3], (int) Math.hypot(coord[2], coord[3]) + 200, 0, new AccelerateDecelerateInterpolator(), circularRevealDuration, fadeAnimDuration, a); anim.fadeIn(R.id.placeholder, 0, fadeAnimDuration, "settingOut", a); } else { w.getView(R.id.fragment_settings_container, a).setVisibility(View.GONE); isSettingsFromMenu = false; } color = prefs.getInt("color", R.color.cyan_400); clearToggleButton(); setSettingVisible(false); Handler closeSettings = new Handler(); closeSettings.postDelayed(new Runnable() { @Override public void run() { if (isAboutVisible) { // about visible set taskdesc w.setRecentColor(R.string.about, 0, themeColor, a); } else { setPresetInfo(); } w.getView(R.id.fragment_settings_container, a).setVisibility(View.GONE); } }, fadeAnimDuration); // reset the touch coords coord[2] = 0; coord[3] = 0; } private void closePresetStore() { setPresetInfo(); if (coord[0] > 0 && coord[1] > 0) { anim.circularRevealInPx(R.id.placeholder, coord[0], coord[1], (int) Math.hypot(coord[0], coord[1]) + 200, 0, new AccelerateDecelerateInterpolator(), circularRevealDuration, 200, a); } if (prefs.getInt(qs, 0) == 7) { promptTutorial = new MaterialTapTargetPrompt.Builder(a) .setTarget(a.findViewById(R.id.toolbar_tutorial)) .setPrimaryText(R.string.dialog_tap_target_tutorial_primary) .setSecondaryText(R.string.dialog_tap_target_tutorial_secondary) .setAnimationInterpolator(new FastOutSlowInInterpolator()) .setFocalColourFromRes(R.color.blue_500) .setAutoDismiss(false) .setAutoFinish(false) .setCaptureTouchEventOutsidePrompt(true) .setOnHidePromptListener(new MaterialTapTargetPrompt.OnHidePromptListener() { @Override public void onHidePrompt(MotionEvent event, boolean tappedTarget) { if (tappedTarget) { promptTutorial.finish(); promptTutorial = null; prefs.edit().putInt(qs, -1).apply(); Log.i("sharedPrefs", "quickstart edited to -1, completed"); } } @Override public void onHidePromptComplete() { } }) .show(); } } private void loadPreset(int delay) { if (currentPreset != null) { Handler preset = new Handler(); preset.postDelayed(new Runnable() { @Override public void run() { sound.loadSound(currentPreset, a); } }, delay); } else { // show null preset } } private void setToggleButton(final int color_id) { // 1 - 4 w.setOnTouch(R.id.tgl1, new Runnable() { @Override public void run() { clearDeck(a); if (tgl1 == false) { toggleSoundId = 1; if (tgl5 || tgl6 || tgl7 || tgl8) { sound.setButtonToggle(toggleSoundId, color, togglePatternId, a); } else { sound.setButtonToggle(toggleSoundId, color, a); } w.setViewBackgroundColor(R.id.tgl1, color_id, a); w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a); if (tgl2 || tgl3 || tgl4) { sound.playToggleButtonSound(1); } } else { w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a); toggleSoundId = 0; sound.setButton(R.color.grey_dark, a); sound.soundAllStop(); } } }, new Runnable() { @Override public void run() { if (tgl1 == false) { tgl1 = true; tgl2 = false; tgl3 = false; tgl4 = false; } else { tgl1 = false; } } }, a); w.setOnTouch(R.id.tgl2, new Runnable() { @Override public void run() { clearDeck(a); if (tgl2 == false) { toggleSoundId = 2; if (tgl5 || tgl6 || tgl7 || tgl8) { sound.setButtonToggle(toggleSoundId, color, togglePatternId, a); } else { sound.setButtonToggle(toggleSoundId, color, a); } w.setViewBackgroundColor(R.id.tgl2, color_id, a); w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a); sound.playToggleButtonSound(2); } else { w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a); toggleSoundId = 0; sound.setButton(R.color.grey_dark, a); sound.soundAllStop(); } } }, new Runnable() { @Override public void run() { if (tgl2 == false) { tgl2 = true; tgl1 = false; tgl3 = false; tgl4 = false; } else { tgl2 = false; } } }, a); w.setOnTouch(R.id.tgl3, new Runnable() { @Override public void run() { clearDeck(a); if (tgl3 == false) { toggleSoundId = 3; if (tgl5 || tgl6 || tgl7 || tgl8) { sound.setButtonToggle(toggleSoundId, color, togglePatternId, a); } else { sound.setButtonToggle(toggleSoundId, color, a); } w.setViewBackgroundColor(R.id.tgl3, color_id, a); w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a); sound.playToggleButtonSound(3); } else { w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a); toggleSoundId = 0; sound.setButton(R.color.grey_dark, a); sound.soundAllStop(); } } }, new Runnable() { @Override public void run() { if (tgl3 == false) { tgl3 = true; tgl2 = false; tgl1 = false; tgl4 = false; } else { tgl3 = false; } } }, a); w.setOnTouch(R.id.tgl4, new Runnable() { @Override public void run() { clearDeck(a); if (tgl4 == false) { toggleSoundId = 4; if (tgl5 || tgl6 || tgl7 || tgl8) { sound.setButtonToggle(toggleSoundId, color, togglePatternId, a); } else { sound.setButtonToggle(toggleSoundId, color, a); } w.setViewBackgroundColor(R.id.tgl4, color_id, a); w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a); sound.playToggleButtonSound(4); } else { w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a); toggleSoundId = 0; sound.setButton(R.color.grey_dark, a); sound.soundAllStop(); } } }, new Runnable() { @Override public void run() { if (tgl4 == false) { tgl4 = true; tgl2 = false; tgl3 = false; tgl1 = false; } else { tgl4 = false; } } }, a); // 5 - 8 w.setOnTouch(R.id.tgl5, new Runnable() { @Override public void run() { if (tgl5 == false) { togglePatternId = 1; if (tgl1 || tgl2 || tgl3 || tgl4) { sound.setButtonToggle(toggleSoundId, color, togglePatternId, a); } w.setViewBackgroundColor(R.id.tgl5, color_id, a); w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a); } else { w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a); togglePatternId = 0; if (tgl1 || tgl2 || tgl3 || tgl4) { sound.setButtonToggle(toggleSoundId, color, a); } } } }, new Runnable() { @Override public void run() { if (tgl5 == false) { tgl5 = true; tgl6 = false; tgl7 = false; tgl8 = false; } else { tgl5 = false; } } }, a); w.setOnTouch(R.id.tgl6, new Runnable() { @Override public void run() { if (tgl6 == false) { togglePatternId = 2; if (tgl1 || tgl2 || tgl3 || tgl4) { sound.setButtonToggle(toggleSoundId, color, togglePatternId, a); } w.setViewBackgroundColor(R.id.tgl6, color_id, a); w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a); } else { w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a); togglePatternId = 0; if (tgl1 || tgl2 || tgl3 || tgl4) { sound.setButtonToggle(toggleSoundId, color, a); } } } }, new Runnable() { @Override public void run() { if (tgl6 == false) { tgl6 = true; tgl5 = false; tgl7 = false; tgl8 = false; } else { tgl6 = false; } } }, a); w.setOnTouch(R.id.tgl7, new Runnable() { @Override public void run() { if (tgl7 == false) { togglePatternId = 3; if (tgl1 || tgl2 || tgl3 || tgl4) { sound.setButtonToggle(toggleSoundId, color, togglePatternId, a); } w.setViewBackgroundColor(R.id.tgl7, color_id, a); w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a); } else { w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a); togglePatternId = 0; if (tgl1 || tgl2 || tgl3 || tgl4) { sound.setButtonToggle(toggleSoundId, color, a); } } } }, new Runnable() { @Override public void run() { if (tgl7 == false) { tgl7 = true; tgl6 = false; tgl5 = false; tgl8 = false; } else { tgl7 = false; } } }, a); w.setOnTouch(R.id.tgl8, new Runnable() { @Override public void run() { if (tgl8 == false) { togglePatternId = 4; if (tgl1 || tgl2 || tgl3 || tgl4) { sound.setButtonToggle(toggleSoundId, color, togglePatternId, a); } w.setViewBackgroundColor(R.id.tgl8, color_id, a); w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a); } else { w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a); togglePatternId = 0; if (tgl1 || tgl2 || tgl3 || tgl4) { sound.setButtonToggle(toggleSoundId, color, a); } } } }, new Runnable() { @Override public void run() { if (tgl8 == false) { tgl8 = true; tgl6 = false; tgl7 = false; tgl5 = false; } else { tgl8 = false; } } }, a); } public void clearDeck(Activity activity) { // clear button colors int buttonIds[] = { R.id.btn00, R.id.btn11, R.id.btn12, R.id.btn13, R.id.btn14, R.id.btn21, R.id.btn22, R.id.btn23, R.id.btn24, R.id.btn31, R.id.btn32, R.id.btn33, R.id.btn34, R.id.btn41, R.id.btn42, R.id.btn43, R.id.btn44 }; for (int buttonId : buttonIds) { View pad = activity.findViewById(buttonId); pad.setBackgroundColor(activity.getResources().getColor(R.color.grey)); } // stop all looping sounds Integer streamIds[] = w.getLoopStreamIds(); SoundPool soundPool = sound.getSoundPool(); try { for (Integer streamId : streamIds) { soundPool.stop(streamId); } } finally { w.clearLoopStreamId(); } } private void clearToggleButton() { if (isDeckShouldCleared) { w.setViewBackgroundColor(R.id.tgl1, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl2, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl3, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl4, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl5, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl6, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl7, R.color.grey, a); w.setViewBackgroundColor(R.id.tgl8, R.color.grey, a); tgl1 = false; tgl2 = false; tgl3 = false; tgl4 = false; tgl5 = false; tgl6 = false; tgl7 = false; tgl8 = false; sound.setButton(R.color.grey_dark, a); toggleSoundId = 0; sound.soundAllStop(); isDeckShouldCleared = false; } } private void setPresetInfo() { if (isSettingVisible == false && isAboutVisible == false && currentPreset != null) { themeColor = currentPreset.getAbout().getActionbarColor(); toolbar.setActionBarTitle(0); toolbar.setActionBarColor(themeColor, a); toolbar.setActionBarPadding(a); toolbar.setActionBarImage( PROJECT_LOCATION_PRESETS + "/" + currentPreset.getFirebaseLocation() + "/about/artist_icon.png", this); w.setRecentColor(0, 0, themeColor, a); } else if (currentPreset == null) { toolbar.setActionBarTitle(R.string.app_name); toolbar.setActionBarColor(R.color.colorPrimary, a); toolbar.setActionBarPadding(a); w.setRecentColor(0, 0, R.color.colorPrimary, a); w.getView(R.id.main_cardview_preset_store, a).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { intent.intent(a, "activity.PresetStoreActivity"); } }); w.getView(R.id.main_cardview_preset_store_download, a).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { intent.intent(a, "activity.PresetStoreActivity"); } }); w.setVisible(R.id.main_cardview_preset_store, 0, a); } } public String getCurrentPresetLocation() { if (getSavedPreset() != null) { return PROJECT_LOCATION_PRESETS + "/" + getSavedPreset(); } else { return null; } } public String getSavedPreset() { String savedPreset = prefs.getString(PRESET_KEY, null); if (savedPreset == null) { prefs.edit().putString(PRESET_KEY, getAvailableDownloadedPreset()).apply(); } return prefs.getString(PRESET_KEY, null); } private String getAvailableDownloadedPreset() { File directory = new File(PROJECT_LOCATION_PRESETS); File[] files = directory.listFiles(); String presetName = null; if (files != null) { for (File file : files) { if (file.isDirectory()) { presetName = file.getName(); if (isPresetExists(presetName)) { if (isPresetAvailable(presetName)) { // available preset break; } } } } } return presetName; } private boolean isPresetExists(String presetName) { // preset exist File folder = new File(PROJECT_LOCATION_PRESETS + "/" + presetName); // folder check return folder.isDirectory() && folder.exists(); } private boolean isPresetAvailable(String presetName) { // preset available File folderSound = new File(PROJECT_LOCATION_PRESETS + "/" + presetName + "/sounds"); File folderTiming = new File(PROJECT_LOCATION_PRESETS + "/" + presetName + "/timing"); File folderAbout = new File(PROJECT_LOCATION_PRESETS + "/" + presetName + "/about"); File fileJson = new File(PROJECT_LOCATION_PRESETS + "/" + presetName + "/about/json.txt"); return folderSound.isDirectory() && folderSound.exists() && folderTiming.isDirectory() && folderTiming.exists() && folderAbout.isDirectory() && folderAbout.exists() && fileJson.exists(); } public static void setSettingVisible(boolean isVisible) { isSettingVisible = isVisible; Log.d("SettingVisible", String.valueOf(isSettingVisible)); } public static void setAboutVisible(boolean isVisible) { isAboutVisible = isVisible; Log.d("AboutVisible", String.valueOf(isAboutVisible)); } private void makeJson() { Item fadedItems[] = { new Item("facebook", w.getStringFromId("preset_faded_detail_facebook", a)), new Item("twitter", w.getStringFromId("preset_faded_detail_twitter", a)), new Item("soundcloud", w.getStringFromId("preset_faded_detail_soundcloud", a)), new Item("instagram", w.getStringFromId("preset_faded_detail_instagram", a)), new Item("google_plus", w.getStringFromId("preset_faded_detail_google_plus", a)), new Item("youtube", w.getStringFromId("preset_faded_detail_youtube", a)), //new Item("twitch", w.getStringFromId("preset_faded_detail_twitch", a)), // only omfg new Item("web", w.getStringFromId("preset_faded_detail_web", a)) }; Detail fadedDetail = new Detail(w.getStringFromId("preset_faded_detail_title", a), fadedItems); Item fadedSongItems[] = { new Item("soundcloud", w.getStringFromId("preset_faded_song_detail_soundcloud", a), false), new Item("youtube", w.getStringFromId("preset_faded_song_detail_youtube", a), false), new Item("spotify", w.getStringFromId("preset_faded_song_detail_spotify", a), false), new Item("google_play_music", w.getStringFromId("preset_faded_song_detail_google_play_music", a), false), new Item("apple", w.getStringFromId("preset_faded_song_detail_apple", a), false), new Item("amazon", w.getStringFromId("preset_faded_song_detail_amazon", a), false), new Item("pandora", w.getStringFromId("preset_faded_song_detail_pandora", a), false) }; Detail fadedSongDetail = new Detail(w.getStringFromId("preset_faded_song_detail_title", a), fadedSongItems); Bio fadedBio = new Bio( w.getStringFromId("preset_faded_bio_title", a), "alan_walker_faded_gesture", w.getStringFromId("preset_faded_bio_name", a), w.getStringFromId("preset_faded_bio_text", a), w.getStringFromId("preset_faded_bio_source", a) ); Detail fadedDetails[] = { fadedDetail, fadedSongDetail }; About fadedAbout = new About( w.getStringFromId("preset_faded_title", a), "alan_walker_faded_gesture", w.getStringFromId("preset_faded_tutorial_link", a), "Studio Berict", "#00D3BE", fadedBio, fadedDetails ); Music fadedMusic = new Music( "preset_faded", "alan_walker_faded_gesture", true, 246, 90, null ); Preset fadedPreset = new Preset("alan_walker_faded_gesture", fadedMusic, fadedAbout); largeLog("JSON", gson.toJson(fadedPreset)); Preset[] presets = { fadedPreset }; FirebaseMetadata firebaseMetadata = new FirebaseMetadata(presets, 15); largeLog("Metadata", gson.toJson(firebaseMetadata)); // Bio tapadBio = new Bio( // w.getStringFromId("info_tapad_bio_title", a), // "about_bio_tapad", // w.getStringFromId("info_tapad_bio_name", a), // w.getStringFromId("info_tapad_bio_text", a), // w.getStringFromId("info_tapad_bio_source", a) // Item tapadInfo[] = { // new Item("info_tapad_info_check_update", w.getStringFromId("info_tapad_info_check_update_hint", a), "google_play", true), // new Item("info_tapad_info_tester", w.getStringFromId("info_tapad_info_tester_hint", a), "experiment", true), // new Item("info_tapad_info_version", w.getStringFromId("info_tapad_info_version_hint", a), ""), // new Item("info_tapad_info_build_date", w.getStringFromId("info_tapad_info_build_date_hint", a), ""), // new Item("info_tapad_info_changelog", null, "changelog", false), // new Item("info_tapad_info_thanks", null, "thanks", false), // new Item("info_tapad_info_dev", w.getStringFromId("info_tapad_info_dev_hint", a), "developer", false) // // TODO ADD ITEMS // Item tapadOthers[] = { // new Item("info_tapad_others_song", w.getStringFromId("info_tapad_others_song_hint", a), "song", true), // new Item("info_tapad_others_feedback", w.getStringFromId("info_tapad_others_feedback_hint", a), "feedback", true), // new Item("info_tapad_others_report_bug", w.getStringFromId("info_tapad_others_report_bug_hint", a), "report_bug", true), // new Item("info_tapad_others_rate", w.getStringFromId("info_tapad_others_rate_hint", a), "rate", true), // new Item("info_tapad_others_translate", w.getStringFromId("info_tapad_others_translate_hint", a), "web", false), // new Item("info_tapad_others_recommend", w.getStringFromId("info_tapad_others_recommend_hint", a), "recommend", true) // Detail tapadDetails[] = { // new Detail(w.getStringFromId("info_tapad_info_title", a), tapadInfo), // new Detail(w.getStringFromId("info_tapad_others_title", a), tapadOthers) // About tapadAbout = new About( // w.getStringFromId("info_tapad_title", a), // "about_image_tapad", // "#9C27B0", // tapadBio, tapadDetails // largeLog("tapadAboutJSON", gson.toJson(tapadAbout)); // Bio berictBio = new Bio( // w.getStringFromId("info_berict_bio_title", a), // null, // w.getStringFromId("info_berict_bio_name", a), // w.getStringFromId("info_berict_bio_text", a), // w.getStringFromId("info_berict_bio_source", a) // Item devItems[] = { // new Item("facebook", w.getStringFromId("info_berict_detail_facebook", a)), // new Item("twitter", w.getStringFromId("info_berict_detail_twitter", a)), // new Item("google_plus", w.getStringFromId("info_berict_detail_google_plus", a)), // new Item("youtube", w.getStringFromId("info_berict_detail_youtube", a)), // new Item("discord", w.getStringFromId("info_berict_detail_discord", a)), // new Item("web", w.getStringFromId("info_berict_detail_web", a)) // Item devSupport[] = { // new Item("info_berict_action_report_bug", w.getStringFromId("info_berict_action_report_bug_hint", a), "report_bug", true), // new Item("info_berict_action_rate", w.getStringFromId("info_berict_action_rate_hint", a), "rate", true), // new Item("info_berict_action_translate", w.getStringFromId("info_berict_action_translate_hint", a), "translate", false), // new Item("info_berict_action_donate", w.getStringFromId("info_berict_action_donate_hint", a), "donate", false) // Detail berictDetails[] = { // new Detail(w.getStringFromId("info_berict_detail_title", a), devItems), // new Detail(w.getStringFromId("info_berict_action_title", a), devSupport) // About berictAbout = new About( // w.getStringFromId("info_berict_title", a), // "about_image_berict", // "#607D8B", // berictBio, berictDetails // largeLog("berictAboutJSON", gson.toJson(berictAbout)); } }
package io.advantageous.config; import org.junit.Before; import org.junit.Test; import java.net.URI; import java.util.List; import java.util.Map; import static io.advantageous.boon.core.Maps.map; import static java.util.Arrays.asList; import static org.junit.Assert.*; public class ConfigImplTest { Map map; Config config; @Before public void setUp() throws Exception { map = map("int1", 1, "float1", 1.0, "double1", 1.0, "long1", 1L, "string1", "rick", "stringList", asList("Foo", "Bar"), "configInner", map( "int2", 2, "float2", 2.0 ), "uri", URI.create("http://localhost:8080/foo"), "myClass", "java.lang.Object", "myURI", "http://localhost:8080/foo", "employee", map("id", 123, "name", "Geoff"), "employees", asList( map("id", 123, "name", "Geoff"), map("id", 456, "name", "Rick"), map("id", 789, "name", "Paul") ) ); config = new ConfigFromObject(map); } @Test public void testSimple() throws Exception { assertEquals(Object.class, config.get("myClass", Class.class)); assertEquals(URI.create("http://localhost:8080/foo"), config.get("uri", URI.class)); assertEquals(URI.create("http://localhost:8080/foo"), config.get("myURI", URI.class)); assertEquals(1, config.getInt("int1")); assertEquals(asList("Foo", "Bar"), config.getStringList("stringList")); assertEquals("rick", config.getString("string1")); assertEquals(1.0, config.getDouble("double1"), 0.001); assertEquals(1L, config.getLong("long1")); assertEquals(1.0f, config.getFloat("float1"), 0.001); config.toString(); } @Test public void testReadClass() throws Exception { final Employee employee = config.get("employee", Employee.class); assertEquals("Geoff", employee.name); assertEquals("123", employee.id); } @Test public void testReadListOfClass() throws Exception { final List<Employee> employees = config.getList("employees", Employee.class); assertEquals("Geoff", employees.get(0).name); assertEquals("123", employees.get(0).id); } @Test public void testReadListOfConfig() throws Exception { final List<Config> employees = config.getConfigList("employees"); assertEquals("Geoff", employees.get(0).getString("name")); assertEquals("123", employees.get(0).getString("id")); } @Test public void testSimplePath() throws Exception { assertTrue(config.hasPath("configInner.int2")); assertFalse(config.hasPath("configInner.foo.bar")); assertEquals(2, config.getInt("configInner.int2")); assertEquals(2.0f, config.getFloat("configInner.float2"), 0.001); } @Test public void testGetConfig() throws Exception { final Config configInner = config.getConfig("configInner"); assertEquals(2, configInner.getInt("int2")); assertEquals(2.0f, configInner.getFloat("float2"), 0.001); } @Test public void testGetConfigConvertIntoPojo() throws Exception { final Config configInner = config.getConfig("employee"); final Employee employee = configInner.get("this", Employee.class); assertEquals("Geoff", employee.name); assertEquals("123", employee.id); } @Test public void testGetMap() throws Exception { final Map<String, Object> map = config.getMap("configInner"); assertEquals(2, (int) map.get("int2")); assertEquals(2.0f, (double) map.get("float2"), 0.001); } @Test(expected = java.lang.IllegalArgumentException.class) public void testNoPath() throws Exception { config.getInt("department.employees"); } public static class Employee { private String id; private String name; } }
package web.component.impl.aws.model; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import web.component.api.model.Instance; import web.component.api.model.LoadBalancer; /** * * @author Hiroshi */ public class InstanceImplTest { private static Instance testInstance; private static final List<Instance> testInstances = new ArrayList<>(); private static final String testImageId = ""; private static final String testInstanceType = ""; private static final String testInstanceLifeCycle = ""; private static final String testPlacement = ""; private static final String testZoneName = ""; private static String testInstanceId; private static LoadBalancer testLb; public InstanceImplTest() { } @BeforeClass public static void setUpClass() { //build instance from create method to obtain reference to the object of the newly created instance. testInstance = new InstanceImpl.Builder().imageId(testImageId).type(testInstanceType).create(); testInstanceId = testInstance.getId(); testInstances.add(testInstance); testLb = new LoadBalancerImpl.Builder("testLb").defaultHttpListener().zone(testZoneName).build(); while(!testLb.isStarted()){ try{ Thread.sleep(10000); }catch(IOException e){ throw new RuntimeException("failed to create test load balancer."); } } testLb.registerInstance(testInstance); } @AfterClass public static void tearDownClass() { testLb.deregisterInstance(testInstance); testLb.delete(); //stop and terminate the test instances. for(Instance toDelete : testInstances){ System.out.println("stop test instance [" + toDelete + "]"); toDelete.stop(); while(!toDelete.isStopped()){ try{ Thread.sleep(3000); }catch(IOException e){ } } System.out.println("terminate test instance [" + toDelete + "]"); toDelete.terminate(); } } @Before public void setUp() { } @After public void tearDown() { } /** * Test of asElbInstance method, of class InstanceImpl. */ @Test public void testAsElbInstance() { System.out.println("asElbInstance"); AWSELB elb = (AWSELB)AWS.get(AWS.BlockName.ELB); com.amazonaws.services.elasticloadbalancing.model.Instance source = elb.getExistElbInstance(testInstance.getId()); for(Instance testInstance : testInstances){ com.amazonaws.services.elasticloadbalancing.model.Instance elbInstance1 = ((InstanceImpl)testInstance).asElbInstance(); assertTrue(elbInstance1.getInstanceId() != null && !elbInstance1.getInstanceId().isEmpty()); } } /** * Test of asEc2Instance method, of class InstanceImpl. */ @Test public void testAsEc2Instance() { System.out.println("asEc2Instance"); AWSEC2 ec2 = (AWSEC2)AWS.get(AWS.BlockName.EC2); com.amazonaws.services.ec2.model.Instance source = ec2.getExistEc2Instance(testInstanceId); com.amazonaws.services.ec2.model.Instance viewAsEc2Instance = ((InstanceImpl)testInstance).asEc2Instance(); //two instances are equal but not the same. assertTrue(viewAsEc2Instance.equals(source)); assertFalse(viewAsEc2Instance == source); assertEquals(testInstanceId,viewAsEc2Instance.getInstanceId()); assertEquals(testImageId,viewAsEc2Instance.getImageId()); assertEquals(testInstanceType,viewAsEc2Instance.getInstanceType()); assertEquals(testInstanceLifeCycle,viewAsEc2Instance.getInstanceLifecycle()); assertEquals(testPlacement,viewAsEc2Instance.getPlacement().toString()); } /** * Test of getLoadBalancer method, of class InstanceImpl. */ @Test public void testGetLoadBalancer() { System.out.println("getLoadBalancer"); int counter = 0; for(Instance testInstance : testInstances){ try{ testInstance.getLoadBalancer(); }catch(UnsupportedOperationException e){ counter++; } } assertEquals(testInstances.size(), counter); } /** * Test of getLoadBalancers method, of class InstanceImpl. */ @Test public void testGetLoadBalancers() { System.out.println("getLoadBalancers"); int counter = 0; for(Instance testInstance : testInstances){ try{ testInstance.getLoadBalancers(); }catch(UnsupportedOperationException e){ counter++; } } assertEquals(testInstances.size(), counter); } /** * Test of getId method, of class InstanceImpl. */ @Test public void testGetId() { System.out.println("getId"); assertEquals(testInstanceId, testInstances.get(1).getId()); } /** * Test of registerWith method, of class InstanceImpl. */ @Test public void testRegisterWith() { System.out.println("registerWith"); fail("The test case is a prototype."); } /** * Test of deregisterFrom method, of class InstanceImpl. */ @Test public void testDeregisterFrom() { System.out.println("deregisterFrom"); fail("The test case is a prototype."); } /** * Test of equals method, of class InstanceImpl. */ @Test public void testEquals() { System.out.println("equals"); fail("The test case is a prototype."); } /** * Test of hashCode method, of class InstanceImpl. */ @Test public void testHashCode() { System.out.println("hashCode"); fail("The test case is a prototype."); } /** * Test of getState method, of class InstanceImpl. */ @Test public void testGetState() { System.out.println("getState"); fail("The test case is a prototype."); } /** * Test of getStateFromLB method, of class InstanceImpl. */ @Test public void testGetStateFromLB() { System.out.println("getStateFromLB"); fail("The test case is a prototype."); } /** * Test of toString method, of class InstanceImpl. */ @Test public void testToString() { System.out.println("toString"); fail("The test case is a prototype."); } /** * Test of start method, of class InstanceImpl. */ @Test public void testStart() { System.out.println("start"); fail("The test case is a prototype."); } /** * Test of stop method, of class InstanceImpl. */ @Test public void testStop() { System.out.println("stop"); fail("The test case is a prototype."); } /** * Test of getPlacement method, of class InstanceImpl. */ @Test public void testGetPlacement() { System.out.println("getPlacement"); for(Instance testInstance : testInstances) assertEquals(testPlacement, testInstance.getPlacement()); } /** * Test of terminate method, of class InstanceImpl. */ @Test public void testTerminate() { System.out.println("terminate"); fail("The test case is a prototype."); } }
package com.google.sps.tool; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.List; import java.util.ArrayList; import com.google.sps.data.Card; import com.google.sps.data.Folder; public class EntityTestingTool { public static boolean checkForNoNullValues(Entity card) { return (card.getProperty("blobKey") != null && card.getProperty("labels") != null && card.getProperty("textTranslated") != null && card.getProperty("textNotTranslated") != null && card.getProperty("fromLang") != null && card.getProperty("toLang") != null && card.getProperty("cardKey") != null); } public static Folder populateDatastoreWithAFolder(Folder folder, DatastoreService datastore, String userKey) { Entity folderEntity = folder.createEntity(KeyFactory.stringToKey(userKey)); // Update entity in datastore datastore.put(folderEntity); Folder folderObject = new Folder(folderEntity); folderObject.setFolderKey(KeyFactory.keyToString(folderEntity.getKey())); return folderObject; } /* public static List<Card> populateDatastoreWithCards(Card cardA, Card cardB, DatastoreService datastore, String folderKey) { Entity cardEntityA = cardA.createEntity(KeyFactory.stringToKey(folderKey)); Entity cardEntityB = cardB.createEntity(KeyFactory.stringToKey(folderKey)); // Update entity in datastore datastore.put(cardEntityA); datastore.put(cardEntityB); List<Card> cards = new ArrayList<>(); cards.add(new Card(cardEntityA)); cards.add(new Card(cardEntityB)); return cards; } */ }
package me.moocar.logbackgelf; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import java.io.IOException; import java.net.*; import java.util.Random; import static org.junit.Assert.assertTrue; public class IntegrationTest { private static final String longMessage = createLongMessage(); private TestServer server; private String ipAddress; private String requestID; private String host; private ImmutableSet<String> fieldsToIgnore = ImmutableSet.of("level", "timestamp"); private ImmutableMap<String, String> lastRequest = null; private static String createLongMessage() { Random rand = new Random(); StringBuilder str = new StringBuilder(); for (int i=0; i< 1000; i++) { char theChar = (char)(rand.nextInt(30) + 65); for (int j=0; j < 80; j++) { str.append(theChar); } str.append('\n'); } return str.toString(); } @Before public void setup() throws SocketException, UnknownHostException { server = TestServer.build(); server.start(); host = getLocalHostName(); } @Test public void test() throws IOException { Logger logger = LoggerFactory.getLogger(this.getClass()); logger.debug("Testing empty MDC"); sleep(); lastRequest = server.lastRequest(); assertMapEquals(makeMap("Testing empty MDC"), removeFields(lastRequest)); assertTrue(lastRequest.containsKey("level")); assertTrue(lastRequest.containsKey("timestamp")); ipAddress = "87.345.23.55"; MDC.put("ipAddress", ipAddress); requestID = String.valueOf(new Random().nextInt(100000)); MDC.put("requestId", requestID); logger.debug("this is a new test"); sleep(); lastRequest = server.lastRequest(); assertMapEquals(makeMap("this is a new test"), removeFields(lastRequest)); assertTrue(lastRequest.containsKey("level")); assertTrue(lastRequest.containsKey("timestamp")); logger.debug("this is a test with ({}) parameter", "this"); sleep(); lastRequest = server.lastRequest(); assertMapEquals(makeMap("this is a test with (this) parameter"), removeFields(lastRequest)); assertTrue(lastRequest.containsKey("level")); assertTrue(lastRequest.containsKey("timestamp")); try { new URL("app://asdfs"); } catch (Exception e) { logger.error("expected error", new IllegalStateException(e)); sleep(); lastRequest = server.lastRequest(); assertMapEquals(makeErrorMap( "expected errorjava.net.MalformedURLException: unknown protocol: app\n" + "\tat java.net.URL.<init>(URL.java:574) ~[na:1.6.0_41]\n" + "\tat java.net.URL.<init>(URL.java:464) ~[na:1.6.0_41]\n" + "\tat java.net.URL.<init>(URL.java:413) ~[na:1.6.0_41]\n" + "\tat me.moocar.logbackgelf.In"), ImmutableMap.copyOf(Maps.filterKeys(removeFields(lastRequest), Predicates.not(Predicates.in(ImmutableSet.of("full_message")))))); } server.shutdown(); logger.debug("This is a test with a really long ending: " + longMessage); } private void assertMapEquals (ImmutableMap<String, String> m1, ImmutableMap<String, String> m2) { assertTrue("Difference:" + Maps.difference(m1, m2).entriesDiffering(), Maps.difference(m1, m2).areEqual()); } private ImmutableMap<String, String> makeErrorMap(String shortMessage) throws IOException { return ImmutableMap.<String, String>builder() .put("_ip_address", ipAddress) .put("_request_id", requestID) .put("host", host) .put("facility", "logback-gelf-test") .put("short_message", shortMessage) .put("_loggerName", "me.moocar.logbackgelf.IntegrationTest") .put("version", "1.0").build(); } private ImmutableMap<String, String> makeMap(String message) { return makeMap(message, message); } private ImmutableMap<String, String> makeMap(String fullMessage, String shortMessage) { ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder() .put("host", host) .put("facility", "logback-gelf-test") .put("short_message", shortMessage) .put("full_message", fullMessage) .put("_loggerName", "me.moocar.logbackgelf.IntegrationTest") .put("version", "1.0"); if (ipAddress != null) builder.put("_ip_address", ipAddress); if (requestID != null) builder.put("_request_id", requestID); return builder.build(); } private ImmutableMap<String, String> removeFields(ImmutableMap<String, String> map) { return ImmutableMap.copyOf(Maps.filterKeys(map,Predicates.not(Predicates.in(fieldsToIgnore)))); } private void sleep() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } private String getLocalHostName() throws SocketException, UnknownHostException { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { NetworkInterface networkInterface = NetworkInterface.getNetworkInterfaces().nextElement(); if (networkInterface == null) throw e; InetAddress ipAddress = networkInterface.getInetAddresses().nextElement(); if (ipAddress == null) throw e; return ipAddress.getHostAddress(); } } }
package net.ssehub.kernel_haven.fe_analysis.pcs; import static net.ssehub.kernel_haven.util.null_checks.NullHelpers.notNull; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import net.ssehub.kernel_haven.SetUpException; import net.ssehub.kernel_haven.analysis.AnalysisComponent; import net.ssehub.kernel_haven.build_model.BuildModel; import net.ssehub.kernel_haven.code_model.CodeElement; import net.ssehub.kernel_haven.code_model.SourceFile; import net.ssehub.kernel_haven.config.Configuration; import net.ssehub.kernel_haven.config.Setting; import net.ssehub.kernel_haven.config.Setting.Type; import net.ssehub.kernel_haven.fe_analysis.PresenceConditionAnalysisHelper; import net.ssehub.kernel_haven.fe_analysis.Settings.SimplificationType; import net.ssehub.kernel_haven.fe_analysis.pcs.PcFinder.VariableWithPcs; import net.ssehub.kernel_haven.util.io.TableElement; import net.ssehub.kernel_haven.util.io.TableRow; import net.ssehub.kernel_haven.util.logic.Conjunction; import net.ssehub.kernel_haven.util.logic.Formula; import net.ssehub.kernel_haven.util.logic.FormulaSimplifier; import net.ssehub.kernel_haven.util.logic.Variable; import net.ssehub.kernel_haven.util.null_checks.NonNull; import net.ssehub.kernel_haven.util.null_checks.Nullable; /** * A component that creates a mapping variable -> set of all PCs the variable is used in. * * @author Adam */ public class PcFinder extends AnalysisComponent<VariableWithPcs> { public static final @NonNull Setting<@NonNull Boolean> CONSIDER_ALL_BM = new Setting<>( "analysis.pc_finder.add_all_bm_pcs", Type.BOOLEAN, true, "false", "Whether the " + PcFinder.class.getName() + " should consider all presence conditions from the build model. If true, then all PCs from the build" + " model will be considered, even if no real file for it exists."); /** * A variable together with all presence conditions it is used in. * * @author Adam */ @TableRow public static class VariableWithPcs { private @NonNull String variable; private @NonNull Set<@NonNull Formula> pcs; /** * Creates a new {@link VariableWithPcs}. * * @param variable The variable name. * @param pcs All the PCs that the variable is used in. Must not be <code>null</code>. */ public VariableWithPcs(@NonNull String variable, @NonNull Set<@NonNull Formula> pcs) { this.variable = variable; this.pcs = pcs; } /** * Returns the variable name. * * @return The name of the variable. */ @TableElement(name = "Variable", index = 0) public @NonNull String getVariable() { return variable; } /** * Returns a set of all presence conditions that this variable is used in. * * @return A set of all PCs, never <code>null</code>. */ @TableElement(name = "Presence conditions", index = 1) public @NonNull Set<@NonNull Formula> getPcs() { return pcs; } @Override public @NonNull String toString() { return "PCs[" + variable + "] = " + pcs.toString(); } } private @NonNull AnalysisComponent<SourceFile> sourceFiles; private @Nullable AnalysisComponent<BuildModel> bmComponent; private @NonNull PresenceConditionAnalysisHelper helper; private boolean addAllBmPcs; /** * Creates a {@link PcFinder} for the given code model. * * @param config The global configuration. * @param sourceFiles The code model provider component. * * @throws SetUpException If setting up this component fails. */ public PcFinder(@NonNull Configuration config, @NonNull AnalysisComponent<SourceFile> sourceFiles) throws SetUpException { super(config); this.sourceFiles = sourceFiles; this.helper = new PresenceConditionAnalysisHelper(config); config.registerSetting(CONSIDER_ALL_BM); addAllBmPcs = config.getValue(CONSIDER_ALL_BM); } /** * Creates a {@link PcFinder} for the given code and build model. The build model presence conditions will be * added to the code model conditions. * * @param config The global configuration. * @param sourceFiles The code model provider component. * @param bm The build model provider component. * * @throws SetUpException If setting up this component fails. */ public PcFinder(@NonNull Configuration config, @NonNull AnalysisComponent<SourceFile> sourceFiles, @NonNull AnalysisComponent<BuildModel> bm) throws SetUpException { this(config, sourceFiles); this.bmComponent = bm; } @Override protected void execute() { BuildModel bm = null; if (bmComponent != null) { bm = bmComponent.getNextResult(); if (bm != null) { LOGGER.logDebug("Calculating presence conditions including information from build model"); } else { LOGGER.logWarning("Should use build information for calculation of presence conditions, " + "but build model provider returned null", "Ignoring build model"); } } else { LOGGER.logDebug("Calculating presence conditions without considering build model"); } Map<String, Set<@NonNull Formula>> result = new HashMap<>(); SourceFile file; while ((file = sourceFiles.getNextResult()) != null) { Formula filePc = null; if (null != bm) { filePc = bm.getPc(file.getPath()); if (filePc != null) { LOGGER.logDebug("File PC for " + file.getPath() + ": " + filePc); // add the file PC as a stand-alone PC addPcToResult(result, filePc); } else { LOGGER.logWarning("No file PC for " + file.getPath() + " in build model"); } } for (CodeElement b : file) { // TODO: check if parentIsRelevant should be true if we added the file PC to the result above findPcsInElement(b, result, filePc, false); } } // consider all presence conditions from the build model, if configured if (null != bm && addAllBmPcs) { LOGGER.logInfo("Adding all build model PCs"); // TODO: temporary debug logging findPcsInBuildModel(bm, result); } @NonNull VariableWithPcs[] list = sortResults(result); LOGGER.logInfo("Got " + list.length + " sorted results"); // TODO: temporary debug logging for (VariableWithPcs var : list) { addResult(var); } LOGGER.logInfo("Sent all results away"); // TODO: temporary debug logging } /** * Turns the map of collected PCs into a sorted array of {@link VariableWithPcs}s. The results are sorted by * variable name. If enabled in the config, this also simplifies the presence conditions. * * @param pcMap The map of collected presence conditions. * * @return A sorted array of {@link VariableWithPcs}s created from the map. */ @SuppressWarnings("null") // stream API and null annotations don't work so nicely together :-/ private @NonNull VariableWithPcs @NonNull [] sortResults(Map<String, Set<@NonNull Formula>> pcMap) { LOGGER.logInfo("Creating VariableWithPcs elements"); // TODO: temporary debug logging @NonNull VariableWithPcs[] result = new @NonNull VariableWithPcs[pcMap.size()]; int i = 0; for (Map.Entry<String, Set<@NonNull Formula>> entry : pcMap.entrySet()) { LOGGER.logInfo("(" + (i + 1) + "/" + result.length + ") Calculating PC set for " + entry.getKey() + " with " + entry.getValue().size() + " PCs"); // TODO: temporary debug logging Set<@NonNull Formula> pcs = notNull(entry.getValue()); if (helper.getSimplificationMode() == SimplificationType.PRESENCE_CONDITIONS) { // Stream-based simplification of formulas and re-creation of set in multiple threads. pcs = notNull(pcs.parallelStream().map(FormulaSimplifier::simplify).collect(Collectors.toSet())); } result[i++] = new VariableWithPcs(notNull(entry.getKey()), pcs); } LOGGER.logInfo2("Sorting ", result.length, " elements"); // TODO: temporary debug logging Arrays.sort(result, (o1, o2) -> o1.getVariable().compareTo(o2.getVariable())); return result; } /** * Finds all PCs in an element and recursively in all child elements. Adds the PC to the set for * all variables that are found in the PC. * * @param element The element to find PCs in. * @param result The result to add the PCs to. * @param filePc Optional: The presence condition of the file which is currently processed. Will be ignored if it is * <tt>null</tt>. * @param parentIsRelevant Used for optimization (<tt>true</tt> parent condition is relevant and, thus, also all * nested conditions are relevant, <tt>false</tt> this method will check if the condition should be considered). */ private void findPcsInElement(@NonNull CodeElement element, @NonNull Map<String, Set<@NonNull Formula>> result, @Nullable Formula filePc, boolean parentIsRelevant) { Formula pc = element.getPresenceCondition(); if (parentIsRelevant || helper.isRelevant(pc)) { // Skip retrieval of variables for nested conditions (last for loop) parentIsRelevant = true; if (null != filePc) { pc = new Conjunction(filePc, pc); } addPcToResult(result, pc); } for (CodeElement child : element.iterateNestedElements()) { findPcsInElement(child, result, filePc, parentIsRelevant); } } /** * Adds a presence condition to the result. * * @param result The result map to add to. * @param pc The presence condition that was found. */ private void addPcToResult(@NonNull Map<String, Set<@NonNull Formula>> result, @NonNull Formula pc) { Set<@NonNull Variable> vars = new HashSet<>(); helper.findVars(pc, vars); for (Variable var : vars) { result.putIfAbsent(var.getName(), new HashSet<>()); result.get(var.getName()).add(pc); } } /** * Adds all PCs found in the build model to the result set. * * @param bm The build model to walk through. * @param result The result set to add PCs to. */ private void findPcsInBuildModel(@NonNull BuildModel bm, @NonNull Map<String, Set<@NonNull Formula>> result) { for (File f : bm) { Formula pc = bm.getPc(f); if (pc != null) { addPcToResult(result, pc); } } } @Override public @NonNull String getResultName() { return "Presence Conditions"; } }
package io.flutter.run.daemon; import com.google.common.base.Joiner; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static io.flutter.testing.JsonTesting.curly; import static org.junit.Assert.assertEquals; /** * Verifies that we can read events sent using the Flutter daemon protocol. */ public class DaemonEventTest { private List<String> log; private DaemonEvent.Listener listener; @Before public void setUp() { log = new ArrayList<>(); listener = new DaemonEvent.Listener() { // daemon domain @Override public void onDaemonLogMessage(DaemonEvent.DaemonLogMessage event) { logEvent(event, event.level, event.message, event.stackTrace); } @Override public void onDaemonShowMessage(DaemonEvent.DaemonShowMessage event) { logEvent(event, event.level, event.title, event.message); } // app domain @Override public void onAppStarting(DaemonEvent.AppStarting event) { logEvent(event, event.appId, event.deviceId, event.directory, event.launchMode); } @Override public void onAppDebugPort(DaemonEvent.AppDebugPort event) { logEvent(event, event.appId, event.wsUri, event.baseUri); } @Override public void onAppStarted(DaemonEvent.AppStarted event) { logEvent(event, event.appId); } @Override public void onAppLog(DaemonEvent.AppLog event) { logEvent(event, event.appId, event.log, event.error); } @Override public void onAppProgressStarting(DaemonEvent.AppProgress event) { logEvent(event, "starting", event.appId, event.id, event.getType(), event.message); } @Override public void onAppProgressFinished(DaemonEvent.AppProgress event) { logEvent(event, "finished", event.appId, event.id, event.getType(), event.message); } @Override public void onAppStopped(DaemonEvent.AppStopped event) { if (event.error != null) { logEvent(event, event.appId, event.error); } else { logEvent(event, event.appId); } } // device domain @Override public void onDeviceAdded(DaemonEvent.DeviceAdded event) { logEvent(event, event.id, event.name, event.platform); } @Override public void onDeviceRemoved(DaemonEvent.DeviceRemoved event) { logEvent(event, event.id, event.name, event.platform); } }; } @Test public void shouldIgnoreUnknownEvent() { send("unknown.message", curly()); checkLog(); } // daemon domain @Test public void canReceiveLogMessage() { send("daemon.logMessage", curly("level:\"spam\"", "message:\"Make money fast\"", "stackTrace:\"Las Vegas\"")); checkLog("DaemonLogMessage: spam, Make money fast, Las Vegas"); } @Test public void canReceiveShowMessage() { send("daemon.showMessage", curly("level:\"info\"", "title:\"Spam\"", "message:\"Make money fast\"")); checkLog("DaemonShowMessage: info, Spam, Make money fast"); } // app domain @Test public void canReceiveAppStarting() { send("app.start", curly("appId:42", "deviceId:456", "directory:somedir", "launchMode:run")); checkLog("AppStarting: 42, 456, somedir, run"); } @Test public void canReceiveDebugPort() { // The port parameter is deprecated; should ignore it. send("app.debugPort", curly("appId:42", "port:456", "wsUri:\"example.com\"", "baseUri:\"belongto:us\"")); checkLog("AppDebugPort: 42, example.com, belongto:us"); } @Test public void canReceiveAppStarted() { send("app.started", curly("appId:42")); checkLog("AppStarted: 42"); } @Test public void canReceiveAppLog() { send("app.log", curly("appId:42", "log:\"Oh no!\"", "error:true")); checkLog("AppLog: 42, Oh no!, true"); } @Test public void canReceiveProgressStarting() { send("app.progress", curly("appId:42", "id:opaque", "progressId:very.hot", "message:\"Please wait\"")); checkLog("AppProgress: starting, 42, opaque, very.hot, Please wait"); } @Test public void canReceiveProgressFinished() { send("app.progress", curly("appId:42", "id:opaque", "progressId:very.hot", "message:\"All done!\"", "finished:true")); checkLog("AppProgress: finished, 42, opaque, very.hot, All done!"); } @Test public void canReceiveAppStopped() { send("app.stop", curly("appId:42")); checkLog("AppStopped: 42"); } @Test public void canReceiveAppStoppedWithError() { send("app.stop", curly("appId:42", "error:\"foobar\"")); checkLog("AppStopped: 42, foobar"); } // device domain @Test public void canReceiveDeviceAdded() { send("device.added", curly("id:9000", "name:\"Banana Jr\"", "platform:\"feet\"")); checkLog("DeviceAdded: 9000, Banana Jr, feet"); } @Test public void canReceiveDeviceRemoved() { send("device.removed", curly("id:9000", "name:\"Banana Jr\"", "platform:\"feet\"")); checkLog("DeviceRemoved: 9000, Banana Jr, feet"); } private void send(String eventName, String params) { DaemonEvent.dispatch( GSON.fromJson(curly("event:\"" + eventName + "\"", "params:" + params), JsonObject.class), listener); } private void logEvent(DaemonEvent event, Object... items) { log.add(event.getClass().getSimpleName() + ": " + Joiner.on(", ").join(items)); } private void checkLog(String... expectedEntries) { assertEquals("log entries are different", Arrays.asList(expectedEntries), log); log.clear(); } private static final Gson GSON = new Gson(); }
package com.dallinc.masstexter; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.dallinc.masstexter.messaging.Compose; import com.dallinc.masstexter.messaging.SentMessageDetails; import com.dallinc.masstexter.models.GroupMessage; import com.dallinc.masstexter.models.SingleMessage; import com.dallinc.masstexter.models.Template; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import java.util.List; public class MessagingFragment extends Fragment { List<GroupMessage> sentMessages = GroupMessage.listAll(GroupMessage.class); GroupMessageAdapter ca; /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static MessagingFragment newInstance(int sectionNumber) { MessagingFragment fragment = new MessagingFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public MessagingFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.messaging_fragment, container, false); final RelativeLayout messageVeil = (RelativeLayout) rootView.findViewById(R.id.messageVeil); final FloatingActionsMenu composeButton = (FloatingActionsMenu) rootView.findViewById(R.id.buttonComposeMessage); rootView.setFocusableInTouchMode(true); rootView.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if( keyCode == KeyEvent.KEYCODE_BACK && composeButton.isExpanded()) { composeButton.collapse(); return true; } return false; } }); messageVeil.setVisibility(View.INVISIBLE); messageVeil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { composeButton.collapse(); } }); composeButton.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() { @Override public void onMenuExpanded() { messageVeil.setAlpha(0f); messageVeil.setVisibility(View.VISIBLE); messageVeil.animate().alpha(1f).setDuration(300).setListener(null); } @Override public void onMenuCollapsed() { messageVeil.animate().alpha(0f).setDuration(500).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { messageVeil.setVisibility(View.INVISIBLE); } }); } }); FloatingActionButton usingTemplateButton = (FloatingActionButton) rootView.findViewById(R.id.buttonComposeUsingTemplate); usingTemplateButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { composeButton.collapse(); final AlertDialog.Builder builder = new AlertDialog.Builder(rootView.getContext()); builder.setTitle("Select Template"); List<Template> _templates = Template.listAll(Template.class); if(_templates.size() < 1) { Toast.makeText(rootView.getContext(), "You do not have any templates saved!", Toast.LENGTH_LONG).show(); return; } final Template[] templates = _templates.toArray(new Template[_templates.size()]); final String[] template_titles = new String[templates.length]; for(int i=0; i<templates.length; i++) { template_titles[i] = templates[i].title; } builder.setItems(template_titles, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(rootView.getContext(), Compose.class); intent.putExtra("template_id", templates[which].getId()); startActivity(intent); } }); builder.create().show(); } }); FloatingActionButton quickComposeButton = (FloatingActionButton) rootView.findViewById(R.id.buttonQuickCompose); quickComposeButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { composeButton.collapse(); Intent intent = new Intent(rootView.getContext(), Compose.class); startActivity(intent); } }); RecyclerView recList = (RecyclerView) rootView.findViewById(R.id.sentMessagesCardList); recList.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(rootView.getContext()); llm.setOrientation(LinearLayoutManager.VERTICAL); recList.setLayoutManager(llm); ca = new GroupMessageAdapter(sentMessages); recList.setAdapter(ca); recList.smoothScrollToPosition(ca.getItemCount() - 1); return rootView; } @Override public void onResume() { // TODO: get this actually updating the list sentMessages = GroupMessage.listAll(GroupMessage.class); ca.notifyDataSetChanged(); super.onResume(); } public class GroupMessageAdapter extends RecyclerView.Adapter<GroupMessageAdapter.GroupMessageViewHolder> { private List<GroupMessage> sentMessageList; public GroupMessageAdapter(List<GroupMessage> sentMessageList) { this.sentMessageList = sentMessageList; } @Override public int getItemCount() { return sentMessageList.size(); } @Override public void onBindViewHolder(final GroupMessageViewHolder GroupMessageViewHolder, int i) { final GroupMessage sentMessage = sentMessageList.get(i); GroupMessageViewHolder.vTitle.setText(sentMessage.sentAt); String body = sentMessage.messageBody; sentMessage.buildArrayListFromString(); for(String variable: sentMessage.variables) { body = body.replaceFirst("¬", variable); } GroupMessageViewHolder.vBody.setText(body); GroupMessageViewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GroupMessageViewHolder.itemView.getContext(), SentMessageDetails.class); intent.putExtra("message_id", sentMessage.getId()); startActivity(intent); } }); GroupMessageViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { final AlertDialog.Builder builder = new AlertDialog.Builder(GroupMessageViewHolder.itemView.getContext()); builder.setTitle("Delete Message?"); builder.setMessage("Do you want to delete this message from the list?"); builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sentMessage.delete(); sentMessageList = sentMessages = GroupMessage.listAll(GroupMessage.class); notifyDataSetChanged(); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); return false; } }); Long totalRecipients = SingleMessage.count(SingleMessage.class, "group_message = ?", new String[]{Long.toString(sentMessage.getId())}); GroupMessageViewHolder.vRecipientCount.setText(Long.toString(totalRecipients)); } @Override public GroupMessageViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.template_card_layout, viewGroup, false); return new GroupMessageViewHolder(itemView); } public class GroupMessageViewHolder extends RecyclerView.ViewHolder { protected TextView vTitle; protected TextView vBody; protected TextView vRecipientCount; public GroupMessageViewHolder(View v) { super(v); vTitle = (TextView) v.findViewById(R.id.templateCardTitle); vBody = (TextView) v.findViewById(R.id.templateCardBody); vRecipientCount = (TextView) v.findViewById(R.id.recipientCount); } } } }
package net.imagej.ops.math; import net.imagej.ops.AbstractNamespaceTest; import net.imagej.ops.MathOps.Abs; import net.imagej.ops.MathOps.Add; import net.imagej.ops.MathOps.AddNoise; import net.imagej.ops.MathOps.And; import net.imagej.ops.MathOps.Arccos; import net.imagej.ops.MathOps.Arccosh; import net.imagej.ops.MathOps.Arccot; import net.imagej.ops.MathOps.Arccoth; import net.imagej.ops.MathOps.Arccsc; import net.imagej.ops.MathOps.Arccsch; import net.imagej.ops.MathOps.Arcsec; import net.imagej.ops.MathOps.Arcsech; import net.imagej.ops.MathOps.Arcsin; import net.imagej.ops.MathOps.Arcsinh; import net.imagej.ops.MathOps.Arctan; import net.imagej.ops.MathOps.Arctanh; import net.imagej.ops.MathOps.Ceil; import net.imagej.ops.MathOps.Complement; import net.imagej.ops.MathOps.Copy; import net.imagej.ops.MathOps.Cos; import net.imagej.ops.MathOps.Cosh; import net.imagej.ops.MathOps.Cot; import net.imagej.ops.MathOps.Coth; import org.junit.Test; /** * Tests that the ops of the math namespace have corresponding type-safe Java * method signatures declared in the {@link MathNamespace} class. * * @author Curtis Rueden */ public class MathNamespaceTest extends AbstractNamespaceTest { /** Tests for {@link Abs} method convergence. */ @Test public void testAbs() { assertComplete("math", MathNamespace.class, Abs.NAME); } /** Tests for {@link Add} method convergence. */ @Test public void testAdd() { assertComplete("math", MathNamespace.class, Add.NAME); } /** Tests for {@link AddNoise} method convergence. */ @Test public void testAddNoise() { assertComplete("math", MathNamespace.class, AddNoise.NAME); } /** Tests for {@link And} method convergence. */ @Test public void testAnd() { assertComplete("math", MathNamespace.class, And.NAME); } /** Tests for {@link Arccos} method convergence. */ @Test public void testArccos() { assertComplete("math", MathNamespace.class, Arccos.NAME); } /** Tests for {@link Arccosh} method convergence. */ @Test public void testArccosh() { assertComplete("math", MathNamespace.class, Arccosh.NAME); } /** Tests for {@link Arccot} method convergence. */ @Test public void testArccot() { assertComplete("math", MathNamespace.class, Arccot.NAME); } /** Tests for {@link Arccoth} method convergence. */ @Test public void testArccoth() { assertComplete("math", MathNamespace.class, Arccoth.NAME); } /** Tests for {@link Arccsc} method convergence. */ @Test public void testArccsc() { assertComplete("math", MathNamespace.class, Arccsc.NAME); } /** Tests for {@link Arccsch} method convergence. */ @Test public void testArccsch() { assertComplete("math", MathNamespace.class, Arccsch.NAME); } /** Tests for {@link Arcsec} method convergence. */ @Test public void testArcsec() { assertComplete("math", MathNamespace.class, Arcsec.NAME); } /** Tests for {@link Arcsech} method convergence. */ @Test public void testArcsech() { assertComplete("math", MathNamespace.class, Arcsech.NAME); } /** Tests for {@link Arcsin} method convergence. */ @Test public void testArcsin() { assertComplete("math", MathNamespace.class, Arcsin.NAME); } /** Tests for {@link Arcsinh} method convergence. */ @Test public void testArcsinh() { assertComplete("math", MathNamespace.class, Arcsinh.NAME); } /** Tests for {@link Arctan} method convergence. */ @Test public void testArctan() { assertComplete("math", MathNamespace.class, Arctan.NAME); } /** Tests for {@link Arctanh} method convergence. */ @Test public void testArctanh() { assertComplete("math", MathNamespace.class, Arctanh.NAME); } /** Tests for {@link Ceil} method convergence. */ @Test public void testCeil() { assertComplete("math", MathNamespace.class, Ceil.NAME); } /** Tests for {@link Complement} method convergence. */ @Test public void testComplement() { assertComplete("math", MathNamespace.class, Complement.NAME); } /** Tests for {@link Copy} method convergence. */ @Test public void testCopy() { assertComplete("math", MathNamespace.class, Copy.NAME); } /** Tests for {@link Cos} method convergence. */ @Test public void testCos() { assertComplete("math", MathNamespace.class, Cos.NAME); } /** Tests for {@link Cosh} method convergence. */ @Test public void testCosh() { assertComplete("math", MathNamespace.class, Cosh.NAME); } /** Tests for {@link Cot} method convergence. */ @Test public void testCot() { assertComplete("math", MathNamespace.class, Cot.NAME); } /** Tests for {@link Coth} method convergence. */ @Test public void testCoth() { assertComplete("math", MathNamespace.class, Coth.NAME); } }
package nl.esciencecenter.xenon.adaptors.gftp; import java.io.File; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import org.globus.common.CoGProperties; import org.globus.gsi.GlobusCredential; import org.globus.gsi.OpenSSLKey; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.bc.BouncyCastleOpenSSLKey; import org.globus.tools.proxy.DefaultGridProxyModel; import org.globus.tools.proxy.GridProxyModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Static Globus Configuration.<br> * GftpAdaptor uses Globus (CoG) defaults from this class if not specified by Adaptor Properties. * * @author Piter T. de Boer */ public class GlobusUtil { public static final Logger logger = LoggerFactory.getLogger(GlobusUtil.class); /** * In cog-jglobus 1.4 this string isn't defined. Define it here to stay 1.4 compatible. This property is defined in CoG * jGlobus 1.7 and higher. */ public static final String COG_ENFORCE_SIGNING_POLICY = "java.security.gsi.signing.policy"; /** * PKCS11 Model property (not used). */ public static final String PKCS11_MODEL = "org.globus.tools.proxy.PKCS11GridProxyModel"; /** * User sub-directory '~/.globus' for globus configurations. */ public static final String GLOBUSRC = ".globus"; /** * Default user (grid) public certificate file for example in the "~/.globus" directory. */ public static final String USERCERTPEM = "usercert.pem"; /** * Default user (grid) private certificate key file, for example in the "~/.globus/" directory. */ public static final String USERKEYPEM = "userkey.pem"; /** * Default system wide grid certificates directory. */ public static final String DEFAULT_SYSTEM_CERTIFICATES_DIR = "/etc/grid-security/certificates"; public static void staticInit() { // Some Globus properties must be defined Globally initCogProperties(); } /** * Returns global defined Cog Properties. Will be used as defaults. * @deprecated */ public static CoGProperties getStaticCoGProperties() { // initialize defaults from Globus Proxy Model GridProxyModel staticModel = staticGetModel(false); CoGProperties props = staticModel.getProperties(); String defaultUserCertFile = props.getUserCertFile(); String defaultUserKeyFile = props.getUserKeyFile(); String defaultProxyFilename = props.getProxyFile(); int defaultLifetimeInHours = props.getProxyLifeTime(); logger.info("default user certFile = {}", defaultUserCertFile); logger.info("default user keyFile = {}", defaultUserKeyFile); logger.info("default user proxy file = {}", defaultProxyFilename); logger.info("default proxy lifetime = {}H", defaultLifetimeInHours); // Update (Global) Properties ? return props; } /** * Initializes static Cog Properties. */ public static void initCogProperties() { // update static properties: CoGProperties props = CoGProperties.getDefault(); String val = props.getProperty(COG_ENFORCE_SIGNING_POLICY); if ((val == null) || (val.equals(""))) { props.setProperty(COG_ENFORCE_SIGNING_POLICY, "false"); } } /** * * Todo: support for external PKCS11 device. */ protected static GridProxyModel staticGetModel(boolean usePKCS11Device) { GridProxyModel staticModel; if (usePKCS11Device) { try { // Do We Need: PKCS11 ??? Class<?> iClass = Class.forName(PKCS11_MODEL); staticModel = (GridProxyModel) iClass.newInstance(); } catch (Exception e) { staticModel = new DefaultGridProxyModel(); } } else { staticModel = new DefaultGridProxyModel(); } return staticModel; } public static GlobusCredential createCredential(String userCert, String userKey, char passphrase[], boolean legacyProxy) throws Exception { return createCredential(userCert, userKey, passphrase, null, -1, true); } /** * Static method to create a Globus Proxy Credential. * * @param userCert * - location of usercert.pem file, default is 'usercert.pem' from ~/.globus * @param userKey * - location of userkey.pem file, default is 'userkey.pem' from ~/.globus * @param passphrase * - actual passphrase * @param userProxyLocation * - optional location to save proxy file to. I null the proxy won't be saved. * @param lifeTimeInSeconds - proxy life time in seconds. Set to -1 for default lifeTime. * @return actual globus proxy credential if proxy creation is successful. * @throws Exception */ public static GlobusCredential createCredential(String userCert, String userKey, char passphrase[], String userProxyLocation, int lifeTime, boolean legacyProxy) throws Exception { ProxyInit proxyInit = new ProxyInit(); if (passphrase == null) { throw new NullPointerException("Can't create proxy without passphrase. passphrase==null!"); } // update default settings. if (legacyProxy) { proxyInit.setProxyTypeToGSI2Legacy(); } if (lifeTime > 0) { proxyInit.setLifetime(lifeTime); } GlobusCredential cred = proxyInit.createProxy(userCert, userKey, passphrase, true, userProxyLocation); return cred; } /** * Load certificates from list of locations. If directory doesn't exist, the location will be skipped. * * @param customDirs * - List of directories to look for X509 Certificates. * @return loaded X509 Certificates from specified directories. */ public static List<X509Certificate> loadX509Certificates(String[] customDirs) { int n = 0; if (customDirs != null) { n = customDirs.length; } // default dir: String dirs[] = new String[1 + n]; // add custom dirs (if specified): dirs[0] = DEFAULT_SYSTEM_CERTIFICATES_DIR; int index = 1; for (int i = 0; i < n; i++) { if (customDirs[i] != null) { dirs[index++] = customDirs[i]; // filter existing here ? } } return loadCertificates(dirs); } public static List<X509Certificate> loadCertificates(String caCertificateDirs[]) { if (caCertificateDirs == null) { return null; // null in null out } List<X509Certificate> allCerts = new ArrayList<X509Certificate>(); // Default globus certificates. try { TrustedCertificates defCerts = null; X509Certificate[] defXCerts = null; defCerts = TrustedCertificates.getDefault(); if (defCerts != null) { defXCerts = defCerts.getCertificates(); } if (defXCerts != null) { for (X509Certificate cert : defXCerts) { logger.debug(" + loaded default grid certificate: {}", cert.getSubjectDN()); allCerts.add(cert); } } } catch (NullPointerException e) { // (old) Bug in Globus! logger.warn("Globus NullPointer bug: TrustedCertificates.getDefault(): NullPointerException:"); } logger.info(" + Got {} default certificates", allCerts.size()); for (String certPath : caCertificateDirs) { if ((certPath == null) || certPath == "") { continue; } File file = new File(certPath); if (file.exists()) { logger.debug(" +++ Loading Extra Certificates from: {} +++", certPath); TrustedCertificates extraCerts = TrustedCertificates.load(certPath); X509Certificate extraXCertsArr[] = extraCerts.getCertificates(); if ((extraXCertsArr == null) || (extraXCertsArr.length <= 0)) { logger.debug(" - No certificates found in: {}", certPath); } for (X509Certificate cert : extraXCertsArr) { logger.debug(" + loaded extra certificate: {}", cert.getSubjectDN()); allCerts.add(cert); } } else { logger.debug("skipping non-existing certificate directory:{}", certPath); } } return allCerts; } /** * Update static loaded Trusted Certificates used by Globus. * * @param certs * - Trusted certificates needed by Globus. */ public static void staticUpdateTrustedCertificates(List<X509Certificate> certs) { X509Certificate[] newXCerts = new X509Certificate[certs.size()]; newXCerts = certs.toArray(newXCerts); TrustedCertificates trustedCertificates = new TrustedCertificates(newXCerts); TrustedCertificates.setDefaultTrustedCertificates(trustedCertificates); // Debug: print out actual certificates. TrustedCertificates tcerts = TrustedCertificates.getDefault(); if (certs != null) { X509Certificate[] xcerts = tcerts.getCertificates(); for (X509Certificate xcert : xcerts) { logger.info(" > updating Trusted Certificate: {}", xcert.getSubjectX500Principal()); } } } /** * Decode user private key (userkey.pem) and return it.<br> * <strong>warning</strong> this method return the <emph>decoded</emph> prive key. Handle with care. * * @return decode users private key. * @throws Exception */ public static PrivateKey getPrivateKey(String filename, char passphrase[]) throws Exception { // X509Certificate userCert = // CertUtil.loadCertificate(this.getDefaultUserCertLocation()); OpenSSLKey key = new BouncyCastleOpenSSLKey(filename); // String charSet="UTF-8"; byte bytes[] = new byte[passphrase.length]; if (key.isEncrypted()) { try { for (int i = 0; i < passphrase.length; i++) { bytes[i] = (byte) passphrase[i]; } key.decrypt(bytes); } catch (GeneralSecurityException e) { throw new Exception("Wrong password or other security error"); } finally { for (int i = 0; i < bytes.length; i++) { bytes[i] = 0; } } } java.security.PrivateKey userKey = key.getPrivateKey(); return userKey; } }
package com.dreiri.smarping.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.TextView; import com.dreiri.smarping.R; import com.dreiri.smarping.activities.ListActivity; import com.dreiri.smarping.models.Item; import com.dreiri.smarping.models.List; import com.dreiri.smarping.persistence.PersistenceManager; import java.util.ArrayList; public class ItemAdapter extends BaseAdapter { private List list; private Context context; private ListActivity activity; private LayoutInflater inflater; private View.OnTouchListener onTouchListener; private ViewHolder viewHolder; private ArrayList<Boolean> checkBoxStates = new ArrayList<Boolean>(); private class ViewHolder { TextView textViewItemName; CheckBox checkBox; } public ItemAdapter(Context context, List list, View.OnTouchListener onTouchListener) { this.context = context; this.inflater = LayoutInflater.from(context); this.activity = (ListActivity) context; this.list = list; this.onTouchListener = onTouchListener; resetCheckBoxStates(); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.fragment_list_row, null, false); viewHolder = new ViewHolder(); viewHolder.textViewItemName = (TextView) convertView.findViewById(R.id.textViewItemName); viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } for (int i = checkBoxStates.size(); i < list.size(); i++) { checkBoxStates.add(0, false); } final Item item = list.get(position); viewHolder.textViewItemName.setText(item.name); viewHolder.checkBox.setChecked(checkBoxStates.get(position)); viewHolder.checkBox.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox); checkBoxStates.set(position, checkBox.isChecked()); activity.updateMenu(); } }); viewHolder.textViewItemName.setOnTouchListener(onTouchListener); return convertView; } public int[] getIndexesOfCheckedItems() { ArrayList<Integer> checkedItemsIndexes = new ArrayList<Integer>(); for (int i = 0; i < checkBoxStates.size(); i++) { if (checkBoxStates.get(i)) { checkedItemsIndexes.add(i); } } int[] checkedIndexes = new int[checkedItemsIndexes.size()]; for (int i = 0; i < checkedItemsIndexes.size(); i++) { checkedIndexes[i] = checkedItemsIndexes.get(i); } return checkedIndexes; } public void setCheckedItems(ArrayList<Integer> checkedItemsIndexes) { checkBoxStates.clear(); for (int i = 0; i < getCount(); i++) { checkBoxStates.add(checkedItemsIndexes.contains(i)); } } private void resetCheckBoxStates() { checkBoxStates.clear(); for (int i = 0; i < getCount(); i++) { checkBoxStates.add(false); } } public void remove(Object object) { list.remove((Item) object); notifyDataSetChanged(); PersistenceManager persistenceManager = new PersistenceManager(context); persistenceManager.saveList(list); } public void refreshWithNewData(List list) { this.list = list; notifyDataSetChanged(); } public void refreshWithNewDataAndResetCheckBoxes(List list) { this.list = list; resetCheckBoxStates(); notifyDataSetChanged(); } }
package org.adligo.models.core.client; import org.adligo.i.util.client.ClassUtils; import org.adligo.i.util.client.StringUtils; import org.adligo.models.core.client.ids.I_StorageIdentifier; public class OrganizationMutant implements I_OrganizationMutant { private static final long serialVersionUID = 1L; public static final String SET_NAME = "setName"; public static final String SET_TYPE = "setType"; public static final String ORGANIZAITION = "Organization"; private I_StorageIdentifier id; private Integer version; private String name; /** * the type pertains to something like a School, Band, Company * to be defined depending on your problem domain */ private I_StorageIdentifier type; /** * custom info specific to your system */ private I_CustomInfo customInfo; /** * detailed information about where this was stored */ private I_StorageInfo storageInfo; /** * for gwt serialization */ public OrganizationMutant() {} public OrganizationMutant(I_Organization p) throws InvalidParameterException { try { if (p.getId() != null) { setId(p.getId()); } setVersion(p.getVersion()); setName(p.getName()); setType(p.getType()); I_StorageInfo storageInfo = p.getStorageInfo(); if (storageInfo != null) { setStorageInfo(storageInfo); } I_CustomInfo customInfo = p.getStorageInfo(); if (customInfo != null) { setCustomInfo(customInfo); } } catch (InvalidParameterException x) { InvalidParameterException ipe = new InvalidParameterException( x.getMessage(), ORGANIZAITION, x); throw ipe; } } public void setId(I_StorageIdentifier p_id) throws InvalidParameterException { if (p_id == null) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getStorageIdRequired(),SET_ID); } if (!p_id.hasValue()) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getStorageIdRequired(),SET_ID); } id = p_id; } public I_StorageIdentifier getId() { return id; } public String getName() { return name; } public void setName(String p) throws InvalidParameterException { if (StringUtils.isEmpty(p)) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyNameError(),SET_NAME); } name = p; } /* (non-Javadoc) * @see org.adligo.models.core.client.I_Org#getType() */ public I_StorageIdentifier getType() { return type; } public void setType(I_StorageIdentifier p) throws InvalidParameterException { if (p == null) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyTypeError(),SET_TYPE); } if (!p.hasValue()) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyTypeError(),SET_TYPE); } type = p; } public boolean isValid() { try { new Organization(this); return true; } catch (InvalidParameterException e) { //do nothing } return false; } public int hashCode() { return genHashCode(this); } public static int genHashCode(I_Organization me) { final int prime = 31; int result = 1; String name = me.getName(); I_StorageIdentifier type = me.getType(); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; try { return equals(this, (I_Organization) obj); } catch (ClassCastException x) { //eat gwt doesn't impl instance of } return false; } public static boolean equals(I_Organization me, I_Organization other) { if (me.getName() == null) { if (other.getName() != null) return false; } else if (!me.getName().equals(other.getName())) return false; if (me.getType() == null) { if (other.getType() != null) return false; } else if (!me.getType().equals(other.getType())) return false; return true; } public String toString() { return toString(this.getClass(),this); } public String toString(Class c, I_Organization p) { StringBuffer sb = new StringBuffer(); sb.append(ClassUtils.getClassShortName(c)); sb.append(" [name="); sb.append(p.getName()); sb.append(",type="); sb.append(p.getType()); sb.append(",id="); sb.append(p.getId()); sb.append(",customInfo="); sb.append(customInfo); sb.append(",storageInfo="); sb.append(storageInfo); sb.append("]"); return sb.toString(); } public I_CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(I_CustomInfo customInfo) throws InvalidParameterException { try { this.customInfo = customInfo.toMutant(); } catch (ValidationException ve) { throw new InvalidParameterException(ve); } } public I_StorageInfo getStorageInfo() { return storageInfo; } public void setStorageInfo(I_StorageInfo storageInfo) throws InvalidParameterException { try { this.storageInfo = (I_StorageInfo) storageInfo.toMutant(); } catch (ValidationException ve) { throw new InvalidParameterException(ve); } } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public I_Organization toImmutable() throws ValidationException { try { return new Organization(this); } catch (InvalidParameterException ipe) { throw new ValidationException(ipe); } } public I_OrganizationMutant toMutant() throws ValidationException { return this; } }
package com.example.android.pets; import android.app.LoaderManager; import android.content.ContentValues; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import com.example.android.pets.data.PetContract.PetEntry; /** * Displays list of pets that were entered and stored in the app. */ public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { // Identifies a particular Loader being used in this component private static final int PET_LOADER = 0; // This is the Adapter being used to display the list's data. private PetCursorAdapter mPetAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_catalog); //Find the ListView that will be populated with pet data ListView petListView = (ListView) findViewById(R.id.list); // Find and set empty view on the ListView, so that it only shows when the list has 0 items. View emptyView = findViewById(R.id.empty_view); petListView.setEmptyView(emptyView); //Set up an adapter to set a list item for each row of pet data in the cursor mPetAdapter = new PetCursorAdapter(this, null); //Attach adapter to the ListView petListView.setAdapter(mPetAdapter); //Initialize the CursorLoader getLoaderManager().initLoader(PET_LOADER, null, this); // Setup FAB to open EditorActivity FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(CatalogActivity.this, EditorActivity.class); startActivity(intent); } }); } private void insertPet() { // Create a ContentValues object where column names are the keys, // and Toto's pet attributes are the values. ContentValues values = new ContentValues(); values.put(PetEntry.COLUMN_PET_NAME, "Toto"); values.put(PetEntry.COLUMN_PET_BREED, "Terrier"); values.put(PetEntry.COLUMN_PET_GENDER, PetEntry.GENDER_MALE); values.put(PetEntry.COLUMN_PET_WEIGHT, 7); Uri newUri = getContentResolver().insert(PetEntry.CONTENT_URI, values); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu options from the res/menu/menu_catalog.xml file. // This adds menu items to the app bar. getMenuInflater().inflate(R.menu.menu_catalog, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Insert dummy data" menu option case R.id.action_insert_dummy_data: insertPet(); return true; // Respond to a click on the "Delete all entries" menu option case R.id.action_delete_all_entries: // Do nothing for now return true; } return super.onOptionsItemSelected(item); } @Override public Loader<Cursor> onCreateLoader(int loaderID, Bundle args) { // Perform this raw SQL query "SELECT * FROM pets" String[] projection = {PetEntry._ID, PetEntry.COLUMN_PET_NAME, PetEntry.COLUMN_PET_BREED, PetEntry.COLUMN_PET_GENDER, PetEntry.COLUMN_PET_WEIGHT}; switch (loaderID) { case PET_LOADER: // Returns a new CursorLoader return new CursorLoader(this, PetEntry.CONTENT_URI, projection, null, null, null); default: // An invalid id was passed in return null; } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Swap the new cursor in. mPetAdapter.swapCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { // Callback called when data needs to be deleted mPetAdapter.swapCursor(null); } }
package ucar.nc2; import junit.framework.*; /** * TestSuite that runs IOSP tests * */ public class TestIosp { public static junit.framework.Test suite ( ) { TestSuite suite= new TestSuite(); suite.addTest( new TestSuite( ucar.nc2.iosp.dmsp.TestDmspIosp.class)); suite.addTest( new TestSuite( ucar.nc2.iosp.gini.TestGini.class)); suite.addTest( new TestSuite( ucar.nc2.iosp.nexrad2.TestNexrad2.class)); suite.addTest( new TestSuite( ucar.nc2.iosp.nexrad2.TestNexrad2HiResolution.class)); suite.addTest( new TestSuite( ucar.nc2.iosp.nids.TestNids.class)); suite.addTest( new TestSuite( ucar.nc2.iosp.dorade.TestDorade.class)); return suite; } }
package com.jaamsim.controllers; import com.jaamsim.math.Mat4d; import com.jaamsim.math.MathUtils; import com.jaamsim.math.Plane; import com.jaamsim.math.Quaternion; import com.jaamsim.math.Ray; import com.jaamsim.math.Transform; import com.jaamsim.math.Vec3d; import com.jaamsim.math.Vec4d; import com.jaamsim.render.CameraInfo; import com.jaamsim.render.RenderUtils; import com.jaamsim.render.Renderer; import com.jaamsim.render.WindowInteractionListener; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.View; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.MouseEvent; public class CameraControl implements WindowInteractionListener { private static final double ZOOM_FACTOR = 1.1; // Scale from pixels dragged to radians rotated private static final double ROT_SCALE_X = 0.005; private static final double ROT_SCALE_Z = 0.005; private Renderer _renderer; private int _windowID; private View _updateView; private final Vec3d POI = new Vec3d(); private static class PolarInfo { double rotZ; // The spherical coordinate that rotates around Z (in radians) double rotX; // Ditto for X double radius; // The distance the camera is from the view center final Vec3d viewCenter; PolarInfo(Vec3d center) { viewCenter = new Vec3d(center); } @Override public boolean equals(Object o) { if (!(o instanceof PolarInfo)) { return false; } PolarInfo pi = (PolarInfo)o; return pi.rotZ == rotZ && pi.rotX == rotX && pi.radius == radius && viewCenter.equals3(pi.viewCenter); } } private PolarInfo piCache; // The last polar info this view has re-drawn for public CameraControl(Renderer renderer, View updateView) { _renderer = renderer; _updateView = updateView; POI.set3(_updateView.getGlobalCenter()); } @Override public void mouseDragged(WindowInteractionListener.DragInfo dragInfo) { // Give the RenderManager first crack at this if (RenderManager.inst().handleDrag(dragInfo)) { RenderManager.redraw(); return; // Handled } if (!_updateView.isMovable() || _updateView.isScripted()) { return; } if (dragInfo.button == 1) { if (dragInfo.shiftDown()) { handleExpVertPan(dragInfo.x, dragInfo.y, dragInfo.dx, dragInfo.dy); } else { handleExpPan(dragInfo.x, dragInfo.y, dragInfo.dx, dragInfo.dy); } } else if (dragInfo.button == 3) { if (dragInfo.shiftDown()) { handleTurnCamera(dragInfo.dx, dragInfo.dy); } else { handleRotAroundPoint(dragInfo.x, dragInfo.y, dragInfo.dx, dragInfo.dy); } } } private void handleTurnCamera(int dx, int dy) { Vec3d camPos = _updateView.getGlobalPosition(); Vec3d center = _updateView.getGlobalCenter(); PolarInfo origPi = getPolarFrom(center, camPos); Quaternion origRot = polarToRot(origPi); Mat4d rot = new Mat4d(); rot.setRot3(origRot); Vec3d rotXAxis = new Vec3d(1.0d, 0.0d, 0.0d); rotXAxis.mult3(rot, rotXAxis); Quaternion rotX = new Quaternion(); rotX.setAxisAngle(rotXAxis, dy * ROT_SCALE_X / 4); Quaternion rotZ = new Quaternion(); rotZ.setRotZAxis(dx * ROT_SCALE_Z / 4); Mat4d rotTransX = MathUtils.rotateAroundPoint(rotX, camPos); Mat4d rotTransZ = MathUtils.rotateAroundPoint(rotZ, camPos); center.multAndTrans3(rotTransX, center); center.multAndTrans3(rotTransZ, center); PolarInfo pi = getPolarFrom(center, camPos); updateCamTrans(pi, true); } private void handleExpPan(int x, int y, int dx, int dy) { Renderer.WindowMouseInfo info = _renderer.getMouseInfo(_windowID); if (info == null) return; //Cast a ray into the XY plane both for now, and for the previous mouse position Ray currRay = RenderUtils.getPickRayForPosition(info.cameraInfo, x, y, info.width, info.height); Ray prevRay = RenderUtils.getPickRayForPosition(info.cameraInfo, x - dx, y - dy, info.width, info.height); double currZDot = currRay.getDirRef().z; double prevZDot = prevRay.getDirRef().z; if (Math.abs(currZDot) < 0.017 || Math.abs(prevZDot) < 0.017) // 0.017 is roughly sin(1 degree) { // This is too close to the xy-plane and will lead to too wild a translation return; } Plane dragPlane = new Plane(null, POI.z); double currDist = dragPlane.collisionDist(currRay); double prevDist = dragPlane.collisionDist(prevRay); if (currDist < 0 || prevDist < 0 || currDist == Double.POSITIVE_INFINITY || prevDist == Double.POSITIVE_INFINITY) { // We're either parallel to or beneath the collision plane, bail out return; } Vec3d currIntersect = currRay.getPointAtDist(currDist); Vec3d prevIntersect = prevRay.getPointAtDist(prevDist); Vec3d diff = new Vec3d(); diff.sub3(currIntersect, prevIntersect); Vec3d camPos = _updateView.getGlobalPosition(); Vec3d center = _updateView.getGlobalCenter(); camPos.sub3(diff); center.sub3(diff); PolarInfo pi = getPolarFrom(center, camPos); updateCamTrans(pi, true); } private void handleExpVertPan(int x, int y, int dx, int dy) { Renderer.WindowMouseInfo info = _renderer.getMouseInfo(_windowID); if (info == null) return; //Cast a ray into the XY plane both for now, and for the previous mouse position Ray currRay = RenderUtils.getPickRayForPosition(info.cameraInfo, x, y, info.width, info.height); Ray prevRay = RenderUtils.getPickRayForPosition(info.cameraInfo, x - dx, y - dy, info.width, info.height); double zDiff = RenderUtils.getZDiff(POI, currRay, prevRay); Vec3d camPos = _updateView.getGlobalPosition(); Vec3d center = _updateView.getGlobalCenter(); camPos.z -= zDiff; center.z -= zDiff; PolarInfo pi = getPolarFrom(center, camPos); updateCamTrans(pi, true); } private void handleRotAroundPoint(int x, int y, int dx, int dy) { Vec3d camPos = _updateView.getGlobalPosition(); Vec3d center = _updateView.getGlobalCenter(); PolarInfo origPi = getPolarFrom(center, camPos); if ( camPos.x == center.x && camPos.y == center.y ) { // This is a degenerate camera view, tweak the polar info a bit to // prevent view flipping origPi.rotX = 0.00001; origPi.rotZ = 0; } Quaternion origRot = polarToRot(origPi); Mat4d rot = new Mat4d(); rot.setRot3(origRot); Vec3d origUp = new Vec3d(0.0d, 1.0d, 0.0d); origUp.mult3(rot, origUp); Vec3d rotXAxis = new Vec3d(1.0d, 0.0d, 0.0d); rotXAxis.mult3(rot, rotXAxis); Quaternion rotX = new Quaternion(); rotX.setAxisAngle(rotXAxis, -dy * ROT_SCALE_X); Quaternion rotZ = new Quaternion(); rotZ.setRotZAxis(-dx * ROT_SCALE_Z); Mat4d rotTransX = MathUtils.rotateAroundPoint(rotX, POI); Mat4d rotTransZ = MathUtils.rotateAroundPoint(rotZ, POI); camPos.multAndTrans3(rotTransX, camPos); center.multAndTrans3(rotTransX, center); camPos.multAndTrans3(rotTransZ, camPos); center.multAndTrans3(rotTransZ, center); PolarInfo pi = getPolarFrom(center, camPos); Quaternion newRot = polarToRot(pi); rot.setRot3(newRot); Vec3d newUp = new Vec3d(0.0d, 1.0d, 0.0d); newUp.mult3(rot, newUp); double upDot = origUp.dot3(newUp); if (upDot < 0) { // The up angle has changed by more than 90 degrees, we probably are looking directly up or down // Instead only apply the rotation around Z camPos = _updateView.getGlobalPosition(); center = _updateView.getGlobalCenter(); camPos.multAndTrans3(rotTransZ, camPos); center.multAndTrans3(rotTransZ, center); pi = getPolarFrom(center, camPos); } updateCamTrans(pi, true); } @Override public void mouseWheelMoved(int windowID, int x, int y, int wheelRotation, int modifiers) { if (!_updateView.isMovable() || _updateView.isScripted()) { return; } Vec3d camPos = _updateView.getGlobalPosition(); Vec3d center = _updateView.getGlobalCenter(); Vec3d diff = new Vec3d(); diff.sub3(POI, camPos); double scale = 1; double zoomFactor = (wheelRotation > 0) ? 1/ZOOM_FACTOR : ZOOM_FACTOR; for (int i = 0; i < Math.abs(wheelRotation); ++i) { scale = scale * zoomFactor; } // offset is the difference from where we are to where we're going diff.scale3(1 - scale); camPos.add3(diff); center.add3(diff); PolarInfo pi = getPolarFrom(center, camPos); updateCamTrans(pi, true); } @Override public void mouseClicked(int windowID, int x, int y, int button, int modifiers) { if (!RenderManager.isGood()) { return; } RenderManager.inst().hideExistingPopups(); if (button == 3) { // Hand this off to the RenderManager to deal with RenderManager.inst().popupMenu(windowID); } if (button == 1 && (modifiers & WindowInteractionListener.MOD_CTRL) == 0) { RenderManager.inst().handleSelection(windowID); } } @Override public void mouseMoved(int windowID, int x, int y) { if (!RenderManager.isGood()) { return; } RenderManager.inst().mouseMoved(windowID, x, y); } @Override public void rawMouseEvent(MouseEvent me) { } @Override public void mouseEntry(int windowID, int x, int y, boolean isInWindow) { if (!RenderManager.isGood()) { return; } if (isInWindow && RenderManager.inst().isDragAndDropping()) { RenderManager.inst().createDNDObject(windowID, x, y); } } private Quaternion polarToRot(PolarInfo pi) { Quaternion rot = new Quaternion(); rot.setRotZAxis(pi.rotZ); Quaternion tmp = new Quaternion(); tmp.setRotXAxis(pi.rotX); rot.mult(rot, tmp); return rot; } private void updateCamTrans(PolarInfo pi, boolean updateInputs) { if (pi.rotX == 0) { pi.rotZ = 0; // If we're ever looking directly down, which is degenerate, force Y up } if (piCache != null && piCache.equals(pi) && !updateInputs) { return; // This update won't do anything } piCache = pi; Vec4d zOffset = new Vec4d(0, 0, pi.radius, 1.0d); Quaternion rot = polarToRot(pi); Transform finalTrans = new Transform(pi.viewCenter); finalTrans.merge(finalTrans, new Transform(null, rot, 1)); finalTrans.merge(finalTrans, new Transform(zOffset)); if (updateInputs) { updateViewPos(finalTrans.getTransRef(), pi.viewCenter); } // Finally update the renders camera info CameraInfo info = _renderer.getCameraInfo(_windowID); if (info == null) { // This window has not been opened yet (or is closed) force a redraw as everything will catch up // and the information has been saved to the view object RenderManager.redraw(); piCache = null; return; } info.trans = finalTrans; info.skyboxTexture = _updateView.getSkyboxTexture(); _renderer.setCameraInfoForWindow(_windowID, info); // Queue a redraw RenderManager.redraw(); } public void setRotationAngles(double rotX, double rotZ) { PolarInfo pi = getPolarCoordsFromView(); pi.rotX = rotX; pi.rotZ = rotZ; updateCamTrans(pi, true); } public void setWindowID(int windowID) { _windowID = windowID; } @Override public void windowClosing() { if (!RenderManager.isGood()) { return; } RenderManager.inst().hideExistingPopups(); RenderManager.inst().windowClosed(_windowID); } @Override public void mouseButtonDown(int windowID, int x, int y, int button, boolean isDown, int modifiers) { if (!RenderManager.isGood()) { return; } // We need to cache dragging if (button == 1 && isDown) { Vec3d clickPoint = RenderManager.inst().getNearestPick(_windowID); if (clickPoint != null) { POI.set3(clickPoint); //dragPlane = new Plane(Vec4d.Z_AXIS, clickPoint.z); } else { // Set the drag plane to the XY_PLANE Renderer.WindowMouseInfo info = _renderer.getMouseInfo(_windowID); if (info == null) return; //Cast a ray into the XY plane both for now, and for the previous mouse position Ray mouseRay = RenderUtils.getPickRayForPosition(info.cameraInfo, x, y, info.width, info.height); double dist = Plane.XY_PLANE.collisionDist(mouseRay); if (dist < 0) { return; } POI.set3(mouseRay.getPointAtDist(dist)); //dragPlane = Plane.XY_PLANE; } } RenderManager.inst().handleMouseButton(windowID, x, y, button, isDown, modifiers); } @Override public void windowGainedFocus() { if (!RenderManager.isGood()) { return; } RenderManager.inst().setActiveWindow(_windowID); } /** * Set the position information in the saved view to match this window */ private void updateViewPos(Vec3d viewPos, Vec3d viewCenter) { if (_updateView == null) { return; } _updateView.updateCenterAndPos(viewCenter, viewPos); FrameBox.valueUpdate(); } @Override public void windowMoved(int x, int y, int width, int height) { // Filter out large negative values occuring from window minimize: if (x < -30000 || y < - 30000) return; _updateView.setWindowPos(x, y, width, height); } public View getView() { return _updateView; } private PolarInfo getPolarFrom(Vec3d center, Vec3d pos) { PolarInfo pi = new PolarInfo(center); Vec3d viewDiff = new Vec3d(); viewDiff.sub3(pos, pi.viewCenter); pi.radius = viewDiff.mag3(); pi.rotZ = Math.atan2(viewDiff.x, -viewDiff.y); double xyDist = Math.hypot(viewDiff.x, viewDiff.y); pi.rotX = Math.atan2(xyDist, viewDiff.z); return pi; } private PolarInfo getPolarCoordsFromView() { return getPolarFrom(_updateView.getGlobalCenter(), _updateView.getGlobalPosition()); } public void checkForUpdate() { PolarInfo pi = getPolarCoordsFromView(); updateCamTrans(pi, false); } @Override public void keyPressed(KeyEvent event) { switch (event.getKeySymbol()) { case KeyEvent.VK_DELETE: RenderManager.inst().deleteSelected(); break; } } @Override public void keyReleased(KeyEvent event) { // Empty } }
package org.apache.xerces.validators.common; import org.apache.xerces.framework.XMLAttrList; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.framework.XMLDocumentHandler; import org.apache.xerces.framework.XMLDocumentScanner; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.Hash2intTable; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.validators.dtd.DTDGrammar; import org.apache.xerces.validators.schema.EquivClassComparator; import org.apache.xerces.validators.schema.SchemaGrammar; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.TraverseSchema; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; /** * This class is the super all-in-one validator used by the parser. * * @version $Id$ */ public final class XMLValidator implements DefaultEntityHandler.EventHandler, XMLEntityHandler.CharDataHandler, XMLDocumentScanner.EventHandler, NamespacesScope.NamespacesHandler { // Constants // debugging private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; private static final boolean DEBUG_PRINT_ATTRIBUTES = false; private static final boolean DEBUG_PRINT_CONTENT = false; private static final boolean DEBUG_SCHEMA_VALIDATION = false; private static final boolean DEBUG_ELEMENT_CHILDREN = false; // Chunk size constants private static final int CHUNK_SHIFT = 8; // 2^8 = 256 private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT); private static final int CHUNK_MASK = CHUNK_SIZE - 1; private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k // Data // REVISIT: The data should be regrouped and re-organized so that // it's easier to find a meaningful field. // debugging // private static boolean DEBUG = false; // other private Hashtable fIdDefs = null; private Hashtable fIdRefs = null; private Object fNullValue = null; // attribute validators private AttributeValidator fAttValidatorCDATA = null; private AttributeValidator fAttValidatorID = new AttValidatorID(); private AttributeValidator fAttValidatorIDREF = new AttValidatorIDREF(); private AttributeValidator fAttValidatorIDREFS = new AttValidatorIDREFS(); private AttributeValidator fAttValidatorENTITY = new AttValidatorENTITY(); private AttributeValidator fAttValidatorENTITIES = new AttValidatorENTITIES(); private AttributeValidator fAttValidatorNMTOKEN = new AttValidatorNMTOKEN(); private AttributeValidator fAttValidatorNMTOKENS = new AttValidatorNMTOKENS(); private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION(); private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION(); private AttributeValidator fAttValidatorDATATYPE = null; // Package access for use by AttributeValidator classes. StringPool fStringPool = null; boolean fValidating = false; boolean fInElementContent = false; int fStandaloneReader = -1; // settings private boolean fValidationEnabled = false; private boolean fDynamicValidation = false; private boolean fSchemaValidation = true; private boolean fValidationEnabledByDynamic = false; private boolean fDynamicDisabledByValidation = false; private boolean fWarningOnDuplicateAttDef = false; private boolean fWarningOnUndeclaredElements = false; // declarations private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementTypeStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private int[] fElementLocalPartStack = new int[8]; private QName[] fElementChildren = new QName[32]; private int fElementChildrenLength = 0; private int[] fElementChildrenOffsetStack = new int[32]; private int fElementDepth = -1; private boolean fNamespacesEnabled = false; private NamespacesScope fNamespacesScope = null; private int fNamespacesPrefix = -1; private QName fRootElement = new QName(); private int fAttrListHandle = -1; private int fCurrentElementEntity = -1; private int fCurrentElementIndex = -1; private int fCurrentContentSpecType = -1; private boolean fSeenDoctypeDecl = false; private final int TOP_LEVEL_SCOPE = -1; private int fCurrentScope = TOP_LEVEL_SCOPE; private int fCurrentSchemaURI = -1; private int fEmptyURI = - 1; private int fXsiPrefix = - 1; private int fXsiURI = -2; private int fXsiTypeAttValue = -1; private Grammar fGrammar = null; private int fGrammarNameSpaceIndex = -1; private GrammarResolver fGrammarResolver = null; // state and stuff private boolean fScanningDTD = false; private XMLDocumentScanner fDocumentScanner = null; private boolean fCalledStartDocument = false; private XMLDocumentHandler fDocumentHandler = null; private XMLDocumentHandler.DTDHandler fDTDHandler = null; private boolean fSeenRootElement = false; private XMLAttrList fAttrList = null; private int fXMLLang = -1; private LocatorImpl fAttrNameLocator = null; private boolean fCheckedForSchema = false; private boolean fDeclsAreExternal = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; private char[] fCharRefData = null; private boolean fSendCharDataAsCharArray = false; private boolean fBufferDatatype = false; private StringBuffer fDatatypeBuffer = new StringBuffer(); private QName fTempQName = new QName(); private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); private boolean fGrammarIsDTDGrammar = false; private boolean fGrammarIsSchemaGrammar = false; // symbols private int fEMPTYSymbol = -1; private int fANYSymbol = -1; private int fMIXEDSymbol = -1; private int fCHILDRENSymbol = -1; private int fCDATASymbol = -1; private int fIDSymbol = -1; private int fIDREFSymbol = -1; private int fIDREFSSymbol = -1; private int fENTITYSymbol = -1; private int fENTITIESSymbol = -1; private int fNMTOKENSymbol = -1; private int fNMTOKENSSymbol = -1; private int fNOTATIONSymbol = -1; private int fENUMERATIONSymbol = -1; private int fREQUIREDSymbol = -1; private int fFIXEDSymbol = -1; private int fDATATYPESymbol = -1; private int fEpsilonIndex = -1; // Constructors /** Constructs an XML validator. */ public XMLValidator(StringPool stringPool, XMLErrorReporter errorReporter, DefaultEntityHandler entityHandler, XMLDocumentScanner documentScanner) { // keep references fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fDocumentScanner = documentScanner; fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); // initialize fAttrList = new XMLAttrList(fStringPool); entityHandler.setEventHandler(this); entityHandler.setCharDataHandler(this); fDocumentScanner.setEventHandler(this); init(); } // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner) public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } // Public methods // initialization /** Set char data processing preference and handlers. */ public void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fSendCharDataAsCharArray = sendCharDataAsCharArray; fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray); fDocumentHandler = docHandler; fDTDHandler = dtdHandler; } // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler) /** Reset or copy. */ public void resetOrCopy(StringPool stringPool) throws Exception { fAttrList = new XMLAttrList(stringPool); resetCommon(stringPool); } /** Reset. */ public void reset(StringPool stringPool) throws Exception { fAttrList.reset(stringPool); resetCommon(stringPool); } // settings /** * Turning on validation/dynamic turns on validation if it is off, and * this is remembered. Turning off validation DISABLES validation/dynamic * if it is on. Turning off validation/dynamic DOES NOT turn off * validation if it was explicitly turned on, only if it was turned on * BECAUSE OF the call to turn validation/dynamic on. Turning on * validation will REENABLE and turn validation/dynamic back on if it * was disabled by a call that turned off validation while * validation/dynamic was enabled. */ public void setValidationEnabled(boolean flag) throws Exception { fValidationEnabled = flag; fValidationEnabledByDynamic = false; if (fValidationEnabled) { if (fDynamicDisabledByValidation) { fDynamicValidation = true; fDynamicDisabledByValidation = false; } } else if (fDynamicValidation) { fDynamicValidation = false; fDynamicDisabledByValidation = true; } fValidating = fValidationEnabled; } /** Returns true if validation is enabled. */ public boolean getValidationEnabled() { return fValidationEnabled; } /** Sets whether Schema support is on/off. */ public void setSchemaValidationEnabled(boolean flag) { fSchemaValidation = flag; } /** Returns true if Schema support is on. */ public boolean getSchemaValidationEnabled() { return fSchemaValidation; } /** Sets whether validation is dynamic. */ public void setDynamicValidationEnabled(boolean flag) throws Exception { fDynamicValidation = flag; fDynamicDisabledByValidation = false; if (!fDynamicValidation) { if (fValidationEnabledByDynamic) { fValidationEnabled = false; fValidationEnabledByDynamic = false; } } else if (!fValidationEnabled) { fValidationEnabled = true; fValidationEnabledByDynamic = true; } fValidating = fValidationEnabled; } /** Returns true if validation is dynamic. */ public boolean getDynamicValidationEnabled() { return fDynamicValidation; } /** Sets whether namespaces are enabled. */ public void setNamespacesEnabled(boolean flag) { fNamespacesEnabled = flag; } /** Returns true if namespaces are enabled. */ public boolean getNamespacesEnabled() { return fNamespacesEnabled; } /** Sets whether duplicate attribute definitions signal a warning. */ public void setWarningOnDuplicateAttDef(boolean flag) { fWarningOnDuplicateAttDef = flag; } /** Returns true if duplicate attribute definitions signal a warning. */ public boolean getWarningOnDuplicateAttDef() { return fWarningOnDuplicateAttDef; } /** Sets whether undeclared elements signal a warning. */ public void setWarningOnUndeclaredElements(boolean flag) { fWarningOnUndeclaredElements = flag; } /** Returns true if undeclared elements signal a warning. */ public boolean getWarningOnUndeclaredElements() { return fWarningOnUndeclaredElements; } // DefaultEntityHandler.EventHandler methods /** Start entity reference. */ public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.startEntityReference(entityName, entityType, entityContext); } /** End entity reference. */ public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.endEntityReference(entityName, entityType, entityContext); } /** Send end of input notification. */ public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception { fDocumentScanner.endOfInput(entityName, moreToFollow); /** Send reader change notifications. */ /** External entity standalone check. */ /** Return true if validating. */ /** Process characters. */ /** Process characters. */ /** Process whitespace. */ /** Process whitespace. */ /** Scans element type. */ /** Scans expected element type. */ /** Scans attribute name. */ /** Call start document. */ /** Call end document. */ /** Call XML declaration. */ /** Call text declaration. */ /** * Signal the scanning of an element name in a start element tag. * * @param element Element name scanned. */ public void element(QName element) throws Exception { fAttrListHandle = -1; } /** * Signal the scanning of an attribute associated to the previous * start element tag. * * @param element Element name scanned. * @param attrName Attribute name scanned. * @param attrValue The string pool index of the attribute value. */ public boolean attribute(QName element, QName attrName, int attrValue) throws Exception { if (fAttrListHandle == -1) { fAttrListHandle = fAttrList.startAttrList(); } // if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element. // specified: true, search : true return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1; } /** Call start element. */ public void callStartElement(QName element) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart)); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) add default attrs (FIXED and NOT_FIXED) if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } fCheckedForSchema = true; if (fNamespacesEnabled) { bindNamespacesToElementAndAttributes(element, fAttrList); } validateElementAndAttributes(element, fAttrList); if (fAttrListHandle != -1) { fAttrList.endAttrList(); } fDocumentHandler.startElement(element, fAttrList, fAttrListHandle); fAttrListHandle = -1; //before we increment the element depth, add this element's QName to its enclosing element 's children list fElementDepth++; //if (fElementDepth >= 0) { if (fValidating) { // push current length onto stack if (fElementChildrenOffsetStack.length < fElementDepth) { int newarray[] = new int[fElementChildrenOffsetStack.length * 2]; System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length); fElementChildrenOffsetStack = newarray; } fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength; // add this element to children if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildrenLength * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.setValues(element); fElementChildrenLength++; if (DEBUG_ELEMENT_CHILDREN) { printChildren(); printStack(); } } // One more level of depth //fElementDepth++; ensureStackCapacity(fElementDepth); fCurrentElement.setValues(element); fCurrentElementEntity = fEntityHandler.getReaderId(); fElementTypeStack[fElementDepth] = fCurrentElement.rawname; fElementLocalPartStack[fElementDepth]=fCurrentElement.localpart; fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementTypeStack.length) { int[] newStack = new int[newElementDepth * 2]; System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth); fScopeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth); fGrammarNameSpaceIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementTypeStack, 0, newStack, 0, newElementDepth); fElementTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy( this.fElementLocalPartStack , 0, newStack, 0, newElementDepth); fElementLocalPartStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth); fElementEntityStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth); fElementIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth); fContentSpecTypeStack = newStack; } } /** Call end element. */ public void callEndElement(int readerId) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n"); int prefixIndex = fCurrentElement.prefix; int elementType = fCurrentElement.rawname; if (fCurrentElementEntity != readerId) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH, XMLMessages.P78_NOT_WELLFORMED, new Object[] { fStringPool.toString(elementType) }, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } fElementDepth if (fValidating) { int elementIndex = fCurrentElementIndex; if (elementIndex != -1 && fCurrentContentSpecType != -1) { QName children[] = fElementChildren; int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1; int childrenLength = fElementChildrenLength - childrenOffset; if (DEBUG_ELEMENT_CHILDREN) { System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')'); System.out.print("offset: "); System.out.print(childrenOffset); System.out.print(", length: "); System.out.print(childrenLength); System.out.println(); printChildren(); printStack(); } int result = checkContent(elementIndex, children, childrenOffset, childrenLength); if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result); if (result != -1) { int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE; fGrammar.getElementDecl(elementIndex, fTempElementDecl); if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) { reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), "EMPTY"); } else reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex)); } } fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1; } fDocumentHandler.endElement(fCurrentElement); if (fNamespacesEnabled) { fNamespacesScope.decreaseDepth(); } // now pop this element off the top of the element stack //if (fElementDepth-- < 0) { if (fElementDepth < -1) { throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth < 0) { fCurrentElement.clear(); fCurrentElementEntity = -1; fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; // Check after document is fully parsed // (1) check that there was an element with a matching id for every // IDREF and IDREFS attr (V_IDREF0) if (fValidating && fIdRefs != null) { checkIdRefs(); } return; } //restore enclosing element to all the "current" variables // REVISIT: Validation. This information needs to be stored. fCurrentElement.prefix = -1; if (fNamespacesEnabled) { //If Namespace enable then localName != rawName fCurrentElement.localpart = fElementLocalPartStack[fElementDepth]; } else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off fCurrentElement.localpart = fElementTypeStack[fElementDepth]; } fCurrentElement.rawname = fElementTypeStack[fElementDepth]; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; fCurrentScope = fScopeStack[fElementDepth]; //if ( DEBUG_SCHEMA_VALIDATION ) { /** Call start CDATA section. */ /** Call end CDATA section. */ /** Call characters. */ /** Call processing instruction. */ /** Call comment. */ /** Start a new namespace declaration scope. */ /** End a namespace declaration scope. */ /** Normalize attribute value. */ /** Sets the root element. */ /** * Returns true if the element declaration is external. * <p> * <strong>Note:</strong> This method is primarilly useful for * DTDs with internal and external subsets. */ private boolean getElementDeclIsExternal(int elementIndex) { /*if (elementIndex < 0 || elementIndex >= fElementCount) { return false; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; return (fElementDeclIsExternal[chunk][index] != 0); */ if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex); } return false; } /** Returns the content spec type for an element index. */ public int getContentSpecType(int elementIndex) { int contentSpecType = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecType = fTempElementDecl.type; } } return contentSpecType; } /** Returns the content spec handle for an element index. */ public int getContentSpecHandle(int elementIndex) { int contentSpecHandle = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecHandle = fTempElementDecl.contentSpecIndex; } } return contentSpecHandle; } // Protected methods // error reporting /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String,String) // content spec protected int whatCanGoHere(int elementIndex, boolean fullyValid, InsertableElementsInfo info) throws Exception { // Do some basic sanity checking on the info packet. First, make sure // that insertAt is not greater than the child count. It can be equal, // which means to get appendable elements, but not greater. Or, if // the current children array is null, that's bad too. // Since the current children array must have a blank spot for where // the insert is going to be, the child count must always be at least // one. // Make sure that the child count is not larger than the current children // array. It can be equal, which means get appendable elements, but not // greater. if (info.insertAt > info.childCount || info.curChildren == null || info.childCount < 1 || info.childCount > info.curChildren.length) { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_WCGHI, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } int retVal = 0; try { // Get the content model for this element final XMLContentModel cmElem = getElementContentModel(elementIndex); // And delegate this call to it retVal = cmElem.whatCanGoHere(fullyValid, info); } catch (CMException excToCatch) { // REVISIT - Translate caught error to the protected error handler interface int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); throw excToCatch; } return retVal; } // whatCanGoHere(int,boolean,InsertableElementsInfo):int // attribute information /** Protected for use by AttributeValidator classes. */ protected boolean getAttDefIsExternal(QName element, QName attribute) { int attDefIndex = getAttDef(element, attribute); if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex); } return false; } /** addId. */ protected boolean addId(int idIndex) { Integer key = new Integer(idIndex); if (fIdDefs == null) { fIdDefs = new Hashtable(); } else if (fIdDefs.containsKey(key)) { return false; } if (fNullValue == null) { fNullValue = new Object(); } fIdDefs.put(key, fNullValue/*new Integer(elementType)*/); return true; } // addId(int):boolean /** addIdRef. */ protected void addIdRef(int idIndex) { Integer key = new Integer(idIndex); if (fIdDefs != null && fIdDefs.containsKey(key)) { return; } if (fIdRefs == null) { fIdRefs = new Hashtable(); } else if (fIdRefs.containsKey(key)) { return; } if (fNullValue == null) { fNullValue = new Object(); } fIdRefs.put(key, fNullValue/*new Integer(elementType)*/); } // addIdRef(int) // Private methods // other /** Returns true if using a standalone reader. */ private boolean usingStandaloneReader() { return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader; } /** Returns a locator implementation. */ private LocatorImpl getLocatorImpl(LocatorImpl fillin) { Locator here = fErrorReporter.getLocator(); if (fillin == null) return new LocatorImpl(here); fillin.setPublicId(here.getPublicId()); fillin.setSystemId(here.getSystemId()); fillin.setLineNumber(here.getLineNumber()); fillin.setColumnNumber(here.getColumnNumber()); return fillin; } // getLocatorImpl(LocatorImpl):LocatorImpl // initialization /** Reset pool. */ private void poolReset() { if (fIdDefs != null) { fIdDefs.clear(); } if (fIdRefs != null) { fIdRefs.clear(); } } // poolReset() /** Reset common. */ private void resetCommon(StringPool stringPool) throws Exception { fStringPool = stringPool; fValidating = fValidationEnabled; fValidationEnabledByDynamic = false; fDynamicDisabledByValidation = false; poolReset(); fCalledStartDocument = false; fStandaloneReader = -1; fElementChildrenLength = 0; fElementDepth = -1; fSeenRootElement = false; fSeenDoctypeDecl = false; fNamespacesScope = null; fNamespacesPrefix = -1; fRootElement.clear(); fAttrListHandle = -1; fCheckedForSchema = false; fCurrentScope = TOP_LEVEL_SCOPE; fCurrentSchemaURI = -1; fEmptyURI = - 1; fXsiPrefix = - 1; fGrammar = null; fGrammarNameSpaceIndex = -1; fGrammarResolver = null; fGrammarIsDTDGrammar = false; fGrammarIsSchemaGrammar = false; init(); } // resetCommon(StringPool) /** Initialize. */ private void init() { fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); fEMPTYSymbol = fStringPool.addSymbol("EMPTY"); fANYSymbol = fStringPool.addSymbol("ANY"); fMIXEDSymbol = fStringPool.addSymbol("MIXED"); fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN"); fCDATASymbol = fStringPool.addSymbol("CDATA"); fIDSymbol = fStringPool.addSymbol("ID"); fIDREFSymbol = fStringPool.addSymbol("IDREF"); fIDREFSSymbol = fStringPool.addSymbol("IDREFS"); fENTITYSymbol = fStringPool.addSymbol("ENTITY"); fENTITIESSymbol = fStringPool.addSymbol("ENTITIES"); fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN"); fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS"); fNOTATIONSymbol = fStringPool.addSymbol("NOTATION"); fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION"); fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED"); fFIXEDSymbol = fStringPool.addSymbol("#FIXED"); fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>"); fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>"); fXMLLang = fStringPool.addSymbol("xml:lang"); } // init() // other // default attribute /** addDefaultAttributes. */ private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { //System.out.println("XMLValidator#addDefaultAttributes"); //System.out.print(" "); //fGrammar.printAttributes(elementIndex); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) check that FIXED attrs have matching value (V_TAGd) // (3) add default attrs (FIXED and NOT_FIXED) fGrammar.getElementDecl(elementIndex,fTempElementDecl); //System.out.println("addDefaultAttributes: " + fStringPool.toString(fTempElementDecl.name.localpart)+ // "," + attrIndex + "," + validationEnabled); int elementNameIndex = fTempElementDecl.name.localpart; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { //int adChunk = attlistIndex >> CHUNK_SHIFT; //int adIndex = attlistIndex & CHUNK_MASK; fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); // TO DO: For ericye Debug only /** Queries the content model for the specified element index. */ /** Returns the validatator for an attribute type. */ /** Returns an attribute definition for an element type. */ /** Returns an attribute definition for an element type. */ /** Root element specified. */ /** Switchs to correct validating symbol tables when Schema changes.*/ /** Binds namespaces to the element and attributes. */ /** Warning. */ /** Error. */ /** Fatal error. */ /** Returns a string of the location. */ /** Validates element and attributes. */ /** Character data in content. */ /** * Check that the content of an element is valid. * <p> * This is the method of primary concern to the validator. This method is called * upon the scanner reaching the end tag of an element. At that time, the * element's children must be structurally validated, so it calls this method. * The index of the element being checked (in the decl pool), is provided as * well as an array of element name indexes of the children. The validator must * confirm that this element can have these children in this order. * <p> * This can also be called to do 'what if' testing of content models just to see * if they would be valid. * <p> * Note that the element index is an index into the element decl pool, whereas * the children indexes are name indexes, i.e. into the string pool. * <p> * A value of -1 in the children array indicates a PCDATA node. All other * indexes will be positive and represent child elements. The count can be * zero, since some elements have the EMPTY content model and that must be * confirmed. * * @param elementIndex The index within the <code>ElementDeclPool</code> of this * element. * @param childCount The number of entries in the <code>children</code> array. * @param children The children of this element. Each integer is an index within * the <code>StringPool</code> of the child element name. An index * of -1 is used to indicate an occurrence of non-whitespace character * data. * * @return The value -1 if fully valid, else the 0 based index of the child * that first failed. If the value returned is equal to the number * of children, then additional content is required to reach a valid * ending state. * * @exception Exception Thrown on error. */ private int checkContent(int elementIndex, QName[] children, int childOffset, int childCount) throws Exception { // Get the element name index from the element // REVISIT: Validation final int elementType = fCurrentElement.rawname; if (DEBUG_PRINT_CONTENT) { String strTmp = fStringPool.toString(elementType); System.out.println("Name: "+strTmp+", "+ "Count: "+childCount+", "+ "ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex)); for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) { if (index == 0) { System.out.print(" ("); } String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart); if (index + 1 == childCount) { System.out.println(childName + ")"); } else if (index + 1 == 10) { System.out.println(childName + ",...)"); } else { System.out.print(childName + ","); } } } // Get out the content spec for this element final int contentType = fCurrentContentSpecType; // debugging //System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType); // Deal with the possible types of content. We try to optimized here // by dealing specially with content models that don't require the // full DFA treatment. if (contentType == XMLElementDecl.TYPE_EMPTY) { // If the child count is greater than zero, then this is // an error right off the bat at index 0. if (childCount != 0) { return 0; } } else if (contentType == XMLElementDecl.TYPE_ANY) { // This one is open game so we don't pass any judgement on it // at all. Its assumed to fine since it can hold anything. } else if (contentType == XMLElementDecl.TYPE_MIXED || contentType == XMLElementDecl.TYPE_CHILDREN) { // Get the content model for this element, faulting it in if needed XMLContentModel cmElem = null; try { cmElem = getElementContentModel(elementIndex); int result = cmElem.validateContent(children, childOffset, childCount); if (result != -1 && fGrammarIsSchemaGrammar) { // REVISIT: not optimized for performance, EquivClassComparator comparator = new EquivClassComparator(fGrammarResolver, fStringPool); cmElem.setEquivClassComparator(comparator); result = cmElem.validateContentSpecial(children, childOffset, childCount); } return result; } catch(CMException excToCatch) { // REVISIT - Translate the caught exception to the protected error API int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } else if (contentType == -1) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, elementType); } else if (contentType == XMLElementDecl.TYPE_SIMPLE ) { XMLContentModel cmElem = null; try { fGrammar.getElementDecl(elementIndex, fTempElementDecl); DatatypeValidator dv = fTempElementDecl.datatypeValidator; if (dv == null) { System.out.println("Internal Error: this element have a simpletype "+ "but no datatypevalidator was found, element "+fTempElementDecl.name +",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart)); } else { dv.validate(fDatatypeBuffer.toString(), null); } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage() }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_CST, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } // We succeeded return -1; } // checkContent(int,int,int[]):int /** * Check that all ID references were to ID attributes present in the document. * <p> * This method is a convenience call that allows the validator to do any id ref * checks above and beyond those done by the scanner. The scanner does the checks * specificied in the XML spec, i.e. that ID refs refer to ids which were * eventually defined somewhere in the document. * <p> * If the validator is for a Schema perhaps, which defines id semantics beyond * those of the XML specificiation, this is where that extra checking would be * done. For most validators, this is a no-op. * * @exception Exception Thrown on error. */ private void checkIdRefs() throws Exception { if (fIdRefs == null) return; Enumeration en = fIdRefs.keys(); while (en.hasMoreElements()) { Integer key = (Integer)en.nextElement(); if (fIdDefs == null || !fIdDefs.containsKey(key)) { Object[] args = { fStringPool.toString(key.intValue()) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_WITH_ID_REQUIRED, XMLMessages.VC_IDREF, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } // checkIdRefs() /** * Checks that all declared elements refer to declared elements * in their content models. This method calls out to the error * handler to indicate warnings. */ private void printChildren() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('['); for (int i = 0; i < fElementChildrenLength; i++) { System.out.print(' '); QName qname = fElementChildren[i]; if (qname != null) { System.out.print(fStringPool.toString(qname.rawname)); } else { System.out.print("null"); } if (i < fElementChildrenLength - 1) { System.out.print(", "); } System.out.flush(); } System.out.print(" ]"); System.out.println(); } } private void printStack() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('{'); for (int i = 0; i <= fElementDepth; i++) { System.out.print(' '); System.out.print(fElementChildrenOffsetStack[i]); if (i < fElementDepth) { System.out.print(", "); } System.out.flush(); } System.out.print(" }"); System.out.println(); } } // Interfaces /** * AttributeValidator. */ public interface AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValue, int attType, int enumHandle) throws Exception; } // interface AttributeValidator // Classes /** * AttValidatorCDATA. */ final class AttValidatorCDATA implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... return attValueHandle; } } // class AttValidatorCDATA /** * AttValidatorID. */ final class AttValidatorID implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validName(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_ID_INVALID, XMLMessages.VC_ID, fStringPool.toString(attribute.rawname), newAttValue); } // ID - check that the id value is unique within the document (V_TAG8) if (element.rawname != -1 && !addId(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ID_NOT_UNIQUE, XMLMessages.VC_ID, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalong attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorID /** * AttValidatorIDREF. */ final class AttValidatorIDREF implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validName(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_IDREF_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attribute.rawname), newAttValue); } // IDREF - remember the id value if (element.rawname != -1) addIdRef(attValueHandle); } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorIDREF /** * AttValidatorIDREFS. */ final class AttValidatorIDREFS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String idName = tokenizer.nextToken(); if (fValidating) { if (!XMLCharacterProperties.validName(idName)) { ok = false; } // IDREFS - remember the id values if (element.rawname != -1) { addIdRef(fStringPool.addSymbol(idName)); } } sb.append(idName); if (!tokenizer.hasMoreTokens()) break; sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorIDREFS /** * AttValidatorENTITY. */ final class AttValidatorENTITY implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENTITY - check that the value is an unparsed entity name (V_TAGa) if (!fEntityHandler.isUnparsedEntity(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITY /** * AttValidatorENTITIES. */ final class AttValidatorENTITIES implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String entityName = tokenizer.nextToken(); // ENTITIES - check that each value is an unparsed entity name (V_TAGa) if (fValidating && !fEntityHandler.isUnparsedEntity(fStringPool.addSymbol(entityName))) { ok = false; } sb.append(entityName); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITIES_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITIES /** * AttValidatorNMTOKEN. */ final class AttValidatorNMTOKEN implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validNmtoken(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKEN /** * AttValidatorNMTOKENS. */ final class AttValidatorNMTOKENS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String nmtoken = tokenizer.nextToken(); if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) { ok = false; } sb.append(nmtoken); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKENS /** * AttValidatorNOTATION. */ final class AttValidatorNOTATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // NOTATION - check that the value is in the AttDef enumeration (V_TAGo) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_NOTATION_ATTRIBUTES, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNOTATION /** * AttValidatorENUMERATION. */ final class AttValidatorENUMERATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENUMERATION - check that value is in the AttDef enumeration (V_TAG9) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_ENUMERATION, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENUMERATION } // class XMLValidator
package com.fisheradelakin.vortex; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class CurrentWeather { private String mIcon; private long mTime; private double mTemperature; private double mHumidity; private double mPrecipChance; private String mSummary; public String getTimeZone() { return mTimeZone; } public void setTimeZone(String timeZone) { mTimeZone = timeZone; } private String mTimeZone; public String getIcon() { return mIcon; } public void setIcon(String icon) { mIcon = icon; } public int getIconId() { // clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night int iconId; switch (mIcon) { case "clear-day": iconId = R.drawable.clear_day; break; case "clear-night": iconId = R.drawable.clear_night; break; case "rain": iconId = R.drawable.rain; break; case "snow": iconId = R.drawable.snow; break; case "sleet": iconId = R.drawable.sleet; break; case "wind": iconId = R.drawable.wind; break; case "fog": iconId = R.drawable.fog; break; case "cloudy": iconId = R.drawable.cloudy; break; case "partly-cloudy-day": iconId = R.drawable.partly_cloudy; break; case "partly-cloudy-night": iconId = R.drawable.cloudy_night; break; default: iconId = R.drawable.clear_day; break; } return iconId; } public long getTime() { return mTime; } public String getFormattedTime() { SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone())); Date dateTime = new Date(getTime() * 1000); return formatter.format(dateTime); } public void setTime(long time) { mTime = time; } public double getTemperature() { return mTemperature; } public void setTemperature(double temperature) { mTemperature = temperature; } public double getHumidity() { return mHumidity; } public void setHumidity(double humidity) { mHumidity = humidity; } public double getPrecipChance() { return mPrecipChance; } public void setPrecipChance(double precipChance) { mPrecipChance = precipChance; } public String getSummary() { return mSummary; } public void setSummary(String summary) { mSummary = summary; } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TCPConnectTest { public static void main(String[] args) throws IOException, InterruptedException { String inputfile; String defaultinput = "outsideresults"; try{ inputfile = args[0]; }catch(Exception e){ System.out.println("Defaulting to input file " + defaultinput); inputfile = defaultinput; } int cores = Runtime.getRuntime().availableProcessors()-1; cores = 2000; ThreadPoolExecutor es = (ThreadPoolExecutor) Executors.newFixedThreadPool(cores); try(BufferedReader br = new BufferedReader(new FileReader(inputfile))) { for(String line; (line = br.readLine()) != null; ) { final String linef = line; Runnable run = (new Runnable() { @Override public void run() { String serverN = linef; serverN = serverN.substring(0, serverN.indexOf(',')); serverN = serverN.replaceAll("http: serverN = serverN.replaceAll("https: serverN = serverN.replaceAll("ftp: serverN = serverN.replaceAll("ftps: serverN = serverN.replaceAll("/", ""); serverN = serverN.trim(); serverN = serverN.toLowerCase(); String result = "Error"; int trys = 3; while (trys-- >= 0 && !("Success".equals(result))){ try{ testConnection(serverN); result = "Success"; }catch(Exception e){ result = e.getClass().getSimpleName(); try { //Sleep for a moment before trying again Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } System.out.println(serverN + "," + 80 + "," + result); } }); es.execute(run); } } es.shutdown(); //wait forever es.awaitTermination(9999, TimeUnit.DAYS); System.out.println(" } public static void testConnection(String server) throws UnknownHostException, IOException{ URL u = new URL("http://" + server); URLConnection c = u.openConnection(); c.connect(); //System.out.println(c.getContentLength()); // Socket client = new Socket(server, port); // System.out.println("Just connected to " + client.getRemoteSocketAddress()); // OutputStream outToServer = client.getOutputStream(); // DataOutputStream out = new DataOutputStream(outToServer); // out.writeUTF("GET / HTTP/1.1\n\n"); // InputStream inFromServer = client.getInputStream(); // DataInputStream in = new DataInputStream(inFromServer); // System.out.println("Server says " + in.readUTF()); // client.close(); } }
package org.jgroups.tests; import java.net.*; /** * @author Bela Ban Dec 19 * @author 2003 * @version $Id: McastLoopbackTest1_4.java,v 1.2 2003/12/19 21:04:42 belaban Exp $ */ public class McastLoopbackTest1_4 { public static void main(String[] args) { byte[] recv_buf=new byte[1024], send_buf="Bela Ban".getBytes(); MulticastSocket mcast_sock; String group_name="230.1.2.3"; int mcast_port=7500; SocketAddress mcast_addr, local_addr; NetworkInterface bind_interface; DatagramPacket send_packet, recv_packet; if(args.length != 1) { System.out.println("McastTest <bind interface>"); return; } try { bind_interface=NetworkInterface.getByInetAddress(InetAddress.getByName(args[0])); if(bind_interface == null) { System.err.println("bind interface " + args[0] + " not found"); return; } local_addr=new InetSocketAddress(args[0], 0); System.out.println("local_addr=" + local_addr); mcast_addr=new InetSocketAddress(InetAddress.getByName(group_name), mcast_port); mcast_sock=new MulticastSocket(local_addr); local_addr=mcast_sock.getLocalSocketAddress(); mcast_sock.setTimeToLive(32); // mcast_sock.setLoopbackMode(false); System.out.println("mcast_sock: local addr=" + mcast_sock.getLocalSocketAddress() + ", interface=" + mcast_sock.getInterface()); mcast_sock.setInterface(InetAddress.getByName(args[0])); mcast_sock.setNetworkInterface(bind_interface); System.out.println("mcast_sock: local addr=" + mcast_sock.getLocalSocketAddress() + ", interface=" + mcast_sock.getInterface()); System.out.println("-- joining " + mcast_addr + " on " + bind_interface); mcast_sock.joinGroup(mcast_addr, bind_interface); System.out.println("mcast_sock: local addr=" + mcast_sock.getLocalSocketAddress() + ", interface=" + mcast_sock.getInterface()); send_packet=new DatagramPacket(send_buf, send_buf.length, mcast_addr); recv_packet=new DatagramPacket(recv_buf, recv_buf.length); mcast_sock.send(send_packet); mcast_sock.receive(recv_packet); System.out.println("-- received " + new String(recv_packet.getData(), 0, 8) + " from " + recv_packet.getSocketAddress()); } catch(Exception e) { e.printStackTrace(); } } }
package org.apache.xerces.validators.common; import org.apache.xerces.framework.XMLAttrList; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.framework.XMLDocumentHandler; import org.apache.xerces.framework.XMLDocumentScanner; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.Hash2intTable; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.validators.dtd.DTDGrammar; import org.apache.xerces.validators.schema.EquivClassComparator; import org.apache.xerces.validators.schema.SchemaGrammar; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.TraverseSchema; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; /** * This class is the super all-in-one validator used by the parser. * * @version $Id$ */ public final class XMLValidator implements DefaultEntityHandler.EventHandler, XMLEntityHandler.CharDataHandler, XMLDocumentScanner.EventHandler, NamespacesScope.NamespacesHandler { // Constants // debugging private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; private static final boolean DEBUG_PRINT_ATTRIBUTES = false; private static final boolean DEBUG_PRINT_CONTENT = false; private static final boolean DEBUG_SCHEMA_VALIDATION = false; private static final boolean DEBUG_ELEMENT_CHILDREN = false; // Chunk size constants private static final int CHUNK_SHIFT = 8; // 2^8 = 256 private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT); private static final int CHUNK_MASK = CHUNK_SIZE - 1; private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k // Data // REVISIT: The data should be regrouped and re-organized so that // it's easier to find a meaningful field. // debugging // private static boolean DEBUG = false; // other private Hashtable fIdDefs = null; private Hashtable fIdRefs = null; private Object fNullValue = null; // attribute validators private AttributeValidator fAttValidatorCDATA = null; private AttributeValidator fAttValidatorID = new AttValidatorID(); private AttributeValidator fAttValidatorIDREF = new AttValidatorIDREF(); private AttributeValidator fAttValidatorIDREFS = new AttValidatorIDREFS(); private AttributeValidator fAttValidatorENTITY = new AttValidatorENTITY(); private AttributeValidator fAttValidatorENTITIES = new AttValidatorENTITIES(); private AttributeValidator fAttValidatorNMTOKEN = new AttValidatorNMTOKEN(); private AttributeValidator fAttValidatorNMTOKENS = new AttValidatorNMTOKENS(); private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION(); private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION(); private AttributeValidator fAttValidatorDATATYPE = null; // Package access for use by AttributeValidator classes. StringPool fStringPool = null; boolean fValidating = false; boolean fInElementContent = false; int fStandaloneReader = -1; // settings private boolean fValidationEnabled = false; private boolean fDynamicValidation = false; private boolean fSchemaValidation = true; private boolean fValidationEnabledByDynamic = false; private boolean fDynamicDisabledByValidation = false; private boolean fWarningOnDuplicateAttDef = false; private boolean fWarningOnUndeclaredElements = false; private boolean fLoadDTDGrammar = true; // declarations private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); private ContentLeafNameTypeVector[] fContentLeafStack = new ContentLeafNameTypeVector[8]; private int[] fValidationFlagStack = new int[8]; private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private static final int sizeQNameParts = 8; private QName[] fElementQNamePartsStack = new QName[sizeQNameParts]; private QName[] fElementChildren = new QName[32]; private int fElementChildrenLength = 0; private int[] fElementChildrenOffsetStack = new int[32]; private int fElementDepth = -1; private boolean fNamespacesEnabled = false; private NamespacesScope fNamespacesScope = null; private int fNamespacesPrefix = -1; private QName fRootElement = new QName(); private int fAttrListHandle = -1; private int fCurrentElementEntity = -1; private int fCurrentElementIndex = -1; private int fCurrentContentSpecType = -1; private boolean fSeenDoctypeDecl = false; private final int TOP_LEVEL_SCOPE = -1; private int fCurrentScope = TOP_LEVEL_SCOPE; private int fCurrentSchemaURI = -1; private int fEmptyURI = - 1; private int fXsiPrefix = - 1; private int fXsiURI = -2; private int fXsiTypeAttValue = -1; private DatatypeValidator fXsiTypeValidator = null; private Grammar fGrammar = null; private int fGrammarNameSpaceIndex = -1; private GrammarResolver fGrammarResolver = null; // state and stuff private boolean fScanningDTD = false; private XMLDocumentScanner fDocumentScanner = null; private boolean fCalledStartDocument = false; private XMLDocumentHandler fDocumentHandler = null; private XMLDocumentHandler.DTDHandler fDTDHandler = null; private boolean fSeenRootElement = false; private XMLAttrList fAttrList = null; private int fXMLLang = -1; private LocatorImpl fAttrNameLocator = null; private boolean fCheckedForSchema = false; private boolean fDeclsAreExternal = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; private char[] fCharRefData = null; private boolean fSendCharDataAsCharArray = false; private boolean fBufferDatatype = false; private StringBuffer fDatatypeBuffer = new StringBuffer(); private QName fTempQName = new QName(); private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); private boolean fGrammarIsDTDGrammar = false; private boolean fGrammarIsSchemaGrammar = false; private boolean fNeedValidationOff = false; // symbols private int fEMPTYSymbol = -1; private int fANYSymbol = -1; private int fMIXEDSymbol = -1; private int fCHILDRENSymbol = -1; private int fCDATASymbol = -1; private int fIDSymbol = -1; private int fIDREFSymbol = -1; private int fIDREFSSymbol = -1; private int fENTITYSymbol = -1; private int fENTITIESSymbol = -1; private int fNMTOKENSymbol = -1; private int fNMTOKENSSymbol = -1; private int fNOTATIONSymbol = -1; private int fENUMERATIONSymbol = -1; private int fREQUIREDSymbol = -1; private int fFIXEDSymbol = -1; private int fDATATYPESymbol = -1; private int fEpsilonIndex = -1; // Constructors /** Constructs an XML validator. */ public XMLValidator(StringPool stringPool, XMLErrorReporter errorReporter, DefaultEntityHandler entityHandler, XMLDocumentScanner documentScanner) { // keep references fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fDocumentScanner = documentScanner; fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); // initialize fAttrList = new XMLAttrList(fStringPool); entityHandler.setEventHandler(this); entityHandler.setCharDataHandler(this); fDocumentScanner.setEventHandler(this); for (int i = 0; i < sizeQNameParts; i++) { fElementQNamePartsStack[i] = new QName(); } init(); } // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner) public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } // Public methods // initialization /** Set char data processing preference and handlers. */ public void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fSendCharDataAsCharArray = sendCharDataAsCharArray; fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray); fDocumentHandler = docHandler; fDTDHandler = dtdHandler; } // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler) /** Reset or copy. */ public void resetOrCopy(StringPool stringPool) throws Exception { fAttrList = new XMLAttrList(stringPool); resetCommon(stringPool); } /** Reset. */ public void reset(StringPool stringPool) throws Exception { fAttrList.reset(stringPool); resetCommon(stringPool); } // settings /** * Turning on validation/dynamic turns on validation if it is off, and * this is remembered. Turning off validation DISABLES validation/dynamic * if it is on. Turning off validation/dynamic DOES NOT turn off * validation if it was explicitly turned on, only if it was turned on * BECAUSE OF the call to turn validation/dynamic on. Turning on * validation will REENABLE and turn validation/dynamic back on if it * was disabled by a call that turned off validation while * validation/dynamic was enabled. */ public void setValidationEnabled(boolean flag) throws Exception { fValidationEnabled = flag; fValidationEnabledByDynamic = false; if (fValidationEnabled) { if (fDynamicDisabledByValidation) { fDynamicValidation = true; fDynamicDisabledByValidation = false; } } else if (fDynamicValidation) { fDynamicValidation = false; fDynamicDisabledByValidation = true; } fValidating = fValidationEnabled; } /** Returns true if validation is enabled. */ public boolean getValidationEnabled() { return fValidationEnabled; } /** Sets whether Schema support is on/off. */ public void setSchemaValidationEnabled(boolean flag) { fSchemaValidation = flag; } /** Returns true if Schema support is on. */ public boolean getSchemaValidationEnabled() { return fSchemaValidation; } /** Sets whether validation is dynamic. */ public void setDynamicValidationEnabled(boolean flag) throws Exception { fDynamicValidation = flag; fDynamicDisabledByValidation = false; if (!fDynamicValidation) { if (fValidationEnabledByDynamic) { fValidationEnabled = false; fValidationEnabledByDynamic = false; } } else if (!fValidationEnabled) { fValidationEnabled = true; fValidationEnabledByDynamic = true; } fValidating = fValidationEnabled; } /** Returns true if validation is dynamic. */ public boolean getDynamicValidationEnabled() { return fDynamicValidation; } /** Sets fLoadDTDGrammar when validation is off **/ public void setLoadDTDGrammar(boolean loadDG){ if (fValidating) { fLoadDTDGrammar = true; } else{ fLoadDTDGrammar = loadDG; } } /** Returns fLoadDTDGrammar **/ public boolean getLoadDTDGrammar() { return fLoadDTDGrammar; } /** Sets whether namespaces are enabled. */ public void setNamespacesEnabled(boolean flag) { fNamespacesEnabled = flag; } /** Returns true if namespaces are enabled. */ public boolean getNamespacesEnabled() { return fNamespacesEnabled; } /** Sets whether duplicate attribute definitions signal a warning. */ public void setWarningOnDuplicateAttDef(boolean flag) { fWarningOnDuplicateAttDef = flag; } /** Returns true if duplicate attribute definitions signal a warning. */ public boolean getWarningOnDuplicateAttDef() { return fWarningOnDuplicateAttDef; } /** Sets whether undeclared elements signal a warning. */ public void setWarningOnUndeclaredElements(boolean flag) { fWarningOnUndeclaredElements = flag; } /** Returns true if undeclared elements signal a warning. */ public boolean getWarningOnUndeclaredElements() { return fWarningOnUndeclaredElements; } // DefaultEntityHandler.EventHandler methods /** Start entity reference. */ public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.startEntityReference(entityName, entityType, entityContext); } /** End entity reference. */ public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.endEntityReference(entityName, entityType, entityContext); } /** Send end of input notification. */ public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception { fDocumentScanner.endOfInput(entityName, moreToFollow); /** Send reader change notifications. */ /** External entity standalone check. */ /** Return true if validating. */ /** Process characters. */ /** Process characters. */ /** Process whitespace. */ /** Process whitespace. */ /** Scans element type. */ /** Scans expected element type. */ /** Scans attribute name. */ /** Call start document. */ /** Call end document. */ /** Call XML declaration. */ /** Call text declaration. */ /** * Signal the scanning of an element name in a start element tag. * * @param element Element name scanned. */ public void element(QName element) throws Exception { fAttrListHandle = -1; } /** * Signal the scanning of an attribute associated to the previous * start element tag. * * @param element Element name scanned. * @param attrName Attribute name scanned. * @param attrValue The string pool index of the attribute value. */ public boolean attribute(QName element, QName attrName, int attrValue) throws Exception { if (fAttrListHandle == -1) { fAttrListHandle = fAttrList.startAttrList(); } // if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element. // specified: true, search : true return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1; } /** Call start element. */ public void callStartElement(QName element) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart)); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) add default attrs (FIXED and NOT_FIXED) if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } fCheckedForSchema = true; if (fNamespacesEnabled) { bindNamespacesToElementAndAttributes(element, fAttrList); } validateElementAndAttributes(element, fAttrList); if (fAttrListHandle != -1) { fAttrList.endAttrList(); } fDocumentHandler.startElement(element, fAttrList, fAttrListHandle); fAttrListHandle = -1; //before we increment the element depth, add this element's QName to its enclosing element 's children list fElementDepth++; //if (fElementDepth >= 0) { if (fValidating) { // push current length onto stack if (fElementChildrenOffsetStack.length < fElementDepth) { int newarray[] = new int[fElementChildrenOffsetStack.length * 2]; System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length); fElementChildrenOffsetStack = newarray; } fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength; // add this element to children if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildrenLength * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.setValues(element); fElementChildrenLength++; if (DEBUG_ELEMENT_CHILDREN) { printChildren(); printStack(); } } // One more level of depth //fElementDepth++; ensureStackCapacity(fElementDepth); fCurrentElement.setValues(element); fCurrentElementEntity = fEntityHandler.getReaderId(); fElementQNamePartsStack[fElementDepth].setValues(fCurrentElement); fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; if (fNeedValidationOff) { fValidating = false; fNeedValidationOff = false; } if (fValidating && fGrammarIsSchemaGrammar) { pushContentLeafStack(); } fValidationFlagStack[fElementDepth] = fValidating ? 0 : -1; fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void pushContentLeafStack() throws Exception { int contentType = getContentSpecType(fCurrentElementIndex); if ( contentType == XMLElementDecl.TYPE_CHILDREN) { XMLContentModel cm = getElementContentModel(fCurrentElementIndex); ContentLeafNameTypeVector cv = cm.getContentLeafNameTypeVector(); if (cm != null) { fContentLeafStack[fElementDepth] = cv; } } } private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementQNamePartsStack.length ) { int[] newStack = new int[newElementDepth * 2]; System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth); fScopeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth); fGrammarNameSpaceIndexStack = newStack; QName[] newStackOfQueue = new QName[newElementDepth * 2]; System.arraycopy(this.fElementQNamePartsStack, 0, newStackOfQueue, 0, newElementDepth ); fElementQNamePartsStack = newStackOfQueue; QName qname = fElementQNamePartsStack[newElementDepth]; if (qname == null) { for (int i = newElementDepth; i < fElementQNamePartsStack.length; i++) { fElementQNamePartsStack[i] = new QName(); } } newStack = new int[newElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth); fElementEntityStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth); fElementIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth); fContentSpecTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fValidationFlagStack, 0, newStack, 0, newElementDepth); fValidationFlagStack = newStack; ContentLeafNameTypeVector[] newStackV = new ContentLeafNameTypeVector[newElementDepth * 2]; System.arraycopy(fContentLeafStack, 0, newStackV, 0, newElementDepth); fContentLeafStack = newStackV; } } /** Call end element. */ public void callEndElement(int readerId) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n"); int prefixIndex = fCurrentElement.prefix; int elementType = fCurrentElement.rawname; if (fCurrentElementEntity != readerId) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH, XMLMessages.P78_NOT_WELLFORMED, new Object[] { fStringPool.toString(elementType) }, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } fElementDepth if (fValidating) { int elementIndex = fCurrentElementIndex; if (elementIndex != -1 && fCurrentContentSpecType != -1) { QName children[] = fElementChildren; int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1; int childrenLength = fElementChildrenLength - childrenOffset; if (DEBUG_ELEMENT_CHILDREN) { System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')'); System.out.print("offset: "); System.out.print(childrenOffset); System.out.print(", length: "); System.out.print(childrenLength); System.out.println(); printChildren(); printStack(); } int result = checkContent(elementIndex, children, childrenOffset, childrenLength); if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result); if (result != -1) { int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE; fGrammar.getElementDecl(elementIndex, fTempElementDecl); if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) { reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), "EMPTY"); } else reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex)); } } fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1; } fDocumentHandler.endElement(fCurrentElement); if (fNamespacesEnabled) { fNamespacesScope.decreaseDepth(); } // now pop this element off the top of the element stack //if (fElementDepth-- < 0) { if (fElementDepth < -1) { throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth < 0) { fCurrentElement.clear(); fCurrentElementEntity = -1; fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; // Check after document is fully parsed // (1) check that there was an element with a matching id for every // IDREF and IDREFS attr (V_IDREF0) if (fValidating && fIdRefs != null) { checkIdRefs(); } return; } //restore enclosing element to all the "current" variables // REVISIT: Validation. This information needs to be stored. fCurrentElement.prefix = -1; if (fNamespacesEnabled) { //If Namespace enable then localName != rawName fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].localpart; } else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].rawname; } fCurrentElement.rawname = fElementQNamePartsStack[fElementDepth].rawname; fCurrentElement.uri = fElementQNamePartsStack[fElementDepth].uri; fCurrentElement.prefix = fElementQNamePartsStack[fElementDepth].prefix; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; fValidating = fValidationFlagStack[fElementDepth] == 0 ? true : false; fCurrentScope = fScopeStack[fElementDepth]; //if ( DEBUG_SCHEMA_VALIDATION ) { /** Call start CDATA section. */ /** Call end CDATA section. */ /** Call characters. */ /** Call processing instruction. */ /** Call comment. */ /** Start a new namespace declaration scope. */ /** End a namespace declaration scope. */ /** Normalize attribute value. */ /** Sets the root element. */ /** * Returns true if the element declaration is external. * <p> * <strong>Note:</strong> This method is primarilly useful for * DTDs with internal and external subsets. */ private boolean getElementDeclIsExternal(int elementIndex) { /*if (elementIndex < 0 || elementIndex >= fElementCount) { return false; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; return (fElementDeclIsExternal[chunk][index] != 0); */ if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex); } return false; } /** Returns the content spec type for an element index. */ public int getContentSpecType(int elementIndex) { int contentSpecType = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecType = fTempElementDecl.type; } } return contentSpecType; } /** Returns the content spec handle for an element index. */ public int getContentSpecHandle(int elementIndex) { int contentSpecHandle = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecHandle = fTempElementDecl.contentSpecIndex; } } return contentSpecHandle; } // Protected methods // error reporting /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String,String) // content spec protected int whatCanGoHere(int elementIndex, boolean fullyValid, InsertableElementsInfo info) throws Exception { // Do some basic sanity checking on the info packet. First, make sure // that insertAt is not greater than the child count. It can be equal, // which means to get appendable elements, but not greater. Or, if // the current children array is null, that's bad too. // Since the current children array must have a blank spot for where // the insert is going to be, the child count must always be at least // one. // Make sure that the child count is not larger than the current children // array. It can be equal, which means get appendable elements, but not // greater. if (info.insertAt > info.childCount || info.curChildren == null || info.childCount < 1 || info.childCount > info.curChildren.length) { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_WCGHI, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } int retVal = 0; try { // Get the content model for this element final XMLContentModel cmElem = getElementContentModel(elementIndex); // And delegate this call to it retVal = cmElem.whatCanGoHere(fullyValid, info); } catch (CMException excToCatch) { // REVISIT - Translate caught error to the protected error handler interface int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); throw excToCatch; } return retVal; } // whatCanGoHere(int,boolean,InsertableElementsInfo):int // attribute information /** Protected for use by AttributeValidator classes. */ protected boolean getAttDefIsExternal(QName element, QName attribute) { int attDefIndex = getAttDef(element, attribute); if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex); } return false; } /** addId. */ protected boolean addId(int idIndex) { Integer key = new Integer(idIndex); if (fIdDefs == null) { fIdDefs = new Hashtable(); } else if (fIdDefs.containsKey(key)) { return false; } if (fNullValue == null) { fNullValue = new Object(); } fIdDefs.put(key, fNullValue/*new Integer(elementType)*/); return true; } // addId(int):boolean /** addIdRef. */ protected void addIdRef(int idIndex) { Integer key = new Integer(idIndex); if (fIdDefs != null && fIdDefs.containsKey(key)) { return; } if (fIdRefs == null) { fIdRefs = new Hashtable(); } else if (fIdRefs.containsKey(key)) { return; } if (fNullValue == null) { fNullValue = new Object(); } fIdRefs.put(key, fNullValue/*new Integer(elementType)*/); } // addIdRef(int) // Private methods // other /** Returns true if using a standalone reader. */ private boolean usingStandaloneReader() { return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader; } /** Returns a locator implementation. */ private LocatorImpl getLocatorImpl(LocatorImpl fillin) { Locator here = fErrorReporter.getLocator(); if (fillin == null) return new LocatorImpl(here); fillin.setPublicId(here.getPublicId()); fillin.setSystemId(here.getSystemId()); fillin.setLineNumber(here.getLineNumber()); fillin.setColumnNumber(here.getColumnNumber()); return fillin; } // getLocatorImpl(LocatorImpl):LocatorImpl // initialization /** Reset pool. */ private void poolReset() { if (fIdDefs != null) { fIdDefs.clear(); } if (fIdRefs != null) { fIdRefs.clear(); } } // poolReset() /** Reset common. */ private void resetCommon(StringPool stringPool) throws Exception { fStringPool = stringPool; fValidating = fValidationEnabled; fValidationEnabledByDynamic = false; fDynamicDisabledByValidation = false; poolReset(); fCalledStartDocument = false; fStandaloneReader = -1; fElementChildrenLength = 0; fElementDepth = -1; fSeenRootElement = false; fSeenDoctypeDecl = false; fNamespacesScope = null; fNamespacesPrefix = -1; fRootElement.clear(); fAttrListHandle = -1; fCheckedForSchema = false; fCurrentScope = TOP_LEVEL_SCOPE; fCurrentSchemaURI = -1; fEmptyURI = - 1; fXsiPrefix = - 1; fXsiTypeValidator = null; fGrammar = null; fGrammarNameSpaceIndex = -1; fGrammarResolver = null; fGrammarIsDTDGrammar = false; fGrammarIsSchemaGrammar = false; init(); } // resetCommon(StringPool) /** Initialize. */ private void init() { fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); fEMPTYSymbol = fStringPool.addSymbol("EMPTY"); fANYSymbol = fStringPool.addSymbol("ANY"); fMIXEDSymbol = fStringPool.addSymbol("MIXED"); fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN"); fCDATASymbol = fStringPool.addSymbol("CDATA"); fIDSymbol = fStringPool.addSymbol("ID"); fIDREFSymbol = fStringPool.addSymbol("IDREF"); fIDREFSSymbol = fStringPool.addSymbol("IDREFS"); fENTITYSymbol = fStringPool.addSymbol("ENTITY"); fENTITIESSymbol = fStringPool.addSymbol("ENTITIES"); fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN"); fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS"); fNOTATIONSymbol = fStringPool.addSymbol("NOTATION"); fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION"); fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED"); fFIXEDSymbol = fStringPool.addSymbol("#FIXED"); fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>"); fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>"); fXMLLang = fStringPool.addSymbol("xml:lang"); } // init() // other // default attribute /** addDefaultAttributes. */ private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { //System.out.println("XMLValidator#addDefaultAttributes"); //System.out.print(" "); //fGrammar.printAttributes(elementIndex); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) check that FIXED attrs have matching value (V_TAGd) // (3) add default attrs (FIXED and NOT_FIXED) fGrammar.getElementDecl(elementIndex,fTempElementDecl); //System.out.println("addDefaultAttributes: " + fStringPool.toString(fTempElementDecl.name.localpart)+ // "," + attrIndex + "," + validationEnabled); int elementNameIndex = fTempElementDecl.name.localpart; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { //int adChunk = attlistIndex >> CHUNK_SHIFT; //int adIndex = attlistIndex & CHUNK_MASK; fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); // TO DO: For ericye Debug only /** Queries the content model for the specified element index. */ /** Returns the validatator for an attribute type. */ /** Returns an attribute definition for an element type. */ /** Returns an attribute definition for an element type. */ /** Root element specified. */ /** Switchs to correct validating symbol tables when Schema changes.*/ /** Binds namespaces to the element and attributes. */ /** Warning. */ /** Error. */ /** Fatal error. */ /** Returns a string of the location. */ /** Validates element and attributes. */ /** Character data in content. */ /** * Check that the content of an element is valid. * <p> * This is the method of primary concern to the validator. This method is called * upon the scanner reaching the end tag of an element. At that time, the * element's children must be structurally validated, so it calls this method. * The index of the element being checked (in the decl pool), is provided as * well as an array of element name indexes of the children. The validator must * confirm that this element can have these children in this order. * <p> * This can also be called to do 'what if' testing of content models just to see * if they would be valid. * <p> * Note that the element index is an index into the element decl pool, whereas * the children indexes are name indexes, i.e. into the string pool. * <p> * A value of -1 in the children array indicates a PCDATA node. All other * indexes will be positive and represent child elements. The count can be * zero, since some elements have the EMPTY content model and that must be * confirmed. * * @param elementIndex The index within the <code>ElementDeclPool</code> of this * element. * @param childCount The number of entries in the <code>children</code> array. * @param children The children of this element. Each integer is an index within * the <code>StringPool</code> of the child element name. An index * of -1 is used to indicate an occurrence of non-whitespace character * data. * * @return The value -1 if fully valid, else the 0 based index of the child * that first failed. If the value returned is equal to the number * of children, then additional content is required to reach a valid * ending state. * * @exception Exception Thrown on error. */ private int checkContent(int elementIndex, QName[] children, int childOffset, int childCount) throws Exception { // Get the element name index from the element // REVISIT: Validation final int elementType = fCurrentElement.rawname; if (DEBUG_PRINT_CONTENT) { String strTmp = fStringPool.toString(elementType); System.out.println("Name: "+strTmp+", "+ "Count: "+childCount+", "+ "ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex)); for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) { if (index == 0) { System.out.print(" ("); } String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart); if (index + 1 == childCount) { System.out.println(childName + ")"); } else if (index + 1 == 10) { System.out.println(childName + ",...)"); } else { System.out.print(childName + ","); } } } // Get out the content spec for this element final int contentType = fCurrentContentSpecType; // debugging //System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType); // Deal with the possible types of content. We try to optimized here // by dealing specially with content models that don't require the // full DFA treatment. if (contentType == XMLElementDecl.TYPE_EMPTY) { // If the child count is greater than zero, then this is // an error right off the bat at index 0. if (childCount != 0) { return 0; } } else if (contentType == XMLElementDecl.TYPE_ANY) { // This one is open game so we don't pass any judgement on it // at all. Its assumed to fine since it can hold anything. } else if (contentType == XMLElementDecl.TYPE_MIXED || contentType == XMLElementDecl.TYPE_CHILDREN) { // Get the content model for this element, faulting it in if needed XMLContentModel cmElem = null; try { cmElem = getElementContentModel(elementIndex); int result = cmElem.validateContent(children, childOffset, childCount); if (result != -1 && fGrammarIsSchemaGrammar) { // REVISIT: not optimized for performance, EquivClassComparator comparator = new EquivClassComparator(fGrammarResolver, fStringPool); cmElem.setEquivClassComparator(comparator); result = cmElem.validateContentSpecial(children, childOffset, childCount); } return result; } catch(CMException excToCatch) { // REVISIT - Translate the caught exception to the protected error API int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } else if (contentType == -1) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, elementType); } else if (contentType == XMLElementDecl.TYPE_SIMPLE ) { XMLContentModel cmElem = null; if (childCount > 0) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { "Can not have element children within a simple type content" }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } else { try { fGrammar.getElementDecl(elementIndex, fTempElementDecl); DatatypeValidator dv = fTempElementDecl.datatypeValidator; // If there is xsi:type validator, substitute it. if ( fXsiTypeValidator != null ) { dv = fXsiTypeValidator; fXsiTypeValidator = null; } if (dv == null) { System.out.println("Internal Error: this element have a simpletype "+ "but no datatypevalidator was found, element "+fTempElementDecl.name +",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart)); } else { dv.validate(fDatatypeBuffer.toString(), null); } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage() }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_CST, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } // We succeeded return -1; } // checkContent(int,int,int[]):int /** * Check that all ID references were to ID attributes present in the document. * <p> * This method is a convenience call that allows the validator to do any id ref * checks above and beyond those done by the scanner. The scanner does the checks * specificied in the XML spec, i.e. that ID refs refer to ids which were * eventually defined somewhere in the document. * <p> * If the validator is for a Schema perhaps, which defines id semantics beyond * those of the XML specificiation, this is where that extra checking would be * done. For most validators, this is a no-op. * * @exception Exception Thrown on error. */ private void checkIdRefs() throws Exception { if (fIdRefs == null) return; Enumeration en = fIdRefs.keys(); while (en.hasMoreElements()) { Integer key = (Integer)en.nextElement(); if (fIdDefs == null || !fIdDefs.containsKey(key)) { Object[] args = { fStringPool.toString(key.intValue()) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_WITH_ID_REQUIRED, XMLMessages.VC_IDREF, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } // checkIdRefs() /** * Checks that all declared elements refer to declared elements * in their content models. This method calls out to the error * handler to indicate warnings. */ private void printChildren() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('['); for (int i = 0; i < fElementChildrenLength; i++) { System.out.print(' '); QName qname = fElementChildren[i]; if (qname != null) { System.out.print(fStringPool.toString(qname.rawname)); } else { System.out.print("null"); } if (i < fElementChildrenLength - 1) { System.out.print(", "); } System.out.flush(); } System.out.print(" ]"); System.out.println(); } } private void printStack() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('{'); for (int i = 0; i <= fElementDepth; i++) { System.out.print(' '); System.out.print(fElementChildrenOffsetStack[i]); if (i < fElementDepth) { System.out.print(", "); } System.out.flush(); } System.out.print(" }"); System.out.println(); } } // Interfaces /** * AttributeValidator. */ public interface AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValue, int attType, int enumHandle) throws Exception; } // interface AttributeValidator // Classes /** * AttValidatorCDATA. */ final class AttValidatorCDATA implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... return attValueHandle; } } // class AttValidatorCDATA /** * AttValidatorID. */ final class AttValidatorID implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validName(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_ID_INVALID, XMLMessages.VC_ID, fStringPool.toString(attribute.rawname), newAttValue); } // ID - check that the id value is unique within the document (V_TAG8) if (element.rawname != -1 && !addId(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ID_NOT_UNIQUE, XMLMessages.VC_ID, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalong attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorID /** * AttValidatorIDREF. */ final class AttValidatorIDREF implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validName(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_IDREF_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attribute.rawname), newAttValue); } // IDREF - remember the id value if (element.rawname != -1) addIdRef(attValueHandle); } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorIDREF /** * AttValidatorIDREFS. */ final class AttValidatorIDREFS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String idName = tokenizer.nextToken(); if (fValidating) { if (!XMLCharacterProperties.validName(idName)) { ok = false; } // IDREFS - remember the id values if (element.rawname != -1) { addIdRef(fStringPool.addSymbol(idName)); } } sb.append(idName); if (!tokenizer.hasMoreTokens()) break; sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorIDREFS /** * AttValidatorENTITY. */ final class AttValidatorENTITY implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENTITY - check that the value is an unparsed entity name (V_TAGa) if (!fEntityHandler.isUnparsedEntity(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITY /** * AttValidatorENTITIES. */ final class AttValidatorENTITIES implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String entityName = tokenizer.nextToken(); // ENTITIES - check that each value is an unparsed entity name (V_TAGa) if (fValidating && !fEntityHandler.isUnparsedEntity(fStringPool.addSymbol(entityName))) { ok = false; } sb.append(entityName); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITIES_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITIES /** * AttValidatorNMTOKEN. */ final class AttValidatorNMTOKEN implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validNmtoken(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKEN /** * AttValidatorNMTOKENS. */ final class AttValidatorNMTOKENS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String nmtoken = tokenizer.nextToken(); if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) { ok = false; } sb.append(nmtoken); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKENS /** * AttValidatorNOTATION. */ final class AttValidatorNOTATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // NOTATION - check that the value is in the AttDef enumeration (V_TAGo) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_NOTATION_ATTRIBUTES, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNOTATION /** * AttValidatorENUMERATION. */ final class AttValidatorENUMERATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENUMERATION - check that value is in the AttDef enumeration (V_TAG9) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_ENUMERATION, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENUMERATION } // class XMLValidator
package com.gabmus.co2photoeditor; import android.opengl.GLES20; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; public class RenderTarget2D { private int[] fb; private int[] depthRb; private int[] renderTex; private IntBuffer texBuffer; public int Width; public int Height; public RenderTarget2D(int w, int h) { Width = w; Height = h; generateframebuffer(); } public int GetTex() {return renderTex[0];} public boolean Set() { GLES20.glViewport(0, 0, Width, Height); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fb[0]); GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, renderTex[0], 0); GLES20.glFramebufferRenderbuffer(GLES20.GL_FRAMEBUFFER, GLES20.GL_DEPTH_ATTACHMENT, GLES20.GL_RENDERBUFFER, depthRb[0]); int status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER); if (status != GLES20.GL_FRAMEBUFFER_COMPLETE) throw (new RuntimeException("SHEE")); GLES20.glClearColor(.0f, .0f, .0f, 1.0f); GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); return true; } public void Release() { try { GLES20.glDeleteRenderbuffers(1, depthRb, 0); GLES20.glDeleteTextures(1, renderTex, 0); GLES20.glDeleteFramebuffers(1, fb, 0); GLES20.glFlush(); } catch(Exception e){ } } public static void SetDefault(int w, int h) { GLES20.glViewport(0, 0, w, h); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); GLES20.glClearColor(.0f, .0f, .0f, 1.0f); GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); } private void generateframebuffer() { fb = new int[1]; depthRb = new int[1]; renderTex = new int[1]; GLES20.glGenFramebuffers(1, fb, 0); GLES20.glGenRenderbuffers(1, depthRb, 0); GLES20.glGenTextures(1, renderTex, 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, renderTex[0]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); int[] buf = new int[Width * Height]; texBuffer = ByteBuffer.allocateDirect(buf.length * 4).order(ByteOrder.nativeOrder()).asIntBuffer();; GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGB, Width, Height, 0, GLES20.GL_RGB, GLES20.GL_UNSIGNED_SHORT_5_6_5, texBuffer); GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, depthRb[0]); GLES20.glRenderbufferStorage(GLES20.GL_RENDERBUFFER, GLES20.GL_DEPTH_COMPONENT16, Width, Height); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fb[0]); GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, renderTex[0], 0); GLES20.glFramebufferRenderbuffer(GLES20.GL_FRAMEBUFFER, GLES20.GL_DEPTH_ATTACHMENT, GLES20.GL_RENDERBUFFER, depthRb[0]); } }
package com.jakewharton.trakt; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import com.jakewharton.apibuilder.ApiBuilder; import com.jakewharton.apibuilder.ApiException; import com.jakewharton.trakt.entities.Response; /** * Trakt-specific API builder extension which provides helper methods for * adding fields, parameters, and post-parameters commonly used in the API. * * @param <T> Native class type of the HTTP method call result. * @author Jake Wharton <jakewharton@gmail.com> */ public abstract class TraktApiBuilder<T> extends ApiBuilder { /** API key field name. */ protected static final String FIELD_API_KEY = API_URL_DELIMITER_START + "apikey" + API_URL_DELIMITER_END; protected static final String FIELD_USERNAME = API_URL_DELIMITER_START + "username" + API_URL_DELIMITER_END; protected static final String FIELD_DATE = API_URL_DELIMITER_START + "date" + API_URL_DELIMITER_END; protected static final String FIELD_DAYS = API_URL_DELIMITER_START + "days" + API_URL_DELIMITER_END; protected static final String FIELD_QUERY = API_URL_DELIMITER_START + "query" + API_URL_DELIMITER_END; protected static final String FIELD_SEASON = API_URL_DELIMITER_START + "season" + API_URL_DELIMITER_END; protected static final String FIELD_TITLE = API_URL_DELIMITER_START + "title" + API_URL_DELIMITER_END; protected static final String FIELD_EPISODE = API_URL_DELIMITER_START + "episode" + API_URL_DELIMITER_END; protected static final String FIELD_EXTENDED = API_URL_DELIMITER_START + "extended" + API_URL_DELIMITER_END; private static final String POST_PLUGIN_VERSION = "plugin_version"; private static final String POST_MEDIA_CENTER_VERSION = "media_center_version"; private static final String POST_MEDIA_CENTER_DATE = "media_center_date"; /** Format for encoding a {@link java.util.Date} in a URL. */ private static final SimpleDateFormat URL_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); /** Trakt API URL base. */ private static final String BASE_URL = "http://api.trakt.tv"; /** Number of milliseconds in a single second. */ /*package*/ static final long MILLISECONDS_IN_SECOND = 1000; /** Valued-list seperator. */ private static final char SEPERATOR = ','; /** Valid HTTP request methods. */ protected static enum HttpMethod { Get, Post } /** Service instance. */ private final TraktApiService service; /** Type token of return type. */ private final TypeToken<T> token; /** HTTP request method to use. */ private final HttpMethod method; /** String representation of JSON POST body. */ private JsonObject postBody; /** * Initialize a new builder for an HTTP GET call. * * @param service Service to bind to. * @param token Return type token. * @param methodUri URI method format string. */ public TraktApiBuilder(TraktApiService service, TypeToken<T> token, String methodUri) { this(service, token, methodUri, HttpMethod.Get); } /** * Initialize a new builder for the specified HTTP method call. * * @param service Service to bind to. * @param token Return type token. * @param urlFormat URL format string. * @param method HTTP method. */ public TraktApiBuilder(TraktApiService service, TypeToken<T> token, String urlFormat, HttpMethod method) { super(BASE_URL + urlFormat); this.service = service; this.token = token; this.method = method; this.postBody = new JsonObject(); this.field(FIELD_API_KEY, this.service.getApiKey()); } /** * Execute remote API method and unmarshall the result to its native type. * * @return Instance of result type. * @throws ApiException if validation fails. */ public final T fire() { this.preFireCallback(); try { this.performValidation(); } catch (Exception e) { throw new ApiException(e); } T result = this.service.unmarshall(this.token, this.execute()); this.postFireCallback(result); return result; } /** * Perform any required actions before validating the request. */ protected void preFireCallback() { //Override me! } /** * Perform any required validation before firing off the request. */ protected void performValidation() { //Override me! } /** * Perform any required actions before returning the request result. * * @param result Request result. */ protected void postFireCallback(T result) { //Override me! } /** * Mark current builder as Trakt developer method. This will automatically * add the debug fields to the post body. */ protected final void includeDebugStrings() { this.postParameter(POST_PLUGIN_VERSION, service.getPluginVersion()); this.postParameter(POST_MEDIA_CENTER_VERSION, service.getMediaCenterVersion()); this.postParameter(POST_MEDIA_CENTER_DATE, service.getMediaCenterDate()); } /** * <p>Execute the remote API method and return the JSON object result.<p> * * <p>This method can be overridden to select a specific subset of the JSON * object. The overriding implementation should still call 'super.execute()' * and then perform the filtering from there.</p> * * @return JSON object instance. */ protected final JsonElement execute() { String url = this.buildUrl(); while (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } try { switch (this.method) { case Get: return this.service.get(url); case Post: return this.service.post(url, this.postBody.toString()); default: throw new IllegalArgumentException("Unknown HttpMethod type " + this.method.toString()); } } catch (ApiException ae) { try { Response response = this.service.unmarshall(new TypeToken<Response>() {}, ae.getMessage()); if (response != null) { throw new TraktException(url, this.postBody, ae, response); } } catch (JsonParseException jpe) { } throw new TraktException(url, this.postBody, ae); } } /** * Print the HTTP request that would be made */ public final void print() { this.preFireCallback(); try { this.performValidation(); } catch (Exception e) { throw new ApiException(e); } String url = this.buildUrl(); while (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } System.out.println(this.method.toString().toUpperCase() + " " + url); for (String name : this.service.getRequestHeaderNames()) { System.out.println(name + ": " + this.service.getRequestHeader(name)); } switch (this.method) { case Post: System.out.println(); System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(this.postBody)); break; } } /** * Set the API key. * * @param apiKey API key string. * @return Current instance for builder pattern. */ /*package*/ final ApiBuilder api(String apiKey) { return this.field(FIELD_API_KEY, apiKey); } /** * Add a URL parameter value. * * @param name Name. * @param value Value. * @return Current instance for builder pattern. */ protected final ApiBuilder parameter(String name, Date value) { return this.parameter(name, Long.toString(TraktApiBuilder.dateToUnixTimestamp(value))); } /** * Add a URL parameter value. * * @param name Name. * @param value Value. * @return Current instance for builder pattern. */ protected final <K extends TraktEnumeration> ApiBuilder parameter(String name, K value) { if ((value == null) || (value.toString() == null) || (value.toString().length() == 0)) { return this.parameter(name, ""); } else { return this.parameter(name, value.toString()); } } /** * Add a URL parameter value. * * @param name Name. * @param valueList List of values. * @return Current instance for builder pattern. */ protected final <K extends Object> ApiBuilder parameter(String name, List<K> valueList) { StringBuilder builder = new StringBuilder(); Iterator<K> iterator = valueList.iterator(); while (iterator.hasNext()) { builder.append(encodeUrl(iterator.next().toString())); if (iterator.hasNext()) { builder.append(SEPERATOR); } } return this.parameter(name, builder.toString()); } /** * Add a URL field value. * * @param name Name. * @param date Value. * @return Current instance for builder pattern. */ protected final ApiBuilder field(String name, Date date) { return this.field(name, URL_DATE_FORMAT.format(date)); } /** * Add a URL field value. * * @param name Name. * @param value Value. * @return Current instance for builder pattern. */ protected final <K extends TraktEnumeration> ApiBuilder field(String name, K value) { if ((value == null) || (value.toString() == null) || (value.toString().length() == 0)) { return this.field(name); } else { return this.field(name, value.toString()); } } protected final boolean hasPostParameter(String name) { return this.postBody.has(name); } protected final TraktApiBuilder<T> postParameter(String name, String value) { this.postBody.addProperty(name, value); return this; } protected final TraktApiBuilder<T> postParameter(String name, int value) { return this.postParameter(name, Integer.toString(value)); } protected final <K extends TraktEnumeration> TraktApiBuilder<T> postParameter(String name, K value) { if ((value != null) && (value.toString() != null) && (value.toString().length() > 0)) { return this.postParameter(name, value.toString()); } return this; } protected final TraktApiBuilder<T> postParameter(String name, JsonElement value) { this.postBody.add(name, value); return this; } /** * Convert a {@link Date} to its Unix timestamp equivalent. * * @param date Date value. * @return Unix timestamp value. */ protected static final long dateToUnixTimestamp(Date date) { return date.getTime() / MILLISECONDS_IN_SECOND; } }
package org.callimachusproject.server.chain; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Future; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.cache.ResourceFactory; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.client.cache.CacheConfig; import org.apache.http.impl.client.cache.CachingHttpAsyncClient; import org.apache.http.impl.client.cache.ManagedHttpCacheStorage; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.nio.conn.ClientAsyncConnectionManager; import org.apache.http.nio.protocol.HttpAsyncRequestProducer; import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.callimachusproject.server.AsyncExecChain; import org.callimachusproject.server.helpers.AutoClosingAsyncClient; import org.callimachusproject.server.helpers.CalliContext; import org.callimachusproject.server.helpers.ResponseCallback; import org.callimachusproject.server.util.HTTPDateFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CacheHandler implements AsyncExecChain { private final class DelegatingClient extends CloseableHttpAsyncClient { private final AsyncExecChain delegate; private boolean running; public DelegatingClient(AsyncExecChain delegate) { this.delegate = delegate; } public void start() { running = true; } public void close() { shutdown(); } public void shutdown() { running = false; } public boolean isRunning() { return running; } public IOReactorStatus getStatus() { return null; } public HttpParams getParams() { return null; } public ClientAsyncConnectionManager getConnectionManager() { return null; } public <T> Future<T> execute(HttpAsyncRequestProducer arg0, HttpAsyncResponseConsumer<T> arg1, HttpContext arg2, FutureCallback<T> arg3) { throw new UnsupportedOperationException("CachingHttpAsyncClient does not caching for streaming HTTP exchanges"); } public Future<HttpResponse> execute(HttpHost target, final HttpRequest request, final HttpContext context, FutureCallback<HttpResponse> callback) { return delegate.execute(target, request, context, callback); } } private final Logger logger = LoggerFactory.getLogger(CacheHandler.class); private final HTTPDateFormat modifiedformat = new HTTPDateFormat(); private final AsyncExecChain delegate; private final ResourceFactory resourceFactory; private final CacheConfig config; private final Map<HttpHost, HttpAsyncClient> clients = new HashMap<HttpHost, HttpAsyncClient>(); public CacheHandler(AsyncExecChain delegate, ResourceFactory resourceFactory, CacheConfig config) { this.delegate = delegate; this.resourceFactory = resourceFactory; this.config = config; } public synchronized void reset() { clients.clear(); } @Override public Future<HttpResponse> execute(HttpHost target, final HttpRequest request, final HttpContext context, FutureCallback<HttpResponse> callback) { if (config.isHeuristicCachingEnabled()) { return getClient(target).execute(target, request, context, new ResponseCallback(callback) { public void completed(HttpResponse result) { setCacheControlIfCacheable(request, result, context); super.completed(result); } }); } else { return getClient(target) .execute(target, request, context, callback); } } private synchronized HttpAsyncClient getClient(HttpHost target) { if (clients.containsKey(target)) return clients.get(target); logger.debug("Initializing server side cache for {}", target); ManagedHttpCacheStorage storage = new ManagedHttpCacheStorage(config); CachingHttpAsyncClient cachingClient = new CachingHttpAsyncClient(new DelegatingClient(delegate), resourceFactory, storage, config); HttpAsyncClient client = new AutoClosingAsyncClient(cachingClient, storage); clients.put(target, client); return client; } /** * Adds max-age cache-control based on last-modified heuristic for client * caching. */ void setCacheControlIfCacheable(final HttpRequest request, HttpResponse response, final HttpContext context) { String method = request.getRequestLine().getMethod(); int sc = response.getStatusLine().getStatusCode(); if ("GET".equals(method)) { switch (sc) { case 200: case 203: case 206: case 300: case 301: case 302: case 303: case 307: case 308: case 410: setCacheControl(response, context); case 304: if (response.getFirstHeader("Cache-Control") != null) { setCacheControl(response, context); } } } } private void setCacheControl(HttpResponse response, final HttpContext context) { long now = CalliContext.adapt(context).getReceivedOn(); Header lastMod = response.getLastHeader("Last-Modified"); Header[] headers = response.getHeaders("Cache-Control"); if (headers != null && headers.length > 0 && now > 0 && lastMod != null) { String cc = getCacheControl(headers, lastMod, now); if (cc != null) { response.removeHeaders("Cache-Control"); response.setHeader("Cache-Control", cc); } } } private String getCacheControl(Header[] cache, Header lastMod, long now) { StringBuilder sb = new StringBuilder(); for (Header hd : cache) { if (sb.length() > 0) { sb.append(","); } sb.append(hd.getValue()); } if (sb.length() == 0 || sb.indexOf("max-age") < 0 && sb.indexOf("s-maxage") < 0 && sb.indexOf("no-cache") < 0 && sb.indexOf("no-store") < 0) { int maxage = getMaxAgeHeuristic(lastMod, now); if (maxage > 0) { if (sb.length() > 0) { sb.append(","); } sb.append("max-age=").append(maxage); return sb.toString(); } } return null; } private int getMaxAgeHeuristic(Header lastModified, long now) { long lm = lastModified(lastModified); int fraction = (int) ((now - lm) / 10000); return Math.min(fraction, 24 * 60 * 60); } private long lastModified(Header lastModified) { return modifiedformat.parseHeader(lastModified); } }
package com.malmstein.hnews.stories; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.malmstein.hnews.HNewsActivity; import com.malmstein.hnews.R; import com.malmstein.hnews.comments.CommentsFragment; import com.malmstein.hnews.model.Story; import com.malmstein.hnews.presenters.StoriesPagerAdapter; import com.malmstein.hnews.settings.SettingsActivity; import com.malmstein.hnews.views.sliding_tabs.SlidingTabLayout; import com.malmstein.hnews.views.toolbar.AppBarContainer; import com.novoda.notils.caster.Views; public class NewsActivity extends HNewsActivity implements StoryListener { private static final int OFFSCREEN_PAGE_LIMIT = 1; private AppBarContainer appBarContainer; private ViewPager headersPager; private SlidingTabLayout slidingTabs; private StoriesPagerAdapter headersAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news); setupCategories(); setupTabsAndHeaders(); } private void setupCategories() { headersAdapter = new StoriesPagerAdapter(getSupportFragmentManager()); headersPager = Views.findById(this, R.id.news_pager); headersPager.setOffscreenPageLimit(OFFSCREEN_PAGE_LIMIT); headersPager.setAdapter(headersAdapter); } private void setupTabsAndHeaders() { appBarContainer = Views.findById(this, R.id.app_bar_container); appBarContainer.setAppBar(getAppBar()); setTitle(getString(R.string.title_app)); slidingTabs = Views.findById(this, R.id.sliding_tabs); slidingTabs.setCustomTabView(R.layout.view_tab_indicator, android.R.id.text1); slidingTabs.setSelectedIndicatorColors(getResources().getColor(R.color.feed_tabs_selected_indicator)); slidingTabs.setViewPager(headersPager); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_settings) { startActivity(new Intent(this, SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } @Override public void onShareClicked(Intent shareIntent) { startActivity(shareIntent); } @Override public void onCommentsClicked(View v, Story story) { showOrNavigateToCommentsOf(story); } @Override public void onContentClicked(Story story) { showOrNavigateTo(story); } private boolean isTwoPaneLayout() { return findViewById(R.id.story_fragment_root) != null; } private void showOrNavigateTo(Story story) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); boolean preferInternalBrowser = preferences.getBoolean(getString(R.string.pref_enable_browser_key), Boolean.valueOf(getString(R.string.pref_enable_browser_default))); if (story.isHackerNewsLocalItem()) { navigate().toComments(story); } else { if (preferInternalBrowser) { if (isTwoPaneLayout()) { showInnerBrowserFragment(story); } else { navigate().toInnerBrowser(story); } } else { navigate().toExternalBrowser(Uri.parse(story.getUrl())); } } } private void showOrNavigateToCommentsOf(Story story) { if (isTwoPaneLayout()) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.story_fragment_root, CommentsFragment.from(story), CommentsFragment.TAG) .commit(); } else { navigate().toComments(story); } } public void showInnerBrowserFragment(Story story) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.story_fragment_root, ArticleFragment.from(story.getId(), story.getTitle()), CommentsFragment.TAG) .commit(); } }
package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.abstraction.MCEntity; import com.laytonsmith.abstraction.MCItemStack; import com.laytonsmith.abstraction.MCMerchant; import com.laytonsmith.abstraction.MCMerchantRecipe; import com.laytonsmith.abstraction.MCPlayer; import com.laytonsmith.abstraction.StaticLayer; import com.laytonsmith.abstraction.entities.MCVillager; import com.laytonsmith.abstraction.enums.MCRecipeType; import com.laytonsmith.annotations.api; import com.laytonsmith.core.ArgumentValidation; import com.laytonsmith.core.MSVersion; import com.laytonsmith.core.ObjectGenerator; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CInt; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.CVoid; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.exceptions.CRE.CREBadEntityException; import com.laytonsmith.core.exceptions.CRE.CRECastException; import com.laytonsmith.core.exceptions.CRE.CREFormatException; import com.laytonsmith.core.exceptions.CRE.CREIllegalArgumentException; import com.laytonsmith.core.exceptions.CRE.CRELengthException; import com.laytonsmith.core.exceptions.CRE.CRENotFoundException; import com.laytonsmith.core.exceptions.CRE.CREPlayerOfflineException; import com.laytonsmith.core.exceptions.CRE.CRERangeException; import com.laytonsmith.core.exceptions.CRE.CREThrowable; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.natives.interfaces.Mixed; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Trades { public static String docs() { return "Functions related to the management of trades and merchants. A trade is a special kind of recipe" + " accessed through the merchant interface. A merchant is a provider of trades," + " which may or may not be attached to a Villager."; } @api public static class get_merchant_trades extends Recipes.recipeFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREIllegalArgumentException.class, CREFormatException.class, CREBadEntityException.class}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { CArray ret = new CArray(t); for(MCMerchantRecipe mr : GetMerchant(args[0], t).getRecipes()) { ret.push(trade(mr, t), t); } return ret; } @Override public Version since() { return MSVersion.V3_3_3; } @Override public String getName() { return "get_merchant_trades"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "array {specifier} Returns a list of trades used by the specified merchant." + " Specifier can be the UUID of an entity or a virtual merchant ID."; } } @api public static class set_merchant_trades extends Recipes.recipeFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREIllegalArgumentException.class, CREFormatException.class, CRECastException.class, CREBadEntityException.class, CRENotFoundException.class}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { MCMerchant merchant = GetMerchant(args[0], t); CArray trades = Static.getArray(args[1], t); List<MCMerchantRecipe> recipes = new ArrayList<>(); if(trades.isAssociative()) { throw new CRECastException("Expected non-associative array for list of trade arrays.", t); } for(Mixed trade : trades.asList()) { recipes.add(trade(trade, t)); } merchant.setRecipes(recipes); return CVoid.VOID; } @Override public Version since() { return MSVersion.V3_3_3; } @Override public String getName() { return "set_merchant_trades"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {specifier, array} Sets the list of trades the specified merchant can use to the provided" + " array of TradeArrays. The specifier can be the UUID of a physical entity or the ID" + " of a user-created virtual merchant. + " TradeArrays are similar to RecipeArray format and contain the following keys:" + " <pre>" + " result: The result item array of the trade.\n" + " ingredients: Items the player must provide. Must be 1 or 2 itemstacks.\n" + " uses: (Optional) The number of times the recipe has been used. Defaults to 0." + " Note: this number is not kept in sync between merchants and the master list.\n" + " maxuses: (Optional) The maximum number of times this trade can be made before it is disabled." + " Defaults to " + Integer.MAX_VALUE + ".\n" + " hasxpreward: (Optional) Whether xp is given to the player for making this trade." + " Defaults to true." + " </pre>" + " Example 1: Turns 9 stone into obsidian." + " <pre>" + "{\n" + " result: {name: OBSIDIAN},\n" + " ingredients: {{name: STONE, qty: 9}}\n" + "}" + "</pre>" + " Example 2: Combines a diamond and dirt to make grass, but only once." + "<pre>" + "{\n" + " result: {name: 'GRASS'},\n" + " ingredients: {{name: 'DIRT'}, {name: 'DIAMOND'}}\n" + " maxuses: 1\n" + "}" + "</pre>"; } } @api public static class get_virtual_merchants extends Recipes.recipeFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[0]; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { CArray ret = CArray.GetAssociativeArray(t); for(Map.Entry<String, MCMerchant> entry : VIRTUAL_MERCHANTS.entrySet()) { if(entry.getValue() == null) { VIRTUAL_MERCHANTS.remove(entry.getKey()); continue; } ret.set(entry.getKey(), entry.getValue().getTitle(), t); } return ret; } @Override public Version since() { return MSVersion.V3_3_3; } @Override public String getName() { return "get_virtual_merchants"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an array where the keys are currently registered merchant IDs and the values are" + " the corresponding window titles of those merchants."; } } @api public static class create_virtual_merchant extends Recipes.recipeFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[] {CREIllegalArgumentException.class}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { if(VIRTUAL_MERCHANTS.containsKey(args[0].val())) { throw new CREIllegalArgumentException("There is already a merchant with id " + args[0].val(), t); } else { VIRTUAL_MERCHANTS.put(args[0].val(), Static.getServer().createMerchant(args[1].val())); return CVoid.VOID; } } @Override public Version since() { return MSVersion.V3_3_3; } @Override public String getName() { return "create_virtual_merchant"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {ID, title} Creates a merchant that can be traded with by players but is not attached to" + " a physical entity. The ID given should not be a UUID. The title is the text that will display" + " at the top of the window while a player is trading with it. Created merchants will persist" + " across recompiles, but not across server restarts. An exception will be thrown if a merchant" + " already exists using the given ID."; } } @api public static class delete_virtual_merchant extends Recipes.recipeFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[0]; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { return CBoolean.get(VIRTUAL_MERCHANTS.remove(args[0].val()) != null); } @Override public Version since() { return MSVersion.V3_3_3; } @Override public String getName() { return "delete_virtual_merchant"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "boolean {string} Deletes a virtual merchant if one by the given ID exists. Returns true if" + " one was removed, or false if there was no match for the ID."; } } @api public static class popen_trading extends Recipes.recipeFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREPlayerOfflineException.class, CRELengthException.class, CREIllegalArgumentException.class, CREBadEntityException.class, CREFormatException.class}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { MCPlayer player; boolean force = false; if(args.length > 1) { player = Static.GetPlayer(args[1], t); } else { player = Static.getPlayer(env, t); } if(args.length == 3) { force = ArgumentValidation.getBoolean(args[2], t); } MCMerchant merchant = GetMerchant(args[0], t); if(!force && merchant.isTrading()) { return CBoolean.FALSE; } return CBoolean.get(player.openMerchant(merchant, force) != null); } @Override public Version since() { return MSVersion.V3_3_3; } @Override public String getName() { return "popen_trading"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "boolean {specifier, [player], [force]} Opens a trading interface for the current player," + " or the one specified. Only one player can trade with a merchant at a time." + " If the merchant is already being traded with, the function will do nothing." + " When true, force will make the merchant trade with the player, closing the trade with" + " the previous player if there was one. Function returns true if trading was successfully" + " opened, and false if not."; } } @api public static class merchant_trader extends Recipes.recipeFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREBadEntityException.class, CREFormatException.class, CREFormatException.class, CREIllegalArgumentException.class, CRELengthException.class}; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCMerchant merchant = GetMerchant(args[0], t); return merchant.isTrading() ? new CString(merchant.getTrader().getUniqueId().toString(), t) : CNull.NULL; } @Override public Version since() { return MSVersion.V3_3_3; } @Override public String getName() { return "merchant_trader"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "UUID {specifier} Returns the UUID of the user trading with the merchant, or null if no one is."; } } private static final HashMap<String, MCMerchant> VIRTUAL_MERCHANTS = new HashMap<>(); /** * Returns the merchant specified. * @param specifier The string representing the merchant, whether entity UUID or virtual id. * @param t * @return abstracted merchant */ private static MCMerchant GetMerchant(Mixed specifier, Target t) { MCMerchant merchant; if(specifier.val().length() == 36 || specifier.val().length() == 32) { try { MCEntity entity = Static.getEntity(specifier, t); if(!(entity instanceof MCVillager)) { throw new CREIllegalArgumentException("The entity specified is not capable of being an merchant.", t); } return ((MCVillager) entity).asMerchant(); } catch (CREFormatException iae) { // not a UUID } } merchant = VIRTUAL_MERCHANTS.get(specifier.val()); if(merchant == null) { throw new CREIllegalArgumentException("A merchant named \"" + specifier.val() + "\" does not exist.", t); } return merchant; } private static MCMerchantRecipe trade(Mixed c, Target t) { CArray recipe = Static.getArray(c, t); MCItemStack result = ObjectGenerator.GetGenerator().item(recipe.get("result", t), t); MCMerchantRecipe mer = (MCMerchantRecipe) StaticLayer.GetNewRecipe(null, MCRecipeType.MERCHANT, result); if(recipe.containsKey("maxuses")) { mer.setMaxUses(Static.getInt32(recipe.get("maxuses", t), t)); } if(recipe.containsKey("uses")) { mer.setUses(Static.getInt32(recipe.get("uses", t), t)); } if(recipe.containsKey("hasxpreward")) { mer.setHasExperienceReward(ArgumentValidation.getBoolean(recipe.get("hasxpreward", t), t)); } CArray ingredients = Static.getArray(recipe.get("ingredients", t), t); if(ingredients.inAssociativeMode()) { throw new CREFormatException("Ingredients array is invalid.", t); } if(ingredients.size() < 1 || ingredients.size() > 2) { throw new CRERangeException("Ingredients for merchants must contain 1 or 2 items, found " + ingredients.size(), t); } List<MCItemStack> mcIngredients = new ArrayList<>(); for(Mixed ingredient : ingredients.asList()) { mcIngredients.add(ObjectGenerator.GetGenerator().item(ingredient, t)); } mer.setIngredients(mcIngredients); return mer; } private static Mixed trade(MCMerchantRecipe r, Target t) { if(r == null) { return CNull.NULL; } CArray ret = CArray.GetAssociativeArray(t); ret.set("result", ObjectGenerator.GetGenerator().item(r.getResult(), t), t); CArray il = new CArray(t); for(MCItemStack i : r.getIngredients()) { il.push(ObjectGenerator.GetGenerator().item(i, t), t); } ret.set("ingredients", il, t); ret.set("maxuses", new CInt(r.getMaxUses(), t), t); ret.set("uses", new CInt(r.getUses(), t), t); ret.set("hasxpreward", CBoolean.get(r.hasExperienceReward()), t); return ret; } }
package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.SportletLog; import org.gridlab.gridsphere.portlet.impl.SportletRoleInfo; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.PortletServiceFactory; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.GridSphereConfig; import org.gridlab.gridsphere.portletcontainer.PortletSessionManager; import org.gridlab.gridsphere.services.core.portal.PortalConfigService; import org.gridlab.gridsphere.services.core.security.group.GroupManagerService; import javax.servlet.ServletContext; import java.io.*; import java.net.URLEncoder; import java.util.*; import java.security.Principal; /** * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ public class PortletPageFactory implements PortletSessionListener { private String userLayoutDir = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/CustomPortal/layouts/users"); public static String PAGE = "gsPageLayout"; public static String SETUP_PAGE = "SetupLayout.xml"; private static String DEFAULT_THEME = "default"; private static PortletPageFactory instance = null; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); protected static PortalConfigService portalConfigService = null; protected static GroupManagerService groupManagerService = null; private static PortletLog log = SportletLog.getInstance(PortletPageFactory.class); private PortletPage templatePage = null; private PortletPage setupPage = null; //private PortletPage newuserPage = null; private PortletPage errorPage = null; private String layoutMappingFile = null; // Store user layouts in a hash private static Map userLayouts = new Hashtable(); private Map tckLayouts = new Hashtable(); private static Map guests = new Hashtable(); private static Map customPages = new Hashtable(); private static Map customLayouts = new Hashtable(); private PortletPageFactory() { } public void init(ServletContext ctx) throws PortletException { layoutMappingFile = ctx.getRealPath("/WEB-INF/mapping/layout-mapping.xml"); String templateLayoutPath = ctx.getRealPath("/WEB-INF/CustomPortal/layouts/TemplateLayout.xml"); String newuserLayoutPath = ctx.getRealPath("/WEB-INF/CustomPortal/layouts/users/"); String setupLayoutFile = ctx.getRealPath("/WEB-INF/CustomPortal/layouts/SetupLayout.xml"); String errorLayoutFile = ctx.getRealPath("/WEB-INF/CustomPortal/layouts/ErrorLayout.xml"); try { errorPage = PortletLayoutDescriptor.loadPortletPage(errorLayoutFile, layoutMappingFile); templatePage = PortletLayoutDescriptor.loadPortletPage(templateLayoutPath, layoutMappingFile); errorPage.setLayoutDescriptor(errorLayoutFile); setupPage = PortletLayoutDescriptor.loadPortletPage(setupLayoutFile, layoutMappingFile); setupPage.setLayoutDescriptor(setupLayoutFile); } catch (Exception e) { throw new PortletException("Error unmarshalling layout file", e); } String layoutsDirPath = ctx.getRealPath("/WEB-INF/CustomPortal/layouts/custom"); File layoutsDir = new File(layoutsDirPath); if (!layoutsDir.exists()) layoutsDir.mkdir(); File[] files = layoutsDir.listFiles(); PortletPage customPage = null; for (int i = 0; i < files.length; i++) { File f = (File)files[i]; try { String pageName = f.getName(); pageName = pageName.substring(0, pageName.lastIndexOf(".")); System.err.println("found a page= " + pageName); customPage = PortletLayoutDescriptor.loadPortletPage(f.getAbsolutePath(), layoutMappingFile); customPages.put(pageName, customPage); } catch (Exception e) { throw new PortletException("Error unmarshalling layout file", e); } } PortletServiceFactory factory = SportletServiceFactory.getInstance(); try { portalConfigService = (PortalConfigService) factory.createPortletService(PortalConfigService.class, true); groupManagerService = (GroupManagerService) factory.createPortletService(GroupManagerService.class, true); } catch (PortletServiceException e) { log.error("Unable to init portal config service! ", e); throw new PortletException("Unable to init portal config service! ", e); } File userdir = new File(newuserLayoutPath); if (!userdir.exists()) { userdir.mkdir(); } } public static synchronized PortletPageFactory getInstance() { if (instance == null) { instance = new PortletPageFactory(); } return instance; } public PortletPage createErrorPage(PortletRequest req) { errorPage.init(req, new ArrayList()); return errorPage; } public PortletPage createSetupPage(PortletRequest req) { setupPage.init(req, new ArrayList()); setupPage.setTheme(DEFAULT_THEME); return setupPage; } public void login(PortletRequest request) { } public void logout(PortletSession session) { log.debug("in logout PortletPageFactory"); String sessionId = session.getId(); log.debug("in logout PortletPageFactory for session: " + sessionId); if (guests.containsKey(sessionId)) { log.debug("Removing guest container for:" + sessionId); guests.remove(sessionId); } if (userLayouts.containsKey(sessionId)) { log.debug("Removing user container for:" + sessionId); userLayouts.remove(sessionId); } if (customLayouts.containsKey(sessionId)) { log.debug("Removing custom containers for:" + sessionId); customLayouts.remove(sessionId); } } public synchronized void destroy() { guests.clear(); userLayouts.clear(); } public void addPortletGroupTab(PortletRequest req, String groupName) { PortletPage page = createPortletPage(req); PortletTabbedPane pagePane = page.getPortletTabbedPane(); PortletTabbedPane appPane = PortletTabRegistry.getGroupTabs(groupName); //getApplicationTabs(webAppName); if (appPane != null) { List tabs = appPane.getPortletTabs(); try { for (int j = 0; j < tabs.size(); j++) { PortletTab tab = (PortletTab) tabs.get(j); pagePane.addTab((PortletTab) deepCopy(tab)); } } catch (Exception e) { log.error("Unable to copy application tabs for webapp: " + groupName); } page.setPortletTabbedPane(pagePane); page.init(req, new ArrayList()); } } public void removePortletGroupTab(PortletRequest req, String groupName) { PortletPage page = createPortletPage(req); PortletTabbedPane pagePane = page.getPortletTabbedPane(); PortletTabbedPane appPane = PortletTabRegistry.getGroupTabs(groupName); //getApplicationTabs(webAppName); if (appPane != null) { List tabs = appPane.getPortletTabs(); try { for (int j = 0; j < tabs.size(); j++) { PortletTab tab = (PortletTab) tabs.get(j); pagePane.removeTab(tab); } } catch (Exception e) { log.error("Unable to copy application tabs for webapp: " + groupName); } page.setPortletTabbedPane(pagePane); page.init(req, new ArrayList()); } } public PortletTabbedPane getUserTabbedPane(PortletRequest req) { User user = req.getUser(); String sessionId = req.getPortletSession(true).getId(); String userLayout = userLayoutDir + File.separator + user.getUserName(); if (userLayouts.containsKey(sessionId)) { PortletPage page = (PortletPage) userLayouts.get(sessionId); PortletTabbedPane pane = new PortletTabbedPane(); pane.setLayoutDescriptor(userLayout); PortletTabbedPane existPane = page.getPortletTabbedPane(); List tabs = existPane.getPortletTabs(); Iterator it = tabs.iterator(); while (it.hasNext()) { PortletTab tab = (PortletTab) it.next(); if (tab.getCanModify()) { pane.addTab(tab); } } return (!pane.getPortletTabs().isEmpty() ? pane : null); } File f = new File(userLayout); PortletTabbedPane pane = null; // try { if (f.exists()) { //page = (PortletPage)deepCopy(templatePage); //page.setLayoutDescriptor(userLayout); try { pane = PortletLayoutDescriptor.loadPortletTabs(userLayout, layoutMappingFile); pane.setLayoutDescriptor(userLayout); log.debug("Adding user tab to layout"); } catch (Exception e) { log.error("Unable to make a clone of the templatePage", e); } } else { return null; } // check for portlets no longer in groups and remove if necessary List groups = (List) req.getGroups(); List allowedPortlets = new ArrayList(); Iterator it = groups.iterator(); while (it.hasNext()) { String groupName = (String) it.next(); PortletGroup group = groupManagerService.getGroup(groupName); Set s = group.getPortletRoleList(); Iterator sit = s.iterator(); while (sit.hasNext()) { SportletRoleInfo roleInfo = (SportletRoleInfo) sit.next(); allowedPortlets.add(roleInfo.getPortletClass()); } } // create tmp page PortletPage tmpPage = new PortletPage(); try { //tmpPage.setLayoutDescriptor(userLayout + ".tmp"); PortletTabbedPane tmpPane = (PortletTabbedPane) deepCopy(pane); tmpPage.setPortletTabbedPane(tmpPane); this.setPageTheme(tmpPage, req); tmpPage.init(req, new ArrayList()); // when deleting must reinit everytime int i = 0; boolean found; while (i < tmpPage.getComponentIdentifierList().size()) { found = false; it = tmpPage.getComponentIdentifierList().iterator(); while (it.hasNext() && (!found)) { found = false; ComponentIdentifier cid = (ComponentIdentifier) it.next(); if (cid.getPortletComponent() instanceof PortletFrame) { if (!allowedPortlets.contains(cid.getPortletClass())) { PortletComponent pc = cid.getPortletComponent(); PortletComponent parent = pc.getParentComponent(); parent.remove(pc, req); tmpPage.init(req, new ArrayList()); found = true; } } } i++; } tmpPane.save(); return tmpPane; } catch (Exception e) { log.error("Unable to save user pane!", e); } return null; } public PortletPage createFromGroups(PortletRequest req) { List groups = (List) req.getGroups(); PortletPage newPage = null; PortletTabbedPane pane; try { //newPage = (PortletPage)templatePage.clone(); newPage = (PortletPage) deepCopy(templatePage); log.debug("Returning cloned layout from webapps:"); pane = newPage.getPortletTabbedPane(); PortletTabbedPane gsTab = PortletTabRegistry.getGroupTabs(req.getGroup().getName()); List tabs = gsTab.getPortletTabs(); for (int j = 0; j < tabs.size(); j++) { PortletTab tab = (PortletTab) tabs.get(j); log.debug("adding tab: " + tab.getTitle("en")); pane.addTab((PortletTab) deepCopy(tab)); } Iterator it = groups.iterator(); while (it.hasNext()) { String groupName = (String)it.next(); if (groupName.equals(((PortletGroup)req.getGroup()).getName())) continue; log.debug("adding group layout: " + groupName); PortletTabbedPane portletTabs = PortletTabRegistry.getGroupTabs(groupName); if (portletTabs != null) { tabs = portletTabs.getPortletTabs(); for (int j = 0; j < tabs.size(); j++) { PortletTab tab = (PortletTab) tabs.get(j); log.debug("adding tab: " + tab.getTitle("en")); //pane.addTab(g.getName(), (PortletTab)tab.clone()); pane.addTab((PortletTab) deepCopy(tab)); } } } // place user tabs after group tabs PortletTabbedPane userPane = getUserTabbedPane(req); if (userPane != null) { List userTabs = userPane.getPortletTabs(); for (int i = 0; i < userTabs.size(); i++) { PortletTab tab = (PortletTab) userTabs.get(i); log.debug("adding user tab: " + tab.getTitle("en")); pane.addTab((PortletTab) deepCopy(tab)); } } // sorting tabs Collections.sort(pane.getPortletTabs(), new PortletTab()); // first use default theme setPageTheme(newPage, req); newPage.setPortletTabbedPane(pane); //newPage = (PortletPage)templatePage; newPage.init(req, new ArrayList()); List list = newPage.getComponentIdentifierList(); StringBuffer compSB = new StringBuffer(); for (int i = 0; i < list.size(); i++) { ComponentIdentifier c = (ComponentIdentifier) list.get(i); compSB.append("\tid: " + c.getComponentID() + " : " + c.getClassName() + " : " + c.hasPortlet() + "\n"); //if (c.hasPortlet()) System.err.println("portlet= " + c.getPortletID()); } log.debug("Made a components list!!!! " + list.size() + "\n" + compSB.toString()); } catch (Exception e) { log.error("Unable to make a clone of the templatePage", e); } return newPage; } protected void setPageTheme(PortletPage page, PortletRequest req) { String defaultTheme = portalConfigService.getPortalConfigSettings().getDefaultTheme(); if (defaultTheme != null) { page.setTheme(defaultTheme); } User user = req.getUser(); if (user != null) { String theme = (String) user.getAttribute(User.THEME); if (theme != null) { page.setTheme(theme); } } if ((page.getTheme() == null) || (page.getTheme().equals(""))) { page.setTheme(DEFAULT_THEME); } } public PortletTabbedPane createNewUserPane(PortletRequest req, int cols, String tabName) { PortletTabbedPane pane = null; try { pane = getUserTabbedPane(req); int tabNum = PortletTab.DEFAULT_USERTAB_ORDER; if (pane == null) { pane = new PortletTabbedPane(); User user = req.getUser(); String userLayout = userLayoutDir + File.separator + user.getUserName(); pane.setLayoutDescriptor(userLayout); } else { tabNum = pane.getLastPortletTab().getTabOrder() + 1; } PortletTab topTab = new PortletTab(); System.err.println("setting tab num to " + tabNum); topTab.setTabOrder(tabNum); topTab.setCanModify(true); topTab.setTitle(req.getLocale().getLanguage(), tabName); PortletTabbedPane childPane = new PortletTabbedPane(); PortletTab childTab = new PortletTab(); childPane.setStyle("sub-menu"); topTab.setPortletComponent(childPane); pane.addTab(topTab); topTab.setName(tabName); topTab.setLabel(URLEncoder.encode(tabName, "UTF-8") + "Tab"); //pane.save(userLayout); PortletTableLayout table = new PortletTableLayout(); table.setCanModify(true); table.setLabel(URLEncoder.encode(tabName, "UTF-8") + "TL"); PortletRowLayout row = new PortletRowLayout(); int width = 100 / cols; for (int i = 0; i < cols; i++) { PortletColumnLayout col = new PortletColumnLayout(); col.setWidth(String.valueOf(width) + "%"); row.addPortletComponent(col); } table.addPortletComponent(row); childTab.setPortletComponent(table); childTab.setTitle(req.getLocale().getLanguage(), ""); childPane.addTab(childTab); } catch (Exception e) { log.error("Unable to make a clone of the templatePage", e); } return pane; } public PortletPage createTCKPage(PortletRequest req, String[] portletNames) { String pageName = req.getParameter("pageName"); PortletPage page = new PortletPage(); PortletTableLayout tableLayout = new PortletTableLayout(); StringTokenizer tokenizer; for (int i = 0; i < portletNames.length; i++) { tokenizer = new StringTokenizer(portletNames[i], "/"); String appName = tokenizer.nextToken(); String portletName = tokenizer.nextToken(); //String portletClass = registry.getPortletClassName(appName, portletName); //if (portletClass == null) { // log.error("Unable to find portlet class for " + portletName); if (pageName == null) { pageName = "TCK_testpage_" + portletName; } PortletFrame frame = new PortletFrame(); PortletTitleBar tb = new PortletTitleBar(); //tb.setPortletClass(portletClass); tb.setPortletClass(appName + "#" + portletName); frame.setPortletTitleBar(tb); //frame.setPortletClass(portletClass); frame.setPortletClass(appName + "#" + portletName); tableLayout.addPortletComponent(frame); } PortletTab tab = new PortletTab(); tab.setTitle(pageName); tab.setPortletComponent(tableLayout); PortletTabbedPane pane = new PortletTabbedPane(); pane.addTab(tab); page.setPortletTabbedPane(pane); page.setLayoutDescriptor("/tmp/test.xml"); try { page.save(); this.setPageTheme(page, req); page.init(req, new ArrayList()); } catch (IOException e) { log.error("Unale to save TCK page to /tmp/test.xml", e); } return page; } public PortletPage createPortletPage(PortletRequest req) { String sessionId = req.getPortletSession().getId(); User user = req.getUser(); String[] portletNames = req.getParameterValues("portletName"); // Sun TCK test uses Jakarta Commons-HttpClient/2.0beta1 if (req.getClient().getUserAgent().indexOf("HttpClient") > 0) { if (portletNames != null) { log.info("Creating TCK LAYOUT!"); PortletPage tckLayout = createTCKPage(req, portletNames); tckLayout.init(req, new ArrayList()); tckLayouts.put(sessionId, tckLayout); sessionManager.addSessionListener(sessionId, this); } if (tckLayouts.containsKey(sessionId)) { return (PortletPage)tckLayouts.get(sessionId); } } String pageLayout = (String)req.getAttribute(PAGE); if (pageLayout != null) { return this.createSetupPage(req); } PortletPage page; // check for custom page page = getCustomPage(req); if (page != null) return page; Principal principal = req.getUserPrincipal(); if (principal == null) { log.debug("Creating a guest layout!!"); return createFromGuestLayoutXML(req); } // Need to provide one guest container per users session if (userLayouts.containsKey(sessionId)) { page = (PortletPage) userLayouts.get(sessionId); log.debug("Returning existing layout for:" + sessionId + " for user=" + user.getUserName()); } else { // Now the user is user so remove guest layout if (guests.containsKey(sessionId)) { log.debug("Removing guest container for:" + sessionId); guests.remove(sessionId); } page = createFromGroups(req); userLayouts.put(sessionId, page); sessionManager.addSessionListener(sessionId, this); } return page; } public void removePortletPage(PortletRequest req) { PortletSession session = req.getPortletSession(); /* String userLayout = ""; try { userLayout = userLayoutDir + File.separator + req.getUser().getID(); File f = new File(userLayout); if (f.exists()) { f.delete(); } } catch (Exception e) { log.error("Unable to delete layout: " + userLayout, e); } */ String id = session.getId(); if (userLayouts.containsKey(id)) { userLayouts.remove(id); } //log.debug("removed user layout: " + userLayout); } public List getAllCustomPages(PortletRequest req) { PortletSession session = req.getPortletSession(); String id = session.getId(); Map userLayouts = (Map)customLayouts.get(id); return (userLayouts != null) ? (List)userLayouts.values() : new ArrayList(); } public PortletPage getCustomPage(PortletRequest req) { PortletSession session = req.getPortletSession(); String customPageDesc = (String)req.getAttribute(PAGE); if (customPageDesc == null) customPageDesc = req.getParameter(PAGE); if (customPageDesc == null) return null; String id = session.getId(); Map userLayouts = (Map)customLayouts.get(id); if (userLayouts == null) userLayouts = new Hashtable(); PortletPage customPage = (PortletPage)userLayouts.get(customPageDesc); if (customPage == null) { PortletPage page = (PortletPage)customPages.get(customPageDesc); try { PortletPage newpage = (PortletPage) deepCopy(page); newpage.init(req, new ArrayList()); newpage.setTheme(DEFAULT_THEME); userLayouts.put(customPageDesc, newpage); customLayouts.put(id, userLayouts); } catch (Exception e) { log.error("Unable to clone page: " + customPageDesc); } } return customPage; } public PortletPage createFromGuestLayoutXML(PortletRequest req) { PortletSession session = req.getPortletSession(); String id = session.getId(); if (userLayouts.containsKey(id)) { userLayouts.remove(id); } if ((id != null) && (guests.containsKey(id))) { return (PortletPage) guests.get(id); } else { PortletPage newcontainer = null; try { //newcontainer = (PortletPage)guestPage.clone(); PortletPage guestPage = PortletTabRegistry.getGuestLayoutPage(); newcontainer = (PortletPage) deepCopy(guestPage); this.setPageTheme(newcontainer, req); // theme has to be set before it is inited newcontainer.init(req, new ArrayList()); guests.put(id, newcontainer); sessionManager.addSessionListener(id, this); } catch (Exception e) { log.error("Unable to clone GuestUserLayout!", e); e.printStackTrace(); } return newcontainer; } } protected void copyFile(File oldFile, File newFile) throws IOException { // Destination and streams log.debug("in copyFile(): oldFile: " + oldFile.getAbsolutePath() + " newFile: " + newFile.getCanonicalPath()); FileInputStream fis = new FileInputStream(oldFile); FileOutputStream fos = new FileOutputStream(newFile); // Amount of data to copy long fileLength = oldFile.length(); byte[] bytes = new byte[1024]; // 1K at a time int length = 0; long totalLength = 0; while (length > -1) { length = fis.read(bytes); if (length > 0) { fos.write(bytes, 0, length); totalLength += length; } } // Test that we copied all the data if (fileLength != totalLength) { throw new IOException("File copy size missmatch"); } fos.flush(); fos.close(); fis.close(); } static public Object deepCopy(Object oldObj) throws Exception { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); // serialize and pass the object oos.writeObject(oldObj); oos.flush(); ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bin); // return the new object return ois.readObject(); } catch (Exception e) { System.out.println("Exception in ObjectCloner = " + e); throw(e); } finally { if (oos != null) oos.close(); if (ois != null) ois.close(); } } public void logStatistics() { log.debug("\n\nnumber of guest layouts: " + guests.size()); Iterator it = guests.keySet().iterator(); while (it.hasNext()) { String id = (String) it.next(); log.debug("guest has session: " + id); } log.debug("number of user layouts: " + userLayouts.size()); it = userLayouts.keySet().iterator(); while (it.hasNext()) { String id = (String) it.next(); log.debug("user has session: " + id); } } }
package com.micsc15.xpark.activities; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import com.mapbox.mapboxsdk.geometry.BoundingBox; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.overlay.Icon; import com.mapbox.mapboxsdk.views.MapView; import com.micsc15.xpark.R; import com.micsc15.xpark.activities.helpers.CustomMarker; import com.micsc15.xpark.managers.MapManager; import com.micsc15.xpark.managers.PairiDaizaManager; import com.micsc15.xpark.models.ParkAttraction; import com.micsc15.xpark.models.enums.AttractionType; public class MapActivity extends BaseActivity implements View.OnClickListener { private MapView mapView; private FloatingActionsMenu floatingActionsMenu; private FloatingActionButton fab_FilterAll, fab_FilterNews2015, fab_FilterEat, fab_FilterAnimationsAndFeed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); mapView = (MapView) findViewById(R.id.mapView); mapView.setCenter(PairiDaizaManager.iLatLng); mapView.setZoom(18); mapView.setScrollableAreaLimit(new BoundingBox(new LatLng(50.588746, 3.896243), new LatLng(50.580461, 3.879834))); fab_FilterAll = (FloatingActionButton) findViewById(R.id.fab_FilterAll); fab_FilterAll.setOnClickListener(this); fab_FilterNews2015 = (FloatingActionButton) findViewById(R.id.fab_FilterNews2015); fab_FilterNews2015.setOnClickListener(this); fab_FilterEat = (FloatingActionButton) findViewById(R.id.fab_FilterEat); fab_FilterEat.setOnClickListener(this); fab_FilterAnimationsAndFeed = (FloatingActionButton) findViewById(R.id.fab_FilterAnimationsAndFeed); fab_FilterAnimationsAndFeed.setOnClickListener(this); floatingActionsMenu = (FloatingActionsMenu) findViewById(R.id.floatingActionsMenu); drawMarkers(null); } @Override public void onClick(View v) { if (v == fab_FilterAll) drawMarkers(null); else if (v == fab_FilterAnimationsAndFeed) drawMarkers(AttractionType.ATTRACTION); else if (v == fab_FilterEat) drawMarkers(AttractionType.RESTAURANT); else if ( v == fab_FilterNews2015) drawMarkers(null); floatingActionsMenu.collapse(); } private void drawMarkers(AttractionType attractionType) { mapView.clear(); for (ParkAttraction attraction : attractionType != null ? MapManager.GetMapPins(getBaseContext(), attractionType) : MapManager.GetMapPins(getBaseContext())) { CustomMarker marker = new CustomMarker(mapView, attraction); marker.setIcon(new Icon(getResources().getDrawable(R.drawable.ic_launcher))); mapView.addMarker(marker); } } private final int MENU_NEWS = 3473; @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_NEWS, 0, "News"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_NEWS: startActivity(new Intent(MapActivity.this, NewsActivity.class)); break; } return super.onOptionsItemSelected(item); } }
package seedu.taskList.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.taskList.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.taskList.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.taskList.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.taskList.commons.core.EventsCenter; import seedu.taskList.commons.events.model.TaskListChangedEvent; import seedu.taskList.commons.events.ui.JumpToListRequestEvent; import seedu.taskList.commons.events.ui.ShowHelpRequestEvent; import seedu.taskList.logic.Logic; import seedu.taskList.logic.LogicManager; import seedu.taskList.logic.commands.AddCommand; import seedu.taskList.logic.commands.ClearCommand; import seedu.taskList.logic.commands.Command; import seedu.taskList.logic.commands.CommandResult; import seedu.taskList.logic.commands.DeleteCommand; import seedu.taskList.logic.commands.ExitCommand; import seedu.taskList.logic.commands.FindCommand; import seedu.taskList.logic.commands.HelpCommand; import seedu.taskList.logic.commands.ListCommand; import seedu.taskList.logic.commands.SelectCommand; import seedu.taskList.logic.commands.exceptions.CommandException; import seedu.taskList.model.TaskList; import seedu.taskList.model.Model; import seedu.taskList.model.ModelManager; import seedu.taskList.model.ReadOnlyTaskList; import seedu.taskList.model.tag.Tag; import seedu.taskList.model.tag.UniqueTagList; import seedu.taskList.model.task.Comment; import seedu.taskList.model.task.Name; import seedu.taskList.model.task.Task; import seedu.taskList.model.task.ReadOnlyTask; import seedu.taskList.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyTaskList latestSavedTaskList; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(TaskListChangedEvent abce) { latestSavedTaskList = new TaskList(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempTaskListFile = saveFolder.getRoot().getPath() + "TempTaskList.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempTaskListFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedTaskList = new TaskList(model.getTaskList()); // last saved assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and that the result message is correct. * Also confirms that both the 'address book' and the 'last shown list' are as specified. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskList, List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyTaskList expectedTaskList, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedTaskList, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that the result message is correct. * Both the 'address book' and the 'last shown list' are verified to be unchanged. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskList, List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { TaskList expectedTaskList = new TaskList(model.getTaskList()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedTaskList, expectedShownList); } /** * Executes the command, confirms that the result message is correct * and that a CommandException is thrown if expected * and also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedTaskList} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedTaskList} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyTaskList expectedTaskList, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } //Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedTaskList, model.getTaskList()); assertEquals(expectedTaskList, latestSavedTaskList); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskList(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskList(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskList(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandFailure("add wrong args wrong args", expectedMessage); assertCommandFailure("add Valid Name.butNoCommentPrefix valid, address", expectedMessage); } @Test public void execute_add_invalidTaskData() { assertCommandFailure("add []\\[;] c/valid, address", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandFailure("add Valid Name c/valid, t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); TaskList expectedAB = new TaskList(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // task already in internal address book // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskList expectedAB = helper.generateTaskManager(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list * based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord , expectedMessage); //index missing assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list * based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new TaskList()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskList expectedAB = helper.generateTaskManager(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskList expectedAB = helper.generateTaskManager(threeTasks); expectedAB.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); TaskList expectedAB = helper.generateTaskManager(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); TaskList expectedAB = helper.generateTaskManager(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); TaskList expectedAB = helper.generateTaskManager(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { Task adam() throws Exception { Name name = new Name("Event"); Comment privateComment = new Comment("urgent"); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, privateComment, tags); } /** * Generates a valid task using the given seed. * Running this function with the same parameter values guarantees the returned task will have the same state. * Each unique seed will generate a unique Task object. * * @param seed used to generate the task data field values */ Task generateTask(int seed) throws Exception { return new Task( new Name("Task " + seed), new Comment("House of " + seed), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the task given */ String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getName().toString()); cmd.append(" c/").append(p.getComment()); UniqueTagList tags = p.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } return cmd.toString(); } /** * Generates an TaskList with auto-generated tasks. */ TaskList generateTaskManager(int numGenerated) throws Exception { TaskList taskList = new TaskList(); addToTaskList(taskList, numGenerated); return taskList; } /** * Generates an TaskList based on the list of Tasks given. */ TaskList generateTaskManager(List<Task> tasks) throws Exception { TaskList taskList = new TaskList(); addToTaskList(taskList, tasks); return taskList; } /** * Adds auto-generated Task objects to the given TaskList * @param taskList The TaskList to which the Tasks will be added */ void addToTaskList(TaskList taskList, int numGenerated) throws Exception { addToTaskList(taskList, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given TaskList */ void addToTaskList(TaskList taskList, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { taskList.addTask(p); } } /** * Adds auto-generated Task objects to the given model * @param model The model to which the Tasks will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { model.addTask(p); } } /** * Generates a list of Tasks based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some dummy values. */ Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new Comment("House of 1"), new UniqueTagList(new Tag("tag")) ); } } }
package com.loginsigh; import org.apache.commons.lang3.StringUtils; import org.elasticsearch.common.inject.internal.Nullable; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.script.ExecutableScript; import org.elasticsearch.script.NativeScriptFactory; import org.elasticsearch.script.ScriptException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class GrokNativeScriptFactory implements NativeScriptFactory { public ExecutableScript newScript(@Nullable Map<String, Object> params) { String pattern = params == null ? "" : XContentMapValues.nodeStringValue(params.get("pattern"), ""); String fieldName = params == null ? "" : XContentMapValues.nodeStringValue(params.get("fieldName"), ""); String groupkeys = params == null ? "" : XContentMapValues.nodeStringValue(params.get("groupkeys"), ""); String isHashMap = params == null ? "" : XContentMapValues.nodeStringValue(params.get("isHashMap"), ""); if (StringUtils.isBlank(fieldName)) { throw new ScriptException("Missing field parameter"); } if (StringUtils.isBlank(pattern)) { throw new ScriptException("Missing field parameter"); } List<String> groupkeyList = new ArrayList<>(); if (StringUtils.isNotBlank(groupkeys)) { groupkeyList = Arrays.asList(groupkeys.split(",")); } Boolean isHashMapBoolean; if (StringUtils.isBlank(isHashMap) || "false".equals(isHashMap.toLowerCase())) { isHashMapBoolean = false; } else { isHashMapBoolean = true; } return new GrokNativeScript(pattern, fieldName, groupkeyList, isHashMapBoolean); } public boolean needsScores() { return false; } }
package org.opencms.security; import org.opencms.configuration.CmsSystemConfiguration; import org.opencms.db.CmsCacheSettings; import org.opencms.db.CmsDbContext; import org.opencms.db.CmsDriverManager; import org.opencms.db.CmsSecurityManager; import org.opencms.db.I_CmsCacheKey; import org.opencms.file.CmsProject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsUser; import org.opencms.file.types.CmsResourceTypeJsp; import org.opencms.lock.CmsLock; import org.opencms.main.CmsException; import org.opencms.main.CmsInitException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import java.util.Iterator; import org.apache.commons.logging.Log; /** * Generic base driver interface.<p> * * @since 7.0.2 */ public class CmsDefaultPermissionHandler implements I_CmsPermissionHandler { /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsDefaultPermissionHandler.class); /** Driver Manager instance. */ protected CmsDriverManager m_driverManager; /** Security Manager instance. */ protected CmsSecurityManager m_securityManager; /** The class used for cache key generation. */ private I_CmsCacheKey m_keyGenerator; public CmsPermissionCheckResult hasPermissions( CmsDbContext dbc, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException { // check if the resource is valid according to the current filter // if not, throw a CmsResourceNotFoundException if (!filter.isValid(dbc.getRequestContext(), resource)) { return I_CmsPermissionHandler.PERM_FILTERED; } // checking the filter is less cost intensive then checking the cache, // this is why basic filter results are not cached String cacheKey = m_keyGenerator.getCacheKeyForUserPermissions( filter.requireVisible() && checkLock ? "11" : (!filter.requireVisible() && checkLock ? "01" : (filter.requireVisible() && !checkLock ? "10" : "00")), dbc, resource, requiredPermissions); CmsPermissionCheckResult cacheResult = OpenCms.getMemoryMonitor().getCachedPermission(cacheKey); if (cacheResult != null) { return cacheResult; } int denied = 0; // if this is the online project, write is rejected if (dbc.currentProject().isOnlineProject()) { denied |= CmsPermissionSet.PERMISSION_WRITE; } // check if the current user is admin boolean canIgnorePermissions = m_securityManager.hasRoleForResource( dbc, dbc.currentUser(), CmsRole.VFS_MANAGER, resource); // check lock status boolean writeRequired = requiredPermissions.requiresWritePermission() || requiredPermissions.requiresControlPermission(); // if the resource type is jsp // write is only allowed for administrators if (writeRequired && !canIgnorePermissions && (CmsResourceTypeJsp.isJsp(resource))) { if (!m_securityManager.hasRoleForResource(dbc, dbc.currentUser(), CmsRole.DEVELOPER, resource)) { denied |= CmsPermissionSet.PERMISSION_WRITE; denied |= CmsPermissionSet.PERMISSION_CONTROL; } } if (writeRequired && checkLock) { // check lock state only if required CmsLock lock = m_driverManager.getLock(dbc, resource); // if the resource is not locked by the current user, write and control if (lock.isUnlocked() || !lock.isLockableBy(dbc.currentUser())) { return I_CmsPermissionHandler.PERM_NOTLOCKED; } } CmsPermissionSetCustom permissions; if (canIgnorePermissions) { // if the current user is administrator, anything is allowed permissions = new CmsPermissionSetCustom(~0); } else { permissions = m_driverManager.getPermissions(dbc, resource, dbc.currentUser()); } permissions.denyPermissions(denied); if ((permissions.getPermissions() & CmsPermissionSet.PERMISSION_VIEW) == 0) { // resource "invisible" flag is set for this user if (!canIgnorePermissions && filter.requireVisible()) { requiredPermissions = new CmsPermissionSet( requiredPermissions.getAllowedPermissions() | CmsPermissionSet.PERMISSION_VIEW, requiredPermissions.getDeniedPermissions()); } else { permissions.setPermissions( permissions.getAllowedPermissions() | CmsPermissionSet.PERMISSION_VIEW, permissions.getDeniedPermissions() & ~CmsPermissionSet.PERMISSION_VIEW); } } if (requiredPermissions.requiresDirectPublishPermission()) { if ((permissions.getPermissions() & CmsPermissionSet.PERMISSION_DIRECT_PUBLISH) == 0) { boolean canIgnorePublishPermission = m_securityManager.hasRoleForResource( dbc, dbc.currentUser(), CmsRole.PROJECT_MANAGER, resource); // if not, check the manageable projects if (!canIgnorePublishPermission) { CmsUser user = dbc.currentUser(); Iterator<CmsProject> itProjects = m_driverManager.getAllManageableProjects( dbc, m_driverManager.readOrganizationalUnit(dbc, user.getOuFqn()), true).iterator(); while (itProjects.hasNext()) { CmsProject project = itProjects.next(); if (CmsProject.isInsideProject(m_driverManager.readProjectResources(dbc, project), resource)) { canIgnorePublishPermission = true; break; } } } if (canIgnorePublishPermission) { permissions.setPermissions( permissions.getAllowedPermissions() | CmsPermissionSet.PERMISSION_DIRECT_PUBLISH, permissions.getDeniedPermissions() & ~CmsPermissionSet.PERMISSION_DIRECT_PUBLISH); } } } CmsPermissionCheckResult result; if ((requiredPermissions.getPermissions() & (permissions.getPermissions())) == requiredPermissions.getPermissions()) { result = I_CmsPermissionHandler.PERM_ALLOWED; } else { result = I_CmsPermissionHandler.PERM_DENIED; if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_NO_PERMISSION_RESOURCE_USER_4, new Object[] { dbc.getRequestContext().removeSiteRoot(resource.getRootPath()), dbc.currentUser().getName(), requiredPermissions.getPermissionString(), permissions.getPermissionString()})); } } if (dbc.getProjectId().isNullUUID()) { OpenCms.getMemoryMonitor().cachePermission(cacheKey, result); } return result; } public void init(CmsDriverManager driverManager, CmsSystemConfiguration systemConfiguration) { m_driverManager = driverManager; m_securityManager = driverManager.getSecurityManager(); CmsCacheSettings settings = systemConfiguration.getCacheSettings(); String className = settings.getCacheKeyGenerator(); try { // initialize the key generator m_keyGenerator = (I_CmsCacheKey)Class.forName(className).newInstance(); } catch (Exception e) { throw new CmsInitException( org.opencms.main.Messages.get().container( org.opencms.main.Messages.ERR_CRITICAL_CLASS_CREATION_1, className), e); } } }
package com.lothrazar.cyclic.event; import com.lothrazar.cyclic.base.ItemEntityInteractable; import com.lothrazar.cyclic.block.cable.CableWrench; import com.lothrazar.cyclic.block.cable.WrenchActionType; import com.lothrazar.cyclic.block.scaffolding.ItemScaffolding; import com.lothrazar.cyclic.item.AntimatterEvaporatorWandItem; import com.lothrazar.cyclic.item.builder.BuilderActionType; import com.lothrazar.cyclic.item.builder.BuilderItem; import com.lothrazar.cyclic.item.carrot.ItemHorseEnder; import com.lothrazar.cyclic.item.datacard.ShapeCard; import com.lothrazar.cyclic.item.heart.HeartItem; import com.lothrazar.cyclic.item.storagebag.StorageBagItem; import com.lothrazar.cyclic.registry.BlockRegistry; import com.lothrazar.cyclic.registry.PotionRegistry; import com.lothrazar.cyclic.registry.SoundRegistry; import com.lothrazar.cyclic.util.UtilChat; import com.lothrazar.cyclic.util.UtilItemStack; import com.lothrazar.cyclic.util.UtilSound; import com.lothrazar.cyclic.util.UtilWorld; import java.util.Set; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.Attributes; import net.minecraft.entity.ai.attributes.ModifiableAttributeInstance; import net.minecraft.entity.item.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.Effects; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.entity.player.BonemealEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteract; import net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock; import net.minecraftforge.event.entity.player.SleepingLocationCheckEvent; import net.minecraftforge.eventbus.api.Event.Result; import net.minecraftforge.eventbus.api.SubscribeEvent; public class ItemEvents { @SubscribeEvent public void onPlayerCloneDeath(PlayerEvent.Clone event) { ModifiableAttributeInstance original = event.getOriginal().getAttribute(Attributes.MAX_HEALTH); if (original != null) { AttributeModifier healthModifier = original.getModifier(HeartItem.ID); if (healthModifier != null) { event.getPlayer().getAttribute(Attributes.MAX_HEALTH).applyPersistentModifier(healthModifier); } } } @SubscribeEvent public void onEntityUpdate(LivingUpdateEvent event) { LivingEntity liv = event.getEntityLiving(); if (liv.getPersistentData().contains(ItemHorseEnder.NBT_KEYACTIVE) && liv.getPersistentData().getInt(ItemHorseEnder.NBT_KEYACTIVE) > 0) { if (liv.isInWater() && liv.canBreatheUnderwater() == false && liv.getAir() < liv.getMaxAir() && !liv.isPotionActive(Effects.WATER_BREATHING)) { liv.addPotionEffect(new EffectInstance(Effects.WATER_BREATHING, 20 * 60, 4)); liv.addPotionEffect(new EffectInstance(PotionRegistry.PotionEffects.swimspeed, 20 * 60, 1)); ItemHorseEnder.onSuccess(liv); } if (liv.isBurning() && !liv.isPotionActive(Effects.FIRE_RESISTANCE)) { liv.addPotionEffect(new EffectInstance(Effects.FIRE_RESISTANCE, 20 * 60, 4)); liv.extinguish(); ItemHorseEnder.onSuccess(liv); } if (liv.fallDistance > 12 && !liv.isPotionActive(Effects.SLOW_FALLING)) { liv.addPotionEffect(new EffectInstance(Effects.SLOW_FALLING, 20 * 60, 4)); // if (liv.getPassengers().size() > 0) { // liv.getPassengers().get(0).addPotionEffect(new EffectInstance(Effects.SLOW_FALLING, 20 * 60, 1)); ItemHorseEnder.onSuccess(liv); } if (liv.getHealth() < 6 && !liv.isPotionActive(Effects.ABSORPTION)) { liv.addPotionEffect(new EffectInstance(Effects.ABSORPTION, 20 * 60, 4)); liv.addPotionEffect(new EffectInstance(Effects.RESISTANCE, 20 * 60, 4)); ItemHorseEnder.onSuccess(liv); } } } // @SubscribeEvent // public void onLivingDeathEvent(LivingDeathEvent event) { @SubscribeEvent public void onBonemealEvent(BonemealEvent event) { World world = event.getWorld(); BlockPos pos = event.getPos(); if (world.getBlockState(pos).getBlock() == Blocks.PODZOL && world.isAirBlock(pos.up())) { world.setBlockState(pos.up(), BlockRegistry.flower_cyan.getDefaultState()); event.setResult(Result.ALLOW); } else if (world.getBlockState(pos).getBlock() == BlockRegistry.flower_cyan) { event.setResult(Result.ALLOW); if (world.rand.nextDouble() < 0.5) { UtilItemStack.drop(world, pos, new ItemStack(BlockRegistry.flower_cyan)); } } } @SubscribeEvent public void onBedCheck(SleepingLocationCheckEvent event) { if (event.getEntity() instanceof PlayerEntity) { PlayerEntity p = (PlayerEntity) event.getEntity(); if (p.getPersistentData().getBoolean("cyclic_sleeping")) { // TODO: const in sleeping mat event.setResult(Result.ALLOW); } } } @SubscribeEvent public void onRightClickBlock(RightClickBlock event) { if (event.getItemStack().isEmpty()) { return; } if (event.getItemStack().getItem() instanceof ItemScaffolding && event.getPlayer().isCrouching()) { scaffoldHit(event); } } private void scaffoldHit(RightClickBlock event) { ItemScaffolding item = (ItemScaffolding) event.getItemStack().getItem(); Direction opp = event.getFace().getOpposite(); BlockPos dest = UtilWorld.nextReplaceableInDirection(event.getWorld(), event.getPos(), opp, 16, item.getBlock()); if (event.getWorld().isAirBlock(dest)) { event.getWorld().setBlockState(dest, item.getBlock().getDefaultState()); ItemStack stac = event.getPlayer().getHeldItem(event.getHand()); UtilItemStack.shrink(event.getPlayer(), stac); event.setCanceled(true); } } @SubscribeEvent public void onEntityInteractEvent(EntityInteract event) { if (event.getItemStack().getItem() instanceof ItemEntityInteractable) { ItemEntityInteractable item = (ItemEntityInteractable) event.getItemStack().getItem(); item.interactWith(event); } } @SubscribeEvent public void onHit(PlayerInteractEvent.LeftClickBlock event) { PlayerEntity player = event.getPlayer(); ItemStack held = player.getHeldItem(event.getHand()); if (held.isEmpty()) { return; } World world = player.getEntityWorld(); ///////////// shape if (held.getItem() instanceof ShapeCard && player.isCrouching()) { BlockState target = world.getBlockState(event.getPos()); ShapeCard.setBlockState(held, target); UtilChat.sendStatusMessage(player, target.getBlock().getTranslationKey()); } ///////////////// builders if (held.getItem() instanceof BuilderItem) { if (BuilderActionType.getTimeout(held) > 0) { //without a timeout, this fires every tick. so you 'hit once' and get this happening 6 times return; } BuilderActionType.setTimeout(held); event.setCanceled(true); if (player.isCrouching()) { //pick out target block BlockState target = world.getBlockState(event.getPos()); BuilderActionType.setBlockState(held, target); UtilChat.sendStatusMessage(player, target.getBlock().getTranslationKey()); } else { //change size if (!world.isRemote) { BuilderActionType.toggle(held); } UtilSound.playSound(player, SoundRegistry.tool_mode); UtilChat.sendStatusMessage(player, UtilChat.lang(BuilderActionType.getName(held))); } } ////////////////////////// wrench if (held.getItem() instanceof CableWrench && WrenchActionType.getTimeout(held) == 0) { //mode if (!world.isRemote) { WrenchActionType.toggle(held); } UtilSound.playSound(player, SoundRegistry.tool_mode); WrenchActionType.setTimeout(held); UtilChat.sendStatusMessage(player, UtilChat.lang(WrenchActionType.getName(held))); } if (held.getItem() instanceof AntimatterEvaporatorWandItem) { AntimatterEvaporatorWandItem.toggleMode(player, held); } } @SubscribeEvent public void onPlayerPickup(EntityItemPickupEvent event) { if (event.getEntityLiving() instanceof PlayerEntity) { PlayerEntity player = (PlayerEntity) event.getEntityLiving(); ItemEntity itemEntity = event.getItem(); ItemStack resultStack = itemEntity.getItem(); int origCount = resultStack.getCount(); Set<Integer> bagSlots = StorageBagItem.getAllBagSlots(player); for (Integer i : bagSlots) { ItemStack bag = player.inventory.getStackInSlot(i); switch (StorageBagItem.getPickupMode(bag)) { case EVERYTHING: resultStack = StorageBagItem.tryInsert(bag, resultStack); break; case FILTER: resultStack = StorageBagItem.tryFilteredInsert(bag, resultStack); break; case NOTHING: break; } if (resultStack.isEmpty()) { break; } } if (resultStack.getCount() != origCount) { itemEntity.setItem(resultStack); event.setResult(Result.ALLOW); } } } }
package org.owasp.esapi.reference; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.owasp.esapi.ESAPI; import org.owasp.esapi.HTTPUtilities; import org.owasp.esapi.Logger; import org.owasp.esapi.Randomizer; import org.owasp.esapi.User; import org.owasp.esapi.errors.AccessControlException; import org.owasp.esapi.errors.AuthenticationAccountsException; import org.owasp.esapi.errors.AuthenticationCredentialsException; import org.owasp.esapi.errors.AuthenticationException; import org.owasp.esapi.errors.AuthenticationLoginException; import org.owasp.esapi.errors.EncryptionException; public class FileBasedAuthenticator implements org.owasp.esapi.Authenticator { /** Key for user in session */ protected static final String USER = "ESAPIUserSessionKey"; /** The logger. */ private final Logger logger = ESAPI.getLogger("Authenticator"); /** The file that contains the user db */ private File userDB = null; /** How frequently to check the user db for external modifications */ private long checkInterval = 60 * 1000; /** The last modified time we saw on the user db. */ private long lastModified = 0; /** The last time we checked if the user db had been modified externally */ private long lastChecked = 0; private final int MAX_ACCOUNT_NAME_LENGTH = 250; /** * Fail safe main program to add or update an account in an emergency. * <P> * Warning: this method does not perform the level of validation and checks * generally required in ESAPI, and can therefore be used to create a username and password that do not comply * with the username and password strength requirements. * <P> * Example: Use this to add the alice account with the admin role to the users file: * <PRE> * * java -Dorg.owasp.esapi.resources="/path/resources" -classpath esapi.jar org.owasp.esapi.Authenticator alice password admin * * </PRE> * * @param args * the arguments (username, password, role) * @throws Exception * the exception */ public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Usage: Authenticator accountname password role"); return; } FileBasedAuthenticator auth = new FileBasedAuthenticator(); String accountName = args[0].toLowerCase(); String password = args[1]; String role = args[2]; DefaultUser user = (DefaultUser) auth.getUser(args[0]); if (user == null) { user = new DefaultUser(accountName); String newHash = auth.hashPassword(password, accountName); auth.setHashedPassword(user, newHash); user.addRole(role); user.enable(); user.unlock(); auth.userMap.put(new Long(user.getAccountId()), user); System.out.println("New user created: " + accountName); auth.saveUsers(); System.out.println("User account " + user.getAccountName() + " updated"); } else { System.err.println("User account " + user.getAccountName() + " already exists!"); } } /** * Add a hash to a User's hashed password list. This method is used to store a user's old password hashes * to be sure that any new passwords are not too similar to old passwords. * * @param user * the user to associate with the new hash * @param hash * the hash to store in the user's password hash list */ private void setHashedPassword(User user, String hash) { List hashes = getAllHashedPasswords(user, true); hashes.add( 0, hash); if (hashes.size() > ESAPI.securityConfiguration().getMaxOldPasswordHashes() ) hashes.remove( hashes.size() - 1 ); logger.info(Logger.SECURITY, true, "New hashed password stored for " + user.getAccountName() ); } /** * Return the specified User's current hashed password. * * @param user * this User's current hashed password will be returned * @return * the specified User's current hashed password */ String getHashedPassword(User user) { List hashes = getAllHashedPasswords(user, false); return (String) hashes.get(0); } /** * Set the specified User's old password hashes. This will not set the User's current password hash. * * @param user * the User's whose old password hashes will be set * @param oldHashes * a list of the User's old password hashes * */ void setOldPasswordHashes(User user, List oldHashes) { List hashes = getAllHashedPasswords(user, true); if (hashes.size() > 1) hashes.removeAll(hashes.subList(1, hashes.size()-1)); hashes.addAll(oldHashes); } /** * Returns all of the specified User's hashed passwords. If the User's list of passwords is null, * and create is set to true, an empty password list will be associated with the specified User * and then returned. If the User's password map is null and create is set to false, an exception * will be thrown. * * @param user * the User whose old hashes should be returned * @param create * true - if no password list is associated with this user, create one * false - if no password list is associated with this user, do not create one * @return * a List containing all of the specified User's password hashes */ List getAllHashedPasswords(User user, boolean create) { List hashes = (List) passwordMap.get(user); if (hashes != null) return hashes; if (create) { hashes = new ArrayList(); passwordMap.put(user, hashes); return hashes; } throw new RuntimeException("No hashes found for " + user.getAccountName() + ". Is User.hashcode() and equals() implemented correctly?"); } /** * Get a List of the specified User's old password hashes. This will not return the User's current * password hash. * * @param user * he user whose old password hashes should be returned * @return * the specified User's old password hashes */ List getOldPasswordHashes(User user) { List hashes = getAllHashedPasswords(user, false); if (hashes.size() > 1) return Collections.unmodifiableList(hashes.subList(1, hashes.size()-1)); return Collections.EMPTY_LIST; } /** The user map. */ private Map userMap = new HashMap(); // Map<User, List<String>>, where the strings are password hashes, with the current hash in entry 0 private Map passwordMap = new Hashtable(); /** * The currentUser ThreadLocal variable is used to make the currentUser available to any call in any part of an * application. Otherwise, each thread would have to pass the User object through the calltree to any methods that * need it. Because we want exceptions and log calls to contain user data, that could be almost anywhere. Therefore, * the ThreadLocal approach simplifies things greatly. <P> As a possible extension, one could create a delegation * framework by adding another ThreadLocal to hold the delegating user identity. */ private ThreadLocalUser currentUser = new ThreadLocalUser(); private class ThreadLocalUser extends InheritableThreadLocal { public Object initialValue() { return User.ANONYMOUS; } public User getUser() { return (User)super.get(); } public void setUser(User newUser) { super.set(newUser); } }; public FileBasedAuthenticator() { } /** * {@inheritDoc} */ public void clearCurrent() { currentUser.setUser(null); } /** * {@inheritDoc} */ public synchronized User createUser(String accountName, String password1, String password2) throws AuthenticationException { loadUsersIfNecessary(); if (accountName == null) { throw new AuthenticationAccountsException("Account creation failed", "Attempt to create user with null accountName"); } if (getUser(accountName) != null) { throw new AuthenticationAccountsException("Account creation failed", "Duplicate user creation denied for " + accountName); } verifyAccountNameStrength(accountName); if ( password1 == null ) { throw new AuthenticationCredentialsException( "Invalid account name", "Attempt to create account " + accountName + " with a null password" ); } verifyPasswordStrength(null, password1); if (!password1.equals(password2)) throw new AuthenticationCredentialsException("Passwords do not match", "Passwords for " + accountName + " do not match"); DefaultUser user = new DefaultUser(accountName); try { setHashedPassword( user, hashPassword(password1, accountName) ); } catch (EncryptionException ee) { throw new AuthenticationException("Internal error", "Error hashing password for " + accountName, ee); } userMap.put(new Long( user.getAccountId() ), user); logger.info(Logger.SECURITY, true, "New user created: " + accountName); saveUsers(); return user; } /** * {@inheritDoc} */ public boolean exists(String accountName) { return getUser(accountName) != null; } /** * {@inheritDoc} */ public String generateStrongPassword() { return generateStrongPassword(""); } /** * Generate a strong password that is not similar to the specified old password. * * @param oldPassword * the password to be compared to the new password for similarity * @return * a new strong password that is dissimilar to the specified old password */ private String generateStrongPassword(String oldPassword) { Randomizer r = ESAPI.randomizer(); int letters = r.getRandomInteger(4, 6); // inclusive, exclusive int digits = 7-letters; String passLetters = r.getRandomString(letters, DefaultEncoder.CHAR_PASSWORD_LETTERS ); String passDigits = r.getRandomString( digits, DefaultEncoder.CHAR_PASSWORD_DIGITS ); String passSpecial = r.getRandomString( 1, DefaultEncoder.CHAR_PASSWORD_SPECIALS ); String newPassword = passLetters + passSpecial + passDigits; return newPassword; } /** * {@inheritDoc} */ public void changePassword(User user, String currentPassword, String newPassword, String newPassword2) throws AuthenticationException { String accountName = user.getAccountName(); try { String currentHash = getHashedPassword(user); String verifyHash = hashPassword(currentPassword, accountName); if (!currentHash.equals(verifyHash)) { throw new AuthenticationCredentialsException("Password change failed", "Authentication failed for password change on user: " + accountName ); } if (newPassword == null || newPassword2 == null || !newPassword.equals(newPassword2)) { throw new AuthenticationCredentialsException("Password change failed", "Passwords do not match for password change on user: " + accountName ); } verifyPasswordStrength(currentPassword, newPassword); ((DefaultUser)user).setLastPasswordChangeTime(new Date()); String newHash = hashPassword(newPassword, accountName); if (getOldPasswordHashes(user).contains(newHash)) { throw new AuthenticationCredentialsException( "Password change failed", "Password change matches a recent password for user: " + accountName ); } setHashedPassword(user, newHash); logger.info(Logger.SECURITY, true, "Password changed for user: " + accountName ); } catch (EncryptionException ee) { throw new AuthenticationException("Password change failed", "Encryption exception changing password for " + accountName, ee); } } /** * {@inheritDoc} */ public boolean verifyPassword(User user, String password) { String accountName = user.getAccountName(); try { String hash = hashPassword(password, accountName); String currentHash = getHashedPassword(user); if (hash.equals(currentHash)) { ((DefaultUser)user).setLastLoginTime(new Date()); ((DefaultUser)user).setFailedLoginCount(0); logger.info(Logger.SECURITY, true, "Password verified for " + accountName ); return true; } } catch( EncryptionException e ) { logger.fatal(Logger.SECURITY, false, "Encryption error verifying password for " + accountName ); } logger.fatal(Logger.SECURITY, false, "Password verification failed for " + accountName ); return false; } /** * {@inheritDoc} */ public String generateStrongPassword(User user, String oldPassword) { String newPassword = generateStrongPassword(oldPassword); if (newPassword != null) logger.info(Logger.SECURITY, true, "Generated strong password for " + user.getAccountName()); return newPassword; } /** * {@inheritDoc} * * Returns the currently logged user as set by the setCurrentUser() methods. Must not log in this method because the * logger calls getCurrentUser() and this could cause a loop. * * */ public User getCurrentUser() { User user = (User) currentUser.get(); if (user == null) { user = User.ANONYMOUS; } return user; } /** * {@inheritDoc} */ public synchronized User getUser(long accountId) { if ( accountId == 0 ) { return User.ANONYMOUS; } loadUsersIfNecessary(); User user = (User) userMap.get(new Long( accountId )); return user; } /** * {@inheritDoc} */ public synchronized User getUser(String accountName) { if ( accountName == null ) { return User.ANONYMOUS; } loadUsersIfNecessary(); Iterator i = userMap.values().iterator(); while( i.hasNext() ) { User u = (User)i.next(); if ( u.getAccountName().equalsIgnoreCase(accountName) ) return u; } return null; } /** * Gets the user from session. * * @return * the user from session or null if no user is found in the session */ protected User getUserFromSession() { HttpSession session = ESAPI.httpUtilities().getCurrentRequest().getSession(false); if ( session == null ) return null; return (User)session.getAttribute(USER); } /** * Returns the user if a matching remember token is found, or null if the token * is missing, token is corrupt, token is expired, account name does not match * and existing account, or hashed password does not match user's hashed password. * * @return * the user if a matching remember token is found, or null if the token * is missing, token is corrupt, token is expired, account name does not match * and existing account, or hashed password does not match user's hashed password. */ protected DefaultUser getUserFromRememberToken() { Cookie token = ESAPI.httpUtilities().getCookie( ESAPI.currentRequest(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); if ( token == null ) { return null; } String[] data = null; try { data = ESAPI.encryptor().unseal( token.getValue() ).split( ":" ); } catch (EncryptionException e) { logger.warning(Logger.SECURITY, false, "Found corrupt or expired remember token" ); ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); return null; } if ( data.length != 3 ) { return null; } // data[0] is a random nonce, which can be ignored String username = data[1]; String password = data[2]; DefaultUser user = (DefaultUser) getUser( username ); if ( user == null ) { logger.warning( Logger.SECURITY, false, "Found valid remember token but no user matching " + username ); return null; } logger.warning( Logger.SECURITY, true, "Logging in user with remember token: " + user.getAccountName() ); try { user.loginWithPassword(password); } catch (AuthenticationException ae) { logger.warning( Logger.SECURITY, false, "Login via remember me cookie failed for user " + username, ae); ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); return null; } return user; } /** * {@inheritDoc} */ public synchronized Set getUserNames() { loadUsersIfNecessary(); HashSet results = new HashSet(); Iterator i = userMap.values().iterator(); while( i.hasNext() ) { User u = (User)i.next(); results.add( u.getAccountName() ); } return results; } /** * {@inheritDoc} */ public String hashPassword(String password, String accountName) throws EncryptionException { String salt = accountName.toLowerCase(); return ESAPI.encryptor().hash(password, salt); } /** * Load users if they haven't been loaded in a while. */ protected void loadUsersIfNecessary() { if (userDB == null) { userDB = new File((ESAPI.securityConfiguration()).getResourceDirectory(), "users.txt"); } // We only check at most every checkInterval milliseconds long now = System.currentTimeMillis(); if (now - lastChecked < checkInterval) { return; } lastChecked = now; if (lastModified == userDB.lastModified()) { return; } loadUsersImmediately(); } // file was touched so reload it protected void loadUsersImmediately() { synchronized( this ) { logger.trace(Logger.SECURITY, true, "Loading users from " + userDB.getAbsolutePath(), null); BufferedReader reader = null; try { HashMap map = new HashMap(); reader = new BufferedReader(new FileReader(userDB)); String line = null; while ((line = reader.readLine()) != null) { if (line.length() > 0 && line.charAt(0) != ' DefaultUser user = createUser(line); if (map.containsKey( new Long( user.getAccountId()))) { logger.fatal(Logger.SECURITY, false, "Problem in user file. Skipping duplicate user: " + user, null); } map.put( new Long( user.getAccountId() ), user); } } userMap = map; this.lastModified = System.currentTimeMillis(); logger.trace(Logger.SECURITY, true, "User file reloaded: " + map.size(), null); } catch (Exception e) { logger.fatal(Logger.SECURITY, false, "Failure loading user file: " + userDB.getAbsolutePath(), e); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { logger.fatal(Logger.SECURITY, false, "Failure closing user file: " + userDB.getAbsolutePath(), e); } } } } /** * Create a new user with all attributes from a String. The format is: * accountId | accountName | password | roles (comma separated) | unlocked | enabled | old password hashes (comma separated) | last host address | last password change time | last long time | last failed login time | expiration time | failed login count * This method verifies the account name and password strength, creates a new CSRF token, then returns the newly created user. * * @param line * parameters to set as attributes for the new User. * @return * the newly created User * * @throws AuthenticationException */ private DefaultUser createUser(String line) throws AuthenticationException { String[] parts = line.split(" *\\| *"); String accountIdString = parts[0]; long accountId = Long.parseLong(accountIdString); String accountName = parts[1]; verifyAccountNameStrength( accountName ); DefaultUser user = new DefaultUser( accountName ); user.accountId = accountId; String password = parts[2]; verifyPasswordStrength(null, password); setHashedPassword(user, password); String[] roles = parts[3].toLowerCase().split(" *, *"); for (int i=0; i<roles.length; i++) if (!"".equals(roles[i])) user.addRole(roles[i]); if (!"unlocked".equalsIgnoreCase(parts[4])) user.lock(); if ("enabled".equalsIgnoreCase(parts[5])) { user.enable(); } else { user.disable(); } // generate a new csrf token user.resetCSRFToken(); setOldPasswordHashes(user, Arrays.asList(parts[6].split(" *, *"))); user.setLastHostAddress("null".equals(parts[7]) ? null : parts[7]); user.setLastPasswordChangeTime(new Date( Long.parseLong(parts[8]))); user.setLastLoginTime(new Date( Long.parseLong(parts[9]))); user.setLastFailedLoginTime(new Date( Long.parseLong(parts[10]))); user.setExpirationTime(new Date( Long.parseLong(parts[11]))); user.setFailedLoginCount(Integer.parseInt(parts[12])); return user; } /** * Utility method to extract credentials and verify them. * * @param request * The current HTTP request * @param response * The HTTP response being prepared * @return * The user that successfully authenticated * * @throws AuthenticationException * if the submitted credentials are invalid. */ private User loginWithUsernameAndPassword(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String username = request.getParameter(ESAPI.securityConfiguration().getUsernameParameterName()); String password = request.getParameter(ESAPI.securityConfiguration().getPasswordParameterName()); // if a logged-in user is requesting to login, log them out first User user = getCurrentUser(); if (user != null && !user.isAnonymous()) { logger.warning(Logger.SECURITY, true, "User requested relogin. Performing logout then authentication" ); user.logout(); } // now authenticate with username and password if (username == null || password == null) { if (username == null) { username = "unspecified user"; } throw new AuthenticationCredentialsException("Authentication failed", "Authentication failed for " + username + " because of null username or password"); } user = getUser(username); if (user == null) { throw new AuthenticationCredentialsException("Authentication failed", "Authentication failed because user " + username + " doesn't exist"); } user.loginWithPassword(password); request.setAttribute(user.getCSRFToken(), "authenticated"); return user; } /** * {@inheritDoc} */ public synchronized void removeUser(String accountName) throws AuthenticationException { loadUsersIfNecessary(); User user = getUser(accountName); if (user == null) { throw new AuthenticationAccountsException("Remove user failed", "Can't remove invalid accountName " + accountName); } userMap.remove( new Long( user.getAccountId() )); System.out.println("Removing user " +user.getAccountName()); passwordMap.remove(user.getAccountName()); saveUsers(); } /** * Saves the user database to the file system. In this implementation you must call save to commit any changes to * the user file. Otherwise changes will be lost when the program ends. * * @throws AuthenticationException * if the user file could not be written */ public synchronized void saveUsers() throws AuthenticationException { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(userDB)); writer.println(" writer.println("# accountId | accountName | hashedPassword | roles | locked | enabled | csrfToken | oldPasswordHashes | lastPasswordChangeTime | lastLoginTime | lastFailedLoginTime | expirationTime | failedLoginCount"); writer.println(); saveUsers(writer); writer.flush(); logger.info(Logger.SECURITY, true, "User file written to disk" ); } catch (IOException e) { logger.fatal(Logger.SECURITY, false, "Problem saving user file " + userDB.getAbsolutePath(), e ); throw new AuthenticationException("Internal Error", "Problem saving user file " + userDB.getAbsolutePath(), e); } finally { if (writer != null) { writer.close(); lastModified = userDB.lastModified(); lastChecked = lastModified; } } } /** * Save users. * * @param writer * the print writer to use for saving */ protected synchronized void saveUsers(PrintWriter writer) { Iterator i = getUserNames().iterator(); while (i.hasNext()) { String accountName = (String) i.next(); DefaultUser u = (DefaultUser) getUser(accountName); if ( u != null && !u.isAnonymous() ) { writer.println(save(u)); } else { new AuthenticationCredentialsException("Problem saving user", "Skipping save of user " + accountName ); } } } /** * Save. * * @param user * the User to save * @return * a line containing properly formatted information to save regarding the user */ private String save(DefaultUser user) { StringBuffer sb = new StringBuffer(); sb.append( user.getAccountId() ); sb.append( " | " ); sb.append( user.getAccountName() ); sb.append( " | " ); sb.append( getHashedPassword(user) ); sb.append( " | " ); sb.append( dump(user.getRoles()) ); sb.append( " | " ); sb.append( user.isLocked() ? "locked" : "unlocked" ); sb.append( " | " ); sb.append( user.isEnabled() ? "enabled" : "disabled" ); sb.append( " | " ); sb.append( dump(getOldPasswordHashes(user)) ); sb.append( " | " ); sb.append( user.getLastHostAddress() ); sb.append( " | " ); sb.append( user.getLastPasswordChangeTime().getTime() ); sb.append( " | " ); sb.append( user.getLastLoginTime().getTime() ); sb.append( " | " ); sb.append( user.getLastFailedLoginTime().getTime() ); sb.append( " | " ); sb.append( user.getExpirationTime().getTime() ); sb.append( " | " ); sb.append( user.getFailedLoginCount() ); return sb.toString(); } /** * Dump a collection as a comma-separated list. * * @param c * the collection to convert to a comma separated list * * @return * a comma separated list containing the values in c */ private String dump( Collection c ) { StringBuffer sb = new StringBuffer(); Iterator i = c.iterator(); while ( i.hasNext() ) { String s = (String)i.next(); sb.append( s ); if ( i.hasNext() ) sb.append( ","); } return sb.toString(); } /** * {@inheritDoc} */ public User login(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if ( request == null || response == null ) { throw new AuthenticationCredentialsException( "Invalid request", "Request or response objects were null" ); } // if there's a user in the session then use that DefaultUser user = (DefaultUser)getUserFromSession(); // else if there's a remember token then use that if ( user == null ) { user = getUserFromRememberToken(); } // else try to verify credentials - throws exception if login fails if ( user == null ) { user = (DefaultUser)loginWithUsernameAndPassword(request, response); } // set last host address user.setLastHostAddress( request.getRemoteHost() ); // warn if this authentication request was not POST or non-SSL connection, exposing credentials or session id try { ESAPI.httpUtilities().assertSecureRequest( ESAPI.currentRequest() ); } catch( AccessControlException e ) { throw new AuthenticationException( "Attempt to login with an insecure request", e.getLogMessage(), e ); } // don't let anonymous user log in if (user.isAnonymous()) { user.logout(); throw new AuthenticationLoginException("Login failed", "Anonymous user cannot be set to current user. User: " + user.getAccountName() ); } // don't let disabled users log in if (!user.isEnabled()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Disabled user cannot be set to current user. User: " + user.getAccountName() ); } // don't let locked users log in if (user.isLocked()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Locked user cannot be set to current user. User: " + user.getAccountName() ); } // don't let expired users log in if (user.isExpired()) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Expired user cannot be set to current user. User: " + user.getAccountName() ); } // check session inactivity timeout if ( user.isSessionTimeout() ) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Session inactivity timeout: " + user.getAccountName() ); } // check session absolute timeout if ( user.isSessionAbsoluteTimeout() ) { user.logout(); user.incrementFailedLoginCount(); user.setLastFailedLoginTime(new Date()); throw new AuthenticationLoginException("Login failed", "Session absolute timeout: " + user.getAccountName() ); } // create new session for this User HttpSession session = request.getSession(); user.addSession( session ); session.setAttribute(USER, user); setCurrentUser(user); return user; } /** * {@inheritDoc} */ public void logout() { User user = getCurrentUser(); if ( user != null && !user.isAnonymous() ) { user.logout(); } } /** * {@inheritDoc} */ public void setCurrentUser(User user) { currentUser.setUser(user); } /** * {@inheritDoc} * * This implementation simply verifies that account names are at least 5 characters long. This helps to defeat a * brute force attack, however the real strength comes from the name length and complexity. * */ public void verifyAccountNameStrength(String newAccountName) throws AuthenticationException { if (newAccountName == null) { throw new AuthenticationCredentialsException("Invalid account name", "Attempt to create account with a null account name"); } if (!ESAPI.validator().isValidInput("verifyAccountNameStrength", newAccountName, "AccountName", MAX_ACCOUNT_NAME_LENGTH, false )) { throw new AuthenticationCredentialsException("Invalid account name", "New account name is not valid: " + newAccountName); } } /** * {@inheritDoc} * * This implementation checks: - for any 3 character substrings of the old password - for use of a length * * character sets > 16 (where character sets are upper, lower, digit, and special * */ public void verifyPasswordStrength(String oldPassword, String newPassword) throws AuthenticationException { if ( newPassword == null ) throw new AuthenticationCredentialsException("Invalid password", "New password cannot be null" ); // can't change to a password that contains any 3 character substring of old password if ( oldPassword != null ) { int length = oldPassword.length(); for (int i = 0; i < length - 2; i++) { String sub = oldPassword.substring(i, i + 3); if (newPassword.indexOf(sub) > -1 ) { throw new AuthenticationCredentialsException("Invalid password", "New password cannot contain pieces of old password" ); } } } // new password must have enough character sets and length int charsets = 0; for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_LOWERS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_UPPERS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_DIGITS, newPassword.charAt(i)) > 0) { charsets++; break; } for (int i = 0; i < newPassword.length(); i++) if (Arrays.binarySearch(DefaultEncoder.CHAR_SPECIALS, newPassword.charAt(i)) > 0) { charsets++; break; } // calculate and verify password strength int strength = newPassword.length() * charsets; if (strength < 16) { throw new AuthenticationCredentialsException("Invalid password", "New password is not long and complex enough"); } } }
package com.mypodcasts.player; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Log; import com.mypodcasts.player.events.AudioStoppedEvent; import com.mypodcasts.player.notification.AudioPlayerNotification; import com.mypodcasts.repositories.models.Episode; import com.mypodcasts.support.Support; import java.io.IOException; import javax.inject.Inject; import de.greenrobot.event.EventBus; import roboguice.service.RoboService; import static com.mypodcasts.support.Support.MYPODCASTS_TAG; public class AudioPlayerService extends RoboService { public static final int ONGOING_NOTIFICATION_ID = 1; public static final String ACTION_REWIND = "com.mypodcasts.player.action.rewind"; public static final String ACTION_PAUSE = "com.mypodcasts.player.action.pause"; public static final String ACTION_PLAY = "com.mypodcasts.player.action.play"; public static final String ACTION_STOP = "com.mypodcasts.player.action.stop"; public static final String ACTION_FAST_FORWARD = "com.mypodcasts.player.action.fast_foward"; public static final int POSITION = 25 * 1000; @Inject private Context context; @Inject private AudioPlayer audioPlayer; @Inject private AudioPlayerNotification audioPlayerNotification; @Inject private EventBus eventBus; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { try { Log.d(Support.MYPODCASTS_TAG, "[AudioPlayerService][onStartCommand]"); final Episode episode = (Episode) intent.getSerializableExtra(Episode.class.toString()); Log.d(MYPODCASTS_TAG, toString()); if (intent.getAction().equalsIgnoreCase(ACTION_PLAY)) { Log.d(MYPODCASTS_TAG, intent.getAction()); startForeground(ONGOING_NOTIFICATION_ID, audioPlayerNotification.buildNotification(episode)); audioPlayer.play(episode); } else { handleMediaControlByAction(intent); } } catch (IOException e) { Log.e(MYPODCASTS_TAG, e.getMessage()); e.printStackTrace(); } return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); audioPlayer.release(); } private void handleMediaControlByAction(Intent intent) { if (intent.getAction() == null) return; if (intent.getAction().equalsIgnoreCase(ACTION_REWIND)) { Log.d(MYPODCASTS_TAG, ACTION_REWIND); audioPlayer.seekTo(audioPlayer.getCurrentPosition() - POSITION); } if (intent.getAction().equalsIgnoreCase(ACTION_PAUSE)) { Log.d(MYPODCASTS_TAG, ACTION_PAUSE); audioPlayer.pause(); } if (intent.getAction().equalsIgnoreCase(ACTION_STOP)) { Log.d(MYPODCASTS_TAG, ACTION_STOP); audioPlayer.pause(); stopForeground(true); eventBus.post(new AudioStoppedEvent()); } if (intent.getAction().equalsIgnoreCase(ACTION_FAST_FORWARD)) { Log.d(MYPODCASTS_TAG, ACTION_FAST_FORWARD); audioPlayer.seekTo(audioPlayer.getCurrentPosition() + POSITION); } } }
package org.pentaho.di.trans.steps.calculator; import java.util.ArrayList; import java.util.List; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueDataUtil; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.steps.abort.Messages; /** * Calculate new field values using pre-defined functions. * * @author Matt * @since 8-sep-2005 */ public class Calculator extends BaseStep implements StepInterface { public class FieldIndexes { public int indexName; public int indexA; public int indexB; public int indexC; }; private CalculatorMeta meta; private CalculatorData data; public Calculator(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(CalculatorMeta)smi; data=(CalculatorData)sdi; Object[] r=getRow(); // get row, set busy! if (r==null) // no more input to be expected... { setOutputDone(); return false; } if (first) { first=false; data.outputRowMeta = (RowMetaInterface) getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // get all metadata, including source rows and temporary fields. data.calcRowMeta = meta.getAllFields(getInputRowMeta()); data.fieldIndexes = new FieldIndexes[meta.getCalculation().length]; List<Integer> tempIndexes = new ArrayList<Integer>(); // Calculate the indexes of the values and arguments in the target data or temporary data // We do this in advance to save time later on. for (int i=0;i<meta.getCalculation().length;i++) { CalculatorMetaFunction function = meta.getCalculation()[i]; data.fieldIndexes[i] = new FieldIndexes(); if (!Const.isEmpty(function.getFieldName())) { data.fieldIndexes[i].indexName = data.calcRowMeta.indexOfValue(function.getFieldName()); if (data.fieldIndexes[i].indexName<0) { // Nope: throw an exception throw new KettleStepException("Unable to find the specified fieldname '"+function.getFieldName()+"' for calculation } } else { throw new KettleStepException("There is no name specified for calculated field } if (!Const.isEmpty(function.getFieldA())) { if (function.getCalcType()!=CalculatorMetaFunction.CALC_CONSTANT) { data.fieldIndexes[i].indexA = data.calcRowMeta.indexOfValue(function.getFieldA()); if (data.fieldIndexes[i].indexA<0) { // Nope: throw an exception throw new KettleStepException("Unable to find the first argument field '"+function.getFieldName()+" for calculation } } else { data.fieldIndexes[i].indexA = -1; } } else { throw new KettleStepException("There is no first argument specified for calculated field } if (!Const.isEmpty(function.getFieldB())) { data.fieldIndexes[i].indexB = data.calcRowMeta.indexOfValue(function.getFieldB()); if (data.fieldIndexes[i].indexB<0) { // Nope: throw an exception throw new KettleStepException("Unable to find the second argument field '"+function.getFieldName()+" for calculation } } if (!Const.isEmpty(function.getFieldC())) { data.fieldIndexes[i].indexC = data.calcRowMeta.indexOfValue(function.getFieldC()); if (data.fieldIndexes[i].indexC<0) { // Nope: throw an exception throw new KettleStepException("Unable to find the third argument field '"+function.getFieldName()+" for calculation } } if (function.isRemovedFromResult()) { tempIndexes.add(new Integer(getInputRowMeta().size()+i)); } } // Convert temp indexes to int[] data.tempIndexes = new int[tempIndexes.size()]; for (int i=0;i<data.tempIndexes.length;i++) { data.tempIndexes[i] = ((Integer)tempIndexes.get(i)).intValue(); } } if (log.isRowLevel()) log.logRowlevel(toString(), "Read row #"+linesRead+" : "+r); Object[] row = calcFields(getInputRowMeta(), r); putRow(data.outputRowMeta, row); // copy row to possible alternate rowset(s). if (log.isRowLevel()) log.logRowlevel(toString(), "Wrote row #"+linesWritten+" : "+r); if (checkFeedback(linesRead)) logBasic("Linenr "+linesRead); return true; } /** * TODO: Make it backward compatible. * * @param inputRowMeta * @param outputRowMeta * @param r * @return * @throws KettleValueException */ private Object[] calcFields(RowMetaInterface inputRowMeta, Object[] r) throws KettleValueException { // First copy the input data to the new result... Object[] calcData = RowDataUtil.resizeArray(r, data.calcRowMeta.size()); for (int i=0, index=inputRowMeta.size()+i;i<meta.getCalculation().length;i++, index++) { CalculatorMetaFunction fn = meta.getCalculation()[i]; if (!Const.isEmpty(fn.getFieldName())) { ValueMetaInterface targetMeta = data.calcRowMeta.getValueMeta(index); // Get the metadata & the data... // ValueMetaInterface metaTarget = data.calcRowMeta.getValueMeta(i); ValueMetaInterface metaA=null; Object dataA=null; if (data.fieldIndexes[i].indexA>=0) { metaA = data.calcRowMeta.getValueMeta( data.fieldIndexes[i].indexA ); dataA = calcData[ data.fieldIndexes[i].indexA ]; } ValueMetaInterface metaB=null; Object dataB=null; if (data.fieldIndexes[i].indexB>=0) { metaB = data.calcRowMeta.getValueMeta( data.fieldIndexes[i].indexB ); dataB = calcData[ data.fieldIndexes[i].indexB ]; } ValueMetaInterface metaC=null; Object dataC=null; if (data.fieldIndexes[i].indexC>=0) { metaC = data.calcRowMeta.getValueMeta( data.fieldIndexes[i].indexC ); dataC = calcData[ data.fieldIndexes[i].indexC ]; } //The data types are those of the first argument field, convert to the target field. // Exceptions: // - multiply can be string // - constant is string // - all date functions except add days/months // - hex encode / decodes int resultType; if (metaA!=null) { resultType=metaA.getType(); } else { resultType=ValueMetaInterface.TYPE_NONE; } switch(fn.getCalcType()) { case CalculatorMetaFunction.CALC_NONE: break; case CalculatorMetaFunction.CALC_ADD : // A + B { calcData[index] = ValueDataUtil.plus(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_SUBTRACT : // A - B { calcData[index] = ValueDataUtil.minus(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_MULTIPLY : // A * B { calcData[index] = ValueDataUtil.multiply(metaA, dataA, metaB, dataB); if (metaA.isString() || metaB.isString()) resultType=ValueMetaInterface.TYPE_STRING; } break; case CalculatorMetaFunction.CALC_DIVIDE : // A / B { calcData[index] = ValueDataUtil.divide(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_SQUARE : // A * A { calcData[index] = ValueDataUtil.multiply(metaA, dataA, metaA, dataA); } break; case CalculatorMetaFunction.CALC_SQUARE_ROOT : // SQRT( A ) { calcData[index] = ValueDataUtil.sqrt(metaA, dataA); } break; case CalculatorMetaFunction.CALC_PERCENT_1 : // 100 * A / B { calcData[index] = ValueDataUtil.percent1(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_PERCENT_2 : // A - ( A * B / 100 ) { calcData[index] = ValueDataUtil.percent2(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_PERCENT_3 : // A + ( A * B / 100 ) { calcData[index] = ValueDataUtil.percent2(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_COMBINATION_1 : // A + B * C { calcData[index] = ValueDataUtil.combination1(metaA, dataA, metaB, dataB, metaC, dataC); } break; case CalculatorMetaFunction.CALC_COMBINATION_2 : // SQRT( A*A + B*B ) { calcData[index] = ValueDataUtil.combination2(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_ROUND_1 : // ROUND( A ) { calcData[index] = ValueDataUtil.round(metaA, dataA); } break; case CalculatorMetaFunction.CALC_ROUND_2 : // ROUND( A , B ) { calcData[index] = ValueDataUtil.round(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_CONSTANT : // Set field to constant value... { calcData[index] = fn.getFieldA(); // A string resultType=ValueMetaInterface.TYPE_STRING; } break; case CalculatorMetaFunction.CALC_NVL : // Replace null values with another value { calcData[index] = ValueDataUtil.nvl(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_ADD_DAYS : // Add B days to date field A { calcData[index] = ValueDataUtil.addDays(metaA, dataA, metaB, dataB); } break; case CalculatorMetaFunction.CALC_YEAR_OF_DATE : // What is the year (Integer) of a date? { calcData[index] = ValueDataUtil.yearOfDate(metaA, dataA); resultType=ValueMetaInterface.TYPE_INTEGER; } break; case CalculatorMetaFunction.CALC_MONTH_OF_DATE : // What is the month (Integer) of a date? { calcData[index] = ValueDataUtil.monthOfDate(metaA, dataA); resultType=ValueMetaInterface.TYPE_INTEGER; } break; case CalculatorMetaFunction.CALC_DAY_OF_YEAR : // What is the day of year (Integer) of a date? { calcData[index] = ValueDataUtil.dayOfYear(metaA, dataA); resultType=ValueMetaInterface.TYPE_INTEGER; } break; case CalculatorMetaFunction.CALC_DAY_OF_MONTH : // What is the day of month (Integer) of a date? { calcData[index] = ValueDataUtil.dayOfMonth(metaA, dataA); resultType=ValueMetaInterface.TYPE_INTEGER; } break; case CalculatorMetaFunction.CALC_DAY_OF_WEEK : // What is the day of week (Integer) of a date? { calcData[index] = ValueDataUtil.dayOfWeek(metaA, dataA); resultType=ValueMetaInterface.TYPE_INTEGER; } break; case CalculatorMetaFunction.CALC_WEEK_OF_YEAR : // What is the week of year (Integer) of a date? { calcData[index] = ValueDataUtil.weekOfYear(metaA, dataA); resultType=ValueMetaInterface.TYPE_INTEGER; } break; case CalculatorMetaFunction.CALC_WEEK_OF_YEAR_ISO8601 : // What is the week of year (Integer) of a date ISO8601 style? { calcData[index] = ValueDataUtil.weekOfYearISO8601(metaA, dataA); resultType=ValueMetaInterface.TYPE_INTEGER; } break; case CalculatorMetaFunction.CALC_YEAR_OF_DATE_ISO8601 : // What is the year (Integer) of a date ISO8601 style? { calcData[index] = ValueDataUtil.yearOfDateISO8601(metaA, dataA); resultType=ValueMetaInterface.TYPE_INTEGER; } break; case CalculatorMetaFunction.CALC_BYTE_TO_HEX_ENCODE : // Byte to Hex encode string field A { calcData[index] = ValueDataUtil.byteToHexEncode(metaA, dataA); resultType=ValueMetaInterface.TYPE_STRING; } break; case CalculatorMetaFunction.CALC_HEX_TO_BYTE_DECODE : // Hex to Byte decode string field A { calcData[index] = ValueDataUtil.hexToByteDecode(metaA, dataA); resultType=ValueMetaInterface.TYPE_STRING; } break; case CalculatorMetaFunction.CALC_CHAR_TO_HEX_ENCODE : // Char to Hex encode string field A { calcData[index] = ValueDataUtil.charToHexEncode(metaA, dataA); resultType=ValueMetaInterface.TYPE_STRING; } break; case CalculatorMetaFunction.CALC_HEX_TO_CHAR_DECODE : // Hex to Char decode string field A { calcData[index] = ValueDataUtil.hexToCharDecode(metaA, dataA); resultType=ValueMetaInterface.TYPE_STRING; } break; default: throw new KettleValueException("Unknown calculation type #"+fn.getCalcType()); } // If we don't have a target data type, throw an error. // Otherwise the result is non-deterministic. if (fn.getValueType()==ValueMetaInterface.TYPE_NONE) { throw new KettleValueException("No datatype is specified for calculation #"+(i+1)+" : "+fn.getFieldName()+" = "+fn.getCalcTypeDesc()+" / "+fn.getCalcTypeLongDesc()); } // Convert the data to the correct target data type. if (calcData[index]!=null) { if (fn.getValueType()!=resultType) { ValueMetaInterface resultMeta = new ValueMeta("result", resultType); // $NON-NLS-1$ calcData[index] = targetMeta.convertData(resultMeta, calcData[index]); } } } } // OK, now we should refrain from adding the temporary fields to the result. // So we remove them. return RowDataUtil.removeItems(calcData, data.tempIndexes); } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(CalculatorMeta)smi; data=(CalculatorData)sdi; if (super.init(smi, sdi)) { return true; } return false; } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("System.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Throwable t) { logError(Messages.getString("System.Log.UnexpectedError")+" : "+t.toString()); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(t)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package com.microsoft.sqlserver.jdbc; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.security.KeyStore; import java.security.Provider; import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.sql.Timestamp; import java.text.MessageFormat; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SimpleTimeZone; import java.util.TimeZone; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import javax.xml.bind.DatatypeConverter; final class TDS { // TDS protocol versions static final int VER_DENALI = 0x74000004; // TDS 7.4 static final int VER_KATMAI = 0x730B0003; // TDS 7.3B(includes null bit compression) static final int VER_YUKON = 0x72090002; // TDS 7.2 static final int VER_UNKNOWN = 0x00000000; // Unknown/uninitialized static final int TDS_RET_STAT = 0x79; static final int TDS_COLMETADATA = 0x81; static final int TDS_TABNAME = 0xA4; static final int TDS_COLINFO = 0xA5; static final int TDS_ORDER = 0xA9; static final int TDS_ERR = 0xAA; static final int TDS_MSG = 0xAB; static final int TDS_RETURN_VALUE = 0xAC; static final int TDS_LOGIN_ACK = 0xAD; static final int TDS_FEATURE_EXTENSION_ACK = 0xAE; static final int TDS_ROW = 0xD1; static final int TDS_NBCROW = 0xD2; static final int TDS_ENV_CHG = 0xE3; static final int TDS_SSPI = 0xED; static final int TDS_DONE = 0xFD; static final int TDS_DONEPROC = 0xFE; static final int TDS_DONEINPROC = 0xFF; static final int TDS_FEDAUTHINFO = 0xEE; // FedAuth static final int TDS_FEATURE_EXT_FEDAUTH = 0x02; static final int TDS_FEDAUTH_LIBRARY_SECURITYTOKEN = 0x01; static final int TDS_FEDAUTH_LIBRARY_ADAL = 0x02; static final int TDS_FEDAUTH_LIBRARY_RESERVED = 0x7F; static final byte ADALWORKFLOW_ACTIVEDIRECTORYPASSWORD = 0x01; static final byte ADALWORKFLOW_ACTIVEDIRECTORYINTEGRATED = 0x02; static final byte FEDAUTH_INFO_ID_STSURL = 0x01; // FedAuthInfoData is token endpoint URL from which to acquire fed auth token static final byte FEDAUTH_INFO_ID_SPN = 0x02; // FedAuthInfoData is the SPN to use for acquiring fed auth token // AE constants static final int TDS_FEATURE_EXT_AE = 0x04; static final int MAX_SUPPORTED_TCE_VERSION = 0x01; // max version static final int CUSTOM_CIPHER_ALGORITHM_ID = 0; // max version static final int AES_256_CBC = 1; static final int AEAD_AES_256_CBC_HMAC_SHA256 = 2; static final int AE_METADATA = 0x08; static final int TDS_TVP = 0xF3; static final int TVP_ROW = 0x01; static final int TVP_NULL_TOKEN = 0xFFFF; static final int TVP_STATUS_DEFAULT = 0x02; static final int TVP_ORDER_UNIQUE_TOKEN = 0x10; // TVP_ORDER_UNIQUE_TOKEN flags static final byte TVP_ORDERASC_FLAG = 0x1; static final byte TVP_ORDERDESC_FLAG = 0x2; static final byte TVP_UNIQUE_FLAG = 0x4; // TVP flags, may be used in other places static final int FLAG_NULLABLE = 0x01; static final int FLAG_TVP_DEFAULT_COLUMN = 0x200; static final int FEATURE_EXT_TERMINATOR = -1; static final String getTokenName(int tdsTokenType) { switch (tdsTokenType) { case TDS_RET_STAT: return "TDS_RET_STAT (0x79)"; case TDS_COLMETADATA: return "TDS_COLMETADATA (0x81)"; case TDS_TABNAME: return "TDS_TABNAME (0xA4)"; case TDS_COLINFO: return "TDS_COLINFO (0xA5)"; case TDS_ORDER: return "TDS_ORDER (0xA9)"; case TDS_ERR: return "TDS_ERR (0xAA)"; case TDS_MSG: return "TDS_MSG (0xAB)"; case TDS_RETURN_VALUE: return "TDS_RETURN_VALUE (0xAC)"; case TDS_LOGIN_ACK: return "TDS_LOGIN_ACK (0xAD)"; case TDS_FEATURE_EXTENSION_ACK: return "TDS_FEATURE_EXTENSION_ACK (0xAE)"; case TDS_ROW: return "TDS_ROW (0xD1)"; case TDS_NBCROW: return "TDS_NBCROW (0xD2)"; case TDS_ENV_CHG: return "TDS_ENV_CHG (0xE3)"; case TDS_SSPI: return "TDS_SSPI (0xED)"; case TDS_DONE: return "TDS_DONE (0xFD)"; case TDS_DONEPROC: return "TDS_DONEPROC (0xFE)"; case TDS_DONEINPROC: return "TDS_DONEINPROC (0xFF)"; case TDS_FEDAUTHINFO: return "TDS_FEDAUTHINFO (0xEE)"; default: return "unknown token (0x" + Integer.toHexString(tdsTokenType).toUpperCase() + ")"; } } // RPC ProcIDs for use with RPCRequest (PKT_RPC) calls static final short PROCID_SP_CURSOR = 1; static final short PROCID_SP_CURSOROPEN = 2; static final short PROCID_SP_CURSORPREPARE = 3; static final short PROCID_SP_CURSOREXECUTE = 4; static final short PROCID_SP_CURSORPREPEXEC = 5; static final short PROCID_SP_CURSORUNPREPARE = 6; static final short PROCID_SP_CURSORFETCH = 7; static final short PROCID_SP_CURSOROPTION = 8; static final short PROCID_SP_CURSORCLOSE = 9; static final short PROCID_SP_EXECUTESQL = 10; static final short PROCID_SP_PREPARE = 11; static final short PROCID_SP_EXECUTE = 12; static final short PROCID_SP_PREPEXEC = 13; static final short PROCID_SP_PREPEXECRPC = 14; static final short PROCID_SP_UNPREPARE = 15; // Constants for use with cursor RPCs static final short SP_CURSOR_OP_UPDATE = 1; static final short SP_CURSOR_OP_DELETE = 2; static final short SP_CURSOR_OP_INSERT = 4; static final short SP_CURSOR_OP_REFRESH = 8; static final short SP_CURSOR_OP_LOCK = 16; static final short SP_CURSOR_OP_SETPOSITION = 32; static final short SP_CURSOR_OP_ABSOLUTE = 64; // Constants for server-cursored result sets. // See the Engine Cursors Functional Specification for details. static final int FETCH_FIRST = 1; static final int FETCH_NEXT = 2; static final int FETCH_PREV = 4; static final int FETCH_LAST = 8; static final int FETCH_ABSOLUTE = 16; static final int FETCH_RELATIVE = 32; static final int FETCH_REFRESH = 128; static final int FETCH_INFO = 256; static final int FETCH_PREV_NOADJUST = 512; static final byte RPC_OPTION_NO_METADATA = (byte) 0x02; // Transaction manager request types static final short TM_GET_DTC_ADDRESS = 0; static final short TM_PROPAGATE_XACT = 1; static final short TM_BEGIN_XACT = 5; static final short TM_PROMOTE_PROMOTABLE_XACT = 6; static final short TM_COMMIT_XACT = 7; static final short TM_ROLLBACK_XACT = 8; static final short TM_SAVE_XACT = 9; static final byte PKT_QUERY = 1; static final byte PKT_RPC = 3; static final byte PKT_REPLY = 4; static final byte PKT_CANCEL_REQ = 6; static final byte PKT_BULK = 7; static final byte PKT_DTC = 14; static final byte PKT_LOGON70 = 16; // 0x10 static final byte PKT_SSPI = 17; static final byte PKT_PRELOGIN = 18; // 0x12 static final byte PKT_FEDAUTH_TOKEN_MESSAGE = 8; // Authentication token for federated authentication static final byte STATUS_NORMAL = 0x00; static final byte STATUS_BIT_EOM = 0x01; static final byte STATUS_BIT_ATTENTION = 0x02;// this is called ignore bit in TDS spec static final byte STATUS_BIT_RESET_CONN = 0x08; // Various TDS packet size constants static final int INVALID_PACKET_SIZE = -1; static final int INITIAL_PACKET_SIZE = 4096; static final int MIN_PACKET_SIZE = 512; static final int MAX_PACKET_SIZE = 32767; static final int DEFAULT_PACKET_SIZE = 8000; static final int SERVER_PACKET_SIZE = 0; // Accept server's configured packet size // TDS packet header size and offsets static final int PACKET_HEADER_SIZE = 8; static final int PACKET_HEADER_MESSAGE_TYPE = 0; static final int PACKET_HEADER_MESSAGE_STATUS = 1; static final int PACKET_HEADER_MESSAGE_LENGTH = 2; static final int PACKET_HEADER_SPID = 4; static final int PACKET_HEADER_SEQUENCE_NUM = 6; static final int PACKET_HEADER_WINDOW = 7; // Reserved/Not used // MARS header length: // 2 byte header type // 8 byte transaction descriptor // 4 byte outstanding request count static final int MARS_HEADER_LENGTH = 18; // 2 byte header type, 8 byte transaction descriptor, static final int TRACE_HEADER_LENGTH = 26; // header length (4) + header type (2) + guid (16) + Sequence number size (4) static final short HEADERTYPE_TRACE = 3; // trace header type // Message header length static final int MESSAGE_HEADER_LENGTH = MARS_HEADER_LENGTH + 4; // length includes message header itself static final byte B_PRELOGIN_OPTION_VERSION = 0x00; static final byte B_PRELOGIN_OPTION_ENCRYPTION = 0x01; static final byte B_PRELOGIN_OPTION_INSTOPT = 0x02; static final byte B_PRELOGIN_OPTION_THREADID = 0x03; static final byte B_PRELOGIN_OPTION_MARS = 0x04; static final byte B_PRELOGIN_OPTION_TRACEID = 0x05; static final byte B_PRELOGIN_OPTION_FEDAUTHREQUIRED = 0x06; static final byte B_PRELOGIN_OPTION_TERMINATOR = (byte) 0xFF; // Login option byte 1 static final byte LOGIN_OPTION1_ORDER_X86 = 0x00; static final byte LOGIN_OPTION1_ORDER_6800 = 0x01; static final byte LOGIN_OPTION1_CHARSET_ASCII = 0x00; static final byte LOGIN_OPTION1_CHARSET_EBCDIC = 0x02; static final byte LOGIN_OPTION1_FLOAT_IEEE_754 = 0x00; static final byte LOGIN_OPTION1_FLOAT_VAX = 0x04; static final byte LOGIN_OPTION1_FLOAT_ND5000 = 0x08; static final byte LOGIN_OPTION1_DUMPLOAD_ON = 0x00; static final byte LOGIN_OPTION1_DUMPLOAD_OFF = 0x10; static final byte LOGIN_OPTION1_USE_DB_ON = 0x00; static final byte LOGIN_OPTION1_USE_DB_OFF = 0x20; static final byte LOGIN_OPTION1_INIT_DB_WARN = 0x00; static final byte LOGIN_OPTION1_INIT_DB_FATAL = 0x40; static final byte LOGIN_OPTION1_SET_LANG_OFF = 0x00; static final byte LOGIN_OPTION1_SET_LANG_ON = (byte) 0x80; // Login option byte 2 static final byte LOGIN_OPTION2_INIT_LANG_WARN = 0x00; static final byte LOGIN_OPTION2_INIT_LANG_FATAL = 0x01; static final byte LOGIN_OPTION2_ODBC_OFF = 0x00; static final byte LOGIN_OPTION2_ODBC_ON = 0x02; static final byte LOGIN_OPTION2_TRAN_BOUNDARY_OFF = 0x00; static final byte LOGIN_OPTION2_TRAN_BOUNDARY_ON = 0x04; static final byte LOGIN_OPTION2_CACHE_CONNECTION_OFF = 0x00; static final byte LOGIN_OPTION2_CACHE_CONNECTION_ON = 0x08; static final byte LOGIN_OPTION2_USER_NORMAL = 0x00; static final byte LOGIN_OPTION2_USER_SERVER = 0x10; static final byte LOGIN_OPTION2_USER_REMUSER = 0x20; static final byte LOGIN_OPTION2_USER_SQLREPL = 0x30; static final byte LOGIN_OPTION2_INTEGRATED_SECURITY_OFF = 0x00; static final byte LOGIN_OPTION2_INTEGRATED_SECURITY_ON = (byte) 0x80; // Login option byte 3 static final byte LOGIN_OPTION3_DEFAULT = 0x00; static final byte LOGIN_OPTION3_CHANGE_PASSWORD = 0x01; static final byte LOGIN_OPTION3_SEND_YUKON_BINARY_XML = 0x02; static final byte LOGIN_OPTION3_USER_INSTANCE = 0x04; static final byte LOGIN_OPTION3_UNKNOWN_COLLATION_HANDLING = 0x08; static final byte LOGIN_OPTION3_FEATURE_EXTENSION = 0x10; // Login type flag (bits 5 - 7 reserved for future use) static final byte LOGIN_SQLTYPE_DEFAULT = 0x00; static final byte LOGIN_SQLTYPE_TSQL = 0x01; static final byte LOGIN_SQLTYPE_ANSI_V1 = 0x02; static final byte LOGIN_SQLTYPE_ANSI89_L1 = 0x03; static final byte LOGIN_SQLTYPE_ANSI89_L2 = 0x04; static final byte LOGIN_SQLTYPE_ANSI89_IEF = 0x05; static final byte LOGIN_SQLTYPE_ANSI89_ENTRY = 0x06; static final byte LOGIN_SQLTYPE_ANSI89_TRANS = 0x07; static final byte LOGIN_SQLTYPE_ANSI89_INTER = 0x08; static final byte LOGIN_SQLTYPE_ANSI89_FULL = 0x09; static final byte LOGIN_OLEDB_OFF = 0x00; static final byte LOGIN_OLEDB_ON = 0x10; static final byte LOGIN_READ_ONLY_INTENT = 0x20; static final byte LOGIN_READ_WRITE_INTENT = 0x00; static final byte ENCRYPT_OFF = 0x00; static final byte ENCRYPT_ON = 0x01; static final byte ENCRYPT_NOT_SUP = 0x02; static final byte ENCRYPT_REQ = 0x03; static final byte ENCRYPT_INVALID = (byte) 0xFF; static final String getEncryptionLevel(int level) { switch (level) { case ENCRYPT_OFF: return "OFF"; case ENCRYPT_ON: return "ON"; case ENCRYPT_NOT_SUP: return "NOT SUPPORTED"; case ENCRYPT_REQ: return "REQUIRED"; default: return "unknown encryption level (0x" + Integer.toHexString(level).toUpperCase() + ")"; } } // Prelogin packet length, including the tds header, // version, encrpytion, and traceid data sessions. // For detailed info, please check the definition of // preloginRequest in Prelogin function. static final byte B_PRELOGIN_MESSAGE_LENGTH = 67; static final byte B_PRELOGIN_MESSAGE_LENGTH_WITH_FEDAUTH = 73; // Scroll options and concurrency options lifted out // of the the Yukon cursors spec for sp_cursoropen. final static int SCROLLOPT_KEYSET = 1; final static int SCROLLOPT_DYNAMIC = 2; final static int SCROLLOPT_FORWARD_ONLY = 4; final static int SCROLLOPT_STATIC = 8; final static int SCROLLOPT_FAST_FORWARD = 16; final static int SCROLLOPT_PARAMETERIZED_STMT = 4096; final static int SCROLLOPT_AUTO_FETCH = 8192; final static int SCROLLOPT_AUTO_CLOSE = 16384; final static int CCOPT_READ_ONLY = 1; final static int CCOPT_SCROLL_LOCKS = 2; final static int CCOPT_OPTIMISTIC_CC = 4; final static int CCOPT_OPTIMISTIC_CCVAL = 8; final static int CCOPT_ALLOW_DIRECT = 8192; final static int CCOPT_UPDT_IN_PLACE = 16384; // Result set rows include an extra, "hidden" ROWSTAT column which indicates // the overall success or failure of the row fetch operation. With a keyset // cursor, the value in the ROWSTAT column indicates whether the row has been // deleted from the database. static final int ROWSTAT_FETCH_SUCCEEDED = 1; static final int ROWSTAT_FETCH_MISSING = 2; // ColumnInfo status final static int COLINFO_STATUS_EXPRESSION = 0x04; final static int COLINFO_STATUS_KEY = 0x08; final static int COLINFO_STATUS_HIDDEN = 0x10; final static int COLINFO_STATUS_DIFFERENT_NAME = 0x20; final static int MAX_FRACTIONAL_SECONDS_SCALE = 7; final static Timestamp MAX_TIMESTAMP = Timestamp.valueOf("2079-06-06 23:59:59"); final static Timestamp MIN_TIMESTAMP = Timestamp.valueOf("1900-01-01 00:00:00"); static int nanosSinceMidnightLength(int scale) { final int[] scaledLengths = {3, 3, 3, 4, 4, 5, 5, 5}; assert scale >= 0; assert scale <= MAX_FRACTIONAL_SECONDS_SCALE; return scaledLengths[scale]; } final static int DAYS_INTO_CE_LENGTH = 3; final static int MINUTES_OFFSET_LENGTH = 2; // Number of days in a "normal" (non-leap) year according to SQL Server. final static int DAYS_PER_YEAR = 365; final static int BASE_YEAR_1900 = 1900; final static int BASE_YEAR_1970 = 1970; final static String BASE_DATE_1970 = "1970-01-01"; static int timeValueLength(int scale) { return nanosSinceMidnightLength(scale); } static int datetime2ValueLength(int scale) { return DAYS_INTO_CE_LENGTH + nanosSinceMidnightLength(scale); } static int datetimeoffsetValueLength(int scale) { return DAYS_INTO_CE_LENGTH + MINUTES_OFFSET_LENGTH + nanosSinceMidnightLength(scale); } // TDS is just a namespace - it can't be instantiated. private TDS() { } } class Nanos { static final int PER_SECOND = 1000000000; static final int PER_MAX_SCALE_INTERVAL = PER_SECOND / (int) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE); static final int PER_MILLISECOND = PER_SECOND / 1000; static final long PER_DAY = 24 * 60 * 60 * (long) PER_SECOND; private Nanos() { } } // Constants relating to the historically accepted Julian-Gregorian calendar cutover date (October 15, 1582). // Used in processing SQL Server temporal data types whose date component may precede that date. // Scoping these constants to a class defers their initialization to first use. class GregorianChange { // Cutover date for a pure Gregorian calendar - that is, a proleptic Gregorian calendar with // Gregorian leap year behavior throughout its entire range. This is the cutover date is used // with temporal server values, which are represented in terms of number of days relative to a // base date. static final java.util.Date PURE_CHANGE_DATE = new java.util.Date(Long.MIN_VALUE); // The standard Julian to Gregorian cutover date (October 15, 1582) that the JDBC temporal // classes (Time, Date, Timestamp) assume when converting to and from their UTC milliseconds // representations. static final java.util.Date STANDARD_CHANGE_DATE = (new GregorianCalendar(Locale.US)).getGregorianChange(); // A hint as to the number of days since 1/1/0001, past which we do not need to // not rationalize the difference between SQL Server behavior (pure Gregorian) // and Java behavior (standard Gregorian). // Not having to rationalize the difference has a substantial (measured) performance benefit // for temporal getters. // The hint does not need to be exact, as long as it's later than the actual change date. static final int DAYS_SINCE_BASE_DATE_HINT = DDC.daysSinceBaseDate(1583, 1, 1); // Extra days that need to added to a pure gregorian date, post the gergorian // cut over date, to match the default julian-gregorain calendar date of java. static final int EXTRA_DAYS_TO_BE_ADDED; static { // This issue refers to the following bugs in java(same issue). // The issue is fixed in JRE 1.7 // and exists in all the older versions. // Due to the above bug, in older JVM versions(1.6 and before), // the date calculation is incorrect at the Gregorian cut over date. // i.e. the next date after Oct 4th 1582 is Oct 17th 1582, where as // it should have been Oct 15th 1582. // We intentionally do not make a check based on JRE version. // If we do so, our code would break if the bug is fixed in a later update // to an older JRE. So, we check for the existence of the bug instead. GregorianCalendar cal = new GregorianCalendar(Locale.US); cal.clear(); cal.set(1, 1, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582) if (cal.get(Calendar.DAY_OF_MONTH) == 15) { // If the date calculation is correct(the above bug is fixed), // post the default gregorian cut over date, the pure gregorian date // falls short by two days for all dates compared to julian-gregorian date. // so, we add two extra days for functional correctness. // Note: other ways, in which this issue can be fixed instead of // trying to detect the JVM bug is // a) use unoptimized code path in the function convertTemporalToObject // b) use cal.add api instead of cal.set api in the current optimized code path // In both the above approaches, the code is about 6-8 times slower, // resulting in an overall perf regression of about (10-30)% for perf test cases EXTRA_DAYS_TO_BE_ADDED = 2; } else EXTRA_DAYS_TO_BE_ADDED = 0; } private GregorianChange() { } } // UTC/GMT time zone singleton. The enum type delays initialization until first use. enum UTC { INSTANCE; static final TimeZone timeZone = new SimpleTimeZone(0, "UTC"); } final class TDSChannel { private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Channel"); final Logger getLogger() { return logger; } private final String traceID; final public String toString() { return traceID; } private final SQLServerConnection con; private final TDSWriter tdsWriter; final TDSWriter getWriter() { return tdsWriter; } final TDSReader getReader(TDSCommand command) { return new TDSReader(this, con, command); } // Socket for raw TCP/IP communications with SQL Server private Socket tcpSocket; // Socket for SSL-encrypted communications with SQL Server private SSLSocket sslSocket; // Socket providing the communications interface to the driver. // For SSL-encrypted connections, this is the SSLSocket wrapped // around the TCP socket. For unencrypted connections, it is // just the TCP socket itself. private Socket channelSocket; // Implementation of a Socket proxy that can switch from TDS-wrapped I/O // (using the TDSChannel itself) during SSL handshake to raw I/O over // the TCP/IP socket. ProxySocket proxySocket = null; // I/O streams for raw TCP/IP communications with SQL Server private InputStream tcpInputStream; private OutputStream tcpOutputStream; // I/O streams providing the communications interface to the driver. // For SSL-encrypted connections, these are streams obtained from // the SSL socket above. They wrap the underlying TCP streams. // For unencrypted connections, they are just the TCP streams themselves. private InputStream inputStream; private OutputStream outputStream; /** TDS packet payload logger */ private static Logger packetLogger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.DATA"); private final boolean isLoggingPackets = packetLogger.isLoggable(Level.FINEST); final boolean isLoggingPackets() { return isLoggingPackets; } // Number of TDS messages sent to and received from the server int numMsgsSent = 0; int numMsgsRcvd = 0; // Last SPID received from the server. Used for logging and to tag subsequent outgoing // packets to facilitate diagnosing problems from the server side. private int spid = 0; void setSPID(int spid) { this.spid = spid; } int getSPID() { return spid; } void resetPooledConnection() { tdsWriter.resetPooledConnection(); } TDSChannel(SQLServerConnection con) { this.con = con; traceID = "TDSChannel (" + con.toString() + ")"; this.tcpSocket = null; this.sslSocket = null; this.channelSocket = null; this.tcpInputStream = null; this.tcpOutputStream = null; this.inputStream = null; this.outputStream = null; this.tdsWriter = new TDSWriter(this, con); } /** * Opens the physical communications channel (TCP/IP socket and I/O streams) to the SQL Server. */ final void open(String host, int port, int timeoutMillis, boolean useParallel, boolean useTnir, boolean isTnirFirstAttempt, int timeoutMillisForFullTimeout) throws SQLServerException { if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + ": Opening TCP socket..."); SocketFinder socketFinder = new SocketFinder(traceID, con); channelSocket = tcpSocket = socketFinder.findSocket(host, port, timeoutMillis, useParallel, useTnir, isTnirFirstAttempt, timeoutMillisForFullTimeout); try { // Set socket options tcpSocket.setTcpNoDelay(true); tcpSocket.setKeepAlive(true); // set SO_TIMEOUT int socketTimeout = con.getSocketTimeoutMilliseconds(); tcpSocket.setSoTimeout(socketTimeout); inputStream = tcpInputStream = tcpSocket.getInputStream(); outputStream = tcpOutputStream = tcpSocket.getOutputStream(); } catch (IOException ex) { SQLServerException.ConvertConnectExceptionToSQLServerException(host, port, con, ex); } } /** * Disables SSL on this TDS channel. */ void disableSSL() { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Disabling SSL..."); /* * The mission: To close the SSLSocket and release everything that it is holding onto other than the TCP/IP socket and streams. * * The challenge: Simply closing the SSLSocket tries to do additional, unnecessary shutdown I/O over the TCP/IP streams that are bound to the * socket proxy, resulting in a hang and confusing SQL Server. * * Solution: Rewire the ProxySocket's input and output streams (one more time) to closed streams. SSLSocket sees that the streams are already * closed and does not attempt to do any further I/O on them before closing itself. */ // Create a couple of cheap closed streams InputStream is = new ByteArrayInputStream(new byte[0]); try { is.close(); } catch (IOException e) { // No reason to expect a brand new ByteArrayInputStream not to close, // but just in case... logger.fine("Ignored error closing InputStream: " + e.getMessage()); } OutputStream os = new ByteArrayOutputStream(); try { os.close(); } catch (IOException e) { // No reason to expect a brand new ByteArrayOutputStream not to close, // but just in case... logger.fine("Ignored error closing OutputStream: " + e.getMessage()); } // Rewire the proxy socket to the closed streams if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Rewiring proxy streams for SSL socket close"); proxySocket.setStreams(is, os); // Now close the SSL socket. It will see that the proxy socket's streams // are closed and not try to do any further I/O over them. try { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Closing SSL socket"); sslSocket.close(); } catch (IOException e) { // Don't care if we can't close the SSL socket. We're done with it anyway. logger.fine("Ignored error closing SSLSocket: " + e.getMessage()); } // Do not close the proxy socket. Doing so would close our TCP socket // to which the proxy socket is bound. Instead, just null out the reference // to free up the few resources it holds onto. proxySocket = null; // Finally, with all of the SSL support out of the way, put the TDSChannel // back to using the TCP/IP socket and streams directly. inputStream = tcpInputStream; outputStream = tcpOutputStream; channelSocket = tcpSocket; sslSocket = null; if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " SSL disabled"); } /** * Used during SSL handshake, this class implements an InputStream that reads SSL handshake response data (framed in TDS messages) from the TDS * channel. */ private class SSLHandshakeInputStream extends InputStream { private final TDSReader tdsReader; private final SSLHandshakeOutputStream sslHandshakeOutputStream; private final Logger logger; private final String logContext; SSLHandshakeInputStream(TDSChannel tdsChannel, SSLHandshakeOutputStream sslHandshakeOutputStream) { this.tdsReader = tdsChannel.getReader(null); this.sslHandshakeOutputStream = sslHandshakeOutputStream; this.logger = tdsChannel.getLogger(); this.logContext = tdsChannel.toString() + " (SSLHandshakeInputStream):"; } /** * If there is no handshake response data available to be read from existing packets then this method ensures that the SSL handshake output * stream has been flushed to the server, and reads another packet (starting the next TDS response message). * * Note that simply using TDSReader.ensurePayload isn't sufficient as it does not automatically start the new response message. */ private void ensureSSLPayload() throws IOException { if (0 == tdsReader.available()) { if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " No handshake response bytes available. Flushing SSL handshake output stream."); try { sslHandshakeOutputStream.endMessage(); } catch (SQLServerException e) { logger.finer(logContext + " Ending TDS message threw exception:" + e.getMessage()); throw new IOException(e.getMessage()); } if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Reading first packet of SSL handshake response"); try { tdsReader.readPacket(); } catch (SQLServerException e) { logger.finer(logContext + " Reading response packet threw exception:" + e.getMessage()); throw new IOException(e.getMessage()); } } } public long skip(long n) throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Skipping " + n + " bytes..."); if (n <= 0) return 0; if (n > Integer.MAX_VALUE) n = Integer.MAX_VALUE; ensureSSLPayload(); try { tdsReader.skip((int) n); } catch (SQLServerException e) { logger.finer(logContext + " Skipping bytes threw exception:" + e.getMessage()); throw new IOException(e.getMessage()); } return n; } private final byte oneByte[] = new byte[1]; public int read() throws IOException { int bytesRead; while (0 == (bytesRead = readInternal(oneByte, 0, oneByte.length))) ; assert 1 == bytesRead || -1 == bytesRead; return 1 == bytesRead ? oneByte[0] : -1; } public int read(byte[] b) throws IOException { return readInternal(b, 0, b.length); } public int read(byte b[], int offset, int maxBytes) throws IOException { return readInternal(b, offset, maxBytes); } private int readInternal(byte b[], int offset, int maxBytes) throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Reading " + maxBytes + " bytes..."); ensureSSLPayload(); try { tdsReader.readBytes(b, offset, maxBytes); } catch (SQLServerException e) { logger.finer(logContext + " Reading bytes threw exception:" + e.getMessage()); throw new IOException(e.getMessage()); } return maxBytes; } } /** * Used during SSL handshake, this class implements an OutputStream that writes SSL handshake request data (framed in TDS messages) to the TDS * channel. */ private class SSLHandshakeOutputStream extends OutputStream { private final TDSWriter tdsWriter; /** Flag indicating when it is necessary to start a new prelogin TDS message */ private boolean messageStarted; private final Logger logger; private final String logContext; SSLHandshakeOutputStream(TDSChannel tdsChannel) { this.tdsWriter = tdsChannel.getWriter(); this.messageStarted = false; this.logger = tdsChannel.getLogger(); this.logContext = tdsChannel.toString() + " (SSLHandshakeOutputStream):"; } public void flush() throws IOException { // It seems that the security provider implementation in some JVMs // (notably SunJSSE in the 6.0 JVM) likes to add spurious calls to // flush the SSL handshake output stream during SSL handshaking. // We need to ignore these calls because the SSL handshake payload // needs to be completely encapsulated in TDS. The SSL handshake // input stream always ensures that this output stream has been flushed // before trying to read the response. if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Ignored a request to flush the stream"); } void endMessage() throws SQLServerException { // We should only be asked to end the message if we have started one assert messageStarted; if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Finishing TDS message"); // Flush any remaining bytes through the writer. Since there may be fewer bytes // ready to send than a full TDS packet, we end the message here and start a new // one later if additional handshake data needs to be sent. tdsWriter.endMessage(); messageStarted = false; } private final byte singleByte[] = new byte[1]; public void write(int b) throws IOException { singleByte[0] = (byte) (b & 0xFF); writeInternal(singleByte, 0, singleByte.length); } public void write(byte[] b) throws IOException { writeInternal(b, 0, b.length); } public void write(byte[] b, int off, int len) throws IOException { writeInternal(b, off, len); } private void writeInternal(byte[] b, int off, int len) throws IOException { try { // Start out the handshake request in a new prelogin message. Subsequent // writes just add handshake data to the request until flushed. if (!messageStarted) { if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Starting new TDS packet..."); tdsWriter.startMessage(null, TDS.PKT_PRELOGIN); messageStarted = true; } if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Writing " + len + " bytes..."); tdsWriter.writeBytes(b, off, len); } catch (SQLServerException e) { logger.finer(logContext + " Writing bytes threw exception:" + e.getMessage()); throw new IOException(e.getMessage()); } } } /** * This class implements an InputStream that just forwards all of its methods to an underlying InputStream. * * It is more predictable than FilteredInputStream which forwards some of its read methods directly to the underlying stream, but not others. */ private final class ProxyInputStream extends InputStream { private InputStream filteredStream; ProxyInputStream(InputStream is) { filteredStream = is; } final void setFilteredStream(InputStream is) { filteredStream = is; } public long skip(long n) throws IOException { long bytesSkipped; if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Skipping " + n + " bytes"); bytesSkipped = filteredStream.skip(n); if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Skipped " + n + " bytes"); return bytesSkipped; } public int available() throws IOException { int bytesAvailable = filteredStream.available(); if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " " + bytesAvailable + " bytes available"); return bytesAvailable; } private final byte oneByte[] = new byte[1]; public int read() throws IOException { int bytesRead; while (0 == (bytesRead = readInternal(oneByte, 0, oneByte.length))) ; assert 1 == bytesRead || -1 == bytesRead; return 1 == bytesRead ? oneByte[0] : -1; } public int read(byte[] b) throws IOException { return readInternal(b, 0, b.length); } public int read(byte b[], int offset, int maxBytes) throws IOException { return readInternal(b, offset, maxBytes); } private int readInternal(byte b[], int offset, int maxBytes) throws IOException { int bytesRead; if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Reading " + maxBytes + " bytes"); try { bytesRead = filteredStream.read(b, offset, maxBytes); } catch (IOException e) { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " " + e.getMessage()); logger.finer(toString() + " Reading bytes threw exception:" + e.getMessage()); throw e; } if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Read " + bytesRead + " bytes"); return bytesRead; } public boolean markSupported() { boolean markSupported = filteredStream.markSupported(); if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Returning markSupported: " + markSupported); return markSupported; } public void mark(int readLimit) { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Marking next " + readLimit + " bytes"); filteredStream.mark(readLimit); } public void reset() throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Resetting to previous mark"); filteredStream.reset(); } public void close() throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Closing"); filteredStream.close(); } } /** * This class implements an OutputStream that just forwards all of its methods to an underlying OutputStream. * * This class essentially does what FilteredOutputStream does, but is more efficient for our usage. FilteredOutputStream transforms block writes * to sequences of single-byte writes. */ final class ProxyOutputStream extends OutputStream { private OutputStream filteredStream; ProxyOutputStream(OutputStream os) { filteredStream = os; } final void setFilteredStream(OutputStream os) { filteredStream = os; } public void close() throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Closing"); filteredStream.close(); } public void flush() throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Flushing"); filteredStream.flush(); } private final byte singleByte[] = new byte[1]; public void write(int b) throws IOException { singleByte[0] = (byte) (b & 0xFF); writeInternal(singleByte, 0, singleByte.length); } public void write(byte[] b) throws IOException { writeInternal(b, 0, b.length); } public void write(byte[] b, int off, int len) throws IOException { writeInternal(b, off, len); } private void writeInternal(byte[] b, int off, int len) throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Writing " + len + " bytes"); filteredStream.write(b, off, len); } } /** * This class implements a Socket whose I/O streams can be switched from using a TDSChannel for I/O to using its underlying TCP/IP socket. * * The SSL socket binds to a ProxySocket. The initial SSL handshake is done over TDSChannel I/O streams so that the handshake payload is framed in * TDS packets. The I/O streams are then switched to TCP/IP I/O streams using setStreams, and SSL communications continue directly over the TCP/IP * I/O streams. * * Most methods other than those for getting the I/O streams are simply forwarded to the TDSChannel's underlying TCP/IP socket. Methods that * change the socket binding or provide direct channel access are disallowed. */ private class ProxySocket extends Socket { private final TDSChannel tdsChannel; private final Logger logger; private final String logContext; private final ProxyInputStream proxyInputStream; private final ProxyOutputStream proxyOutputStream; ProxySocket(TDSChannel tdsChannel) { this.tdsChannel = tdsChannel; this.logger = tdsChannel.getLogger(); this.logContext = tdsChannel.toString() + " (ProxySocket):"; // Create the I/O streams SSLHandshakeOutputStream sslHandshakeOutputStream = new SSLHandshakeOutputStream(tdsChannel); SSLHandshakeInputStream sslHandshakeInputStream = new SSLHandshakeInputStream(tdsChannel, sslHandshakeOutputStream); this.proxyOutputStream = new ProxyOutputStream(sslHandshakeOutputStream); this.proxyInputStream = new ProxyInputStream(sslHandshakeInputStream); } void setStreams(InputStream is, OutputStream os) { proxyInputStream.setFilteredStream(is); proxyOutputStream.setFilteredStream(os); } public InputStream getInputStream() throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Getting input stream"); return proxyInputStream; } public OutputStream getOutputStream() throws IOException { if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Getting output stream"); return proxyOutputStream; } // Allow methods that should just forward to the underlying TCP socket or return fixed values public InetAddress getInetAddress() { return tdsChannel.tcpSocket.getInetAddress(); } public boolean getKeepAlive() throws SocketException { return tdsChannel.tcpSocket.getKeepAlive(); } public InetAddress getLocalAddress() { return tdsChannel.tcpSocket.getLocalAddress(); } public int getLocalPort() { return tdsChannel.tcpSocket.getLocalPort(); } public SocketAddress getLocalSocketAddress() { return tdsChannel.tcpSocket.getLocalSocketAddress(); } public boolean getOOBInline() throws SocketException { return tdsChannel.tcpSocket.getOOBInline(); } public int getPort() { return tdsChannel.tcpSocket.getPort(); } public int getReceiveBufferSize() throws SocketException { return tdsChannel.tcpSocket.getReceiveBufferSize(); } public SocketAddress getRemoteSocketAddress() { return tdsChannel.tcpSocket.getRemoteSocketAddress(); } public boolean getReuseAddress() throws SocketException { return tdsChannel.tcpSocket.getReuseAddress(); } public int getSendBufferSize() throws SocketException { return tdsChannel.tcpSocket.getSendBufferSize(); } public int getSoLinger() throws SocketException { return tdsChannel.tcpSocket.getSoLinger(); } public int getSoTimeout() throws SocketException { return tdsChannel.tcpSocket.getSoTimeout(); } public boolean getTcpNoDelay() throws SocketException { return tdsChannel.tcpSocket.getTcpNoDelay(); } public int getTrafficClass() throws SocketException { return tdsChannel.tcpSocket.getTrafficClass(); } public boolean isBound() { return true; } public boolean isClosed() { return false; } public boolean isConnected() { return true; } public boolean isInputShutdown() { return false; } public boolean isOutputShutdown() { return false; } public String toString() { return tdsChannel.tcpSocket.toString(); } public SocketChannel getChannel() { return null; } // Disallow calls to methods that would change the underlying TCP socket public void bind(SocketAddress bindPoint) throws IOException { logger.finer(logContext + " Disallowed call to bind. Throwing IOException."); throw new IOException(); } public void connect(SocketAddress endpoint) throws IOException { logger.finer(logContext + " Disallowed call to connect (without timeout). Throwing IOException."); throw new IOException(); } public void connect(SocketAddress endpoint, int timeout) throws IOException { logger.finer(logContext + " Disallowed call to connect (with timeout). Throwing IOException."); throw new IOException(); } // Ignore calls to methods that would otherwise allow the SSL socket // to directly manipulate the underlying TCP socket public void close() throws IOException { if (logger.isLoggable(Level.FINER)) logger.finer(logContext + " Ignoring close"); } public void setReceiveBufferSize(int size) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setReceiveBufferSize size:" + size); } public void setSendBufferSize(int size) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setSendBufferSize size:" + size); } public void setReuseAddress(boolean on) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setReuseAddress"); } public void setSoLinger(boolean on, int linger) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setSoLinger"); } public void setSoTimeout(int timeout) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setSoTimeout"); } public void setTcpNoDelay(boolean on) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setTcpNoDelay"); } public void setTrafficClass(int tc) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setTrafficClass"); } public void shutdownInput() throws IOException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring shutdownInput"); } public void shutdownOutput() throws IOException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring shutdownOutput"); } public void sendUrgentData(int data) throws IOException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring sendUrgentData"); } public void setKeepAlive(boolean on) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setKeepAlive"); } public void setOOBInline(boolean on) throws SocketException { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Ignoring setOOBInline"); } } /** * This class implements an X509TrustManager that always accepts the X509Certificate chain offered to it. * * A PermissiveX509TrustManager is used to "verify" the authenticity of the server when the trustServerCertificate connection property is set to * true. */ private final class PermissiveX509TrustManager extends Object implements X509TrustManager { private final TDSChannel tdsChannel; private final Logger logger; private final String logContext; PermissiveX509TrustManager(TDSChannel tdsChannel) { this.tdsChannel = tdsChannel; this.logger = tdsChannel.getLogger(); this.logContext = tdsChannel.toString() + " (PermissiveX509TrustManager):"; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (logger.isLoggable(Level.FINER)) logger.finer(logContext + " Trusting client certificate (!)"); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (logger.isLoggable(Level.FINER)) logger.finer(logContext + " Trusting server certificate"); } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } /** * This class implements an X509TrustManager that hostname for validation. * * This validates the subject name in the certificate with the host name */ private final class HostNameOverrideX509TrustManager extends Object implements X509TrustManager { private final Logger logger; private final String logContext; private final X509TrustManager defaultTrustManager; private String hostName; HostNameOverrideX509TrustManager(TDSChannel tdsChannel, X509TrustManager tm, String hostName) { this.logger = tdsChannel.getLogger(); this.logContext = tdsChannel.toString() + " (HostNameOverrideX509TrustManager):"; defaultTrustManager = tm; // canonical name is in lower case so convert this to lowercase too. this.hostName = hostName.toLowerCase(); ; } // Parse name in RFC 2253 format // Returns the common name if successful, null if failed to find the common name. // The parser tuned to be safe than sorry so if it sees something it cant parse correctly it returns null private String parseCommonName(String distinguishedName) { int index; // canonical name converts entire name to lowercase index = distinguishedName.indexOf("cn="); if (index == -1) { return null; } distinguishedName = distinguishedName.substring(index + 3); // Parse until a comma or end is reached // Note the parser will handle gracefully (essentially will return empty string) , inside the quotes (e.g cn="Foo, bar") however // RFC 952 says that the hostName cant have commas however the parser should not (and will not) crash if it sees a , within quotes. for (index = 0; index < distinguishedName.length(); index++) { if (distinguishedName.charAt(index) == ',') { break; } } String commonName = distinguishedName.substring(0, index); // strip any quotes if (commonName.length() > 1 && ('\"' == commonName.charAt(0))) { if ('\"' == commonName.charAt(commonName.length() - 1)) commonName = commonName.substring(1, commonName.length() - 1); else { // Be safe the name is not ended in " return null so the common Name wont match commonName = null; } } return commonName; } private boolean validateServerName(String nameInCert) throws CertificateException { // Failed to get the common name from DN or empty CN if (null == nameInCert) { if (logger.isLoggable(Level.FINER)) logger.finer(logContext + " Failed to parse the name from the certificate or name is empty."); return false; } // Verify that the name in certificate matches exactly with the host name if (!nameInCert.equals(hostName)) { if (logger.isLoggable(Level.FINER)) logger.finer(logContext + " The name in certificate " + nameInCert + " does not match with the server name " + hostName + "."); return false; } if (logger.isLoggable(Level.FINER)) logger.finer(logContext + " The name in certificate:" + nameInCert + " validated against server name " + hostName + "."); return true; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Forwarding ClientTrusted."); defaultTrustManager.checkClientTrusted(chain, authType); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " Forwarding Trusting server certificate"); defaultTrustManager.checkServerTrusted(chain, authType); if (logger.isLoggable(Level.FINEST)) logger.finest(logContext + " default serverTrusted succeeded proceeding with server name validation"); validateServerNameInCertificate(chain[0]); } private void validateServerNameInCertificate(X509Certificate cert) throws CertificateException { String nameInCertDN = cert.getSubjectX500Principal().getName("canonical"); if (logger.isLoggable(Level.FINER)) { logger.finer(logContext + " Validating the server name:" + hostName); logger.finer(logContext + " The DN name in certificate:" + nameInCertDN); } boolean isServerNameValidated = false; // the name in cert is in RFC2253 format parse it to get the actual subject name String subjectCN = parseCommonName(nameInCertDN); isServerNameValidated = validateServerName(subjectCN); if (!isServerNameValidated) { Collection<List<?>> sanCollection = cert.getSubjectAlternativeNames(); if (sanCollection != null) { // find a subjectAlternateName entry corresponding to DNS Name for (List<?> sanEntry : sanCollection) { if (sanEntry != null && sanEntry.size() >= 2) { Object key = sanEntry.get(0); Object value = sanEntry.get(1); if (logger.isLoggable(Level.FINER)) { logger.finer(logContext + "Key: " + key + "; KeyClass:" + (key != null ? key.getClass() : null) + ";value: " + value + "; valueClass:" + (value != null ? value.getClass() : null)); } // "Note that the Collection returned may contain // more than one name of the same type." // So, more than one entry of dnsNameType can be present. // Java docs guarantee that the first entry in the list will be an integer. // 2 is the sequence no of a dnsName if ((key != null) && (key instanceof Integer) && ((Integer) key == 2)) { // As per RFC2459, the DNSName will be in the // "preferred name syntax" as specified by RFC // 1034 and the name can be in upper or lower case. // And no significance is attached to case. // Java docs guarantee that the second entry in the list // will be a string for dnsName if (value != null && value instanceof String) { String dnsNameInSANCert = (String) value; // convert to upper case and then to lower case in english locale // to avoid Turkish i issues. // Note that, this conversion was not necessary for // cert.getSubjectX500Principal().getName("canonical"); // as the above API already does this by default as per documentation. dnsNameInSANCert = dnsNameInSANCert.toUpperCase(Locale.US); dnsNameInSANCert = dnsNameInSANCert.toLowerCase(Locale.US); isServerNameValidated = validateServerName(dnsNameInSANCert); if (isServerNameValidated) { if (logger.isLoggable(Level.FINER)) { logger.finer(logContext + " found a valid name in certificate: " + dnsNameInSANCert); } break; } } if (logger.isLoggable(Level.FINER)) { logger.finer(logContext + " the following name in certificate does not match the serverName: " + value); } } } else { if (logger.isLoggable(Level.FINER)) { logger.finer(logContext + " found an invalid san entry: " + sanEntry); } } } } } if (!isServerNameValidated) { String msg = SQLServerException.getErrString("R_certNameFailed"); throw new CertificateException(msg); } } public X509Certificate[] getAcceptedIssuers() { return defaultTrustManager.getAcceptedIssuers(); } } enum SSLHandhsakeState { SSL_HANDHSAKE_NOT_STARTED, SSL_HANDHSAKE_STARTED, SSL_HANDHSAKE_COMPLETE }; /** * Enables SSL Handshake. * * @param host * Server Host Name for SSL Handshake * @param port * Server Port for SSL Handshake * @throws SQLServerException */ void enableSSL(String host, int port) throws SQLServerException { // If enabling SSL fails, which it can for a number of reasons, the following items // are used in logging information to the TDS channel logger to help diagnose the problem. Provider tmfProvider = null; // TrustManagerFactory provider Provider sslContextProvider = null; // SSLContext provider Provider ksProvider = null; // KeyStore provider String tmfDefaultAlgorithm = null; // Default algorithm (typically X.509) used by the TrustManagerFactory SSLHandhsakeState handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_NOT_STARTED; boolean isFips = false; String trustStoreType = null; String fipsProvider = null; // If anything in here fails, terminate the connection and throw an exception try { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Enabling SSL..."); String trustStoreFileName = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE.toString()); String trustStorePassword = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE_PASSWORD.toString()); String hostNameInCertificate = con.activeConnectionProperties .getProperty(SQLServerDriverStringProperty.HOSTNAME_IN_CERTIFICATE.toString()); trustStoreType = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE_TYPE.toString()); if(StringUtils.isEmpty(trustStoreType)) { trustStoreType = SQLServerDriverStringProperty.TRUST_STORE_TYPE.getDefaultValue(); } fipsProvider = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.FIPS_PROVIDER.toString()); isFips = Boolean.valueOf(con.activeConnectionProperties.getProperty(SQLServerDriverBooleanProperty.FIPS.toString())); if (isFips) { validateFips(fipsProvider, trustStoreType, trustStoreFileName); } assert TDS.ENCRYPT_OFF == con.getRequestedEncryptionLevel() || // Login only SSL TDS.ENCRYPT_ON == con.getRequestedEncryptionLevel(); // Full SSL assert TDS.ENCRYPT_OFF == con.getNegotiatedEncryptionLevel() || // Login only SSL TDS.ENCRYPT_ON == con.getNegotiatedEncryptionLevel() || // Full SSL TDS.ENCRYPT_REQ == con.getNegotiatedEncryptionLevel(); // Full SSL // If we requested login only SSL or full SSL without server certificate validation, // then we'll "validate" the server certificate using a naive TrustManager that trusts // everything it sees. TrustManager[] tm = null; if (TDS.ENCRYPT_OFF == con.getRequestedEncryptionLevel() || (TDS.ENCRYPT_ON == con.getRequestedEncryptionLevel() && con.trustServerCertificate())) { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " SSL handshake will trust any certificate"); tm = new TrustManager[] {new PermissiveX509TrustManager(this)}; } // Otherwise, we'll validate the certificate using a real TrustManager obtained // from the a security provider that is capable of validating X.509 certificates. else { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " SSL handshake will validate server certificate"); KeyStore ks = null; // If we are using the system default trustStore and trustStorePassword // then we can skip all of the KeyStore loading logic below. // The security provider's implementation takes care of everything for us. if (null == trustStoreFileName && null == trustStorePassword) { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Using system default trust store and password"); } // Otherwise either the trustStore, trustStorePassword, or both was specified. // In that case, we need to load up a KeyStore ourselves. else { // First, obtain an interface to a KeyStore that can load trust material // stored in Java Key Store (JKS) format. if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Finding key store interface"); if (isFips) { ks = KeyStore.getInstance(trustStoreType, fipsProvider); } else { ks = KeyStore.getInstance(trustStoreType); } ksProvider = ks.getProvider(); // Next, load up the trust store file from the specified location. // Note: This function returns a null InputStream if the trust store cannot // be loaded. This is by design. See the method comment and documentation // for KeyStore.load for details. InputStream is = loadTrustStore(trustStoreFileName); // Finally, load the KeyStore with the trust material (if any) from the // InputStream and close the stream. if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Loading key store"); try { ks.load(is, (null == trustStorePassword) ? null : trustStorePassword.toCharArray()); } finally { // We are done with the trustStorePassword (if set). Clear it for better security. con.activeConnectionProperties.remove(SQLServerDriverStringProperty.TRUST_STORE_PASSWORD.toString()); // We are also done with the trust store input stream. if (null != is) { try { is.close(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) logger.fine(toString() + " Ignoring error closing trust material InputStream..."); } } } } // Either we now have a KeyStore populated with trust material or we are using the // default source of trust material (cacerts). Either way, we are now ready to // use a TrustManagerFactory to create a TrustManager that uses the trust material // to validate the server certificate. // Next step is to get a TrustManagerFactory that can produce TrustManagers // that understands X.509 certificates. TrustManagerFactory tmf = null; if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Locating X.509 trust manager factory"); tmfDefaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); tmf = TrustManagerFactory.getInstance(tmfDefaultAlgorithm); tmfProvider = tmf.getProvider(); // Tell the TrustManagerFactory to give us TrustManagers that we can use to // validate the server certificate using the trust material in the KeyStore. if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Getting trust manager"); tmf.init(ks); tm = tmf.getTrustManagers(); // if the host name in cert provided use it or use the host name Only if it is not FIPS if (!isFips) { if (null != hostNameInCertificate) { tm = new TrustManager[] {new HostNameOverrideX509TrustManager(this, (X509TrustManager) tm[0], hostNameInCertificate)}; } else { tm = new TrustManager[] {new HostNameOverrideX509TrustManager(this, (X509TrustManager) tm[0], host)}; } } } // end if (!con.trustServerCertificate()) // Now, with a real or fake TrustManager in hand, get a context for creating a // SSL sockets through a SSL socket factory. We require at least TLS support. SSLContext sslContext = null; if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Getting TLS or better SSL context"); sslContext = SSLContext.getInstance("TLS"); sslContextProvider = sslContext.getProvider(); if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Initializing SSL context"); sslContext.init(null, tm, null); // Got the SSL context. Now create an SSL socket over our own proxy socket // which we can toggle between TDS-encapsulated and raw communications. // Initially, the proxy is set to encapsulate the SSL handshake in TDS packets. proxySocket = new ProxySocket(this); if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Creating SSL socket"); sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(proxySocket, host, port, false); // don't close proxy when SSL socket // is closed // At long last, start the SSL handshake ... if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Starting SSL handshake"); // TLS 1.2 intermittent exception happens here. handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_STARTED; sslSocket.startHandshake(); handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_COMPLETE; // After SSL handshake is complete, rewire proxy socket to use raw TCP/IP streams ... if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Rewiring proxy streams after handshake"); proxySocket.setStreams(inputStream, outputStream); // ... and rewire TDSChannel to use SSL streams. if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Getting SSL InputStream"); inputStream = sslSocket.getInputStream(); if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Getting SSL OutputStream"); outputStream = sslSocket.getOutputStream(); // SSL is now enabled; switch over the channel socket channelSocket = sslSocket; if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " SSL enabled"); } catch (Exception e) { // Log the original exception and its source at FINER level if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, e.getMessage(), e); // If enabling SSL fails, the following information may help diagnose the problem. // Do not use Level INFO or above which is sent to standard output/error streams. // This is because due to an intermittent TLS 1.2 connection issue, we will be retrying the connection and // do not want to print this message in console. if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "java.security path: " + JAVA_SECURITY + "\n" + "Security providers: " + Arrays.asList(Security.getProviders()) + "\n" + ((null != sslContextProvider) ? ("SSLContext provider info: " + sslContextProvider.getInfo() + "\n" + "SSLContext provider services:\n" + sslContextProvider.getServices() + "\n") : "") + ((null != tmfProvider) ? ("TrustManagerFactory provider info: " + tmfProvider.getInfo() + "\n") : "") + ((null != tmfDefaultAlgorithm) ? ("TrustManagerFactory default algorithm: " + tmfDefaultAlgorithm + "\n") : "") + ((null != ksProvider) ? ("KeyStore provider info: " + ksProvider.getInfo() + "\n") : "") + "java.ext.dirs: " + System.getProperty("java.ext.dirs")); MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_sslFailed")); Object[] msgArgs = {e.getMessage()}; // It is important to get the localized message here, otherwise error messages won't match for different locales. String errMsg = e.getLocalizedMessage(); // The error message may have a connection id appended to it. Extract the message only for comparison. // This client connection id is appended in method checkAndAppendClientConnId(). if (errMsg.contains(SQLServerException.LOG_CLIENT_CONNECTION_ID_PREFIX)) { errMsg = errMsg.substring(0, errMsg.indexOf(SQLServerException.LOG_CLIENT_CONNECTION_ID_PREFIX)); } // Isolate the TLS1.2 intermittent connection error. if (e instanceof IOException && (SSLHandhsakeState.SSL_HANDHSAKE_STARTED == handshakeState) && (errMsg.equals(SQLServerException.getErrString("R_truncatedServerResponse")))) { con.terminate(SQLServerException.DRIVER_ERROR_INTERMITTENT_TLS_FAILED, form.format(msgArgs), e); } else { con.terminate(SQLServerException.DRIVER_ERROR_SSL_FAILED, form.format(msgArgs), e); } } } /** * Validate FIPS if fips set as true * * Valid FIPS settings: * <LI>Encrypt should be true * <LI>trustServerCertificate should be false * <LI>if certificate is not installed FIPSProvider & TrustStoreType should be present. * * @param fipsProvider * FIPS Provider * @param trustStoreType * @param trustStoreFileName * @throws SQLServerException * @since 6.1.4 */ private void validateFips(final String fipsProvider, final String trustStoreType, final String trustStoreFileName) throws SQLServerException { boolean isValid = false; boolean isEncryptOn; boolean isValidTrustStoreType; boolean isValidTrustStore; boolean isTrustServerCertificate; boolean isValidFipsProvider; String strError = SQLServerException.getErrString("R_invalidFipsConfig"); isEncryptOn = (TDS.ENCRYPT_ON == con.getRequestedEncryptionLevel()); // Here different FIPS provider supports different KeyStore type along with different JVM Implementation. isValidFipsProvider = !StringUtils.isEmpty(fipsProvider); isValidTrustStoreType = !StringUtils.isEmpty(trustStoreType); isValidTrustStore = !StringUtils.isEmpty(trustStoreFileName); isTrustServerCertificate = con.trustServerCertificate(); if (isEncryptOn & !isTrustServerCertificate) { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Found parameters are encrypt is true & trustServerCertificate false"); isValid = true; if (isValidTrustStore) { // In case of valid trust store we need to check fipsProvider and TrustStoreType. if (!isValidFipsProvider || !isValidTrustStoreType) { isValid = false; strError = SQLServerException.getErrString("R_invalidFipsProviderConfig"); if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " FIPS provider & TrustStoreType should pass with TrustStore."); } if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Found FIPS parameters seems to be valid."); } } else { strError = SQLServerException.getErrString("R_invalidFipsEncryptConfig"); } if (!isValid) { throw new SQLServerException(strError, null, 0, null); } } private final static String SEPARATOR = System.getProperty("file.separator"); private final static String JAVA_HOME = System.getProperty("java.home"); private final static String JAVA_SECURITY = JAVA_HOME + SEPARATOR + "lib" + SEPARATOR + "security"; private final static String JSSECACERTS = JAVA_SECURITY + SEPARATOR + "jssecacerts"; private final static String CACERTS = JAVA_SECURITY + SEPARATOR + "cacerts"; /** * Loads the contents of a trust store into an InputStream. * * When a location to a trust store is specified, this method attempts to load that store. Otherwise, it looks for and attempts to load the * default trust store using essentially the same logic (outlined in the JSSE Reference Guide) as the default X.509 TrustManagerFactory. * * @return an InputStream containing the contents of the loaded trust store * @return null if the trust store cannot be loaded. * * Note: It is by design that this function returns null when the trust store cannot be loaded rather than throwing an exception. The * reason is that KeyStore.load, which uses the returned InputStream, interprets a null InputStream to mean that there are no trusted * certificates, which mirrors the behavior of the default (no trust store, no password specified) path. */ final InputStream loadTrustStore(String trustStoreFileName) { FileInputStream is = null; // First case: Trust store filename was specified if (null != trustStoreFileName) { try { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Opening specified trust store: " + trustStoreFileName); is = new FileInputStream(trustStoreFileName); } catch (FileNotFoundException e) { if (logger.isLoggable(Level.FINE)) logger.fine(toString() + " Trust store not found: " + e.getMessage()); // If the trustStoreFileName connection property is set, but the file is not found, // then treat it as if the file was empty so that the TrustManager reports // that no certificate is found. } } // Second case: Trust store filename derived from javax.net.ssl.trustStore system property else if (null != (trustStoreFileName = System.getProperty("javax.net.ssl.trustStore"))) { try { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Opening default trust store (from javax.net.ssl.trustStore): " + trustStoreFileName); is = new FileInputStream(trustStoreFileName); } catch (FileNotFoundException e) { if (logger.isLoggable(Level.FINE)) logger.fine(toString() + " Trust store not found: " + e.getMessage()); // If the javax.net.ssl.trustStore property is set, but the file is not found, // then treat it as if the file was empty so that the TrustManager reports // that no certificate is found. } } // Third case: No trust store specified and no system property set. Use jssecerts/cacerts. else { try { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Opening default trust store: " + JSSECACERTS); is = new FileInputStream(JSSECACERTS); } catch (FileNotFoundException e) { if (logger.isLoggable(Level.FINE)) logger.fine(toString() + " Trust store not found: " + e.getMessage()); } // No jssecerts. Try again with cacerts... if (null == is) { try { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Opening default trust store: " + CACERTS); is = new FileInputStream(CACERTS); } catch (FileNotFoundException e) { if (logger.isLoggable(Level.FINE)) logger.fine(toString() + " Trust store not found: " + e.getMessage()); // No jssecerts or cacerts. Treat it as if the trust store is empty so that // the TrustManager reports that no certificate is found. } } } return is; } final int read(byte[] data, int offset, int length) throws SQLServerException { try { return inputStream.read(data, offset, length); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) logger.fine(toString() + " read failed:" + e.getMessage()); if (e instanceof SocketTimeoutException) { con.terminate(SQLServerException.ERROR_SOCKET_TIMEOUT, e.getMessage(), e); } else { con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage()); } return 0; // Keep the compiler happy. } } final void write(byte[] data, int offset, int length) throws SQLServerException { try { outputStream.write(data, offset, length); } catch (IOException e) { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " write failed:" + e.getMessage()); con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage()); } } final void flush() throws SQLServerException { try { outputStream.flush(); } catch (IOException e) { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " flush failed:" + e.getMessage()); con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage()); } } final void close() { if (null != sslSocket) disableSSL(); if (null != inputStream) { if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Closing inputStream..."); try { inputStream.close(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, this.toString() + ": Ignored error closing inputStream", e); } } if (null != outputStream) { if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Closing outputStream..."); try { outputStream.close(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, this.toString() + ": Ignored error closing outputStream", e); } } if (null != tcpSocket) { if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + ": Closing TCP socket..."); try { tcpSocket.close(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, this.toString() + ": Ignored error closing socket", e); } } } /** * Logs TDS packet data to the com.microsoft.sqlserver.jdbc.TDS.DATA logger * * @param data * the buffer containing the TDS packet payload data to log * @param nStartOffset * offset into the above buffer from where to start logging * @param nLength * length (in bytes) of payload * @param messageDetail * other loggable details about the payload */ void logPacket(byte data[], int nStartOffset, int nLength, String messageDetail) { assert 0 <= nLength && nLength <= data.length; assert 0 <= nStartOffset && nStartOffset <= data.length; final char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; final char printableChars[] = {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', ' ', '!', '\"', ' '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'}; // Log message body lines have this form: // "XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX ................" // 012345678911111111112222222222333333333344444444445555555555666666 // 01234567890123456789012345678901234567890123456789012345 final char lineTemplate[] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'}; char logLine[] = new char[lineTemplate.length]; System.arraycopy(lineTemplate, 0, logLine, 0, lineTemplate.length); // Logging builds up a string buffer for the entire log trace // before writing it out. So use an initial size large enough // that the buffer doesn't have to resize itself. StringBuilder logMsg = new StringBuilder(messageDetail.length() + // Message detail 4 * nLength + // 2-digit hex + space + ASCII, per byte 4 * (1 + nLength / 16) + // 2 extra spaces + CR/LF, per line (16 bytes per line) 80); // Extra fluff: IP:Port, Connection #, SPID, ... // Format the headline like so: // /157.55.121.182:2983 Connection 1, SPID 53, Message info here ... // Note: the log formatter itself timestamps what we write so we don't have // to do it again here. logMsg.append(tcpSocket.getLocalAddress().toString() + ":" + tcpSocket.getLocalPort() + " SPID:" + spid + " " + messageDetail + "\r\n"); // Fill in the body of the log message, line by line, 16 bytes per line. int nBytesLogged = 0; int nBytesThisLine; while (true) { // Fill up the line with as many bytes as we can (up to 16 bytes) for (nBytesThisLine = 0; nBytesThisLine < 16 && nBytesLogged < nLength; nBytesThisLine++, nBytesLogged++) { int nUnsignedByteVal = (data[nStartOffset + nBytesLogged] + 256) % 256; logLine[3 * nBytesThisLine] = hexChars[nUnsignedByteVal / 16]; logLine[3 * nBytesThisLine + 1] = hexChars[nUnsignedByteVal % 16]; logLine[50 + nBytesThisLine] = printableChars[nUnsignedByteVal]; } // Pad out the remainder with whitespace for (int nBytesJustified = nBytesThisLine; nBytesJustified < 16; nBytesJustified++) { logLine[3 * nBytesJustified] = ' '; logLine[3 * nBytesJustified + 1] = ' '; } logMsg.append(logLine, 0, 50 + nBytesThisLine); if (nBytesLogged == nLength) break; logMsg.append("\r\n"); } packetLogger.finest(logMsg.toString()); } } /** * SocketFinder is used to find a server socket to which a connection can be made. This class abstracts the logic of finding a socket from TDSChannel * class. * * In the case when useParallel is set to true, this is achieved by trying to make parallel connections to multiple IP addresses. This class is * responsible for spawning multiple threads and keeping track of the search result and the connected socket or exception to be thrown. * * In the case where multiSubnetFailover is false, we try our old logic of trying to connect to the first ip address * * Typical usage of this class is SocketFinder sf = new SocketFinder(traceId, conn); Socket = sf.getSocket(hostName, port, timeout); */ final class SocketFinder { /** * Indicates the result of a search */ enum Result { UNKNOWN,// search is still in progress SUCCESS,// found a socket FAILURE// failed in finding a socket } // Thread pool - the values in the constructor are chosen based on the // explanation given in design_connection_director_multisubnet.doc private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 5, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); // When parallel connections are to be used, use minimum timeout slice of 1500 milliseconds. private static final int minTimeoutForParallelConnections = 1500; // lock used for synchronization while updating // data within a socketFinder object private final Object socketFinderlock = new Object(); // lock on which the parent thread would wait // after spawning threads. private final Object parentThreadLock = new Object(); // indicates whether the socketFinder has succeeded or failed // in finding a socket or is still trying to find a socket private volatile Result result = Result.UNKNOWN; // total no of socket connector threads // spawned by a socketFinder object private int noOfSpawnedThreads = 0; // no of threads that finished their socket connection // attempts and notified socketFinder about their result private volatile int noOfThreadsThatNotified = 0; // If a valid connected socket is found, this value would be non-null, // else this would be null private volatile Socket selectedSocket = null; // This would be one of the exceptions returned by the // socketConnector threads private volatile IOException selectedException = null; // Logging variables private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SocketFinder"); private final String traceID; // maximum number of IP Addresses supported private static final int ipAddressLimit = 64; // necessary for raising exceptions so that the connection pool can be notified private final SQLServerConnection conn; /** * Constructs a new SocketFinder object with appropriate traceId * * @param callerTraceID * traceID of the caller * @param sqlServerConnection * the SQLServer connection */ SocketFinder(String callerTraceID, SQLServerConnection sqlServerConnection) { traceID = "SocketFinder(" + callerTraceID + ")"; conn = sqlServerConnection; } /** * Used to find a socket to which a connection can be made * * @param hostName * @param portNumber * @param timeoutInMilliSeconds * @return connected socket * @throws IOException */ Socket findSocket(String hostName, int portNumber, int timeoutInMilliSeconds, boolean useParallel, boolean useTnir, boolean isTnirFirstAttempt, int timeoutInMilliSecondsForFullTimeout) throws SQLServerException { assert timeoutInMilliSeconds != 0 : "The driver does not allow a time out of 0"; try { InetAddress[] inetAddrs = null; // inetAddrs is only used if useParallel is true or TNIR is true. Skip resolving address if that's not the case. if (useParallel || useTnir) { // Ignore TNIR if host resolves to more than 64 IPs. Make sure we are using original timeout for this. inetAddrs = InetAddress.getAllByName(hostName); if ((useTnir) && (inetAddrs.length > ipAddressLimit)) { useTnir = false; timeoutInMilliSeconds = timeoutInMilliSecondsForFullTimeout; } } if (!useParallel) { // MSF is false. TNIR could be true or false. DBMirroring could be true or false. // For TNIR first attempt, we should do existing behavior including how host name is resolved. if (useTnir && isTnirFirstAttempt) { return getDefaultSocket(hostName, portNumber, SQLServerConnection.TnirFirstAttemptTimeoutMs); } else if (!useTnir) { return getDefaultSocket(hostName, portNumber, timeoutInMilliSeconds); } } // Code reaches here only if MSF = true or (TNIR = true and not TNIR first attempt) if (logger.isLoggable(Level.FINER)) { String loggingString = this.toString() + " Total no of InetAddresses: " + inetAddrs.length + ". They are: "; for (InetAddress inetAddr : inetAddrs) { loggingString = loggingString + inetAddr.toString() + ";"; } logger.finer(loggingString); } if (inetAddrs.length > ipAddressLimit) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ipAddressLimitWithMultiSubnetFailover")); Object[] msgArgs = {Integer.toString(ipAddressLimit)}; String errorStr = form.format(msgArgs); // we do not want any retry to happen here. So, terminate the connection // as the config is unsupported. conn.terminate(SQLServerException.DRIVER_ERROR_UNSUPPORTED_CONFIG, errorStr); } if (Util.isIBM()) { timeoutInMilliSeconds = Math.max(timeoutInMilliSeconds, minTimeoutForParallelConnections); if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + "Using Java NIO with timeout:" + timeoutInMilliSeconds); } findSocketUsingJavaNIO(inetAddrs, portNumber, timeoutInMilliSeconds); } else { LinkedList<Inet4Address> inet4Addrs = new LinkedList<Inet4Address>(); LinkedList<Inet6Address> inet6Addrs = new LinkedList<Inet6Address>(); for (InetAddress inetAddr : inetAddrs) { if (inetAddr instanceof Inet4Address) { inet4Addrs.add((Inet4Address) inetAddr); } else { assert inetAddr instanceof Inet6Address : "Unexpected IP address " + inetAddr.toString(); inet6Addrs.add((Inet6Address) inetAddr); } } // use half timeout only if both IPv4 and IPv6 addresses are present int timeoutForEachIPAddressType; if ((!inet4Addrs.isEmpty()) && (!inet6Addrs.isEmpty())) { timeoutForEachIPAddressType = Math.max(timeoutInMilliSeconds / 2, minTimeoutForParallelConnections); } else timeoutForEachIPAddressType = Math.max(timeoutInMilliSeconds, minTimeoutForParallelConnections); if (!inet4Addrs.isEmpty()) { if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + "Using Java NIO with timeout:" + timeoutForEachIPAddressType); } // inet4Addrs.toArray(new InetAddress[0]) is java style of converting a linked list to an array of reqd size findSocketUsingJavaNIO(inet4Addrs.toArray(new InetAddress[0]), portNumber, timeoutForEachIPAddressType); } if (!result.equals(Result.SUCCESS)) { // try threading logic if (!inet6Addrs.isEmpty()) { // do not start any threads if there is only one ipv6 address if (inet6Addrs.size() == 1) { return getConnectedSocket(inet6Addrs.get(0), portNumber, timeoutForEachIPAddressType); } if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + "Using Threading with timeout:" + timeoutForEachIPAddressType); } findSocketUsingThreading(inet6Addrs, portNumber, timeoutForEachIPAddressType); } } } // If the thread continued execution due to timeout, the result may not be known. // In that case, update the result to failure. Note that this case is possible // for both IPv4 and IPv6. // Using double-checked locking for performance reasons. if (result.equals(Result.UNKNOWN)) { synchronized (socketFinderlock) { if (result.equals(Result.UNKNOWN)) { result = Result.FAILURE; if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + " The parent thread updated the result to failure"); } } } } // After we reach this point, there is no need for synchronization any more. // Because, the result would be known(success/failure). // And no threads would update SocketFinder // as their function calls would now be no-ops. if (result.equals(Result.FAILURE)) { if (selectedException == null) { if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + " There is no selectedException. The wait calls timed out before any connect call returned or timed out."); } String message = SQLServerException.getErrString("R_connectionTimedOut"); selectedException = new IOException(message); } throw selectedException; } } catch (InterruptedException ex) { close(selectedSocket); SQLServerException.ConvertConnectExceptionToSQLServerException(hostName, portNumber, conn, ex); } catch (IOException ex) { close(selectedSocket); // The code below has been moved from connectHelper. // If we do not move it, the functions open(caller of findSocket) // and findSocket will have to // declare both IOException and SQLServerException in the throws clause // as we throw custom SQLServerExceptions(eg:IPAddressLimit, wrapping other exceptions // like interruptedException) in findSocket. // That would be a bit awkward, because connecthelper(the caller of open) // just wraps IOException into SQLServerException and throws SQLServerException. // Instead, it would be good to wrap all exceptions at one place - Right here, their origin. SQLServerException.ConvertConnectExceptionToSQLServerException(hostName, portNumber, conn, ex); } assert result.equals(Result.SUCCESS) == true; assert selectedSocket != null : "Bug in code. Selected Socket cannot be null here."; return selectedSocket; } /** * This function uses java NIO to connect to all the addresses in inetAddrs with in a specified timeout. If it succeeds in connecting, it closes * all the other open sockets and updates the result to success. * * @param inetAddrs * the array of inetAddress to which connection should be made * @param portNumber * the port number at which connection should be made * @param timeoutInMilliSeconds * @throws IOException */ private void findSocketUsingJavaNIO(InetAddress[] inetAddrs, int portNumber, int timeoutInMilliSeconds) throws IOException { // The driver does not allow a time out of zero. // Also, the unit of time the user can specify in the driver is seconds. // So, even if the user specifies 1 second(least value), the least possible // value that can come here as timeoutInMilliSeconds is 500 milliseconds. assert timeoutInMilliSeconds != 0 : "The timeout cannot be zero"; assert inetAddrs.length != 0 : "Number of inetAddresses should not be zero in this function"; Selector selector = null; LinkedList<SocketChannel> socketChannels = new LinkedList<SocketChannel>(); SocketChannel selectedChannel = null; try { selector = Selector.open(); for (int i = 0; i < inetAddrs.length; i++) { SocketChannel sChannel = SocketChannel.open(); socketChannels.add(sChannel); // make the channel non-blocking sChannel.configureBlocking(false); // register the channel for connect event int ops = SelectionKey.OP_CONNECT; SelectionKey key = sChannel.register(selector, ops); sChannel.connect(new InetSocketAddress(inetAddrs[i], portNumber)); if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + " initiated connection to address: " + inetAddrs[i] + ", portNumber: " + portNumber); } long timerNow = System.currentTimeMillis(); long timerExpire = timerNow + timeoutInMilliSeconds; // Denotes the no of channels that still need to processed int noOfOutstandingChannels = inetAddrs.length; while (true) { long timeRemaining = timerExpire - timerNow; // if the timeout expired or a channel is selected or there are no more channels left to processes if ((timeRemaining <= 0) || (selectedChannel != null) || (noOfOutstandingChannels <= 0)) break; // denotes the no of channels that are ready to be processed. i.e. they are either connected // or encountered an exception while trying to connect int readyChannels = selector.select(timeRemaining); if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + " no of channels ready: " + readyChannels); // There are no real time guarantees on the time out of the select API used above. // This check is necessary // a) to guard against cases where the select returns faster than expected. // b) for cases where no channels could connect with in the time out if (readyChannels != 0) { Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); SocketChannel ch = (SocketChannel) key.channel(); if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + " processing the channel :" + ch);// this traces the IP by default boolean connected = false; try { connected = ch.finishConnect(); // ch.finishConnect should either return true or throw an exception // as we have subscribed for OP_CONNECT. assert connected == true : "finishConnect on channel:" + ch + " cannot be false"; selectedChannel = ch; if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + " selected the channel :" + selectedChannel); break; } catch (IOException ex) { if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + " the exception: " + ex.getClass() + " with message: " + ex.getMessage() + " occured while processing the channel: " + ch); updateSelectedException(ex, this.toString()); // close the channel pro-actively so that we do not // hang on to network resources ch.close(); } // unregister the key and remove from the selector's selectedKeys key.cancel(); keyIterator.remove(); noOfOutstandingChannels } } timerNow = System.currentTimeMillis(); } } catch (IOException ex) { // in case of an exception, close the selected channel. // All other channels will be closed in the finally block, // as they need to be closed irrespective of a success/failure close(selectedChannel); throw ex; } finally { // close the selector // As per java docs, on selector.close(), any uncancelled keys still // associated with this // selector are invalidated, their channels are deregistered, and any other // resources associated with this selector are released. // So, its not necessary to cancel each key again close(selector); // Close all channels except the selected one. // As we close channels pro-actively in the try block, // its possible that we close a channel twice. // Closing a channel second time is a no-op. // This code is should be in the finally block to guard against cases where // we pre-maturely exit try block due to an exception in selector or other places. for (SocketChannel s : socketChannels) { if (s != selectedChannel) { close(s); } } } // if a channel was selected, make the necessary updates if (selectedChannel != null) { //the selectedChannel has the address that is connected successfully //convert it to a java.net.Socket object with the address SocketAddress iadd = selectedChannel.getRemoteAddress(); selectedSocket = new Socket(); selectedSocket.connect(iadd); result = Result.SUCCESS; //close the channel since it is not used anymore selectedChannel.close(); } } // This method contains the old logic of connecting to // a socket of one of the IPs corresponding to a given host name. // In the old code below, the logic around 0 timeout has been removed as // 0 timeout is not allowed. The code has been re-factored so that the logic // is common for hostName or InetAddress. private Socket getDefaultSocket(String hostName, int portNumber, int timeoutInMilliSeconds) throws IOException { // Open the socket, with or without a timeout, throwing an UnknownHostException // if there is a failure to resolve the host name to an InetSocketAddress. // Note that Socket(host, port) throws an UnknownHostException if the host name // cannot be resolved, but that InetSocketAddress(host, port) does not - it sets // the returned InetSocketAddress as unresolved. InetSocketAddress addr = new InetSocketAddress(hostName, portNumber); return getConnectedSocket(addr, timeoutInMilliSeconds); } private Socket getConnectedSocket(InetAddress inetAddr, int portNumber, int timeoutInMilliSeconds) throws IOException { InetSocketAddress addr = new InetSocketAddress(inetAddr, portNumber); return getConnectedSocket(addr, timeoutInMilliSeconds); } private Socket getConnectedSocket(InetSocketAddress addr, int timeoutInMilliSeconds) throws IOException { assert timeoutInMilliSeconds != 0 : "timeout cannot be zero"; if (addr.isUnresolved()) throw new java.net.UnknownHostException(); selectedSocket = new Socket(); selectedSocket.connect(addr, timeoutInMilliSeconds); return selectedSocket; } private void findSocketUsingThreading(LinkedList<Inet6Address> inetAddrs, int portNumber, int timeoutInMilliSeconds) throws IOException, InterruptedException { assert timeoutInMilliSeconds != 0 : "The timeout cannot be zero"; assert inetAddrs.isEmpty() == false : "Number of inetAddresses should not be zero in this function"; LinkedList<Socket> sockets = new LinkedList<Socket>(); LinkedList<SocketConnector> socketConnectors = new LinkedList<SocketConnector>(); try { // create a socket, inetSocketAddress and a corresponding socketConnector per inetAddress noOfSpawnedThreads = inetAddrs.size(); for (InetAddress inetAddress : inetAddrs) { Socket s = new Socket(); sockets.add(s); InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, portNumber); SocketConnector socketConnector = new SocketConnector(s, inetSocketAddress, timeoutInMilliSeconds, this); socketConnectors.add(socketConnector); } // acquire parent lock and spawn all threads synchronized (parentThreadLock) { for (SocketConnector sc : socketConnectors) { threadPoolExecutor.execute(sc); } long timerNow = System.currentTimeMillis(); long timerExpire = timerNow + timeoutInMilliSeconds; // The below loop is to guard against the spurious wake up problem while (true) { long timeRemaining = timerExpire - timerNow; if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + " TimeRemaining:" + timeRemaining + "; Result:" + result + "; Max. open thread count: " + threadPoolExecutor.getLargestPoolSize() + "; Current open thread count:" + threadPoolExecutor.getActiveCount()); } // if there is no time left or if the result is determined, break. // Note that a dirty read of result is totally fine here. // Since this thread holds the parentThreadLock, even if we do a dirty // read here, the child thread, after updating the result, would not be // able to call notify on the parentThreadLock // (and thus finish execution) as it would be waiting on parentThreadLock // held by this thread(the parent thread). // So, this thread will wait again and then be notified by the childThread. // On the other hand, if we try to take socketFinderLock here to avoid // dirty read, we would introduce a dead lock due to the // reverse order of locking in updateResult method. if (timeRemaining <= 0 || (!result.equals(Result.UNKNOWN))) break; parentThreadLock.wait(timeRemaining); if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + " The parent thread wokeup."); } timerNow = System.currentTimeMillis(); } } } finally { // Close all sockets except the selected one. // As we close sockets pro-actively in the child threads, // its possible that we close a socket twice. // Closing a socket second time is a no-op. // If a child thread is waiting on the connect call on a socket s, // closing the socket s here ensures that an exception is thrown // in the child thread immediately. This mitigates the problem // of thread explosion by ensuring that unnecessary threads die // quickly without waiting for "min(timeOut, 21)" seconds for (Socket s : sockets) { if (s != selectedSocket) { close(s); } } } } /** * search result */ Result getResult() { return result; } void close(Selector selector) { if (null != selector) { if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + ": Closing Selector"); try { selector.close(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, this.toString() + ": Ignored the following error while closing Selector", e); } } } void close(Socket socket) { if (null != socket) { if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + ": Closing TCP socket:" + socket); try { socket.close(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, this.toString() + ": Ignored the following error while closing socket", e); } } } void close(SocketChannel socketChannel) { if (null != socketChannel) { if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + ": Closing TCP socket channel:" + socketChannel); try { socketChannel.close(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, this.toString() + "Ignored the following error while closing socketChannel", e); } } } /** * Used by socketConnector threads to notify the socketFinder of their connection attempt result(a connected socket or exception). It updates the * result, socket and exception variables of socketFinder object. This method notifies the parent thread if a socket is found or if all the * spawned threads have notified. It also closes a socket if it is not selected for use by socketFinder. * * @param socket * the SocketConnector's socket * @param exception * Exception that occurred in socket connector thread * @param threadId * Id of the calling Thread for diagnosis */ void updateResult(Socket socket, IOException exception, String threadId) { if (result.equals(Result.UNKNOWN)) { if (logger.isLoggable(Level.FINER)) { logger.finer("The following child thread is waiting for socketFinderLock:" + threadId); } synchronized (socketFinderlock) { if (logger.isLoggable(Level.FINER)) { logger.finer("The following child thread acquired socketFinderLock:" + threadId); } if (result.equals(Result.UNKNOWN)) { // if the connection was successful and no socket has been // selected yet if (exception == null && selectedSocket == null) { selectedSocket = socket; result = Result.SUCCESS; if (logger.isLoggable(Level.FINER)) { logger.finer("The socket of the following thread has been chosen:" + threadId); } } // if an exception occurred if (exception != null) { updateSelectedException(exception, threadId); } } noOfThreadsThatNotified++; // if all threads notified, but the result is still unknown, // update the result to failure if ((noOfThreadsThatNotified >= noOfSpawnedThreads) && result.equals(Result.UNKNOWN)) { result = Result.FAILURE; } if (!result.equals(Result.UNKNOWN)) { // 1) Note that at any point of time, there is only one // thread(parent/child thread) competing for parentThreadLock. // 2) The only time where a child thread could be waiting on // parentThreadLock is before the wait call in the parentThread // 3) After the above happens, the parent thread waits to be // notified on parentThreadLock. After being notified, // it would be the ONLY thread competing for the lock. // for the following reasons // a) The parentThreadLock is taken while holding the socketFinderLock. // So, all child threads, except one, block on socketFinderLock // (not parentThreadLock) // b) After parentThreadLock is notified by a child thread, the result // would be known(Refer the double-checked locking done at the // start of this method). So, all child threads would exit // as no-ops and would never compete with parent thread // for acquiring parentThreadLock // 4) As the parent thread is the only thread that competes for the // parentThreadLock, it need not wait to acquire the lock once it wakes // up and gets scheduled. // This results in better performance as it would close unnecessary // sockets and thus help child threads die quickly. if (logger.isLoggable(Level.FINER)) { logger.finer("The following child thread is waiting for parentThreadLock:" + threadId); } synchronized (parentThreadLock) { if (logger.isLoggable(Level.FINER)) { logger.finer("The following child thread acquired parentThreadLock:" + threadId); } parentThreadLock.notify(); } if (logger.isLoggable(Level.FINER)) { logger.finer("The following child thread released parentThreadLock and notified the parent thread:" + threadId); } } } if (logger.isLoggable(Level.FINER)) { logger.finer("The following child thread released socketFinderLock:" + threadId); } } } /** * Updates the selectedException if * <p> * a) selectedException is null * <p> * b) ex is a non-socketTimeoutException and selectedException is a socketTimeoutException * <p> * If there are multiple exceptions, that are not related to socketTimeout the first non-socketTimeout exception is picked. If all exceptions are * related to socketTimeout, the first exception is picked. Note: This method is not thread safe. The caller should ensure thread safety. * * @param ex * the IOException * @param traceId * the traceId of the thread */ public void updateSelectedException(IOException ex, String traceId) { boolean updatedException = false; if (selectedException == null) { selectedException = ex; updatedException = true; } else if ((!(ex instanceof SocketTimeoutException)) && (selectedException instanceof SocketTimeoutException)) { selectedException = ex; updatedException = true; } if (updatedException) { if (logger.isLoggable(Level.FINER)) { logger.finer("The selected exception is updated to the following: ExceptionType:" + ex.getClass() + "; ExceptionMessage:" + ex.getMessage() + "; by the following thread:" + traceId); } } } /** * Used fof tracing * * @return traceID string */ public String toString() { return traceID; } } /** * This is used to connect a socket in a separate thread */ final class SocketConnector implements Runnable { // socket on which connection attempt would be made private final Socket socket; // the socketFinder associated with this connector private final SocketFinder socketFinder; // inetSocketAddress to connect to private final InetSocketAddress inetSocketAddress; // timeout in milliseconds private final int timeoutInMilliseconds; // Logging variables private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SocketConnector"); private final String traceID; // Id of the thread. used for diagnosis private final String threadID; // a counter used to give unique IDs to each connector thread. // this will have the id of the thread that was last created. private static long lastThreadID = 0; /** * Constructs a new SocketConnector object with the associated socket and socketFinder */ SocketConnector(Socket socket, InetSocketAddress inetSocketAddress, int timeOutInMilliSeconds, SocketFinder socketFinder) { this.socket = socket; this.inetSocketAddress = inetSocketAddress; this.timeoutInMilliseconds = timeOutInMilliSeconds; this.socketFinder = socketFinder; this.threadID = Long.toString(nextThreadID()); this.traceID = "SocketConnector:" + this.threadID + "(" + socketFinder.toString() + ")"; } /** * If search for socket has not finished, this function tries to connect a socket(with a timeout) synchronously. It further notifies the * socketFinder the result of the connection attempt */ public void run() { IOException exception = null; // Note that we do not need socketFinder lock here // as we update nothing in socketFinder based on the condition. // So, its perfectly fine to make a dirty read. SocketFinder.Result result = socketFinder.getResult(); if (result.equals(SocketFinder.Result.UNKNOWN)) { try { if (logger.isLoggable(Level.FINER)) { logger.finer( this.toString() + " connecting to InetSocketAddress:" + inetSocketAddress + " with timeout:" + timeoutInMilliseconds); } socket.connect(inetSocketAddress, timeoutInMilliseconds); } catch (IOException ex) { if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + " exception:" + ex.getClass() + " with message:" + ex.getMessage() + " occured while connecting to InetSocketAddress:" + inetSocketAddress); } exception = ex; } socketFinder.updateResult(socket, exception, this.toString()); } } /** * Used for tracing * * @return traceID string */ public String toString() { return traceID; } /** * Generates the next unique thread id. */ private static synchronized long nextThreadID() { if (lastThreadID == Long.MAX_VALUE) { if (logger.isLoggable(Level.FINER)) logger.finer("Resetting the Id count"); lastThreadID = 1; } else { lastThreadID++; } return lastThreadID; } } /** * TDSWriter implements the client to server TDS data pipe. */ final class TDSWriter { private static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Writer"); private final String traceID; final public String toString() { return traceID; } private final TDSChannel tdsChannel; private final SQLServerConnection con; // Flag to indicate whether data written via writeXXX() calls // is loggable. Data is normally loggable. But sensitive // data, such as user credentials, should never be logged for // security reasons. private boolean dataIsLoggable = true; void setDataLoggable(boolean value) { dataIsLoggable = value; } private TDSCommand command = null; // TDS message type (Query, RPC, DTC, etc.) sent at the beginning // of every TDS message header. Value is set when starting a new // TDS message of the specified type. private byte tdsMessageType; private volatile int sendResetConnection = 0; // Size (in bytes) of the TDS packets to/from the server. // This size is normally fixed for the life of the connection, // but it can change once after the logon packet because packet // size negotiation happens at logon time. private int currentPacketSize = 0; // Size of the TDS packet header, which is: // byte type // byte status // short length // short SPID // byte packet // byte window private final static int TDS_PACKET_HEADER_SIZE = 8; private final static byte[] placeholderHeader = new byte[TDS_PACKET_HEADER_SIZE]; // Intermediate array used to convert typically "small" values such as fixed-length types // (byte, int, long, etc.) and Strings from their native form to bytes for sending to // the channel buffers. private byte valueBytes[] = new byte[256]; // Monotonically increasing packet number associated with the current message private volatile int packetNum = 0; // Bytes for sending decimal/numeric data private final static int BYTES4 = 4; private final static int BYTES8 = 8; private final static int BYTES12 = 12; private final static int BYTES16 = 16; public final static int BIGDECIMAL_MAX_LENGTH = 0x11; // is set to true when EOM is sent for the current message. // Note that this variable will never be accessed from multiple threads // simultaneously and so it need not be volatile private boolean isEOMSent = false; boolean isEOMSent() { return isEOMSent; } // Packet data buffers private ByteBuffer stagingBuffer; private ByteBuffer socketBuffer; private ByteBuffer logBuffer; private CryptoMetadata cryptoMeta = null; TDSWriter(TDSChannel tdsChannel, SQLServerConnection con) { this.tdsChannel = tdsChannel; this.con = con; traceID = "TDSWriter@" + Integer.toHexString(hashCode()) + " (" + con.toString() + ")"; } // TDS message start/end operations void preparePacket() throws SQLServerException { if (tdsChannel.isLoggingPackets()) { Arrays.fill(logBuffer.array(), (byte) 0xFE); logBuffer.clear(); } // Write a placeholder packet header. This will be replaced // with the real packet header when the packet is flushed. writeBytes(placeholderHeader); } /** * Start a new TDS message. */ void writeMessageHeader() throws SQLServerException { // TDS 7.2 & later: // Include ALL_Headers/MARS header in message's first packet // Note: The PKT_BULK message does not nees this ALL_HEADERS if ((TDS.PKT_QUERY == tdsMessageType || TDS.PKT_DTC == tdsMessageType || TDS.PKT_RPC == tdsMessageType)) { boolean includeTraceHeader = false; int totalHeaderLength = TDS.MESSAGE_HEADER_LENGTH; if (TDS.PKT_QUERY == tdsMessageType || TDS.PKT_RPC == tdsMessageType) { if (con.isDenaliOrLater() && !ActivityCorrelator.getCurrent().IsSentToServer() && Util.IsActivityTraceOn()) { includeTraceHeader = true; totalHeaderLength += TDS.TRACE_HEADER_LENGTH; } } writeInt(totalHeaderLength); // allHeaders.TotalLength (DWORD) writeInt(TDS.MARS_HEADER_LENGTH); // MARS header length (DWORD) writeShort((short) 2); // allHeaders.HeaderType(MARS header) (USHORT) writeBytes(con.getTransactionDescriptor()); writeInt(1); // marsHeader.OutstandingRequestCount if (includeTraceHeader) { writeInt(TDS.TRACE_HEADER_LENGTH); // trace header length (DWORD) writeTraceHeaderData(); ActivityCorrelator.setCurrentActivityIdSentFlag(); // set the flag to indicate this ActivityId is sent } } } void writeTraceHeaderData() throws SQLServerException { ActivityId activityId = ActivityCorrelator.getCurrent(); final byte[] actIdByteArray = Util.asGuidByteArray(activityId.getId()); long seqNum = activityId.getSequence(); writeShort(TDS.HEADERTYPE_TRACE); // trace header type writeBytes(actIdByteArray, 0, actIdByteArray.length); // guid part of ActivityId writeInt((int) seqNum); // sequence number of ActivityId if (logger.isLoggable(Level.FINER)) logger.finer("Send Trace Header - ActivityID: " + activityId.toString()); } /** * Convenience method to prepare the TDS channel for writing and start a new TDS message. * * @param command * The TDS command * @param tdsMessageType * The TDS message type (PKT_QUERY, PKT_RPC, etc.) */ void startMessage(TDSCommand command, byte tdsMessageType) throws SQLServerException { this.command = command; this.tdsMessageType = tdsMessageType; this.packetNum = 0; this.isEOMSent = false; this.dataIsLoggable = true; // If the TDS packet size has changed since the last request // (which should really only happen after the login packet) // then allocate new buffers that are the correct size. int negotiatedPacketSize = con.getTDSPacketSize(); if (currentPacketSize != negotiatedPacketSize) { socketBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN); stagingBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN); logBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN); currentPacketSize = negotiatedPacketSize; } socketBuffer.position(socketBuffer.limit()); stagingBuffer.clear(); preparePacket(); writeMessageHeader(); } final void endMessage() throws SQLServerException { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Finishing TDS message"); writePacket(TDS.STATUS_BIT_EOM); } // If a complete request has not been sent to the server, // the client MUST send the next packet with both ignore bit (0x02) and EOM bit (0x01) // set in the status to cancel the request. final boolean ignoreMessage() throws SQLServerException { if (packetNum > 0) { assert !isEOMSent; if (logger.isLoggable(Level.FINER)) logger.finest(toString() + " Finishing TDS message by sending ignore bit and end of message"); writePacket(TDS.STATUS_BIT_EOM | TDS.STATUS_BIT_ATTENTION); return true; } return false; } final void resetPooledConnection() { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " resetPooledConnection"); sendResetConnection = TDS.STATUS_BIT_RESET_CONN; } // Primitive write operations void writeByte(byte value) throws SQLServerException { if (stagingBuffer.remaining() >= 1) { stagingBuffer.put(value); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.put(value); else logBuffer.position(logBuffer.position() + 1); } } else { valueBytes[0] = value; writeWrappedBytes(valueBytes, 1); } } void writeChar(char value) throws SQLServerException { if (stagingBuffer.remaining() >= 2) { stagingBuffer.putChar(value); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.putChar(value); else logBuffer.position(logBuffer.position() + 2); } } else { Util.writeShort((short) value, valueBytes, 0); writeWrappedBytes(valueBytes, 2); } } void writeShort(short value) throws SQLServerException { if (stagingBuffer.remaining() >= 2) { stagingBuffer.putShort(value); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.putShort(value); else logBuffer.position(logBuffer.position() + 2); } } else { Util.writeShort(value, valueBytes, 0); writeWrappedBytes(valueBytes, 2); } } void writeInt(int value) throws SQLServerException { if (stagingBuffer.remaining() >= 4) { stagingBuffer.putInt(value); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.putInt(value); else logBuffer.position(logBuffer.position() + 4); } } else { Util.writeInt(value, valueBytes, 0); writeWrappedBytes(valueBytes, 4); } } /** * Append a real value in the TDS stream. * * @param value * the data value */ void writeReal(Float value) throws SQLServerException { if (false) // stagingBuffer.remaining() >= 4) { stagingBuffer.putFloat(value); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.putFloat(value); else logBuffer.position(logBuffer.position() + 4); } } else { writeInt(Float.floatToRawIntBits(value.floatValue())); } } /** * Append a double value in the TDS stream. * * @param value * the data value */ void writeDouble(double value) throws SQLServerException { if (stagingBuffer.remaining() >= 8) { stagingBuffer.putDouble(value); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.putDouble(value); else logBuffer.position(logBuffer.position() + 8); } } else { long bits = Double.doubleToLongBits(value); long mask = 0xFF; int nShift = 0; for (int i = 0; i < 8; i++) { writeByte((byte) ((bits & mask) >> nShift)); nShift += 8; mask = mask << 8; } } } /** * Append a big decimal in the TDS stream. * * @param bigDecimalVal * the big decimal data value * @param srcJdbcType * the source JDBCType * @param precision * the precision of the data value */ void writeBigDecimal(BigDecimal bigDecimalVal, int srcJdbcType, int precision) throws SQLServerException { /* * Length including sign byte One 1-byte unsigned integer that represents the sign of the decimal value (0 => Negative, 1 => positive) One 4-, * 8-, 12-, or 16-byte signed integer that represents the decimal value multiplied by 10^scale. The maximum size of this integer is determined * based on p as follows: 4 bytes if 1 <= p <= 9. 8 bytes if 10 <= p <= 19. 12 bytes if 20 <= p <= 28. 16 bytes if 29 <= p <= 38. */ boolean isNegative = (bigDecimalVal.signum() < 0); BigInteger bi = bigDecimalVal.unscaledValue(); if (isNegative) bi = bi.negate(); if (9 >= precision) { writeByte((byte) (BYTES4 + 1)); writeByte((byte) (isNegative ? 0 : 1)); writeInt(bi.intValue()); } else if (19 >= precision) { writeByte((byte) (BYTES8 + 1)); writeByte((byte) (isNegative ? 0 : 1)); writeLong(bi.longValue()); } else { int bLength; if (28 >= precision) bLength = BYTES12; else bLength = BYTES16; writeByte((byte) (bLength + 1)); writeByte((byte) (isNegative ? 0 : 1)); // Get the bytes of the BigInteger value. It is in reverse order, with // most significant byte in 0-th element. We need to reverse it first before sending over TDS. byte[] unscaledBytes = bi.toByteArray(); if (unscaledBytes.length > bLength) { // If precession of input is greater than maximum allowed (p><= 38) throw Exception MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange")); Object[] msgArgs = {JDBCType.of(srcJdbcType)}; throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET, null); } // Byte array to hold all the reversed and padding bytes. byte[] bytes = new byte[bLength]; // We need to fill up the rest of the array with zeros, as unscaledBytes may have less bytes // than the required size for TDS. int remaining = bLength - unscaledBytes.length; // Reverse the bytes. int i, j; for (i = 0, j = unscaledBytes.length - 1; i < unscaledBytes.length;) bytes[i++] = unscaledBytes[j // Fill the rest of the array with zeros. for (; i < remaining; i++) bytes[i] = (byte) 0x00; writeBytes(bytes); } } void writeSmalldatetime(String value) throws SQLServerException { GregorianCalendar calendar = initializeCalender(TimeZone.getDefault()); long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT) java.sql.Timestamp timestampValue = java.sql.Timestamp.valueOf(value); utcMillis = timestampValue.getTime(); // Load the calendar with the desired value calendar.setTimeInMillis(utcMillis); // Number of days since the SQL Server Base Date (January 1, 1900) int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900); // Next, figure out the number of milliseconds since midnight of the current day. int millisSinceMidnight = 1000 * calendar.get(Calendar.SECOND) + // Seconds into the current minute 60 * 1000 * calendar.get(Calendar.MINUTE) + // Minutes into the current hour 60 * 60 * 1000 * calendar.get(Calendar.HOUR_OF_DAY); // Hours into the current day // The last millisecond of the current day is always rounded to the first millisecond // of the next day because DATETIME is only accurate to 1/300th of a second. if (1000 * 60 * 60 * 24 - 1 <= millisSinceMidnight) { ++daysSinceSQLBaseDate; millisSinceMidnight = 0; } // Number of days since the SQL Server Base Date (January 1, 1900) writeShort((short) daysSinceSQLBaseDate); int secondsSinceMidnight = (millisSinceMidnight / 1000); int minutesSinceMidnight = (secondsSinceMidnight / 60); // Values that are 29.998 seconds or less are rounded down to the nearest minute minutesSinceMidnight = ((secondsSinceMidnight % 60) > 29.998) ? minutesSinceMidnight + 1 : minutesSinceMidnight; // Minutes since midnight writeShort((short) minutesSinceMidnight); } void writeDatetime(String value) throws SQLServerException { GregorianCalendar calendar = initializeCalender(TimeZone.getDefault()); long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT) int subSecondNanos = 0; java.sql.Timestamp timestampValue = java.sql.Timestamp.valueOf(value); utcMillis = timestampValue.getTime(); subSecondNanos = timestampValue.getNanos(); // Load the calendar with the desired value calendar.setTimeInMillis(utcMillis); // Number of days there have been since the SQL Base Date. // These are based on SQL Server algorithms int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900); // Number of milliseconds since midnight of the current day. int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second 1000 * calendar.get(Calendar.SECOND) + // Seconds into the current minute 60 * 1000 * calendar.get(Calendar.MINUTE) + // Minutes into the current hour 60 * 60 * 1000 * calendar.get(Calendar.HOUR_OF_DAY); // Hours into the current day // The last millisecond of the current day is always rounded to the first millisecond // of the next day because DATETIME is only accurate to 1/300th of a second. if (1000 * 60 * 60 * 24 - 1 <= millisSinceMidnight) { ++daysSinceSQLBaseDate; millisSinceMidnight = 0; } // Last-ditch verification that the value is in the valid range for the // DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then // throw an exception now so that statement execution is safely canceled. // Attempting to put an invalid value on the wire would result in a TDS // exception, which would close the connection. // These are based on SQL Server algorithms if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900) || daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange")); Object[] msgArgs = {SSType.DATETIME}; throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null); } // Number of days since the SQL Server Base Date (January 1, 1900) writeInt(daysSinceSQLBaseDate); // Milliseconds since midnight (at a resolution of three hundredths of a second) writeInt((3 * millisSinceMidnight + 5) / 10); } void writeDate(String value) throws SQLServerException { GregorianCalendar calendar = initializeCalender(TimeZone.getDefault()); long utcMillis = 0; java.sql.Date dateValue = java.sql.Date.valueOf(value); utcMillis = dateValue.getTime(); // Load the calendar with the desired value calendar.setTimeInMillis(utcMillis); writeScaledTemporal(calendar, 0, // subsecond nanos (none for a date value) 0, // scale (dates are not scaled) SSType.DATE); } void writeTime(java.sql.Timestamp value, int scale) throws SQLServerException { GregorianCalendar calendar = initializeCalender(TimeZone.getDefault()); long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT) int subSecondNanos = 0; utcMillis = value.getTime(); subSecondNanos = value.getNanos(); // Load the calendar with the desired value calendar.setTimeInMillis(utcMillis); writeScaledTemporal(calendar, subSecondNanos, scale, SSType.TIME); } void writeDateTimeOffset(Object value, int scale, SSType destSSType) throws SQLServerException { GregorianCalendar calendar = null; TimeZone timeZone = TimeZone.getDefault(); // Time zone to associate with the value in the Gregorian calendar long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT) int subSecondNanos = 0; int minutesOffset = 0; microsoft.sql.DateTimeOffset dtoValue = (microsoft.sql.DateTimeOffset) value; utcMillis = dtoValue.getTimestamp().getTime(); subSecondNanos = dtoValue.getTimestamp().getNanos(); minutesOffset = dtoValue.getMinutesOffset(); // If the target data type is DATETIMEOFFSET, then use UTC for the calendar that // will hold the value, since writeRPCDateTimeOffset expects a UTC calendar. // Otherwise, when converting from DATETIMEOFFSET to other temporal data types, // use a local time zone determined by the minutes offset of the value, since // the writers for those types expect local calendars. timeZone = (SSType.DATETIMEOFFSET == destSSType) ? UTC.timeZone : new SimpleTimeZone(minutesOffset * 60 * 1000, ""); calendar = new GregorianCalendar(timeZone, Locale.US); calendar.setLenient(true); calendar.clear(); calendar.setTimeInMillis(utcMillis); writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET); writeShort((short) minutesOffset); } void writeOffsetDateTimeWithTimezone(OffsetDateTime offsetDateTimeValue, int scale) throws SQLServerException { GregorianCalendar calendar = null; TimeZone timeZone; long utcMillis = 0; int subSecondNanos = 0; int minutesOffset = 0; try { // offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes // components. So the result of the division will be an integer always. SQL Server also supports // offsets in minutes precision. minutesOffset = offsetDateTimeValue.getOffset().getTotalSeconds() / 60; } catch (Exception e) { throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState is null as this error is generated in // the driver 0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor null); } subSecondNanos = offsetDateTimeValue.getNano(); // writeScaledTemporal() expects subSecondNanos in 9 digits precssion // but getNano() used in OffsetDateTime returns precession based on nanoseconds read from csv // padding zeros to match the expectation of writeScaledTemporal() int padding = 9 - String.valueOf(subSecondNanos).length(); while (padding > 0) { subSecondNanos = subSecondNanos * 10; padding } // For TIME_WITH_TIMEZONE, use UTC for the calendar that will hold the value timeZone = UTC.timeZone; // The behavior is similar to microsoft.sql.DateTimeOffset // In Timestamp format, only YEAR needs to have 4 digits. The leading zeros for the rest of the fields can be omitted. String offDateTimeStr = String.format("%04d", offsetDateTimeValue.getYear()) + '-' + offsetDateTimeValue.getMonthValue() + '-' + offsetDateTimeValue.getDayOfMonth() + ' ' + offsetDateTimeValue.getHour() + ':' + offsetDateTimeValue.getMinute() + ':' + offsetDateTimeValue.getSecond(); utcMillis = Timestamp.valueOf(offDateTimeStr).getTime(); calendar = initializeCalender(timeZone); calendar.setTimeInMillis(utcMillis); // Local timezone value in minutes int minuteAdjustment = ((TimeZone.getDefault().getRawOffset()) / (60 * 1000)); // check if date is in day light savings and add daylight saving minutes if (TimeZone.getDefault().inDaylightTime(calendar.getTime())) minuteAdjustment += (TimeZone.getDefault().getDSTSavings()) / (60 * 1000); // If the local time is negative then positive minutesOffset must be subtracted from calender minuteAdjustment += (minuteAdjustment < 0) ? (minutesOffset * (-1)) : minutesOffset; calendar.add(Calendar.MINUTE, minuteAdjustment); writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET); writeShort((short) minutesOffset); } void writeOffsetTimeWithTimezone(OffsetTime offsetTimeValue, int scale) throws SQLServerException { GregorianCalendar calendar = null; TimeZone timeZone; long utcMillis = 0; int subSecondNanos = 0; int minutesOffset = 0; try { // offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes // components. So the result of the division will be an integer always. SQL Server also supports // offsets in minutes precision. minutesOffset = offsetTimeValue.getOffset().getTotalSeconds() / 60; } catch (Exception e) { throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState is null as this error is generated in // the driver 0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor null); } subSecondNanos = offsetTimeValue.getNano(); // writeScaledTemporal() expects subSecondNanos in 9 digits precssion // but getNano() used in OffsetDateTime returns precession based on nanoseconds read from csv // padding zeros to match the expectation of writeScaledTemporal() int padding = 9 - String.valueOf(subSecondNanos).length(); while (padding > 0) { subSecondNanos = subSecondNanos * 10; padding } // For TIME_WITH_TIMEZONE, use UTC for the calendar that will hold the value timeZone = UTC.timeZone; // Using TDS.BASE_YEAR_1900, based on SQL server behavious // If date only contains a time part, the return value is 1900, the base year. // In Timestamp format, leading zeros for the fields can be omitted. String offsetTimeStr = TDS.BASE_YEAR_1900 + "-01-01" + ' ' + offsetTimeValue.getHour() + ':' + offsetTimeValue.getMinute() + ':' + offsetTimeValue.getSecond(); utcMillis = Timestamp.valueOf(offsetTimeStr).getTime(); calendar = initializeCalender(timeZone); calendar.setTimeInMillis(utcMillis); int minuteAdjustment = (TimeZone.getDefault().getRawOffset()) / (60 * 1000); // check if date is in day light savings and add daylight saving minutes to Local timezone(in minutes) if (TimeZone.getDefault().inDaylightTime(calendar.getTime())) minuteAdjustment += ((TimeZone.getDefault().getDSTSavings()) / (60 * 1000)); // If the local time is negative then positive minutesOffset must be subtracted from calender minuteAdjustment += (minuteAdjustment < 0) ? (minutesOffset * (-1)) : minutesOffset; calendar.add(Calendar.MINUTE, minuteAdjustment); writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET); writeShort((short) minutesOffset); } void writeLong(long value) throws SQLServerException { if (stagingBuffer.remaining() >= 8) { stagingBuffer.putLong(value); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.putLong(value); else logBuffer.position(logBuffer.position() + 8); } } else { valueBytes[0] = (byte) ((value >> 0) & 0xFF); valueBytes[1] = (byte) ((value >> 8) & 0xFF); valueBytes[2] = (byte) ((value >> 16) & 0xFF); valueBytes[3] = (byte) ((value >> 24) & 0xFF); valueBytes[4] = (byte) ((value >> 32) & 0xFF); valueBytes[5] = (byte) ((value >> 40) & 0xFF); valueBytes[6] = (byte) ((value >> 48) & 0xFF); valueBytes[7] = (byte) ((value >> 56) & 0xFF); writeWrappedBytes(valueBytes, 8); } } void writeBytes(byte[] value) throws SQLServerException { writeBytes(value, 0, value.length); } void writeBytes(byte[] value, int offset, int length) throws SQLServerException { assert length <= value.length; int bytesWritten = 0; int bytesToWrite; if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Writing " + length + " bytes"); while ((bytesToWrite = length - bytesWritten) > 0) { if (0 == stagingBuffer.remaining()) writePacket(TDS.STATUS_NORMAL); if (bytesToWrite > stagingBuffer.remaining()) bytesToWrite = stagingBuffer.remaining(); stagingBuffer.put(value, offset + bytesWritten, bytesToWrite); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.put(value, offset + bytesWritten, bytesToWrite); else logBuffer.position(logBuffer.position() + bytesToWrite); } bytesWritten += bytesToWrite; } } void writeWrappedBytes(byte value[], int valueLength) throws SQLServerException { // This function should only be used to write a value that is longer than // what remains in the current staging buffer. However, the value must // be short enough to fit in an empty buffer. assert valueLength <= value.length; assert stagingBuffer.remaining() < valueLength; assert valueLength <= stagingBuffer.capacity(); // Fill any remaining space in the staging buffer int remaining = stagingBuffer.remaining(); if (remaining > 0) { stagingBuffer.put(value, 0, remaining); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.put(value, 0, remaining); else logBuffer.position(logBuffer.position() + remaining); } } writePacket(TDS.STATUS_NORMAL); // After swapping, the staging buffer should once again be empty, so the // remainder of the value can be written to it. stagingBuffer.put(value, remaining, valueLength - remaining); if (tdsChannel.isLoggingPackets()) { if (dataIsLoggable) logBuffer.put(value, remaining, valueLength - remaining); else logBuffer.position(logBuffer.position() + remaining); } } void writeString(String value) throws SQLServerException { int charsCopied = 0; int length = value.length(); while (charsCopied < length) { int bytesToCopy = 2 * (length - charsCopied); if (bytesToCopy > valueBytes.length) bytesToCopy = valueBytes.length; int bytesCopied = 0; while (bytesCopied < bytesToCopy) { char ch = value.charAt(charsCopied++); valueBytes[bytesCopied++] = (byte) ((ch >> 0) & 0xFF); valueBytes[bytesCopied++] = (byte) ((ch >> 8) & 0xFF); } writeBytes(valueBytes, 0, bytesCopied); } } void writeStream(InputStream inputStream, long advertisedLength, boolean writeChunkSizes) throws SQLServerException { assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0; long actualLength = 0; final byte[] streamByteBuffer = new byte[4 * currentPacketSize]; int bytesRead = 0; int bytesToWrite; do { // Read in next chunk for (bytesToWrite = 0; -1 != bytesRead && bytesToWrite < streamByteBuffer.length; bytesToWrite += bytesRead) { try { bytesRead = inputStream.read(streamByteBuffer, bytesToWrite, streamByteBuffer.length - bytesToWrite); } catch (IOException e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream")); Object[] msgArgs = {e.toString()}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET); } if (-1 == bytesRead) break; // Check for invalid bytesRead returned from InputStream.read if (bytesRead < 0 || bytesRead > streamByteBuffer.length - bytesToWrite) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream")); Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET); } } // Write it out if (writeChunkSizes) writeInt(bytesToWrite); writeBytes(streamByteBuffer, 0, bytesToWrite); actualLength += bytesToWrite; } while (-1 != bytesRead || bytesToWrite > 0); // If we were given an input stream length that we had to match and // the actual stream length did not match then cancel the request. if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength")); Object[] msgArgs = {Long.valueOf(advertisedLength), Long.valueOf(actualLength)}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET); } } /* * Adding another function for writing non-unicode reader instead of re-factoring the writeReader() for performance efficiency. As this method * will only be used in bulk copy, it needs to be efficient. Note: Any changes in algorithm/logic should propagate to both writeReader() and * writeNonUnicodeReader(). */ void writeNonUnicodeReader(Reader reader, long advertisedLength, boolean isDestBinary, Charset charSet) throws SQLServerException { assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0; long actualLength = 0; char[] streamCharBuffer = new char[currentPacketSize]; // The unicode version, writeReader() allocates a byte buffer that is 4 times the currentPacketSize, not sure why. byte[] streamByteBuffer = new byte[currentPacketSize]; int charsRead = 0; int charsToWrite; int bytesToWrite; String streamString; do { // Read in next chunk for (charsToWrite = 0; -1 != charsRead && charsToWrite < streamCharBuffer.length; charsToWrite += charsRead) { try { charsRead = reader.read(streamCharBuffer, charsToWrite, streamCharBuffer.length - charsToWrite); } catch (IOException e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream")); Object[] msgArgs = {e.toString()}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET); } if (-1 == charsRead) break; // Check for invalid bytesRead returned from Reader.read if (charsRead < 0 || charsRead > streamCharBuffer.length - charsToWrite) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream")); Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET); } } if (!isDestBinary) { // Write it out // This also writes the PLP_TERMINATOR token after all the data in the the stream are sent. // The Do-While loop goes on one more time as charsToWrite is greater than 0 for the last chunk, and // in this last round the only thing that is written is an int value of 0, which is the PLP Terminator token(0x00000000). writeInt(charsToWrite); for (int charsCopied = 0; charsCopied < charsToWrite; ++charsCopied) { if (null == charSet) { streamByteBuffer[charsCopied] = (byte) (streamCharBuffer[charsCopied] & 0xFF); } else { // encoding as per collation streamByteBuffer[charsCopied] = new String(streamCharBuffer[charsCopied] + "").getBytes(charSet)[0]; } } writeBytes(streamByteBuffer, 0, charsToWrite); } else { bytesToWrite = charsToWrite; if (0 != charsToWrite) bytesToWrite = charsToWrite / 2; streamString = new String(streamCharBuffer); byte[] bytes = ParameterUtils.HexToBin(streamString.trim()); writeInt(bytesToWrite); writeBytes(bytes, 0, bytesToWrite); } actualLength += charsToWrite; } while (-1 != charsRead || charsToWrite > 0); // If we were given an input stream length that we had to match and // the actual stream length did not match then cancel the request. if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength")); Object[] msgArgs = {Long.valueOf(advertisedLength), Long.valueOf(actualLength)}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET); } } /* * Note: There is another method with same code logic for non unicode reader, writeNonUnicodeReader(), implemented for performance efficiency. Any * changes in algorithm/logic should propagate to both writeReader() and writeNonUnicodeReader(). */ void writeReader(Reader reader, long advertisedLength, boolean writeChunkSizes) throws SQLServerException { assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0; long actualLength = 0; char[] streamCharBuffer = new char[2 * currentPacketSize]; byte[] streamByteBuffer = new byte[4 * currentPacketSize]; int charsRead = 0; int charsToWrite; do { // Read in next chunk for (charsToWrite = 0; -1 != charsRead && charsToWrite < streamCharBuffer.length; charsToWrite += charsRead) { try { charsRead = reader.read(streamCharBuffer, charsToWrite, streamCharBuffer.length - charsToWrite); } catch (IOException e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream")); Object[] msgArgs = {e.toString()}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET); } if (-1 == charsRead) break; // Check for invalid bytesRead returned from Reader.read if (charsRead < 0 || charsRead > streamCharBuffer.length - charsToWrite) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream")); Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET); } } // Write it out if (writeChunkSizes) writeInt(2 * charsToWrite); // Convert from Unicode characters to bytes // Note: The following inlined code is much faster than the equivalent // call to (new String(streamCharBuffer)).getBytes("UTF-16LE") because it // saves a conversion to String and use of Charset in that conversion. for (int charsCopied = 0; charsCopied < charsToWrite; ++charsCopied) { streamByteBuffer[2 * charsCopied] = (byte) ((streamCharBuffer[charsCopied] >> 0) & 0xFF); streamByteBuffer[2 * charsCopied + 1] = (byte) ((streamCharBuffer[charsCopied] >> 8) & 0xFF); } writeBytes(streamByteBuffer, 0, 2 * charsToWrite); actualLength += charsToWrite; } while (-1 != charsRead || charsToWrite > 0); // If we were given an input stream length that we had to match and // the actual stream length did not match then cancel the request. if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength")); Object[] msgArgs = {Long.valueOf(advertisedLength), Long.valueOf(actualLength)}; error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET); } } GregorianCalendar initializeCalender(TimeZone timeZone) { GregorianCalendar calendar = null; // Create the calendar that will hold the value. For DateTimeOffset values, the calendar's // time zone is UTC. For other values, the calendar's time zone is a local time zone. calendar = new GregorianCalendar(timeZone, Locale.US); // Set the calendar lenient to allow setting the DAY_OF_YEAR and MILLISECOND fields // to roll other fields to their correct values. calendar.setLenient(true); // Clear the calendar of any existing state. The state of a new Calendar object always // reflects the current date, time, DST offset, etc. calendar.clear(); return calendar; } final void error(String reason, SQLState sqlState, DriverError driverError) throws SQLServerException { assert null != command; command.interrupt(reason); throw new SQLServerException(reason, sqlState, driverError, null); } /** * Sends an attention signal to the server, if necessary, to tell it to stop processing the current command on this connection. * * If no packets of the command's request have yet been sent to the server, then no attention signal needs to be sent. The interrupt will be * handled entirely by the driver. * * This method does not need synchronization as it does not manipulate interrupt state and writing is guaranteed to occur only from one thread at * a time. */ final boolean sendAttention() throws SQLServerException { // If any request packets were already written to the server then send an // attention signal to the server to tell it to ignore the request or // cancel its execution. if (packetNum > 0) { // Ideally, we would want to add the following assert here. // But to add that the variable isEOMSent would have to be made // volatile as this piece of code would be reached from multiple // threads. So, not doing it to avoid perf hit. Note that // isEOMSent would be updated in writePacket everytime an EOM is sent // assert isEOMSent; if (logger.isLoggable(Level.FINE)) logger.fine(this + ": sending attention..."); ++tdsChannel.numMsgsSent; startMessage(command, TDS.PKT_CANCEL_REQ); endMessage(); return true; } return false; } private void writePacket(int tdsMessageStatus) throws SQLServerException { final boolean atEOM = (TDS.STATUS_BIT_EOM == (TDS.STATUS_BIT_EOM & tdsMessageStatus)); final boolean isCancelled = ((TDS.PKT_CANCEL_REQ == tdsMessageType) || ((tdsMessageStatus & TDS.STATUS_BIT_ATTENTION) == TDS.STATUS_BIT_ATTENTION)); // Before writing each packet to the channel, check if an interrupt has occurred. if (null != command && (!isCancelled)) command.checkForInterrupt(); writePacketHeader(tdsMessageStatus | sendResetConnection); sendResetConnection = 0; flush(atEOM); // If this is the last packet then flush the remainder of the request // through the socket. The first flush() call ensured that data currently // waiting in the socket buffer was sent, flipped the buffers, and started // sending data from the staging buffer (flipped to be the new socket buffer). // This flush() call ensures that all remaining data in the socket buffer is sent. if (atEOM) { flush(atEOM); isEOMSent = true; ++tdsChannel.numMsgsSent; } // If we just sent the first login request packet and SSL encryption was enabled // for login only, then disable SSL now. if (TDS.PKT_LOGON70 == tdsMessageType && 1 == packetNum && TDS.ENCRYPT_OFF == con.getNegotiatedEncryptionLevel()) { tdsChannel.disableSSL(); } // Notify the currently associated command (if any) that we have written the last // of the response packets to the channel. if (null != command && (!isCancelled) && atEOM) command.onRequestComplete(); } private void writePacketHeader(int tdsMessageStatus) { int tdsMessageLength = stagingBuffer.position(); ++packetNum; // Write the TDS packet header back at the start of the staging buffer stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_TYPE, tdsMessageType); stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_STATUS, (byte) tdsMessageStatus); stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH, (byte) ((tdsMessageLength >> 8) & 0xFF)); // Note: message length is 16 bits, stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH + 1, (byte) ((tdsMessageLength >> 0) & 0xFF)); // written BIG ENDIAN stagingBuffer.put(TDS.PACKET_HEADER_SPID, (byte) ((tdsChannel.getSPID() >> 8) & 0xFF)); // Note: SPID is 16 bits, stagingBuffer.put(TDS.PACKET_HEADER_SPID + 1, (byte) ((tdsChannel.getSPID() >> 0) & 0xFF)); // written BIG ENDIAN stagingBuffer.put(TDS.PACKET_HEADER_SEQUENCE_NUM, (byte) (packetNum % 256)); stagingBuffer.put(TDS.PACKET_HEADER_WINDOW, (byte) 0); // Window (Reserved/Not used) // Write the header to the log buffer too if logging. if (tdsChannel.isLoggingPackets()) { logBuffer.put(TDS.PACKET_HEADER_MESSAGE_TYPE, tdsMessageType); logBuffer.put(TDS.PACKET_HEADER_MESSAGE_STATUS, (byte) tdsMessageStatus); logBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH, (byte) ((tdsMessageLength >> 8) & 0xFF)); // Note: message length is 16 bits, logBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH + 1, (byte) ((tdsMessageLength >> 0) & 0xFF)); // written BIG ENDIAN logBuffer.put(TDS.PACKET_HEADER_SPID, (byte) ((tdsChannel.getSPID() >> 8) & 0xFF)); // Note: SPID is 16 bits, logBuffer.put(TDS.PACKET_HEADER_SPID + 1, (byte) ((tdsChannel.getSPID() >> 0) & 0xFF)); // written BIG ENDIAN logBuffer.put(TDS.PACKET_HEADER_SEQUENCE_NUM, (byte) (packetNum % 256)); logBuffer.put(TDS.PACKET_HEADER_WINDOW, (byte) 0); // Window (Reserved/Not used); } } void flush(boolean atEOM) throws SQLServerException { // First, flush any data left in the socket buffer. tdsChannel.write(socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining()); socketBuffer.position(socketBuffer.limit()); // If there is data in the staging buffer that needs to be written // to the socket, the socket buffer is now empty, so swap buffers // and start writing data from the staging buffer. if (stagingBuffer.position() >= TDS_PACKET_HEADER_SIZE) { // Swap the packet buffers ... ByteBuffer swapBuffer = stagingBuffer; stagingBuffer = socketBuffer; socketBuffer = swapBuffer; // ... and prepare to send data from the from the new socket // buffer (the old staging buffer). // We need to use flip() rather than rewind() here so that // the socket buffer's limit is properly set for the last // packet, which may be shorter than the other packets. socketBuffer.flip(); stagingBuffer.clear(); // If we are logging TDS packets then log the packet we're about // to send over the wire now. if (tdsChannel.isLoggingPackets()) { tdsChannel.logPacket(logBuffer.array(), 0, socketBuffer.limit(), this.toString() + " sending packet (" + socketBuffer.limit() + " bytes)"); } // Prepare for the next packet if (!atEOM) preparePacket(); // Finally, start sending data from the new socket buffer. tdsChannel.write(socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining()); socketBuffer.position(socketBuffer.limit()); } } // Composite write operations /** * Write out elements common to all RPC values. * * @param sName * the optional parameter name * @param bOut * boolean true if the value that follows is being registered as an ouput parameter * @param tdsType * TDS type of the value that follows */ void writeRPCNameValType(String sName, boolean bOut, TDSType tdsType) throws SQLServerException { int nNameLen = 0; if (null != sName) nNameLen = sName.length() + 1; // The @ prefix is required for the param writeByte((byte) nNameLen); // param name len if (nNameLen > 0) { writeChar('@'); writeString(sName); } if (null != cryptoMeta) writeByte((byte) (bOut ? 1 | TDS.AE_METADATA : 0 | TDS.AE_METADATA)); // status else writeByte((byte) (bOut ? 1 : 0)); // status writeByte(tdsType.byteValue()); // type } /** * Append a boolean value in RPC transmission format. * * @param sName * the optional parameter name * @param booleanValue * the data value * @param bOut * boolean true if the data value is being registered as an ouput parameter */ void writeRPCBit(String sName, Boolean booleanValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.BITN); writeByte((byte) 1); // max length of datatype if (null == booleanValue) { writeByte((byte) 0); // len of data bytes } else { writeByte((byte) 1); // length of datatype writeByte((byte) (booleanValue.booleanValue() ? 1 : 0)); } } /** * Append a short value in RPC transmission format. * * @param sName * the optional parameter name * @param shortValue * the data value * @param bOut * boolean true if the data value is being registered as an ouput parameter */ void writeRPCByte(String sName, Byte byteValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.INTN); writeByte((byte) 1); // max length of datatype if (null == byteValue) { writeByte((byte) 0); // len of data bytes } else { writeByte((byte) 1); // length of datatype writeByte(byteValue.byteValue()); } } /** * Append a short value in RPC transmission format. * * @param sName * the optional parameter name * @param shortValue * the data value * @param bOut * boolean true if the data value is being registered as an ouput parameter */ void writeRPCShort(String sName, Short shortValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.INTN); writeByte((byte) 2); // max length of datatype if (null == shortValue) { writeByte((byte) 0); // len of data bytes } else { writeByte((byte) 2); // length of datatype writeShort(shortValue.shortValue()); } } /** * Append an int value in RPC transmission format. * * @param sName * the optional parameter name * @param intValue * the data value * @param bOut * boolean true if the data value is being registered as an ouput parameter */ void writeRPCInt(String sName, Integer intValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.INTN); writeByte((byte) 4); // max length of datatype if (null == intValue) { writeByte((byte) 0); // len of data bytes } else { writeByte((byte) 4); // length of datatype writeInt(intValue.intValue()); } } /** * Append a long value in RPC transmission format. * * @param sName * the optional parameter name * @param longValue * the data value * @param bOut * boolean true if the data value is being registered as an ouput parameter */ void writeRPCLong(String sName, Long longValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.INTN); writeByte((byte) 8); // max length of datatype if (null == longValue) { writeByte((byte) 0); // len of data bytes } else { writeByte((byte) 8); // length of datatype writeLong(longValue.longValue()); } } /** * Append a real value in RPC transmission format. * * @param sName * the optional parameter name * @param floatValue * the data value * @param bOut * boolean true if the data value is being registered as an ouput parameter */ void writeRPCReal(String sName, Float floatValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.FLOATN); // Data and length if (null == floatValue) { writeByte((byte) 4); // max length writeByte((byte) 0); // actual length (0 == null) } else { writeByte((byte) 4); // max length writeByte((byte) 4); // actual length writeInt(Float.floatToRawIntBits(floatValue.floatValue())); } } /** * Append a double value in RPC transmission format. * * @param sName * the optional parameter name * @param doubleValue * the data value * @param bOut * boolean true if the data value is being registered as an ouput parameter */ void writeRPCDouble(String sName, Double doubleValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.FLOATN); int l = 8; writeByte((byte) l); // max length of datatype // Data and length if (null == doubleValue) { writeByte((byte) 0); // len of data bytes } else { writeByte((byte) l); // len of data bytes long bits = Double.doubleToLongBits(doubleValue.doubleValue()); long mask = 0xFF; int nShift = 0; for (int i = 0; i < 8; i++) { writeByte((byte) ((bits & mask) >> nShift)); nShift += 8; mask = mask << 8; } } } /** * Append a big decimal in RPC transmission format. * * @param sName * the optional parameter name * @param bdValue * the data value * @param nScale * the desired scale * @param bOut * boolean true if the data value is being registered as an ouput parameter */ void writeRPCBigDecimal(String sName, BigDecimal bdValue, int nScale, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.DECIMALN); writeByte((byte) 0x11); // maximum length writeByte((byte) SQLServerConnection.maxDecimalPrecision); // precision byte[] valueBytes = DDC.convertBigDecimalToBytes(bdValue, nScale); writeBytes(valueBytes, 0, valueBytes.length); } /** * Appends a standard v*max header for RPC parameter transmission. * * @param headerLength * the total length of the PLP data block. * @param isNull * true if the value is NULL. * @param collation * The SQL collation associated with the value that follows the v*max header. Null for non-textual types. */ void writeVMaxHeader(long headerLength, boolean isNull, SQLCollation collation) throws SQLServerException { // Send v*max length indicator 0xFFFF. writeShort((short) 0xFFFF); // Send collation if requested. if (null != collation) collation.writeCollation(this); // Handle null here and return, we're done here if it's null. if (isNull) { // Null header for v*max types is 0xFFFFFFFFFFFFFFFF. writeLong(0xFFFFFFFFFFFFFFFFL); } else if (DataTypes.UNKNOWN_STREAM_LENGTH == headerLength) { // Append v*max length. // UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE writeLong(0xFFFFFFFFFFFFFFFEL); // NOTE: Don't send the first chunk length, this will be calculated by caller. } else { // For v*max types with known length, length is <totallength8><chunklength4> // We're sending same total length as chunk length (as we're sending 1 chunk). writeLong(headerLength); } } /** * Utility for internal writeRPCString calls */ void writeRPCStringUnicode(String sValue) throws SQLServerException { writeRPCStringUnicode(null, sValue, false, null); } /** * Writes a string value as Unicode for RPC * * @param sName * the optional parameter name * @param sValue * the data value * @param bOut * boolean true if the data value is being registered as an ouput parameter * @param collation * the collation of the data value */ void writeRPCStringUnicode(String sName, String sValue, boolean bOut, SQLCollation collation) throws SQLServerException { boolean bValueNull = (sValue == null); int nValueLen = bValueNull ? 0 : (2 * sValue.length()); boolean isShortValue = nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES; // Textual RPC requires a collation. If none is provided, as is the case when // the SSType is non-textual, then use the database collation by default. if (null == collation) collation = con.getDatabaseCollation(); // Use PLP encoding on Yukon and later with long values and OUT parameters boolean usePLP = (!isShortValue || bOut); if (usePLP) { writeRPCNameValType(sName, bOut, TDSType.NVARCHAR); // Handle Yukon v*max type header here. writeVMaxHeader(nValueLen, // Length bValueNull, // Is null? collation); // Send the data. if (!bValueNull) { if (nValueLen > 0) { writeInt(nValueLen); writeString(sValue); } // Send the terminator PLP chunk. writeInt(0); } } else // non-PLP type { // Write maximum length of data if (isShortValue) { writeRPCNameValType(sName, bOut, TDSType.NVARCHAR); writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES); } else { writeRPCNameValType(sName, bOut, TDSType.NTEXT); writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES); } collation.writeCollation(this); // Data and length if (bValueNull) { writeShort((short) -1); // actual len } else { // Write actual length of data if (isShortValue) writeShort((short) nValueLen); else writeInt(nValueLen); // If length is zero, we're done. if (0 != nValueLen) writeString(sValue); // data } } } void writeTVP(TVP value) throws SQLServerException { if (!value.isNull()) { writeByte((byte) 0); // status } else { // Default TVP writeByte((byte) TDS.TVP_STATUS_DEFAULT); // default TVP } writeByte((byte) TDS.TDS_TVP); /* * TVP_TYPENAME = DbName OwningSchema TypeName */ // Database where TVP type resides if (null != value.getDbNameTVP()) { writeByte((byte) value.getDbNameTVP().length()); writeString(value.getDbNameTVP()); } else writeByte((byte) 0x00); // empty DB name // Schema where TVP type resides if (null != value.getOwningSchemaNameTVP()) { writeByte((byte) value.getOwningSchemaNameTVP().length()); writeString(value.getOwningSchemaNameTVP()); } else writeByte((byte) 0x00); // empty Schema name // TVP type name if (null != value.getTVPName()) { writeByte((byte) value.getTVPName().length()); writeString(value.getTVPName()); } else writeByte((byte) 0x00); // empty TVP name if (!value.isNull()) { writeTVPColumnMetaData(value); // optional OrderUnique metadata writeTvpOrderUnique(value); } else { writeShort((short) TDS.TVP_NULL_TOKEN); } // TVP_END_TOKEN writeByte((byte) 0x00); try { writeTVPRows(value); } catch (NumberFormatException e) { throw new SQLServerException(SQLServerException.getErrString("R_TVPInvalidColumnValue"), e); } catch (ClassCastException e) { throw new SQLServerException(SQLServerException.getErrString("R_TVPInvalidColumnValue"), e); } } void writeTVPRows(TVP value) throws SQLServerException { boolean isShortValue, isNull; int dataLength; boolean tdsWritterCached = false; ByteBuffer cachedTVPHeaders = null; TDSCommand cachedCommand = null; if (!value.isNull()) { // is used, the tdsWriter of the calling preparedStatement is overwritten by the SQLServerResultSet#next() method when fetching new rows. // Therefore, we need to send TVP data row by row before fetching new row. if (TVPType.ResultSet == value.tvpType) { if ((null != value.sourceResultSet) && (value.sourceResultSet instanceof SQLServerResultSet)) { SQLServerResultSet sourceResultSet = (SQLServerResultSet) value.sourceResultSet; SQLServerStatement src_stmt = (SQLServerStatement) sourceResultSet.getStatement(); int resultSetServerCursorId = sourceResultSet.getServerCursorId(); if (con.equals(src_stmt.getConnection()) && 0 != resultSetServerCursorId) { cachedTVPHeaders = ByteBuffer.allocate(stagingBuffer.capacity()).order(stagingBuffer.order()); cachedTVPHeaders.put(stagingBuffer.array(), 0, stagingBuffer.position()); cachedCommand = this.command; tdsWritterCached = true; if (sourceResultSet.isForwardOnly()) { sourceResultSet.setFetchSize(1); } } } } Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata(); Iterator<Entry<Integer, SQLServerMetaData>> columnsIterator; while (value.next()) { // restore command and TDS header, which have been overwritten by value.next() if (tdsWritterCached) { command = cachedCommand; stagingBuffer.clear(); logBuffer.clear(); writeBytes(cachedTVPHeaders.array(), 0, cachedTVPHeaders.position()); } Object[] rowData = value.getRowData(); // ROW writeByte((byte) TDS.TVP_ROW); columnsIterator = columnMetadata.entrySet().iterator(); int currentColumn = 0; while (columnsIterator.hasNext()) { Map.Entry<Integer, SQLServerMetaData> columnPair = columnsIterator.next(); // If useServerDefault is set, client MUST NOT emit TvpColumnData for the associated column if (columnPair.getValue().useServerDefault) { currentColumn++; continue; } JDBCType jdbcType = JDBCType.of(columnPair.getValue().javaSqlType); String currentColumnStringValue = null; Object currentObject = null; if (null != rowData) { // if rowData has value for the current column, retrieve it. If not, current column will stay null. if (rowData.length > currentColumn) { currentObject = rowData[currentColumn]; if (null != currentObject) { currentColumnStringValue = String.valueOf(currentObject); } } } switch (jdbcType) { case BIGINT: if (null == currentColumnStringValue) writeByte((byte) 0); else { writeByte((byte) 8); writeLong(Long.valueOf(currentColumnStringValue).longValue()); } break; case BIT: if (null == currentColumnStringValue) writeByte((byte) 0); else { writeByte((byte) 1); writeByte((byte) (Boolean.valueOf(currentColumnStringValue).booleanValue() ? 1 : 0)); } break; case INTEGER: if (null == currentColumnStringValue) writeByte((byte) 0); else { writeByte((byte) 4); writeInt(Integer.valueOf(currentColumnStringValue).intValue()); } break; case SMALLINT: case TINYINT: if (null == currentColumnStringValue) writeByte((byte) 0); else { writeByte((byte) 2); // length of datatype writeShort(Short.valueOf(currentColumnStringValue).shortValue()); } break; case DECIMAL: case NUMERIC: if (null == currentColumnStringValue) writeByte((byte) 0); else { writeByte((byte) TDSWriter.BIGDECIMAL_MAX_LENGTH); // maximum length BigDecimal bdValue = new BigDecimal(currentColumnStringValue); // setScale of all BigDecimal value based on metadata sent bdValue = bdValue.setScale(columnPair.getValue().scale); byte[] valueBytes = DDC.convertBigDecimalToBytes(bdValue, bdValue.scale()); // 1-byte for sign and 16-byte for integer byte[] byteValue = new byte[17]; // removing the precision and scale information from the valueBytes array System.arraycopy(valueBytes, 2, byteValue, 0, valueBytes.length - 2); writeBytes(byteValue); } break; case DOUBLE: if (null == currentColumnStringValue) writeByte((byte) 0); // len of data bytes else { writeByte((byte) 8); // len of data bytes long bits = Double.doubleToLongBits(Double.valueOf(currentColumnStringValue).doubleValue()); long mask = 0xFF; int nShift = 0; for (int i = 0; i < 8; i++) { writeByte((byte) ((bits & mask) >> nShift)); nShift += 8; mask = mask << 8; } } break; case FLOAT: case REAL: if (null == currentColumnStringValue) writeByte((byte) 0); // actual length (0 == null) else { writeByte((byte) 4); // actual length writeInt(Float.floatToRawIntBits(Float.valueOf(currentColumnStringValue).floatValue())); } break; case DATE: case TIME: case TIMESTAMP: case DATETIMEOFFSET: case TIMESTAMP_WITH_TIMEZONE: case TIME_WITH_TIMEZONE: case CHAR: case VARCHAR: case NCHAR: case NVARCHAR: isShortValue = (2 * columnPair.getValue().precision) <= DataTypes.SHORT_VARTYPE_MAX_BYTES; isNull = (null == currentColumnStringValue); dataLength = isNull ? 0 : currentColumnStringValue.length() * 2; if (!isShortValue) { // check null if (isNull) // Null header for v*max types is 0xFFFFFFFFFFFFFFFF. writeLong(0xFFFFFFFFFFFFFFFFL); else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength) // Append v*max length. // UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE writeLong(0xFFFFFFFFFFFFFFFEL); else // For v*max types with known length, length is <totallength8><chunklength4> writeLong(dataLength); if (!isNull) { if (dataLength > 0) { writeInt(dataLength); writeString(currentColumnStringValue); } // Send the terminator PLP chunk. writeInt(0); } } else { if (isNull) writeShort((short) -1); // actual len else { writeShort((short) dataLength); writeString(currentColumnStringValue); } } break; case BINARY: case VARBINARY: // Handle conversions as done in other types. isShortValue = columnPair.getValue().precision <= DataTypes.SHORT_VARTYPE_MAX_BYTES; isNull = (null == currentObject); if (currentObject instanceof String) dataLength = isNull ? 0 : (toByteArray(currentObject.toString())).length; else dataLength = isNull ? 0 : ((byte[]) currentObject).length; if (!isShortValue) { // check null if (isNull) // Null header for v*max types is 0xFFFFFFFFFFFFFFFF. writeLong(0xFFFFFFFFFFFFFFFFL); else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength) // Append v*max length. // UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE writeLong(0xFFFFFFFFFFFFFFFEL); else // For v*max types with known length, length is <totallength8><chunklength4> writeLong(dataLength); if (!isNull) { if (dataLength > 0) { writeInt(dataLength); if (currentObject instanceof String) writeBytes(toByteArray(currentObject.toString())); else writeBytes((byte[]) currentObject); } // Send the terminator PLP chunk. writeInt(0); } } else { if (isNull) writeShort((short) -1); // actual len else { writeShort((short) dataLength); if (currentObject instanceof String) writeBytes(toByteArray(currentObject.toString())); else writeBytes((byte[]) currentObject); } } break; default: assert false : "Unexpected JDBC type " + jdbcType.toString(); } currentColumn++; } // send this row, read its response (throw exception in case of errors) and reset command status if (tdsWritterCached) { // TVP_END_TOKEN writeByte((byte) 0x00); writePacket(TDS.STATUS_BIT_EOM); TDSReader tdsReader = tdsChannel.getReader(command); int tokenType = tdsReader.peekTokenType(); StreamError databaseError = new StreamError(); databaseError.setFromTDS(tdsReader); if (TDS.TDS_ERR == tokenType) { SQLServerException.makeFromDatabaseError(con, null, databaseError.getMessage(), databaseError, false); } command.setInterruptsEnabled(true); command.setRequestComplete(false); } } } // reset command status which have been overwritten if (tdsWritterCached) { command.setRequestComplete(false); command.setInterruptsEnabled(true); command.setProcessedResponse(false); } else { // TVP_END_TOKEN writeByte((byte) 0x00); } } private static byte[] toByteArray(String s) { return DatatypeConverter.parseHexBinary(s); } void writeTVPColumnMetaData(TVP value) throws SQLServerException { boolean isShortValue; // TVP_COLMETADATA writeShort((short) value.getTVPColumnCount()); Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata(); Iterator<Entry<Integer, SQLServerMetaData>> columnsIterator = columnMetadata.entrySet().iterator(); /* * TypeColumnMetaData = UserType Flags TYPE_INFO ColName ; */ while (columnsIterator.hasNext()) { Map.Entry<Integer, SQLServerMetaData> pair = columnsIterator.next(); JDBCType jdbcType = JDBCType.of(pair.getValue().javaSqlType); boolean useServerDefault = pair.getValue().useServerDefault; // ULONG ; UserType of column // The value will be 0x0000 with the exceptions of TIMESTAMP (0x0050) and alias types (greater than 0x00FF). writeInt(0); /* * Flags = fNullable ; Column is nullable - %x01 fCaseSen -- Ignored ; usUpdateable -- Ignored ; fIdentity ; Column is identity column - * %x10 fComputed ; Column is computed - %x20 usReservedODBC -- Ignored ; fFixedLenCLRType-- Ignored ; fDefault ; Column is default value * - %x200 usReserved -- Ignored ; */ short flags = TDS.FLAG_NULLABLE; if (useServerDefault) { flags |= TDS.FLAG_TVP_DEFAULT_COLUMN; } writeShort(flags); // Type info switch (jdbcType) { case BIGINT: writeByte(TDSType.INTN.byteValue()); writeByte((byte) 8); // max length of datatype break; case BIT: writeByte(TDSType.BITN.byteValue()); writeByte((byte) 1); // max length of datatype break; case INTEGER: writeByte(TDSType.INTN.byteValue()); writeByte((byte) 4); // max length of datatype break; case SMALLINT: case TINYINT: writeByte(TDSType.INTN.byteValue()); writeByte((byte) 2); // max length of datatype break; case DECIMAL: case NUMERIC: writeByte(TDSType.NUMERICN.byteValue()); writeByte((byte) 0x11); // maximum length writeByte((byte) pair.getValue().precision); writeByte((byte) pair.getValue().scale); break; case DOUBLE: writeByte(TDSType.FLOATN.byteValue()); writeByte((byte) 8); // max length of datatype break; case FLOAT: case REAL: writeByte(TDSType.FLOATN.byteValue()); writeByte((byte) 4); // max length of datatype break; case DATE: case TIME: case TIMESTAMP: case DATETIMEOFFSET: case TIMESTAMP_WITH_TIMEZONE: case TIME_WITH_TIMEZONE: case CHAR: case VARCHAR: case NCHAR: case NVARCHAR: writeByte(TDSType.NVARCHAR.byteValue()); isShortValue = (2 * pair.getValue().precision) <= DataTypes.SHORT_VARTYPE_MAX_BYTES; // Use PLP encoding on Yukon and later with long values if (!isShortValue) // PLP { // Handle Yukon v*max type header here. writeShort((short) 0xFFFF); con.getDatabaseCollation().writeCollation(this); } else // non PLP { writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES); con.getDatabaseCollation().writeCollation(this); } break; case BINARY: case VARBINARY: writeByte(TDSType.BIGVARBINARY.byteValue()); isShortValue = pair.getValue().precision <= DataTypes.SHORT_VARTYPE_MAX_BYTES; // Use PLP encoding on Yukon and later with long values if (!isShortValue) // PLP // Handle Yukon v*max type header here. writeShort((short) 0xFFFF); else // non PLP writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES); break; default: assert false : "Unexpected JDBC type " + jdbcType.toString(); } // Column name - must be null (from TDS - TVP_COLMETADATA) writeByte((byte) 0x00); // [TVP_ORDER_UNIQUE] // [TVP_COLUMN_ORDERING] } } void writeTvpOrderUnique(TVP value) throws SQLServerException { /* * TVP_ORDER_UNIQUE = TVP_ORDER_UNIQUE_TOKEN (Count <Count>(ColNum OrderUniqueFlags)) */ Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata(); Iterator<Entry<Integer, SQLServerMetaData>> columnsIterator = columnMetadata.entrySet().iterator(); LinkedList<TdsOrderUnique> columnList = new LinkedList<TdsOrderUnique>(); while (columnsIterator.hasNext()) { byte flags = 0; Map.Entry<Integer, SQLServerMetaData> pair = columnsIterator.next(); SQLServerMetaData metaData = pair.getValue(); if (SQLServerSortOrder.Ascending == metaData.sortOrder) flags = TDS.TVP_ORDERASC_FLAG; else if (SQLServerSortOrder.Descending == metaData.sortOrder) flags = TDS.TVP_ORDERDESC_FLAG; if (metaData.isUniqueKey) flags |= TDS.TVP_UNIQUE_FLAG; // Remember this column if any flags were set if (0 != flags) columnList.add(new TdsOrderUnique(pair.getKey(), flags)); } // Write flagged columns if (!columnList.isEmpty()) { writeByte((byte) TDS.TVP_ORDER_UNIQUE_TOKEN); writeShort((short) columnList.size()); for (TdsOrderUnique column : columnList) { writeShort((short) (column.columnOrdinal + 1)); writeByte(column.flags); } } } private class TdsOrderUnique { int columnOrdinal; byte flags; TdsOrderUnique(int ordinal, byte flags) { this.columnOrdinal = ordinal; this.flags = flags; } } void setCryptoMetaData(CryptoMetadata cryptoMetaForBulk) { this.cryptoMeta = cryptoMetaForBulk; } CryptoMetadata getCryptoMetaData() { return cryptoMeta; } void writeEncryptedRPCByteArray(byte bValue[]) throws SQLServerException { boolean bValueNull = (bValue == null); long nValueLen = bValueNull ? 0 : bValue.length; boolean isShortValue = (nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES); boolean isPLP = (!isShortValue) && (nValueLen <= DataTypes.MAX_VARTYPE_MAX_BYTES); // Handle Shiloh types here. if (isShortValue) { writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES); } else if (isPLP) { writeShort((short) DataTypes.SQL_USHORTVARMAXLEN); } else { writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES); } // Data and length if (bValueNull) { writeShort((short) -1); // actual len } else { if (isShortValue) { writeShort((short) nValueLen); // actual len } else if (isPLP) { writeLong(nValueLen); // actual length } else { writeInt((int) nValueLen); // actual len } // If length is zero, we're done. if (0 != nValueLen) { if (isPLP) { writeInt((int) nValueLen); } writeBytes(bValue); } if (isPLP) { writeInt(0); // PLP_TERMINATOR, 0x00000000 } } } void writeEncryptedRPCPLP() throws SQLServerException { writeShort((short) DataTypes.SQL_USHORTVARMAXLEN); writeLong((long) 0); // actual length writeInt(0); // PLP_TERMINATOR, 0x00000000 } void writeCryptoMetaData() throws SQLServerException { writeByte(cryptoMeta.cipherAlgorithmId); writeByte(cryptoMeta.encryptionType.getValue()); writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).databaseId); writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekId); writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekVersion); writeBytes(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekMdVersion); writeByte(cryptoMeta.normalizationRuleVersion); } void writeRPCByteArray(String sName, byte bValue[], boolean bOut, JDBCType jdbcType, SQLCollation collation) throws SQLServerException { boolean bValueNull = (bValue == null); int nValueLen = bValueNull ? 0 : bValue.length; boolean isShortValue = (nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES); // Use PLP encoding on Yukon and later with long values and OUT parameters boolean usePLP = (!isShortValue || bOut); TDSType tdsType; if (null != cryptoMeta) { // send encrypted data as BIGVARBINARY tdsType = (isShortValue || usePLP) ? TDSType.BIGVARBINARY : TDSType.IMAGE; collation = null; } else switch (jdbcType) { case BINARY: case VARBINARY: case LONGVARBINARY: case BLOB: default: tdsType = (isShortValue || usePLP) ? TDSType.BIGVARBINARY : TDSType.IMAGE; collation = null; break; case CHAR: case VARCHAR: case LONGVARCHAR: case CLOB: tdsType = (isShortValue || usePLP) ? TDSType.BIGVARCHAR : TDSType.TEXT; if (null == collation) collation = con.getDatabaseCollation(); break; case NCHAR: case NVARCHAR: case LONGNVARCHAR: case NCLOB: tdsType = (isShortValue || usePLP) ? TDSType.NVARCHAR : TDSType.NTEXT; if (null == collation) collation = con.getDatabaseCollation(); break; } writeRPCNameValType(sName, bOut, tdsType); if (usePLP) { // Handle Yukon v*max type header here. writeVMaxHeader(nValueLen, bValueNull, collation); // Send the data. if (!bValueNull) { if (nValueLen > 0) { writeInt(nValueLen); writeBytes(bValue); } // Send the terminator PLP chunk. writeInt(0); } } else // non-PLP type { // Handle Shiloh types here. if (isShortValue) { writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES); } else { writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES); } if (null != collation) collation.writeCollation(this); // Data and length if (bValueNull) { writeShort((short) -1); // actual len } else { if (isShortValue) writeShort((short) nValueLen); // actual len else writeInt(nValueLen); // actual len // If length is zero, we're done. if (0 != nValueLen) writeBytes(bValue); } } } /** * Append a timestamp in RPC transmission format as a SQL Server DATETIME data type * * @param sName * the optional parameter name * @param cal * Pure Gregorian calendar containing the timestamp, including its associated time zone * @param subSecondNanos * the sub-second nanoseconds (0 - 999,999,999) * @param bOut * boolean true if the data value is being registered as an ouput parameter * */ void writeRPCDateTime(String sName, GregorianCalendar cal, int subSecondNanos, boolean bOut) throws SQLServerException { assert (subSecondNanos >= 0) && (subSecondNanos < Nanos.PER_SECOND) : "Invalid subNanoSeconds value: " + subSecondNanos; assert (cal != null) || (cal == null && subSecondNanos == 0) : "Invalid subNanoSeconds value when calendar is null: " + subSecondNanos; writeRPCNameValType(sName, bOut, TDSType.DATETIMEN); writeByte((byte) 8); // max length of datatype if (null == cal) { writeByte((byte) 0); // len of data bytes return; } writeByte((byte) 8); // len of data bytes // We need to extract the Calendar's current date & time in terms // of the number of days since the SQL Base Date (1/1/1900) plus // the number of milliseconds since midnight in the current day. // We cannot rely on any pre-calculated value for the number of // milliseconds in a day or the number of milliseconds since the // base date to do this because days with DST changes are shorter // or longer than "normal" days. // ASSUMPTION: We assume we are dealing with a GregorianCalendar here. // If not, we have no basis in which to compare dates. E.g. if we // are dealing with a Chinese Calendar implementation which does not // use the same value for Calendar.YEAR as the GregorianCalendar, // we cannot meaningfully compute a value relative to 1/1/1900. // First, figure out how many days there have been since the SQL Base Date. // These are based on SQL Server algorithms int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900); // Next, figure out the number of milliseconds since midnight of the current day. int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second 1000 * cal.get(Calendar.SECOND) + // Seconds into the current minute 60 * 1000 * cal.get(Calendar.MINUTE) + // Minutes into the current hour 60 * 60 * 1000 * cal.get(Calendar.HOUR_OF_DAY); // Hours into the current day // The last millisecond of the current day is always rounded to the first millisecond // of the next day because DATETIME is only accurate to 1/300th of a second. if (millisSinceMidnight >= 1000 * 60 * 60 * 24 - 1) { ++daysSinceSQLBaseDate; millisSinceMidnight = 0; } // Last-ditch verification that the value is in the valid range for the // DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then // throw an exception now so that statement execution is safely canceled. // Attempting to put an invalid value on the wire would result in a TDS // exception, which would close the connection. // These are based on SQL Server algorithms if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900) || daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange")); Object[] msgArgs = {SSType.DATETIME}; throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null); } // And put it all on the wire... // Number of days since the SQL Server Base Date (January 1, 1900) writeInt(daysSinceSQLBaseDate); // Milliseconds since midnight (at a resolution of three hundredths of a second) writeInt((3 * millisSinceMidnight + 5) / 10); } void writeRPCTime(String sName, GregorianCalendar localCalendar, int subSecondNanos, int scale, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.TIMEN); writeByte((byte) scale); if (null == localCalendar) { writeByte((byte) 0); return; } writeByte((byte) TDS.timeValueLength(scale)); writeScaledTemporal(localCalendar, subSecondNanos, scale, SSType.TIME); } void writeRPCDate(String sName, GregorianCalendar localCalendar, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.DATEN); if (null == localCalendar) { writeByte((byte) 0); return; } writeByte((byte) TDS.DAYS_INTO_CE_LENGTH); writeScaledTemporal(localCalendar, 0, // subsecond nanos (none for a date value) 0, // scale (dates are not scaled) SSType.DATE); } void writeEncryptedRPCTime(String sName, GregorianCalendar localCalendar, int subSecondNanos, int scale, boolean bOut) throws SQLServerException { if (con.getSendTimeAsDatetime()) { throw new SQLServerException(SQLServerException.getErrString("R_sendTimeAsDateTimeForAE"), null); } writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY); if (null == localCalendar) writeEncryptedRPCByteArray(null); else writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, subSecondNanos, scale, SSType.TIME, (short) 0)); writeByte(TDSType.TIMEN.byteValue()); writeByte((byte) scale); writeCryptoMetaData(); } void writeEncryptedRPCDate(String sName, GregorianCalendar localCalendar, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY); if (null == localCalendar) writeEncryptedRPCByteArray(null); else writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, 0, // subsecond nanos (none for a date value) 0, // scale (dates are not scaled) SSType.DATE, (short) 0)); writeByte(TDSType.DATEN.byteValue()); writeCryptoMetaData(); } void writeEncryptedRPCDateTime(String sName, GregorianCalendar cal, int subSecondNanos, boolean bOut, JDBCType jdbcType) throws SQLServerException { assert (subSecondNanos >= 0) && (subSecondNanos < Nanos.PER_SECOND) : "Invalid subNanoSeconds value: " + subSecondNanos; assert (cal != null) || (cal == null && subSecondNanos == 0) : "Invalid subNanoSeconds value when calendar is null: " + subSecondNanos; writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY); if (null == cal) writeEncryptedRPCByteArray(null); else writeEncryptedRPCByteArray(getEncryptedDateTimeAsBytes(cal, subSecondNanos, jdbcType)); if (JDBCType.SMALLDATETIME == jdbcType) { writeByte(TDSType.DATETIMEN.byteValue()); writeByte((byte) 4); } else { writeByte(TDSType.DATETIMEN.byteValue()); writeByte((byte) 8); } writeCryptoMetaData(); } // getEncryptedDateTimeAsBytes is called if jdbcType/ssType is SMALLDATETIME or DATETIME byte[] getEncryptedDateTimeAsBytes(GregorianCalendar cal, int subSecondNanos, JDBCType jdbcType) throws SQLServerException { int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900); // Next, figure out the number of milliseconds since midnight of the current day. int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second 1000 * cal.get(Calendar.SECOND) + // Seconds into the current minute 60 * 1000 * cal.get(Calendar.MINUTE) + // Minutes into the current hour 60 * 60 * 1000 * cal.get(Calendar.HOUR_OF_DAY); // Hours into the current day // The last millisecond of the current day is always rounded to the first millisecond // of the next day because DATETIME is only accurate to 1/300th of a second. if (millisSinceMidnight >= 1000 * 60 * 60 * 24 - 1) { ++daysSinceSQLBaseDate; millisSinceMidnight = 0; } if (JDBCType.SMALLDATETIME == jdbcType) { int secondsSinceMidnight = (millisSinceMidnight / 1000); int minutesSinceMidnight = (secondsSinceMidnight / 60); // Values that are 29.998 seconds or less are rounded down to the nearest minute minutesSinceMidnight = ((secondsSinceMidnight % 60) > 29.998) ? minutesSinceMidnight + 1 : minutesSinceMidnight; // minutesSinceMidnight for (23:59:30) int maxMinutesSinceMidnight_SmallDateTime = 1440; // Verification for smalldatetime to be within valid range of (1900.01.01) to (2079.06.06) // smalldatetime for unencrypted does not allow insertion of 2079.06.06 23:59:59 and it is rounded up // to 2079.06.07 00:00:00, therefore, we are checking minutesSinceMidnight for that condition. If it's not within valid range, then // throw an exception now so that statement execution is safely canceled. // 157 is the calculated day of year from 06-06 , 1440 is minutesince midnight for (23:59:30) if ((daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1900, 1, TDS.BASE_YEAR_1900) || daysSinceSQLBaseDate > DDC.daysSinceBaseDate(2079, 157, TDS.BASE_YEAR_1900)) || (daysSinceSQLBaseDate == DDC.daysSinceBaseDate(2079, 157, TDS.BASE_YEAR_1900) && minutesSinceMidnight >= maxMinutesSinceMidnight_SmallDateTime)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange")); Object[] msgArgs = {SSType.SMALLDATETIME}; throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null); } ByteBuffer days = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN); days.putShort((short) daysSinceSQLBaseDate); ByteBuffer seconds = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN); seconds.putShort((short) minutesSinceMidnight); byte[] value = new byte[4]; System.arraycopy(days.array(), 0, value, 0, 2); System.arraycopy(seconds.array(), 0, value, 2, 2); return SQLServerSecurityUtility.encryptWithKey(value, cryptoMeta, con); } else if (JDBCType.DATETIME == jdbcType) { // Last-ditch verification that the value is in the valid range for the // DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then // throw an exception now so that statement execution is safely canceled. // Attempting to put an invalid value on the wire would result in a TDS // exception, which would close the connection. // These are based on SQL Server algorithms // And put it all on the wire... if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900) || daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange")); Object[] msgArgs = {SSType.DATETIME}; throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null); } // Number of days since the SQL Server Base Date (January 1, 1900) ByteBuffer days = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); days.putInt(daysSinceSQLBaseDate); ByteBuffer seconds = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); seconds.putInt((3 * millisSinceMidnight + 5) / 10); byte[] value = new byte[8]; System.arraycopy(days.array(), 0, value, 0, 4); System.arraycopy(seconds.array(), 0, value, 4, 4); return SQLServerSecurityUtility.encryptWithKey(value, cryptoMeta, con); } assert false : "Unexpected JDBCType type " + jdbcType; return null; } void writeEncryptedRPCDateTime2(String sName, GregorianCalendar localCalendar, int subSecondNanos, int scale, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY); if (null == localCalendar) writeEncryptedRPCByteArray(null); else writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, subSecondNanos, scale, SSType.DATETIME2, (short) 0)); writeByte(TDSType.DATETIME2N.byteValue()); writeByte((byte) (scale)); writeCryptoMetaData(); } void writeEncryptedRPCDateTimeOffset(String sName, GregorianCalendar utcCalendar, int minutesOffset, int subSecondNanos, int scale, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY); if (null == utcCalendar) writeEncryptedRPCByteArray(null); else { assert 0 == utcCalendar.get(Calendar.ZONE_OFFSET); writeEncryptedRPCByteArray( writeEncryptedScaledTemporal(utcCalendar, subSecondNanos, scale, SSType.DATETIMEOFFSET, (short) minutesOffset)); } writeByte(TDSType.DATETIMEOFFSETN.byteValue()); writeByte((byte) (scale)); writeCryptoMetaData(); } void writeRPCDateTime2(String sName, GregorianCalendar localCalendar, int subSecondNanos, int scale, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.DATETIME2N); writeByte((byte) scale); if (null == localCalendar) { writeByte((byte) 0); return; } writeByte((byte) TDS.datetime2ValueLength(scale)); writeScaledTemporal(localCalendar, subSecondNanos, scale, SSType.DATETIME2); } void writeRPCDateTimeOffset(String sName, GregorianCalendar utcCalendar, int minutesOffset, int subSecondNanos, int scale, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.DATETIMEOFFSETN); writeByte((byte) scale); if (null == utcCalendar) { writeByte((byte) 0); return; } assert 0 == utcCalendar.get(Calendar.ZONE_OFFSET); writeByte((byte) TDS.datetimeoffsetValueLength(scale)); writeScaledTemporal(utcCalendar, subSecondNanos, scale, SSType.DATETIMEOFFSET); writeShort((short) minutesOffset); } /** * Returns subSecondNanos rounded to the maximum precision supported. The maximum fractional scale is MAX_FRACTIONAL_SECONDS_SCALE(7). Eg1: if you * pass 456,790,123 the function would return 456,790,100 Eg2: if you pass 456,790,150 the function would return 456,790,200 Eg3: if you pass * 999,999,951 the function would return 1,000,000,000 This is done to ensure that we have consistent rounding behaviour in setters and getters. * Bug #507919 */ private int getRoundedSubSecondNanos(int subSecondNanos) { int roundedNanos = ((subSecondNanos + (Nanos.PER_MAX_SCALE_INTERVAL / 2)) / Nanos.PER_MAX_SCALE_INTERVAL) * Nanos.PER_MAX_SCALE_INTERVAL; return roundedNanos; } /** * Writes to the TDS channel a temporal value as an instance instance of one of the scaled temporal SQL types: DATE, TIME, DATETIME2, or * DATETIMEOFFSET. * * @param cal * Calendar representing the value to write, except for any sub-second nanoseconds * @param subSecondNanos * the sub-second nanoseconds (0 - 999,999,999) * @param scale * the scale (in digits: 0 - 7) to use for the sub-second nanos component * @param ssType * the SQL Server data type (DATE, TIME, DATETIME2, or DATETIMEOFFSET) * * @throws SQLServerException * if an I/O error occurs or if the value is not in the valid range */ private void writeScaledTemporal(GregorianCalendar cal, int subSecondNanos, int scale, SSType ssType) throws SQLServerException { assert con.isKatmaiOrLater(); assert SSType.DATE == ssType || SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: " + ssType; // First, for types with a time component, write the scaled nanos since midnight if (SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) { assert subSecondNanos >= 0; assert subSecondNanos < Nanos.PER_SECOND; assert scale >= 0; assert scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE; int secondsSinceMidnight = cal.get(Calendar.SECOND) + 60 * cal.get(Calendar.MINUTE) + 60 * 60 * cal.get(Calendar.HOUR_OF_DAY); // Scale nanos since midnight to the desired scale, rounding the value as necessary long divisor = Nanos.PER_MAX_SCALE_INTERVAL * (long) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE - scale); // The scaledNanos variable represents the fractional seconds of the value at the scale // indicated by the scale variable. So, for example, scaledNanos = 3 means 300 nanoseconds // at scale TDS.MAX_FRACTIONAL_SECONDS_SCALE, but 3000 nanoseconds at // TDS.MAX_FRACTIONAL_SECONDS_SCALE - 1 long scaledNanos = ((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos) + divisor / 2) / divisor; // SQL Server rounding behavior indicates that it always rounds up unless // we are at the max value of the type(NOT every day), in which case it truncates. // If rounding nanos to the specified scale rolls the value to the next day ... if (Nanos.PER_DAY / divisor == scaledNanos) { // If the type is time, always truncate if (SSType.TIME == ssType) { --scaledNanos; } // If the type is datetime2 or datetimeoffset, truncate only if its the max value supported else { assert SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: " + ssType; // ... then bump the date, provided that the resulting date is still within // the valid date range. // Extreme edge case (literally, the VERY edge...): // If nanos overflow rolls the date value out of range (that is, we have a value // a few nanoseconds later than 9999-12-31 23:59:59) then truncate the nanos // instead of rolling. // This case is very likely never hit by "real world" applications, but exists // here as a security measure to ensure that such values don't result in a // connection-closing TDS exception. cal.add(Calendar.SECOND, 1); if (cal.get(Calendar.YEAR) <= 9999) { scaledNanos = 0; } else { cal.add(Calendar.SECOND, -1); --scaledNanos; } } } // Encode the scaled nanos to TDS int encodedLength = TDS.nanosSinceMidnightLength(scale); byte[] encodedBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength); writeBytes(encodedBytes); } // Second, for types with a date component, write the days into the Common Era if (SSType.DATE == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) { // Computation of the number of days into the Common Era assumes that // the DAY_OF_YEAR field reflects a pure Gregorian calendar - one that // uses Gregorian leap year rules across the entire range of dates. // For the DAY_OF_YEAR field to accurately reflect pure Gregorian behavior, // we need to use a pure Gregorian calendar for dates that are Julian dates // under a standard Gregorian calendar and for (Gregorian) dates later than // the cutover date in the cutover year. if (cal.getTimeInMillis() < GregorianChange.STANDARD_CHANGE_DATE.getTime() || cal.getActualMaximum(Calendar.DAY_OF_YEAR) < TDS.DAYS_PER_YEAR) { int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int date = cal.get(Calendar.DATE); // Set the cutover as early as possible (pure Gregorian behavior) cal.setGregorianChange(GregorianChange.PURE_CHANGE_DATE); // Initialize the date field by field (preserving the "wall calendar" value) cal.set(year, month, date); } int daysIntoCE = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), 1); // Last-ditch verification that the value is in the valid range for the // DATE/DATETIME2/DATETIMEOFFSET TDS data type (1/1/0001 to 12/31/9999). // If it's not, then throw an exception now so that statement execution // is safely canceled. Attempting to put an invalid value on the wire // would result in a TDS exception, which would close the connection. if (daysIntoCE < 0 || daysIntoCE >= DDC.daysSinceBaseDate(10000, 1, 1)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange")); Object[] msgArgs = {ssType}; throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null); } byte encodedBytes[] = new byte[3]; encodedBytes[0] = (byte) ((daysIntoCE >> 0) & 0xFF); encodedBytes[1] = (byte) ((daysIntoCE >> 8) & 0xFF); encodedBytes[2] = (byte) ((daysIntoCE >> 16) & 0xFF); writeBytes(encodedBytes); } } /** * Writes to the TDS channel a temporal value as an instance instance of one of the scaled temporal SQL types: DATE, TIME, DATETIME2, or * DATETIMEOFFSET. * * @param cal * Calendar representing the value to write, except for any sub-second nanoseconds * @param subSecondNanos * the sub-second nanoseconds (0 - 999,999,999) * @param scale * the scale (in digits: 0 - 7) to use for the sub-second nanos component * @param ssType * the SQL Server data type (DATE, TIME, DATETIME2, or DATETIMEOFFSET) * @param minutesOffset * the offset value for DATETIMEOFFSET * @throws SQLServerException * if an I/O error occurs or if the value is not in the valid range */ byte[] writeEncryptedScaledTemporal(GregorianCalendar cal, int subSecondNanos, int scale, SSType ssType, short minutesOffset) throws SQLServerException { assert con.isKatmaiOrLater(); assert SSType.DATE == ssType || SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: " + ssType; // store the time and minutesOffset portion of DATETIME2 and DATETIMEOFFSET to be used with date portion byte encodedBytesForEncryption[] = null; int secondsSinceMidnight = 0; long divisor = 0; long scaledNanos = 0; // First, for types with a time component, write the scaled nanos since midnight if (SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) { assert subSecondNanos >= 0; assert subSecondNanos < Nanos.PER_SECOND; assert scale >= 0; assert scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE; secondsSinceMidnight = cal.get(Calendar.SECOND) + 60 * cal.get(Calendar.MINUTE) + 60 * 60 * cal.get(Calendar.HOUR_OF_DAY); // Scale nanos since midnight to the desired scale, rounding the value as necessary divisor = Nanos.PER_MAX_SCALE_INTERVAL * (long) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE - scale); // The scaledNanos variable represents the fractional seconds of the value at the scale // indicated by the scale variable. So, for example, scaledNanos = 3 means 300 nanoseconds // at scale TDS.MAX_FRACTIONAL_SECONDS_SCALE, but 3000 nanoseconds at // TDS.MAX_FRACTIONAL_SECONDS_SCALE - 1 scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos) + divisor / 2) / divisor) * divisor / 100; // for encrypted time value, SQL server cannot do rounding or casting, // So, driver needs to cast it before encryption. if (SSType.TIME == ssType && 864000000000L <= scaledNanos) { scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor) * divisor / 100; } // SQL Server rounding behavior indicates that it always rounds up unless // we are at the max value of the type(NOT every day), in which case it truncates. // If rounding nanos to the specified scale rolls the value to the next day ... if (Nanos.PER_DAY / divisor == scaledNanos) { // If the type is time, always truncate if (SSType.TIME == ssType) { --scaledNanos; } // If the type is datetime2 or datetimeoffset, truncate only if its the max value supported else { assert SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: " + ssType; // ... then bump the date, provided that the resulting date is still within // the valid date range. // Extreme edge case (literally, the VERY edge...): // If nanos overflow rolls the date value out of range (that is, we have a value // a few nanoseconds later than 9999-12-31 23:59:59) then truncate the nanos // instead of rolling. // This case is very likely never hit by "real world" applications, but exists // here as a security measure to ensure that such values don't result in a // connection-closing TDS exception. cal.add(Calendar.SECOND, 1); if (cal.get(Calendar.YEAR) <= 9999) { scaledNanos = 0; } else { cal.add(Calendar.SECOND, -1); --scaledNanos; } } } // Encode the scaled nanos to TDS int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE); byte[] encodedBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength); if (SSType.TIME == ssType) { byte[] cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytes, cryptoMeta, con); return cipherText; } else if (SSType.DATETIME2 == ssType) { // for DATETIME2 sends both date and time part together for encryption encodedBytesForEncryption = new byte[encodedLength + 3]; System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, 0, encodedBytes.length); } else if (SSType.DATETIMEOFFSET == ssType) { // for DATETIMEOFFSET sends date, time and offset part together for encryption encodedBytesForEncryption = new byte[encodedLength + 5]; System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, 0, encodedBytes.length); } } // Second, for types with a date component, write the days into the Common Era if (SSType.DATE == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) { // Computation of the number of days into the Common Era assumes that // the DAY_OF_YEAR field reflects a pure Gregorian calendar - one that // uses Gregorian leap year rules across the entire range of dates. // For the DAY_OF_YEAR field to accurately reflect pure Gregorian behavior, // we need to use a pure Gregorian calendar for dates that are Julian dates // under a standard Gregorian calendar and for (Gregorian) dates later than // the cutover date in the cutover year. if (cal.getTimeInMillis() < GregorianChange.STANDARD_CHANGE_DATE.getTime() || cal.getActualMaximum(Calendar.DAY_OF_YEAR) < TDS.DAYS_PER_YEAR) { int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int date = cal.get(Calendar.DATE); // Set the cutover as early as possible (pure Gregorian behavior) cal.setGregorianChange(GregorianChange.PURE_CHANGE_DATE); // Initialize the date field by field (preserving the "wall calendar" value) cal.set(year, month, date); } int daysIntoCE = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), 1); // Last-ditch verification that the value is in the valid range for the // DATE/DATETIME2/DATETIMEOFFSET TDS data type (1/1/0001 to 12/31/9999). // If it's not, then throw an exception now so that statement execution // is safely canceled. Attempting to put an invalid value on the wire // would result in a TDS exception, which would close the connection. if (daysIntoCE < 0 || daysIntoCE >= DDC.daysSinceBaseDate(10000, 1, 1)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange")); Object[] msgArgs = {ssType}; throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null); } byte encodedBytes[] = new byte[3]; encodedBytes[0] = (byte) ((daysIntoCE >> 0) & 0xFF); encodedBytes[1] = (byte) ((daysIntoCE >> 8) & 0xFF); encodedBytes[2] = (byte) ((daysIntoCE >> 16) & 0xFF); byte[] cipherText; if (SSType.DATE == ssType) { cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytes, cryptoMeta, con); } else if (SSType.DATETIME2 == ssType) { // for Max value, does not round up, do casting instead. if (3652058 == daysIntoCE) { // 9999-12-31 if (864000000000L == scaledNanos) { // 24:00:00 in nanoseconds // does not round up scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor) * divisor / 100; int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE); byte[] encodedNanoBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength); // for DATETIME2 sends both date and time part together for encryption encodedBytesForEncryption = new byte[encodedLength + 3]; System.arraycopy(encodedNanoBytes, 0, encodedBytesForEncryption, 0, encodedNanoBytes.length); } } // Copy the 3 byte date value System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, (encodedBytesForEncryption.length - 3), 3); cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytesForEncryption, cryptoMeta, con); } else { // for Max value, does not round up, do casting instead. if (3652058 == daysIntoCE) { // 9999-12-31 if (864000000000L == scaledNanos) { // 24:00:00 in nanoseconds // does not round up scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor) * divisor / 100; int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE); byte[] encodedNanoBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength); // for DATETIMEOFFSET sends date, time and offset part together for encryption encodedBytesForEncryption = new byte[encodedLength + 5]; System.arraycopy(encodedNanoBytes, 0, encodedBytesForEncryption, 0, encodedNanoBytes.length); } } // Copy the 3 byte date value System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, (encodedBytesForEncryption.length - 5), 3); // Copy the 2 byte minutesOffset value System.arraycopy(ByteBuffer.allocate(Short.SIZE / Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putShort(minutesOffset).array(), 0, encodedBytesForEncryption, (encodedBytesForEncryption.length - 2), 2); cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytesForEncryption, cryptoMeta, con); } return cipherText; } // Invalid type ssType. This condition should never happen. MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unknownSSType")); Object[] msgArgs = {ssType}; SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), null, true); return null; } private byte[] scaledNanosToEncodedBytes(long scaledNanos, int encodedLength) { byte encodedBytes[] = new byte[encodedLength]; for (int i = 0; i < encodedLength; i++) encodedBytes[i] = (byte) ((scaledNanos >> (8 * i)) & 0xFF); return encodedBytes; } /** * Append the data in a stream in RPC transmission format. * * @param sName * the optional parameter name * @param stream * is the stream * @param streamLength * length of the stream (may be unknown) * @param bOut * boolean true if the data value is being registered as an ouput parameter * @param jdbcType * The JDBC type used to determine whether the value is textual or non-textual. * @param collation * The SQL collation associated with the value. Null for non-textual SQL Server types. * @throws SQLServerException */ void writeRPCInputStream(String sName, InputStream stream, long streamLength, boolean bOut, JDBCType jdbcType, SQLCollation collation) throws SQLServerException { assert null != stream; assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength >= 0; // Send long values and values with unknown length // using PLP chunking on Yukon and later. boolean usePLP = (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength > DataTypes.SHORT_VARTYPE_MAX_BYTES); if (usePLP) { assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength <= DataTypes.MAX_VARTYPE_MAX_BYTES; writeRPCNameValType(sName, bOut, jdbcType.isTextual() ? TDSType.BIGVARCHAR : TDSType.BIGVARBINARY); // Handle Yukon v*max type header here. writeVMaxHeader(streamLength, false, jdbcType.isTextual() ? collation : null); } // Send non-PLP in all other cases else { // If the length of the InputStream is unknown then we need to buffer the entire stream // in memory so that we can determine its length and send that length to the server // before the stream data itself. if (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength) { // Create ByteArrayOutputStream with initial buffer size of 8K to handle typical // binary field sizes more efficiently. Note we can grow beyond 8000 bytes. ByteArrayOutputStream baos = new ByteArrayOutputStream(8000); streamLength = 0L; // Since Shiloh is limited to 64K TDS packets, that's a good upper bound on the maximum // length of InputStream we should try to handle before throwing an exception. long maxStreamLength = 65535L * con.getTDSPacketSize(); try { byte buff[] = new byte[8000]; int bytesRead; while (streamLength < maxStreamLength && -1 != (bytesRead = stream.read(buff, 0, buff.length))) { baos.write(buff); streamLength += bytesRead; } } catch (IOException e) { throw new SQLServerException(e.getMessage(), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET, e); } if (streamLength >= maxStreamLength) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidLength")); Object[] msgArgs = {Long.valueOf(streamLength)}; SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), "", true); } assert streamLength <= Integer.MAX_VALUE; stream = new ByteArrayInputStream(baos.toByteArray(), 0, (int) streamLength); } assert 0 <= streamLength && streamLength <= DataTypes.IMAGE_TEXT_MAX_BYTES; boolean useVarType = streamLength <= DataTypes.SHORT_VARTYPE_MAX_BYTES; writeRPCNameValType(sName, bOut, jdbcType.isTextual() ? (useVarType ? TDSType.BIGVARCHAR : TDSType.TEXT) : (useVarType ? TDSType.BIGVARBINARY : TDSType.IMAGE)); // Write maximum length, optional collation, and actual length if (useVarType) { writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES); if (jdbcType.isTextual()) collation.writeCollation(this); writeShort((short) streamLength); } else { writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES); if (jdbcType.isTextual()) collation.writeCollation(this); writeInt((int) streamLength); } } // Write the data writeStream(stream, streamLength, usePLP); } /** * Append the XML data in a stream in RPC transmission format. * * @param sName * the optional parameter name * @param stream * is the stream * @param streamLength * length of the stream (may be unknown) * @param bOut * boolean true if the data value is being registered as an ouput parameter * @throws SQLServerException */ void writeRPCXML(String sName, InputStream stream, long streamLength, boolean bOut) throws SQLServerException { assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength >= 0; assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength <= DataTypes.MAX_VARTYPE_MAX_BYTES; writeRPCNameValType(sName, bOut, TDSType.XML); writeByte((byte) 0); // No schema // Handle null here and return, we're done here if it's null. if (null == stream) { // Null header for v*max types is 0xFFFFFFFFFFFFFFFF. writeLong(0xFFFFFFFFFFFFFFFFL); } else if (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength) { // Append v*max length. // UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE writeLong(0xFFFFFFFFFFFFFFFEL); // NOTE: Don't send the first chunk length, this will be calculated by caller. } else { // For v*max types with known length, length is <totallength8><chunklength4> // We're sending same total length as chunk length (as we're sending 1 chunk). writeLong(streamLength); } if (null != stream) // Write the data writeStream(stream, streamLength, true); } /** * Append the data in a character reader in RPC transmission format. * * @param sName * the optional parameter name * @param re * the reader * @param reLength * the reader data length (in characters) * @param bOut * boolean true if the data value is being registered as an ouput parameter * @param collation * The SQL collation associated with the value. Null for non-textual SQL Server types. * @throws SQLServerException */ void writeRPCReaderUnicode(String sName, Reader re, long reLength, boolean bOut, SQLCollation collation) throws SQLServerException { assert null != re; assert DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength >= 0; // Textual RPC requires a collation. If none is provided, as is the case when // the SSType is non-textual, then use the database collation by default. if (null == collation) collation = con.getDatabaseCollation(); // Send long values and values with unknown length // using PLP chunking on Yukon and later. boolean usePLP = (DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength > DataTypes.SHORT_VARTYPE_MAX_CHARS); if (usePLP) { assert DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength <= DataTypes.MAX_VARTYPE_MAX_CHARS; writeRPCNameValType(sName, bOut, TDSType.NVARCHAR); // Handle Yukon v*max type header here. writeVMaxHeader((DataTypes.UNKNOWN_STREAM_LENGTH == reLength) ? DataTypes.UNKNOWN_STREAM_LENGTH : 2 * reLength, // Length (in bytes) false, collation); } // Send non-PLP in all other cases else { // Length must be known if we're not sending PLP-chunked data. Yukon is handled above. // For Shiloh, this is enforced in DTV by converting the Reader to some other length- // prefixed value in the setter. assert 0 <= reLength && reLength <= DataTypes.NTEXT_MAX_CHARS; // For non-PLP types, use the long TEXT type rather than the short VARCHAR // type if the stream is too long to fit in the latter or if we don't know the length up // front so we have to assume that it might be too long. boolean useVarType = reLength <= DataTypes.SHORT_VARTYPE_MAX_CHARS; writeRPCNameValType(sName, bOut, useVarType ? TDSType.NVARCHAR : TDSType.NTEXT); // Write maximum length, collation, and actual length of the data if (useVarType) { writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES); collation.writeCollation(this); writeShort((short) (2 * reLength)); } else { writeInt(DataTypes.NTEXT_MAX_CHARS); collation.writeCollation(this); writeInt((int) (2 * reLength)); } } // Write the data writeReader(re, reLength, usePLP); } } /** * TDSPacket provides a mechanism for chaining TDS response packets together in a singly-linked list. * * Having both the link and the data in the same class allows TDSReader marks (see below) to automatically hold onto exactly as much response data as * they need, and no more. Java reference semantics ensure that a mark holds onto its referenced packet and subsequent packets (through next * references). When all marked references to a packet go away, the packet, and any linked unmarked packets, can be reclaimed by GC. */ final class TDSPacket { final byte[] header = new byte[TDS.PACKET_HEADER_SIZE]; final byte[] payload; int payloadLength; volatile TDSPacket next; final public String toString() { return "TDSPacket(SPID:" + Util.readUnsignedShortBigEndian(header, TDS.PACKET_HEADER_SPID) + " Seq:" + header[TDS.PACKET_HEADER_SEQUENCE_NUM] + ")"; } TDSPacket(int size) { payload = new byte[size]; payloadLength = 0; next = null; } final boolean isEOM() { return TDS.STATUS_BIT_EOM == (header[TDS.PACKET_HEADER_MESSAGE_STATUS] & TDS.STATUS_BIT_EOM); } }; /** * TDSReaderMark encapsulates a fixed position in the response data stream. * * Response data is quantized into a linked chain of packets. A mark refers to a specific location in a specific packet and relies on Java's reference * semantics to automatically keep all subsequent packets accessible until the mark is destroyed. */ final class TDSReaderMark { final TDSPacket packet; final int payloadOffset; TDSReaderMark(TDSPacket packet, int payloadOffset) { this.packet = packet; this.payloadOffset = payloadOffset; } } /** * TDSReader encapsulates the TDS response data stream. * * Bytes are read from SQL Server into a FIFO of packets. Reader methods traverse the packets to access the data. */ final class TDSReader { private final static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Reader"); final private String traceID; final public String toString() { return traceID; } private final TDSChannel tdsChannel; private final SQLServerConnection con; private final TDSCommand command; final TDSCommand getCommand() { assert null != command; return command; } final SQLServerConnection getConnection() { return con; } private TDSPacket currentPacket = new TDSPacket(0); private TDSPacket lastPacket = currentPacket; private int payloadOffset = 0; private int packetNum = 0; private boolean isStreaming = true; private boolean useColumnEncryption = false; private boolean serverSupportsColumnEncryption = false; private final byte valueBytes[] = new byte[256]; private static final AtomicInteger lastReaderID = new AtomicInteger(0); private static int nextReaderID() { return lastReaderID.incrementAndGet(); } TDSReader(TDSChannel tdsChannel, SQLServerConnection con, TDSCommand command) { this.tdsChannel = tdsChannel; this.con = con; this.command = command; // may be null // if the logging level is not detailed than fine or more we will not have proper readerids. if (logger.isLoggable(Level.FINE)) traceID = "TDSReader@" + nextReaderID() + " (" + con.toString() + ")"; else traceID = con.toString(); if (con.isColumnEncryptionSettingEnabled()) { useColumnEncryption = true; } serverSupportsColumnEncryption = con.getServerSupportsColumnEncryption(); } final boolean isColumnEncryptionSettingEnabled() { return useColumnEncryption; } final boolean getServerSupportsColumnEncryption() { return serverSupportsColumnEncryption; } final void throwInvalidTDS() throws SQLServerException { if (logger.isLoggable(Level.SEVERE)) logger.severe(toString() + " got unexpected value in TDS response at offset:" + payloadOffset); con.throwInvalidTDS(); } final void throwInvalidTDSToken(String tokenName) throws SQLServerException { if (logger.isLoggable(Level.SEVERE)) logger.severe(toString() + " got unexpected value in TDS response at offset:" + payloadOffset); con.throwInvalidTDSToken(tokenName); } /** * Ensures that payload data is available to be read, automatically advancing to (and possibly reading) the next packet. * * @return true if additional data is available to be read false if no more data is available */ private boolean ensurePayload() throws SQLServerException { if (payloadOffset == currentPacket.payloadLength) if (!nextPacket()) return false; assert payloadOffset < currentPacket.payloadLength; return true; } /** * Advance (and possibly read) the next packet. * * @return true if additional data is available to be read false if no more data is available */ private boolean nextPacket() throws SQLServerException { assert null != currentPacket; // Shouldn't call this function unless we're at the end of the current packet... TDSPacket consumedPacket = currentPacket; assert payloadOffset == consumedPacket.payloadLength; // If no buffered packets are left then maybe we can read one... // This action must be synchronized against against another thread calling // readAllPackets() to read in ALL of the remaining packets of the current response. if (null == consumedPacket.next) { readPacket(); if (null == consumedPacket.next) return false; } // Advance to that packet. If we are streaming through the // response, then unlink the current packet from the next // before moving to allow the packet to be reclaimed. TDSPacket nextPacket = consumedPacket.next; if (isStreaming) { if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Moving to next packet -- unlinking consumed packet"); consumedPacket.next = null; } currentPacket = nextPacket; payloadOffset = 0; return true; } /** * Reads the next packet of the TDS channel. * * This method is synchronized to guard against simultaneously reading packets from one thread that is processing the response and another thread * that is trying to buffer it with TDSCommand.detach(). */ synchronized final boolean readPacket() throws SQLServerException { if (null != command && !command.readingResponse()) return false; // Number of packets in should always be less than number of packets out. // If the server has been notified for an interrupt, it may be less by // more than one packet. assert tdsChannel.numMsgsRcvd < tdsChannel.numMsgsSent : "numMsgsRcvd:" + tdsChannel.numMsgsRcvd + " should be less than numMsgsSent:" + tdsChannel.numMsgsSent; TDSPacket newPacket = new TDSPacket(con.getTDSPacketSize()); // First, read the packet header. for (int headerBytesRead = 0; headerBytesRead < TDS.PACKET_HEADER_SIZE;) { int bytesRead = tdsChannel.read(newPacket.header, headerBytesRead, TDS.PACKET_HEADER_SIZE - headerBytesRead); if (bytesRead < 0) { if (logger.isLoggable(Level.FINER)) logger.finer(toString() + " Premature EOS in response. packetNum:" + packetNum + " headerBytesRead:" + headerBytesRead); con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, ((0 == packetNum && 0 == headerBytesRead) ? SQLServerException.getErrString("R_noServerResponse") : SQLServerException.getErrString("R_truncatedServerResponse"))); } headerBytesRead += bytesRead; } // Header size is a 2 byte unsigned short integer in big-endian order. int packetLength = Util.readUnsignedShortBigEndian(newPacket.header, TDS.PACKET_HEADER_MESSAGE_LENGTH); // Make header size is properly bounded and compute length of the packet payload. if (packetLength < TDS.PACKET_HEADER_SIZE || packetLength > con.getTDSPacketSize()) { logger.warning(toString() + " TDS header contained invalid packet length:" + packetLength + "; packet size:" + con.getTDSPacketSize()); throwInvalidTDS(); } newPacket.payloadLength = packetLength - TDS.PACKET_HEADER_SIZE; // Just grab the SPID for logging (another big-endian unsigned short). tdsChannel.setSPID(Util.readUnsignedShortBigEndian(newPacket.header, TDS.PACKET_HEADER_SPID)); // Packet header looks good enough. // When logging, copy the packet header to the log buffer. byte[] logBuffer = null; if (tdsChannel.isLoggingPackets()) { logBuffer = new byte[packetLength]; System.arraycopy(newPacket.header, 0, logBuffer, 0, TDS.PACKET_HEADER_SIZE); } // Now for the payload... for (int payloadBytesRead = 0; payloadBytesRead < newPacket.payloadLength;) { int bytesRead = tdsChannel.read(newPacket.payload, payloadBytesRead, newPacket.payloadLength - payloadBytesRead); if (bytesRead < 0) con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, SQLServerException.getErrString("R_truncatedServerResponse")); payloadBytesRead += bytesRead; } ++packetNum; lastPacket.next = newPacket; lastPacket = newPacket; // When logging, append the payload to the log buffer and write out the whole thing. if (tdsChannel.isLoggingPackets()) { System.arraycopy(newPacket.payload, 0, logBuffer, TDS.PACKET_HEADER_SIZE, newPacket.payloadLength); tdsChannel.logPacket(logBuffer, 0, packetLength, this.toString() + " received Packet:" + packetNum + " (" + newPacket.payloadLength + " bytes)"); } // If end of message, then bump the count of messages received and disable // interrupts. If an interrupt happened prior to disabling, then expect // to read the attention ack packet as well. if (newPacket.isEOM()) { ++tdsChannel.numMsgsRcvd; // Notify the command (if any) that we've reached the end of the response. if (null != command) command.onResponseEOM(); } return true; } final TDSReaderMark mark() { TDSReaderMark mark = new TDSReaderMark(currentPacket, payloadOffset); isStreaming = false; if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Buffering from: " + mark.toString()); return mark; } final void reset(TDSReaderMark mark) { if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Resetting to: " + mark.toString()); currentPacket = mark.packet; payloadOffset = mark.payloadOffset; } final void stream() { isStreaming = true; } /** * Returns the number of bytes that can be read (or skipped over) from this TDSReader without blocking by the next caller of a method for this * TDSReader. * * @return the actual number of bytes available. */ final int available() { // The number of bytes that can be read without blocking is just the number // of bytes that are currently buffered. That is the number of bytes left // in the current packet plus the number of bytes in the remaining packets. int available = currentPacket.payloadLength - payloadOffset; for (TDSPacket packet = currentPacket.next; null != packet; packet = packet.next) available += packet.payloadLength; return available; } /** * * @return number of bytes available in the current packet */ final int availableCurrentPacket() { /* * The number of bytes that can be read from the current chunk, without including the next chunk that is buffered. This is so the driver can * confirm if the next chunk sent is new packet or just continuation */ int available = currentPacket.payloadLength - payloadOffset; return available; } final int peekTokenType() throws SQLServerException { // Check whether we're at EOF if (!ensurePayload()) return -1; // Peek at the current byte (don't increment payloadOffset!) return currentPacket.payload[payloadOffset] & 0xFF; } final short peekStatusFlag() throws SQLServerException { // skip the current packet(i.e, TDS packet type) and peek into the status flag (USHORT) if (payloadOffset + 3 <= currentPacket.payloadLength) { short value = Util.readShort(currentPacket.payload, payloadOffset + 1); return value; } // as per TDS protocol, TDS_DONE packet should always be followed by status flag // throw exception if status packet is not available throwInvalidTDS(); return 0; } final int readUnsignedByte() throws SQLServerException { // Ensure that we have a packet to read from. if (!ensurePayload()) throwInvalidTDS(); return currentPacket.payload[payloadOffset++] & 0xFF; } final short readShort() throws SQLServerException { if (payloadOffset + 2 <= currentPacket.payloadLength) { short value = Util.readShort(currentPacket.payload, payloadOffset); payloadOffset += 2; return value; } return Util.readShort(readWrappedBytes(2), 0); } final int readUnsignedShort() throws SQLServerException { if (payloadOffset + 2 <= currentPacket.payloadLength) { int value = Util.readUnsignedShort(currentPacket.payload, payloadOffset); payloadOffset += 2; return value; } return Util.readUnsignedShort(readWrappedBytes(2), 0); } final String readUnicodeString(int length) throws SQLServerException { int byteLength = 2 * length; byte bytes[] = new byte[byteLength]; readBytes(bytes, 0, byteLength); return Util.readUnicodeString(bytes, 0, byteLength, con); } final char readChar() throws SQLServerException { return (char) readShort(); } final int readInt() throws SQLServerException { if (payloadOffset + 4 <= currentPacket.payloadLength) { int value = Util.readInt(currentPacket.payload, payloadOffset); payloadOffset += 4; return value; } return Util.readInt(readWrappedBytes(4), 0); } final int readIntBigEndian() throws SQLServerException { if (payloadOffset + 4 <= currentPacket.payloadLength) { int value = Util.readIntBigEndian(currentPacket.payload, payloadOffset); payloadOffset += 4; return value; } return Util.readIntBigEndian(readWrappedBytes(4), 0); } final long readUnsignedInt() throws SQLServerException { return readInt() & 0xFFFFFFFFL; } final long readLong() throws SQLServerException { if (payloadOffset + 8 <= currentPacket.payloadLength) { long value = Util.readLong(currentPacket.payload, payloadOffset); payloadOffset += 8; return value; } return Util.readLong(readWrappedBytes(8), 0); } final void readBytes(byte[] value, int valueOffset, int valueLength) throws SQLServerException { for (int bytesRead = 0; bytesRead < valueLength;) { // Ensure that we have a packet to read from. if (!ensurePayload()) throwInvalidTDS(); // Figure out how many bytes to copy from the current packet // (the lesser of the remaining value bytes and the bytes left in the packet). int bytesToCopy = valueLength - bytesRead; if (bytesToCopy > currentPacket.payloadLength - payloadOffset) bytesToCopy = currentPacket.payloadLength - payloadOffset; // Copy some bytes from the current packet to the destination value. if (logger.isLoggable(Level.FINEST)) logger.finest(toString() + " Reading " + bytesToCopy + " bytes from offset " + payloadOffset); System.arraycopy(currentPacket.payload, payloadOffset, value, valueOffset + bytesRead, bytesToCopy); bytesRead += bytesToCopy; payloadOffset += bytesToCopy; } } final byte[] readWrappedBytes(int valueLength) throws SQLServerException { assert valueLength <= valueBytes.length; readBytes(valueBytes, 0, valueLength); return valueBytes; } final Object readDecimal(int valueLength, TypeInfo typeInfo, JDBCType jdbcType, StreamType streamType) throws SQLServerException { if (valueLength > valueBytes.length) { logger.warning(toString() + " Invalid value length:" + valueLength); throwInvalidTDS(); } readBytes(valueBytes, 0, valueLength); return DDC.convertBigDecimalToObject(Util.readBigDecimal(valueBytes, valueLength, typeInfo.getScale()), jdbcType, streamType); } final Object readMoney(int valueLength, JDBCType jdbcType, StreamType streamType) throws SQLServerException { BigInteger bi; switch (valueLength) { case 8: // money { int intBitsHi = readInt(); int intBitsLo = readInt(); if (JDBCType.BINARY == jdbcType) { byte value[] = new byte[8]; Util.writeIntBigEndian(intBitsHi, value, 0); Util.writeIntBigEndian(intBitsLo, value, 4); return value; } bi = BigInteger.valueOf(((long) intBitsHi << 32) | (intBitsLo & 0xFFFFFFFFL)); break; } case 4: // smallmoney if (JDBCType.BINARY == jdbcType) { byte value[] = new byte[4]; Util.writeIntBigEndian(readInt(), value, 0); return value; } bi = BigInteger.valueOf(readInt()); break; default: throwInvalidTDS(); return null; } return DDC.convertBigDecimalToObject(new BigDecimal(bi, 4), jdbcType, streamType); } final Object readReal(int valueLength, JDBCType jdbcType, StreamType streamType) throws SQLServerException { if (4 != valueLength) throwInvalidTDS(); return DDC.convertFloatToObject(Float.intBitsToFloat(readInt()), jdbcType, streamType); } final Object readFloat(int valueLength, JDBCType jdbcType, StreamType streamType) throws SQLServerException { if (8 != valueLength) throwInvalidTDS(); return DDC.convertDoubleToObject(Double.longBitsToDouble(readLong()), jdbcType, streamType); } final Object readDateTime(int valueLength, Calendar appTimeZoneCalendar, JDBCType jdbcType, StreamType streamType) throws SQLServerException { // Build and return the right kind of temporal object. int daysSinceSQLBaseDate; int ticksSinceMidnight; int msecSinceMidnight; switch (valueLength) { case 8: // SQL datetime is 4 bytes for days since SQL Base Date // (January 1, 1900 00:00:00 GMT) and 4 bytes for // the number of three hundredths (1/300) of a second // since midnight. daysSinceSQLBaseDate = readInt(); ticksSinceMidnight = readInt(); if (JDBCType.BINARY == jdbcType) { byte value[] = new byte[8]; Util.writeIntBigEndian(daysSinceSQLBaseDate, value, 0); Util.writeIntBigEndian(ticksSinceMidnight, value, 4); return value; } msecSinceMidnight = (ticksSinceMidnight * 10 + 1) / 3; // Convert to msec (1 tick = 1 300th of a sec = 3 msec) break; case 4: // SQL smalldatetime has less precision. It stores 2 bytes // for the days since SQL Base Date and 2 bytes for minutes // after midnight. daysSinceSQLBaseDate = readUnsignedShort(); ticksSinceMidnight = readUnsignedShort(); if (JDBCType.BINARY == jdbcType) { byte value[] = new byte[4]; Util.writeShortBigEndian((short) daysSinceSQLBaseDate, value, 0); Util.writeShortBigEndian((short) ticksSinceMidnight, value, 2); return value; } msecSinceMidnight = ticksSinceMidnight * 60 * 1000; // Convert to msec (1 tick = 1 min = 60,000 msec) break; default: throwInvalidTDS(); return null; } // Convert the DATETIME/SMALLDATETIME value to the desired Java type. return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME, appTimeZoneCalendar, daysSinceSQLBaseDate, msecSinceMidnight, 0); // scale // (ignored // for // fixed-scale // DATETIME/SMALLDATETIME // types) } final Object readDate(int valueLength, Calendar appTimeZoneCalendar, JDBCType jdbcType) throws SQLServerException { if (TDS.DAYS_INTO_CE_LENGTH != valueLength) throwInvalidTDS(); // Initialize the date fields to their appropriate values. int localDaysIntoCE = readDaysIntoCE(); // Convert the DATE value to the desired Java type. return DDC.convertTemporalToObject(jdbcType, SSType.DATE, appTimeZoneCalendar, localDaysIntoCE, 0, // midnight local to app time zone 0); // scale (ignored for DATE) } final Object readTime(int valueLength, TypeInfo typeInfo, Calendar appTimeZoneCalendar, JDBCType jdbcType) throws SQLServerException { if (TDS.timeValueLength(typeInfo.getScale()) != valueLength) throwInvalidTDS(); // Read the value from the server long localNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale()); // Convert the TIME value to the desired Java type. return DDC.convertTemporalToObject(jdbcType, SSType.TIME, appTimeZoneCalendar, 0, localNanosSinceMidnight, typeInfo.getScale()); } final Object readDateTime2(int valueLength, TypeInfo typeInfo, Calendar appTimeZoneCalendar, JDBCType jdbcType) throws SQLServerException { if (TDS.datetime2ValueLength(typeInfo.getScale()) != valueLength) throwInvalidTDS(); // Read the value's constituent components long localNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale()); int localDaysIntoCE = readDaysIntoCE(); // Convert the DATETIME2 value to the desired Java type. return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME2, appTimeZoneCalendar, localDaysIntoCE, localNanosSinceMidnight, typeInfo.getScale()); } final Object readDateTimeOffset(int valueLength, TypeInfo typeInfo, JDBCType jdbcType) throws SQLServerException { if (TDS.datetimeoffsetValueLength(typeInfo.getScale()) != valueLength) throwInvalidTDS(); // The nanos since midnight and days into Common Era parts of DATETIMEOFFSET values // are in UTC. Use the minutes offset part to convert to local. long utcNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale()); int utcDaysIntoCE = readDaysIntoCE(); int localMinutesOffset = readShort(); // Convert the DATETIMEOFFSET value to the desired Java type. return DDC.convertTemporalToObject(jdbcType, SSType.DATETIMEOFFSET, new GregorianCalendar(new SimpleTimeZone(localMinutesOffset * 60 * 1000, ""), Locale.US), utcDaysIntoCE, utcNanosSinceMidnight, typeInfo.getScale()); } private int readDaysIntoCE() throws SQLServerException { byte value[] = new byte[TDS.DAYS_INTO_CE_LENGTH]; readBytes(value, 0, value.length); int daysIntoCE = 0; for (int i = 0; i < value.length; i++) daysIntoCE |= ((value[i] & 0xFF) << (8 * i)); // Theoretically should never encounter a value that is outside of the valid date range if (daysIntoCE < 0) throwInvalidTDS(); return daysIntoCE; } // Scale multipliers used to convert variable-scaled temporal values to a fixed 100ns scale. // Using this array is measurably faster than using Math.pow(10, ...) private final static int[] SCALED_MULTIPLIERS = {10000000, 1000000, 100000, 10000, 1000, 100, 10, 1}; private long readNanosSinceMidnight(int scale) throws SQLServerException { assert 0 <= scale && scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE; byte value[] = new byte[TDS.nanosSinceMidnightLength(scale)]; readBytes(value, 0, value.length); long hundredNanosSinceMidnight = 0; for (int i = 0; i < value.length; i++) hundredNanosSinceMidnight |= (value[i] & 0xFFL) << (8 * i); hundredNanosSinceMidnight *= SCALED_MULTIPLIERS[scale]; if (!(0 <= hundredNanosSinceMidnight && hundredNanosSinceMidnight < Nanos.PER_DAY / 100)) throwInvalidTDS(); return 100 * hundredNanosSinceMidnight; } final static String guidTemplate = "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN"; final Object readGUID(int valueLength, JDBCType jdbcType, StreamType streamType) throws SQLServerException { // GUIDs must be exactly 16 bytes if (16 != valueLength) throwInvalidTDS(); // Read in the GUID's binary value byte guid[] = new byte[16]; readBytes(guid, 0, 16); switch (jdbcType) { case CHAR: case VARCHAR: case LONGVARCHAR: case GUID: { StringBuilder sb = new StringBuilder(guidTemplate.length()); for (int i = 0; i < 4; i++) { sb.append(Util.hexChars[(guid[3 - i] & 0xF0) >> 4]); sb.append(Util.hexChars[guid[3 - i] & 0x0F]); } sb.append('-'); for (int i = 0; i < 2; i++) { sb.append(Util.hexChars[(guid[5 - i] & 0xF0) >> 4]); sb.append(Util.hexChars[guid[5 - i] & 0x0F]); } sb.append('-'); for (int i = 0; i < 2; i++) { sb.append(Util.hexChars[(guid[7 - i] & 0xF0) >> 4]); sb.append(Util.hexChars[guid[7 - i] & 0x0F]); } sb.append('-'); for (int i = 0; i < 2; i++) { sb.append(Util.hexChars[(guid[8 + i] & 0xF0) >> 4]); sb.append(Util.hexChars[guid[8 + i] & 0x0F]); } sb.append('-'); for (int i = 0; i < 6; i++) { sb.append(Util.hexChars[(guid[10 + i] & 0xF0) >> 4]); sb.append(Util.hexChars[guid[10 + i] & 0x0F]); } try { return DDC.convertStringToObject(sb.toString(), Encoding.UNICODE.charset(), jdbcType, streamType); } catch (UnsupportedEncodingException e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue")); throw new SQLServerException(form.format(new Object[] {"UNIQUEIDENTIFIER", jdbcType}), null, 0, e); } } default: { if (StreamType.BINARY == streamType || StreamType.ASCII == streamType) return new ByteArrayInputStream(guid); return guid; } } } /** * Reads a multi-part table name from TDS and returns it as an array of Strings. */ final SQLIdentifier readSQLIdentifier() throws SQLServerException { // Multi-part names should have between 1 and 4 parts int numParts = readUnsignedByte(); if (!(1 <= numParts && numParts <= 4)) throwInvalidTDS(); // Each part is a length-prefixed Unicode string String[] nameParts = new String[numParts]; for (int i = 0; i < numParts; i++) nameParts[i] = readUnicodeString(readUnsignedShort()); // Build the identifier from the name parts SQLIdentifier identifier = new SQLIdentifier(); identifier.setObjectName(nameParts[numParts - 1]); if (numParts >= 2) identifier.setSchemaName(nameParts[numParts - 2]); if (numParts >= 3) identifier.setDatabaseName(nameParts[numParts - 3]); if (4 == numParts) identifier.setServerName(nameParts[numParts - 4]); return identifier; } final SQLCollation readCollation() throws SQLServerException { SQLCollation collation = null; try { collation = new SQLCollation(this); } catch (UnsupportedEncodingException e) { con.terminate(SQLServerException.DRIVER_ERROR_INVALID_TDS, e.getMessage(), e); // not reached } return collation; } final void skip(int bytesToSkip) throws SQLServerException { assert bytesToSkip >= 0; while (bytesToSkip > 0) { // Ensure that we have a packet to read from. if (!ensurePayload()) throwInvalidTDS(); int bytesSkipped = bytesToSkip; if (bytesSkipped > currentPacket.payloadLength - payloadOffset) bytesSkipped = currentPacket.payloadLength - payloadOffset; bytesToSkip -= bytesSkipped; payloadOffset += bytesSkipped; } } final void TryProcessFeatureExtAck(boolean featureExtAckReceived) throws SQLServerException { // in case of redirection, do not check if TDS_FEATURE_EXTENSION_ACK is received or not. if (null != this.con.getRoutingInfo()) { return; } if (isColumnEncryptionSettingEnabled() && !featureExtAckReceived) throw new SQLServerException(this, SQLServerException.getErrString("R_AE_NotSupportedByServer"), null, 0, false); } } /** * Timer for use with Commands that support a timeout. * * Once started, the timer runs for the prescribed number of seconds unless stopped. If the timer runs out, it interrupts its associated Command with * a reason like "timed out". */ final class TimeoutTimer implements Runnable { private static final String threadGroupName = "mssql-jdbc-TimeoutTimer"; private final int timeoutSeconds; private final TDSCommand command; private volatile Future<?> task; private static final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { private final ThreadGroup tg = new ThreadGroup(threadGroupName); private final String threadNamePrefix = tg.getName() + "-"; private final AtomicInteger threadNumber = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(tg, r, threadNamePrefix + threadNumber.incrementAndGet()); t.setDaemon(true); return t; } }); private volatile boolean canceled = false; TimeoutTimer(int timeoutSeconds, TDSCommand command) { assert timeoutSeconds > 0; assert null != command; this.timeoutSeconds = timeoutSeconds; this.command = command; } final void start() { task = executor.submit(this); } final void stop() { task.cancel(true); canceled = true; } public void run() { int secondsRemaining = timeoutSeconds; try { // Poll every second while time is left on the timer. // Return if/when the timer is canceled. do { if (canceled) return; Thread.sleep(1000); } while (--secondsRemaining > 0); } catch (InterruptedException e) { // re-interrupt the current thread, in order to restore the thread's interrupt status. Thread.currentThread().interrupt(); return; } // If the timer wasn't canceled before it ran out of // time then interrupt the registered command. try { command.interrupt(SQLServerException.getErrString("R_queryTimedOut")); } catch (SQLServerException e) { // Unfortunately, there's nothing we can do if we // fail to time out the request. There is no way // to report back what happened. command.log(Level.FINE, "Command could not be timed out. Reason: " + e.getMessage()); } } } /** * TDSCommand encapsulates an interruptable TDS conversation. * * A conversation may consist of one or more TDS request and response messages. A command may be interrupted at any point, from any thread, and for * any reason. Acknowledgement and handling of an interrupt is fully encapsulated by this class. * * Commands may be created with an optional timeout (in seconds). Timeouts are implemented as a form of interrupt, where the interrupt event occurs * when the timeout period expires. Currently, only the time to receive the response from the channel counts against the timeout period. */ abstract class TDSCommand { abstract boolean doExecute() throws SQLServerException; final static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Command"); private final String logContext; final String getLogContext() { return logContext; } private String traceID; final public String toString() { if (traceID == null) traceID = "TDSCommand@" + Integer.toHexString(hashCode()) + " (" + logContext + ")"; return traceID; } final void log(Level level, String message) { logger.log(level, toString() + ": " + message); } // Optional timer that is set if the command was created with a non-zero timeout period. // When the timer expires, the command is interrupted. private final TimeoutTimer timeoutTimer; // TDS channel accessors // These are set/reset at command execution time. // Volatile ensures visibility to execution thread and interrupt thread private volatile TDSWriter tdsWriter; private volatile TDSReader tdsReader; // Lock to ensure atomicity when manipulating more than one of the following // shared interrupt state variables below. private final Object interruptLock = new Object(); // Flag set when this command starts execution, indicating that it is // ready to respond to interrupts; and cleared when its last response packet is // received, indicating that it is no longer able to respond to interrupts. // If the command is interrupted after interrupts have been disabled, then the // interrupt is ignored. private volatile boolean interruptsEnabled = false; protected void setInterruptsEnabled(boolean interruptsEnabled) { this.interruptsEnabled = interruptsEnabled; } // Flag set to indicate that an interrupt has happened. private volatile boolean wasInterrupted = false; private boolean wasInterrupted() { return wasInterrupted; } // The reason for the interrupt. private volatile String interruptReason = null; // Flag set when this command's request to the server is complete. // If a command is interrupted before its request is complete, it is the executing // thread's responsibility to send the attention signal to the server if necessary. // After the request is complete, the interrupting thread must send the attention signal. private volatile boolean requestComplete; protected void setRequestComplete(boolean requestComplete) { this.requestComplete = requestComplete; } // Flag set when an attention signal has been sent to the server, indicating that a // TDS packet containing the attention ack message is to be expected in the response. // This flag is cleared after the attention ack message has been received and processed. private volatile boolean attentionPending = false; boolean attentionPending() { return attentionPending; } // Flag set when this command's response has been processed. Until this flag is set, // there may be unprocessed information left in the response, such as transaction // ENVCHANGE notifications. private volatile boolean processedResponse; protected void setProcessedResponse(boolean processedResponse) { this.processedResponse = processedResponse; } // Flag set when this command's response is ready to be read from the server and cleared // after its response has been received, but not necessarily processed, up to and including // any attention ack. The command's response is read either on demand as it is processed, // or by detaching. private volatile boolean readingResponse; final boolean readingResponse() { return readingResponse; } /** * Creates this command with an optional timeout. * * @param logContext * the string describing the context for this command. * @param timeoutSeconds * (optional) the time before which the command must complete before it is interrupted. A value of 0 means no timeout. */ TDSCommand(String logContext, int timeoutSeconds) { this.logContext = logContext; this.timeoutTimer = (timeoutSeconds > 0) ? (new TimeoutTimer(timeoutSeconds, this)) : null; } /** * Executes this command. * * @param tdsWriter * @param tdsReader * @throws SQLServerException * on any error executing the command, including cancel or timeout. */ boolean execute(TDSWriter tdsWriter, TDSReader tdsReader) throws SQLServerException { this.tdsWriter = tdsWriter; this.tdsReader = tdsReader; assert null != tdsReader; try { return doExecute(); // Derived classes implement the execution details } catch (SQLServerException e) { try { // If command execution threw an exception for any reason before the request // was complete then interrupt the command (it may already be interrupted) // and close it out to ensure that any response to the error/interrupt // is processed. // no point in trying to cancel on a closed connection. if (!requestComplete && !tdsReader.getConnection().isClosed()) { interrupt(e.getMessage()); onRequestComplete(); close(); } } catch (SQLServerException interruptException) { if (logger.isLoggable(Level.FINE)) logger.fine(this.toString() + ": Ignoring error in sending attention: " + interruptException.getMessage()); } // throw the original exception even if trying to interrupt fails even in the case // of trying to send a cancel to the server. throw e; } } /** * Provides sane default response handling. * * This default implementation just consumes everything in the response message. */ void processResponse(TDSReader tdsReader) throws SQLServerException { if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Processing response"); try { TDSParser.parse(tdsReader, getLogContext()); } catch (SQLServerException e) { if (SQLServerException.DRIVER_ERROR_FROM_DATABASE != e.getDriverErrorCode()) throw e; if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Ignoring error from database: " + e.getMessage()); } } /** * Clears this command from the TDS channel so that another command can execute. * * This method does not process the response. It just buffers it in memory, including any attention ack that may be present. */ final void detach() throws SQLServerException { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": detaching..."); // Read any remaining response packets from the server. // This operation may be timed out or cancelled from another thread. while (tdsReader.readPacket()) ; // Postcondition: the entire response has been read assert !readingResponse; } final void close() { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": closing..."); if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": processing response..."); while (!processedResponse) { try { processResponse(tdsReader); } catch (SQLServerException e) { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": close ignoring error processing response: " + e.getMessage()); if (tdsReader.getConnection().isSessionUnAvailable()) { processedResponse = true; attentionPending = false; } } } if (attentionPending) { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": processing attention ack..."); try { TDSParser.parse(tdsReader, "attention ack"); } catch (SQLServerException e) { if (tdsReader.getConnection().isSessionUnAvailable()) { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": giving up on attention ack after connection closed by exception: " + e); attentionPending = false; } else { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": ignored exception: " + e); } } // If the parser returns to us without processing the expected attention ack, // then assume that no attention ack is forthcoming from the server and // terminate the connection to prevent any other command from executing. if (attentionPending) { logger.severe(this + ": expected attn ack missing or not processed; terminating connection..."); try { tdsReader.throwInvalidTDS(); } catch (SQLServerException e) { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": ignored expected invalid TDS exception: " + e); assert tdsReader.getConnection().isSessionUnAvailable(); attentionPending = false; } } } // Postcondition: // Response has been processed and there is no attention pending -- the command is closed. // Of course the connection may be closed too, but the command is done regardless... assert processedResponse && !attentionPending; } /** * Interrupts execution of this command, typically from another thread. * * Only the first interrupt has any effect. Subsequent interrupts are ignored. Interrupts are also ignored until enabled. If interrupting the * command requires an attention signal to be sent to the server, then this method sends that signal if the command's request is already complete. * * Signalling mechanism is "fire and forget". It is up to either the execution thread or, possibly, a detaching thread, to ensure that any pending * attention ack later will be received and processed. * * @param reason * the reason for the interrupt, typically cancel or timeout. * @throws SQLServerException * if interrupting fails for some reason. This call does not throw the reason for the interrupt. */ void interrupt(String reason) throws SQLServerException { // Multiple, possibly simultaneous, interrupts may occur. // Only the first one should be recognized and acted upon. synchronized (interruptLock) { if (interruptsEnabled && !wasInterrupted()) { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": Raising interrupt for reason:" + reason); wasInterrupted = true; interruptReason = reason; if (requestComplete) attentionPending = tdsWriter.sendAttention(); } } } private boolean interruptChecked = false; /** * Checks once whether an interrupt has occurred, and, if it has, throws an exception indicating that fact. * * Any calls after the first to check for interrupts are no-ops. This method is called periodically from this command's execution thread to notify * the app when an interrupt has happened. * * It should only be called from places where consistent behavior can be ensured after the exception is thrown. For example, it should not be * called at arbitrary times while processing the response, as doing so could leave the response token stream in an inconsistent state. Currently, * response processing only checks for interrupts after every result or OUT parameter. * * Request processing checks for interrupts before writing each packet. * * @throws SQLServerException * if this command was interrupted, throws the reason for the interrupt. */ final void checkForInterrupt() throws SQLServerException { // Throw an exception with the interrupt reason if this command was interrupted. // Note that the interrupt reason may be null. Checking whether the // command was interrupted does not require the interrupt lock since only one // of the shared state variables is being manipulated; interruptChecked is not // shared with the interrupt thread. if (wasInterrupted() && !interruptChecked) { interruptChecked = true; if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": throwing interrupt exception, reason: " + interruptReason); throw new SQLServerException(interruptReason, SQLState.STATEMENT_CANCELED, DriverError.NOT_SET, null); } } /** * Notifies this command when no more request packets are to be sent to the server. * * After the last packet has been sent, the only way to interrupt the request is to send an attention signal from the interrupt() method. * * Note that this method is called when the request completes normally (last packet sent with EOM bit) or when it completes after being * interrupted (0 or more packets sent with no EOM bit). */ final void onRequestComplete() throws SQLServerException { assert !requestComplete; if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": request complete"); synchronized (interruptLock) { requestComplete = true; // If this command was interrupted before its request was complete then // we need to send the attention signal if necessary. Note that if no // attention signal is sent (i.e. no packets were sent to the server before // the interrupt happened), then don't expect an attention ack or any // other response. if (!interruptsEnabled) { assert !attentionPending; assert !processedResponse; assert !readingResponse; processedResponse = true; } else if (wasInterrupted()) { if (tdsWriter.isEOMSent()) { attentionPending = tdsWriter.sendAttention(); readingResponse = attentionPending; } else { assert !attentionPending; readingResponse = tdsWriter.ignoreMessage(); } processedResponse = !readingResponse; } else { assert !attentionPending; assert !processedResponse; readingResponse = true; } } } /** * Notifies this command when the last packet of the response has been read. * * When the last packet is read, interrupts are disabled. If an interrupt occurred prior to disabling that caused an attention signal to be sent * to the server, then an extra packet containing the attention ack is read. * * This ensures that on return from this method, the TDS channel is clear of all response packets for this command. * * Note that this method is called for the attention ack message itself as well, so we need to be sure not to expect more than one attention * ack... */ final void onResponseEOM() throws SQLServerException { boolean readAttentionAck = false; // Atomically disable interrupts and check for a previous interrupt requiring // an attention ack to be read. synchronized (interruptLock) { if (interruptsEnabled) { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": disabling interrupts"); // Determine whether we still need to read the attention ack packet. // When a command is interrupted, Yukon (and later) always sends a response // containing at least a DONE(ERROR) token before it sends the attention ack, // even if the command's request was not complete. readAttentionAck = attentionPending; interruptsEnabled = false; } } // If an attention packet needs to be read then read it. This should // be done outside of the interrupt lock to avoid unnecessarily blocking // interrupting threads. Note that it is remotely possible that the call // to readPacket won't actually read anything if the attention ack was // already read by TDSCommand.detach(), in which case this method could // be called from multiple threads, leading to a benign race to clear the // readingResponse flag. if (readAttentionAck) tdsReader.readPacket(); readingResponse = false; } /** * Notifies this command when the end of its response token stream has been reached. * * After this call, we are guaranteed that tokens in the response have been processed. */ final void onTokenEOF() { processedResponse = true; } /** * Notifies this command when the attention ack (a DONE token with a special flag) has been processed. * * After this call, the attention ack should no longer be expected. */ final void onAttentionAck() { assert attentionPending; attentionPending = false; } /** * Starts sending this command's TDS request to the server. * * @param tdsMessageType * the type of the TDS message (RPC, QUERY, etc.) * @return the TDS writer used to write the request. * @throws SQLServerException * on any error, including acknowledgement of an interrupt. */ final TDSWriter startRequest(byte tdsMessageType) throws SQLServerException { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": starting request..."); // Start this command's request message try { tdsWriter.startMessage(this, tdsMessageType); } catch (SQLServerException e) { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": starting request: exception: " + e.getMessage()); throw e; } // (Re)initialize this command's interrupt state for its current execution. // To ensure atomically consistent behavior, do not leave the interrupt lock // until interrupts have been (re)enabled. synchronized (interruptLock) { requestComplete = false; readingResponse = false; processedResponse = false; attentionPending = false; wasInterrupted = false; interruptReason = null; interruptsEnabled = true; } return tdsWriter; } /** * Finishes the TDS request and then starts reading the TDS response from the server. * * @return the TDS reader used to read the response. * @throws SQLServerException * if there is any kind of error. */ final TDSReader startResponse() throws SQLServerException { return startResponse(false); } final TDSReader startResponse(boolean isAdaptive) throws SQLServerException { // Finish sending the request message. If this command was interrupted // at any point before endMessage() returns, then endMessage() throws an // exception with the reason for the interrupt. Request interrupts // are disabled by the time endMessage() returns. if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": finishing request"); try { tdsWriter.endMessage(); } catch (SQLServerException e) { if (logger.isLoggable(Level.FINEST)) logger.finest(this + ": finishing request: endMessage threw exception: " + e.getMessage()); throw e; } // If command execution is subject to timeout then start timing until // the server returns the first response packet. if (null != timeoutTimer) { if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Starting timer..."); timeoutTimer.start(); } if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Reading response..."); try { // Wait for the server to execute the request and read the first packet // (responseBuffering=adaptive) or all packets (responseBuffering=full) // of the response. if (isAdaptive) { tdsReader.readPacket(); } else { while (tdsReader.readPacket()) ; } } catch (SQLServerException e) { if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Exception reading response: " + e.getMessage()); throw e; } finally { // If command execution was subject to timeout then stop timing as soon // as the server returns the first response packet or errors out. if (null != timeoutTimer) { if (logger.isLoggable(Level.FINEST)) logger.finest(this.toString() + ": Stopping timer..."); timeoutTimer.stop(); } } return tdsReader; } } /** * UninterruptableTDSCommand encapsulates an uninterruptable TDS conversation. * * TDSCommands have interruptability built in. However, some TDSCommands such as DTC commands, connection commands, cursor close and prepared * statement handle close shouldn't be interruptable. This class provides a base implementation for such commands. */ abstract class UninterruptableTDSCommand extends TDSCommand { UninterruptableTDSCommand(String logContext) { super(logContext, 0); } final void interrupt(String reason) throws SQLServerException { // Interrupting an uninterruptable command is a no-op. That is, // it can happen, but it should have no effect. logger.finest(toString() + " Ignoring interrupt of uninterruptable TDS command; Reason:" + reason); } }
package org.pentaho.di.trans.steps.systemdata; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.version.BuildVersion; /** * Get information from the System or the supervising transformation. * * @author Matt * @since 4-aug-2003 */ public class SystemData extends BaseStep implements StepInterface { private SystemDataMeta meta; private SystemDataData data; public SystemData(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } private Object[] getSystemData(RowMetaInterface inputRowMeta, Object[] inputRowData) throws KettleException { Object[] row = new Object[data.outputRowMeta.size()]; for (int i=0;i<inputRowMeta.size();i++) { row[i] = inputRowData[i]; // no data is changed, clone is not needed here. } for (int i=0, index=inputRowMeta.size();i<meta.getFieldName().length;i++, index++) { Calendar cal; int argnr=0; switch(meta.getFieldType()[i]) { case SystemDataMeta.TYPE_SYSTEM_INFO_SYSTEM_START: row[index] = getTrans().getCurrentDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_SYSTEM_DATE: row[index] = new Date(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TRANS_DATE_FROM: row[index] = getTrans().getStartDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TRANS_DATE_TO: row[index] = getTrans().getEndDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JOB_DATE_FROM: row[index] = getTrans().getJobStartDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JOB_DATE_TO: row[index] = getTrans().getJobEndDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_DAY_START: cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, -1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_DAY_END: cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, -1); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_DAY_START: cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_DAY_END: cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_DAY_START: cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_DAY_END: cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_MONTH_START: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_MONTH_END: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_MONTH_START: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_MONTH_END: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_MONTH_START: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_MONTH_END: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_COPYNR: row[index] = new Long( getCopy() ); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TRANS_NAME: row[index] = getTransMeta().getName(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_MODIFIED_USER: row[index] = getTransMeta().getModifiedUser(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_MODIFIED_DATE: row[index] = getTransMeta().getModifiedDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TRANS_BATCH_ID: row[index] = new Long( getTrans().getBatchId() ); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JOB_BATCH_ID: row[index] = new Long( getTrans().getPassedBatchId() ); break; case SystemDataMeta.TYPE_SYSTEM_INFO_HOSTNAME: row[index] = Const.getHostname(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_IP_ADDRESS: try { row[index] = Const.getIPAddress(); } catch(Exception e) { throw new KettleException(e); } break; case SystemDataMeta.TYPE_SYSTEM_INFO_FILENAME : row[index] = getTransMeta().getFilename(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_01: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_02: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_03: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_04: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_05: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_06: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_07: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_08: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_09: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_10: argnr = meta.getFieldType()[i]-SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_01; if (argnr<getTransMeta().getArguments().length) { row[index] = getTransMeta().getArguments()[argnr]; } else { row[index] = null; } break; case SystemDataMeta.TYPE_SYSTEM_INFO_KETTLE_VERSION: row[index] = Const.VERSION; break; case SystemDataMeta.TYPE_SYSTEM_INFO_KETTLE_BUILD_VERSION: row[index] = new Long( BuildVersion.getInstance().getVersion() ); break; case SystemDataMeta.TYPE_SYSTEM_INFO_KETTLE_BUILD_DATE: row[index] = BuildVersion.getInstance().getBuildDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_CURRENT_PID: row[index] =new Long(Management.getPID()); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JVM_TOTAL_MEMORY: row[index] = Runtime.getRuntime().totalMemory(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JVM_FREE_MEMORY: row[index] = Runtime.getRuntime().freeMemory(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JVM_MAX_MEMORY: row[index] = Runtime.getRuntime().maxMemory(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JVM_AVAILABLE_MEMORY: Runtime rt=Runtime.getRuntime(); row[index] = rt.freeMemory()+ (rt.maxMemory()-rt.totalMemory()); break; case SystemDataMeta.TYPE_SYSTEM_INFO_AVAILABLE_PROCESSORS: row[index] = (long)Runtime.getRuntime().availableProcessors(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JVM_CPU_TIME: row[index] = Management.getJVMCpuTime()/1000000; break; case SystemDataMeta.TYPE_SYSTEM_INFO_TOTAL_PHYSICAL_MEMORY_SIZE: row[index] = Management.getTotalPhysicalMemorySize(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TOTAL_SWAP_SPACE_SIZE: row[index] = Management.getTotalSwapSpaceSize(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_COMMITTED_VIRTUAL_MEMORY_SIZE: row[index] = Management.getCommittedVirtualMemorySize(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_FREE_PHYSICAL_MEMORY_SIZE: row[index] = Management.getFreePhysicalMemorySize(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_FREE_SWAP_SPACE_SIZE: row[index] = Management.getFreeSwapSpaceSize(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_WEEK_START: cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, -1); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_WEEK_END: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_WEEK_OPEN_END: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); cal.add(Calendar.DAY_OF_WEEK, -2); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_WEEK_START_US: cal = Calendar.getInstance(Locale.US); cal.add(Calendar.WEEK_OF_YEAR, -1); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_WEEK_END_US: cal = Calendar.getInstance(Locale.US); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_WEEK_START: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_WEEK_END: cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, 1); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_WEEK_OPEN_END: cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, 1); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); cal.add(Calendar.DAY_OF_WEEK, -2); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_WEEK_START_US: cal = Calendar.getInstance(Locale.US); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_WEEK_END_US: cal = Calendar.getInstance(Locale.US); cal.add(Calendar.WEEK_OF_YEAR, 1); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_WEEK_START: cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, 1); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_WEEK_END: cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, 2); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_WEEK_OPEN_END: cal = Calendar.getInstance(); cal.add(Calendar.WEEK_OF_YEAR, 2); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); cal.add(Calendar.DAY_OF_WEEK, -2); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_WEEK_START_US: cal = Calendar.getInstance(Locale.US); cal.add(Calendar.WEEK_OF_YEAR, 1); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_WEEK_END_US: cal = Calendar.getInstance(Locale.US); cal.add(Calendar.WEEK_OF_YEAR, 2); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, -1); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_QUARTER_START: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -3-(cal.get(Calendar.MONTH) % 3)); cal.set(Calendar.DAY_OF_MONTH,1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_QUARTER_END: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1 - (cal.get(Calendar.MONTH) % 3)); cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DATE)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_QUARTER_START: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 0 - (cal.get(Calendar.MONTH) % 3)); cal.set(Calendar.DAY_OF_MONTH,1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_QUARTER_END: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 2 - (cal.get(Calendar.MONTH) % 3)); cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DATE)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_QUARTER_START: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 3 -(cal.get(Calendar.MONTH) % 3)); cal.set(Calendar.DAY_OF_MONTH,1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_QUARTER_END: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 5 - (cal.get(Calendar.MONTH) % 3)); cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DATE)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_YEAR_START: cal = Calendar.getInstance(); cal.add(Calendar.YEAR, -1); cal.set(Calendar.DAY_OF_YEAR,cal.getActualMinimum(Calendar.DATE)); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_YEAR_END: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_YEAR,cal.getActualMinimum(Calendar.DATE)); cal.add(Calendar.DAY_OF_YEAR, -1); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_YEAR_START: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_YEAR,cal.getActualMinimum(Calendar.DATE)); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_YEAR_END: cal = Calendar.getInstance(); cal.add(Calendar.YEAR, 1); cal.set(Calendar.DAY_OF_YEAR,cal.getActualMinimum(Calendar.DATE)); cal.add(Calendar.DAY_OF_YEAR, -1); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_YEAR_START: cal = Calendar.getInstance(); cal.add(Calendar.YEAR, 1); cal.set(Calendar.DAY_OF_YEAR,cal.getActualMinimum(Calendar.DATE)); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_YEAR_END: cal = Calendar.getInstance(); cal.add(Calendar.YEAR, 2); cal.set(Calendar.DAY_OF_YEAR,cal.getActualMinimum(Calendar.DATE)); cal.add(Calendar.DAY_OF_YEAR, -1); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_RESULT: Result previousResult = getTransMeta().getPreviousResult(); boolean result=false; if(previousResult!=null) { result= previousResult.getResult(); } row[index] =result; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_EXIT_STATUS: previousResult = getTransMeta().getPreviousResult(); long value=0; if(previousResult!=null) { value= previousResult.getExitStatus(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_ENTRY_NR: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getEntryNr(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_FILES: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getResultFiles().size(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_FILES_RETRIEVED: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrFilesRetrieved(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_LINES_DELETED: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrLinesDeleted(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_LINES_INPUT: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrLinesInput(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_LINES_OUTPUT: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrLinesOutput(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_LINES_READ: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrLinesRead(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_LINES_REJETED: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrLinesRejected(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_LINES_UPDATED: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrLinesUpdated(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_LINES_WRITTEN: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrLinesWritten(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_ROWS: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getRows().size(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_IS_STOPPED: previousResult = getTransMeta().getPreviousResult(); boolean stop=false; if(previousResult!=null) { stop= previousResult.isStopped(); } row[index] =stop; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_NR_ERRORS: previousResult = getTransMeta().getPreviousResult(); value=0; if(previousResult!=null) { value= previousResult.getNrErrors(); } row[index] =value; break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREVIOUS_RESULT_LOG_TEXT: previousResult = getTransMeta().getPreviousResult(); String errorReason=null; if(previousResult!=null) { errorReason= previousResult.getLogText(); } row[index] =errorReason; break; default: break; } } return row; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { Object[] row; if (data.readsRows) { row=getRow(); if (row==null) { setOutputDone(); return false; } if (first) { first=false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); } } else { row=new Object[] {}; // empty row incrementLinesRead(); if (first) { first=false; data.outputRowMeta = new RowMeta(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); } } RowMetaInterface imeta = getInputRowMeta(); if (imeta==null) { imeta=new RowMeta(); this.setInputRowMeta(imeta); } row = getSystemData(imeta, row); if (log.isRowLevel()) logRowlevel("System info returned: "+data.outputRowMeta.getString(row)); putRow(data.outputRowMeta, row); if (!data.readsRows) // Just one row and then stop! { setOutputDone(); return false; } return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(SystemDataMeta)smi; data=(SystemDataData)sdi; if (super.init(smi, sdi)) { // Add init code here. data.readsRows = false; List<StepMeta> previous = getTransMeta().findPreviousSteps(getStepMeta()); if (previous!=null && previous.size()>0) { data.readsRows = true; } return true; } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { super.dispose(smi, sdi); } }
package com.qianfeng.manmankan.ui; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.qianfeng.manmankan.R; import com.qianfeng.manmankan.adapters.PlayerViewPagerAdapter; import com.qianfeng.manmankan.constans.HttpConstants; import com.qianfeng.manmankan.events.EventModel; import com.qianfeng.manmankan.model.playermodels.PlayerModel; import com.qianfeng.manmankan.ui.fragments.LeftFragment; import com.qianfeng.manmankan.ui.fragments.RightFragment; import com.qianfeng.manmankan.utils.LightController; import com.qianfeng.manmankan.utils.MyShare; import com.qianfeng.manmankan.utils.VolumeController; import org.greenrobot.eventbus.EventBus; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.image.ImageOptions; import org.xutils.x; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.vov.vitamio.Vitamio; import io.vov.vitamio.widget.VideoView; public class PlayerActivity extends BaseActivity implements View.OnTouchListener, CompoundButton.OnCheckedChangeListener, View.OnClickListener { private static final String TAG = PlayerActivity.class.getSimpleName(); @BindView(R.id.player_video) VideoView mVideo; @BindView(R.id.video_more_btn) Button mMoreBtn; @BindView(R.id.video_gift) CheckBox mGift; @BindView(R.id.video_on_off) CheckBox mOnOff; @BindView(R.id.video_full_screen) Button mFullScreen; @BindView(R.id.room_icon) ImageView mRoomIcon; @BindView(R.id.room_name) TextView mRoomName; @BindView(R.id.room_content) TextView mRoomContent; @BindView(R.id.room_follow_btn) CheckBox mRoomFollowBtn; @BindView(R.id.room_follow_text) TextView mRoomFollowText; @BindView(R.id.room_remind_btn) CheckBox mRoomRemindBtn; @BindView(R.id.room_remind_circle) ImageView mRoomRemindCircle; @BindView(R.id.room_tab) TabLayout mRoomTab; @BindView(R.id.room_viewpager) ViewPager mRoomViewpager; @BindView(R.id.player_vertical_controller) LinearLayout mControl; @BindView(R.id.player_bottom) LinearLayout mPlayerBottom; @BindView(R.id.full_bottom_control) LinearLayout mFullBottomControl; @BindView(R.id.full_top_control) LinearLayout mFullTopControl; @BindView(R.id.player_vertical_controller_left) LinearLayout mControllerLeft; @BindView(R.id.full_top_exit) Button mFullTopExit; @BindView(R.id.btn_screen_gift) Button mScreenGift; @BindView(R.id.btn_screen_definition) Button mScreenDefinition; @BindView(R.id.btn_full_shared) Button mFullShared; @BindView(R.id.btn_live_exit) Button btnLiveExit; @BindView(R.id.full_bottom_refresh) Button mFullBottomRefresh; @BindView(R.id.full_hot_text) Button mFullHotText; @BindView(R.id.full_send_text) Button mFullSendText; @BindView(R.id.full_gift) Button mFullGift; @BindView(R.id.definition_list) ListView mDefinitionList; private int mScreenHeight; private int mScreenWidth; private float mStartX; private float mStartY; private float mLastX; private float mLastY; private boolean isLandscape; private float threshold = 10; private boolean isFull; private int oldHeight; private boolean screenGift; private PopupWindow popupWindow; private Button mReport; private Button mPopShare; private String uid; private DateFormat format; private PlayerViewPagerAdapter adapter; private ImageOptions options; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Vitamio.isInitialized(getApplication()); setContentView(R.layout.activity_player); ButterKnife.bind(this); initView(); } private void initView() { options = new ImageOptions.Builder().setCircular(true).build(); Intent intent = getIntent(); uid = intent.getStringExtra("uid"); format=new SimpleDateFormat("MMddHHmm"); mVideo.setOnTouchListener(this); mScreenHeight = getResources().getDisplayMetrics().heightPixels; mScreenWidth = getResources().getDisplayMetrics().widthPixels; mGift.setOnCheckedChangeListener(this); mOnOff.setOnCheckedChangeListener(this); mRoomFollowBtn.setOnCheckedChangeListener(this); mRoomRemindBtn.setOnCheckedChangeListener(this); String[] tabdata={"",""}; mRoomTab.addTab(mRoomTab.newTab().setText(tabdata[0])); mRoomTab.addTab(mRoomTab.newTab().setText(tabdata[1])); List<Fragment> data=new ArrayList<>(); data.add(new LeftFragment()); data.add(new RightFragment()); adapter = new PlayerViewPagerAdapter(getSupportFragmentManager(),data,tabdata); mRoomViewpager.setAdapter(adapter); mRoomTab.setupWithViewPager(mRoomViewpager); getData(); } private void getData() { Date date=new Date(); String time=format.format(date); RequestParams params = new RequestParams(HttpConstants.RECOMMEND_VIEWPAGER_START+uid+HttpConstants.RECOMMEND_VIEWPAGER_MIDDLE+time+HttpConstants.RECOMMEND_VIEWPAGER_END); x.http().get(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { if (result==null) { Log.e(TAG, "onSuccess: "+"result } Gson gson = new Gson(); PlayerModel playerModel = gson.fromJson(result, PlayerModel.class); EventModel eventModel = new EventModel(); eventModel.setData(playerModel.getRank_total()); eventModel.setDataTwo(playerModel.getRank_week()); EventBus.getDefault().post(eventModel); String src = playerModel.getRoom_lines().get(0).getHls().getThree().getSrc(); mRoomName.setText(playerModel.getNick()); mRoomContent.setText(playerModel.getIntro()); x.image().bind(mRoomIcon,playerModel.getAvatar(), options); mVideo.setVideoPath(src); mVideo.start(); } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); } @Override public boolean onTouch(View v, MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mStartX = x; mStartY = y; mLastX = x; mLastY = y; if (popupWindow != null) { popupWindow.dismiss(); } break; case MotionEvent.ACTION_MOVE: if (isLandscape) { float xDelta = x - mLastX; float yDetla = y - mLastY; if (Math.abs(yDetla) > threshold) { if (x > mScreenHeight / 2) { if (yDetla > 0) { Log.e(TAG, "onTouch: VolumeController.volumeDown(this, yDetla, mScreenWidth); } else { Log.e(TAG, "onTouch: VolumeController.volumeUp(this, yDetla, mScreenWidth); } } else { if (yDetla > 0) { Log.e(TAG, "onTouch: LightController.lightDown(PlayerActivity.this, yDetla, mScreenWidth); } else { Log.e(TAG, "onTouch: LightController.lightUp(PlayerActivity.this, yDetla, mScreenWidth); } } } } mLastX = x; mLastY = y; break; case MotionEvent.ACTION_UP: if (Math.abs(x - mStartX) < threshold && Math.abs(y - mStartY) < threshold) { if (!isLandscape) { showOrHideController(); } else { horizontalShowOrHideController(); } } break; } return true; } private void horizontalShowOrHideController() { if (mFullTopControl.getVisibility() == View.VISIBLE) { mFullTopControl.setVisibility(View.GONE); mFullBottomControl.setVisibility(View.GONE); Animation animation = AnimationUtils.loadAnimation(this, R.anim.controller_exit); Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.top_control_exit); mFullBottomControl.startAnimation(animation); mFullTopControl.startAnimation(animationTop); } else if (mFullTopControl.getVisibility() == View.GONE) { mFullTopControl.setVisibility(View.VISIBLE); mFullBottomControl.setVisibility(View.VISIBLE); Animation animation = AnimationUtils.loadAnimation(this, R.anim.controller); Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.top_control); mFullBottomControl.startAnimation(animation); mFullTopControl.startAnimation(animationTop); } } private void showOrHideController() { if (mControl.getVisibility() == View.VISIBLE) { mControl.setVisibility(View.GONE); mControllerLeft.setVisibility(View.GONE); // Animation animation = AnimationUtils.loadAnimation(this, R.anim.vertical_control_exit); // mControl.startAnimation(animation); // mControllerLeft.startAnimation(animation); } else if (mControl.getVisibility() == View.GONE) { mControl.setVisibility(View.VISIBLE); mControllerLeft.setVisibility(View.VISIBLE); Animation animation = AnimationUtils.loadAnimation(this, R.anim.vertical_control); mControl.startAnimation(animation); mControllerLeft.startAnimation(animation); } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { switch (buttonView.getId()) { case R.id.video_on_off: if (isChecked) { mVideo.pause(); } else { mVideo.start(); } break; case R.id.video_gift: break; case R.id.room_follow_btn: if (isChecked) { mRoomFollowText.setText(""); } else { mRoomFollowText.setText(""); } break; case R.id.room_remind_btn: if (isChecked) { TranslateAnimation right = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 1 , TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0); right.setDuration(100); right.setFillAfter(true); mRoomRemindCircle.startAnimation(right); mRoomFollowBtn.setChecked(true); } else { TranslateAnimation left = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF, 1, TranslateAnimation.RELATIVE_TO_SELF, 0 , TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0); left.setDuration(100); left.setFillAfter(true); mRoomRemindCircle.startAnimation(left); } break; } } private void exitFull() { horizontalShowOrHideController(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); ViewGroup.LayoutParams params = mVideo.getLayoutParams(); params.height = oldHeight; params.width=ViewGroup.LayoutParams.MATCH_PARENT; mVideo.setLayoutParams(params); isFull = false; isLandscape = false; mPlayerBottom.setVisibility(View.VISIBLE); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (isFull) { exitFull(); } else { finish(); } } return super.onKeyDown(keyCode, event); } @OnClick({R.id.full_top_exit, R.id.btn_screen_gift, R.id.btn_screen_definition, R.id.btn_full_shared, R.id.btn_live_exit, R.id.video_more_btn, R.id.video_full_screen, R.id.full_bottom_refresh, R.id.full_hot_text, R.id.full_send_text, R.id.full_gift}) public void onClick(View view) { DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); int widthPixels = displayMetrics.widthPixels; int heightPixels = displayMetrics.heightPixels; switch (view.getId()) { case R.id.full_top_exit: exitFull(); break; case R.id.btn_screen_gift: if (screenGift) { mScreenGift.setText(""); Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); screenGift = false; } else { mScreenGift.setText(""); Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); screenGift = true; } break; case R.id.btn_screen_definition: mDefinitionList.setVisibility(View.VISIBLE); break; case R.id.btn_full_shared: MyShare.showShare(); break; case R.id.btn_live_exit: finish(); break; case R.id.video_more_btn: if (popupWindow == null) { View pop = LayoutInflater.from(this).inflate(R.layout.popupwindow_more, null); mReport = (Button) pop.findViewById(R.id.pop_report); mPopShare = (Button) pop.findViewById(R.id.pop_share); mReport.setOnClickListener(this); mPopShare.setOnClickListener(this); popupWindow = new PopupWindow(pop); popupWindow.setWidth(widthPixels / 5); popupWindow.setHeight(heightPixels / 9); } if (popupWindow.isShowing()) { popupWindow.dismiss(); } else { // popupWindow.showAsDropDown(view,widthPixels / 6,0); popupWindow.showAtLocation(view, Gravity.RIGHT | Gravity.TOP, 50, 60); } break; case R.id.video_full_screen: mPlayerBottom.setVisibility(View.GONE); mControllerLeft.setVisibility(View.GONE); mControl.setVisibility(View.GONE); mFullTopControl.setVisibility(View.VISIBLE); mFullBottomControl.setVisibility(View.VISIBLE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); ViewGroup.LayoutParams layoutParams = mVideo.getLayoutParams(); oldHeight = layoutParams.height; layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; layoutParams.width = mScreenHeight; mVideo.setLayoutParams(layoutParams); isLandscape = true; isFull = true; break; case R.id.full_bottom_refresh: Toast.makeText(this,"",Toast.LENGTH_SHORT); break; case R.id.full_hot_text: break; case R.id.full_send_text: break; case R.id.full_gift: break; case R.id.pop_report: Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); break; case R.id.pop_share: Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); break; } } }
package com.mixpanel.android.mpmetrics; import android.support.annotation.IntDef; import android.util.Log; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * In general, you won't need to interact with this class directly - * it's used internally to communicate changes in values to the tweaks you define with * {@link MixpanelAPI#stringTweak(String, String)}, {@link MixpanelAPI#booleanTweak(String, boolean)}, * {@link MixpanelAPI#doubleTweak(String, double)}, {@link MixpanelAPI#longTweak(String, long)}, * and other tweak-related interfaces on MixpanelAPI. * * Instances of tweaks aren't available to library user code. */ public class Tweaks { /** * This method is used internally to expose tweaks to the Mixpanel UI, * and will likely not be directly useful to code that imports the Mixpanel library. * The given listener's onTweakDeclared method will be called when a new tweak is declared. */ public synchronized void addOnTweakDeclaredListener(OnTweakDeclaredListener listener) { if (null == listener) { throw new NullPointerException("listener cannot be null"); } mTweakDeclaredListeners.add(listener); } /** * Manually set the value of a tweak. Most users of the library will not need to call this * directly - instead, the library will call set when new values of the tweak are published. */ public synchronized void set(String tweakName, Object value) { if (!mTweakValues.containsKey(tweakName)) { Log.w(LOGTAG, "Attempt to set a tweak \"" + tweakName + "\" which has never been defined."); return; } final TweakValue container = mTweakValues.get(tweakName); final TweakValue updated = container.updateValue(value); mTweakValues.put(tweakName, updated); } public synchronized boolean isNewValue(String tweakName, Object value) { if (!mTweakValues.containsKey(tweakName)) { Log.w(LOGTAG, "Attempt to reference a tweak \"" + tweakName + "\" which has never been defined."); return false; } final TweakValue container = mTweakValues.get(tweakName); return !container.value.equals(value); } /** * Returns the descriptions of all tweaks that currently exist. * * The Mixpanel library uses this method internally to expose tweaks and their types to the UI. Most * users will not need to call this method directly. */ public synchronized Map<String, TweakValue> getAllValues() { return new HashMap<String, TweakValue>(mTweakValues); } public synchronized Map<String, TweakValue> getDefaultValues() { return new HashMap<String, TweakValue>(mTweakDefaultValues); } @IntDef({ BOOLEAN_TYPE, DOUBLE_TYPE, LONG_TYPE, STRING_TYPE }) @Retention(RetentionPolicy.SOURCE) private @interface TweakType {} /** * An internal description of the type of a tweak. * These values are used internally to expose * tweaks to the Mixpanel UI, and will likely not be directly useful to * code that imports the Mixpanel library. */ public static final @TweakType int BOOLEAN_TYPE = 1; /** * An internal description of the type of a tweak. * These values are used internally to expose * tweaks to the Mixpanel UI, and will likely not be directly useful to * code that imports the Mixpanel library. */ public static final @TweakType int DOUBLE_TYPE = 2; /** * An internal description of the type of a tweak. * These values are used internally to expose * tweaks to the Mixpanel UI, and will likely not be directly useful to * code that imports the Mixpanel library. */ public static final @TweakType int LONG_TYPE = 3; /** * An internal description of the type of a tweak. * These values are used internally to expose * tweaks to the Mixpanel UI, and will likely not be directly useful to * code that imports the Mixpanel library. */ public static final @TweakType int STRING_TYPE = 4; /** * Represents the value and definition of a tweak known to the system. This class * is used internally to expose tweaks to the Mixpanel UI, * and will likely not be directly useful to code that imports the Mixpanel library. */ public static class TweakValue { private TweakValue(@TweakType int aType, Object aDefaultValue, Number aMin, Number aMax, Object value) { type = aType; defaultValue = aDefaultValue; minimum = aMin; maximum = aMax; this.value = value; } public TweakValue updateValue(Object newValue) { return new TweakValue(type, defaultValue, minimum, maximum, newValue); } public String getStringValue() { String ret = null; try { ret = (String) defaultValue; } catch (ClassCastException e) { ; } try { ret = (String) value; } catch (ClassCastException e) { ; } return ret; } public Number getNumberValue() { Number ret = 0; if (null != defaultValue) { try { ret = (Number) defaultValue; } catch (ClassCastException e){ ; } } if (null != value) { try { ret = (Number) value; } catch (ClassCastException e) { ; } } return ret; } public Boolean getBooleanValue() { Boolean ret = false; if (null != defaultValue) { try { ret = (Boolean) defaultValue; } catch (ClassCastException e) { ; } } if (null != value) { try { ret = (Boolean) value; } catch (ClassCastException e) { ; } } return ret; } public final @TweakType int type; protected final Object value; private final Object defaultValue; private final Number minimum; private final Number maximum; } /** * This interface is used internally to expose tweaks to the Mixpanel UI, * and will likely not be directly useful to code that imports the Mixpanel library. */ public interface OnTweakDeclaredListener { void onTweakDeclared(); } /* package */ Tweaks() { mTweakValues = new ConcurrentHashMap<>(); mTweakDefaultValues = new ConcurrentHashMap<>(); mTweakDeclaredListeners = new ArrayList<>(); } /* package */ Tweak<String> stringTweak(final String tweakName, final String defaultValue) { declareTweak(tweakName, defaultValue, STRING_TYPE); return new Tweak<String>() { @Override public String get() { final TweakValue tweakValue = getValue(tweakName); return tweakValue.getStringValue(); } }; } /* package */ Tweak<Double> doubleTweak(final String tweakName, final double defaultValue) { declareTweak(tweakName, defaultValue, DOUBLE_TYPE); return new Tweak<Double>() { @Override public Double get() { final TweakValue tweakValue = getValue(tweakName); final Number result = tweakValue.getNumberValue(); return result.doubleValue(); } }; } /* package */ Tweak<Float> floatTweak(final String tweakName, final float defaultValue) { declareTweak(tweakName, defaultValue, DOUBLE_TYPE); return new Tweak<Float>() { @Override public Float get() { final TweakValue tweakValue = getValue(tweakName); final Number result = tweakValue.getNumberValue(); return result.floatValue(); } }; } /* package */ Tweak<Long> longTweak(final String tweakName, final long defaultValue) { declareTweak(tweakName, defaultValue, LONG_TYPE); return new Tweak<Long>() { @Override public Long get() { final TweakValue tweakValue = getValue(tweakName); final Number result = tweakValue.getNumberValue(); return result.longValue(); } }; } /* package */ Tweak<Integer> intTweak(final String tweakName, final int defaultValue) { declareTweak(tweakName, defaultValue, LONG_TYPE); return new Tweak<Integer>() { @Override public Integer get() { final TweakValue tweakValue = getValue(tweakName); final Number result = tweakValue.getNumberValue(); return result.intValue(); } }; } /* package */ Tweak<Byte> byteTweak(final String tweakName, final byte defaultValue) { declareTweak(tweakName, defaultValue, LONG_TYPE); return new Tweak<Byte>() { @Override public Byte get() { final TweakValue tweakValue = getValue(tweakName); final Number result = tweakValue.getNumberValue(); return result.byteValue(); } }; } /* package */ Tweak<Short> shortTweak(final String tweakName, final short defaultValue) { declareTweak(tweakName, defaultValue, LONG_TYPE); return new Tweak<Short>() { @Override public Short get() { final TweakValue tweakValue = getValue(tweakName); final Number result = tweakValue.getNumberValue(); return result.shortValue(); } }; } /* package */ Tweak<Boolean> booleanTweak(final String tweakName, final boolean defaultValue) { declareTweak(tweakName, defaultValue, BOOLEAN_TYPE); return new Tweak<Boolean>() { @Override public Boolean get() { final TweakValue tweakValue = getValue(tweakName); return tweakValue.getBooleanValue(); } }; } private synchronized TweakValue getValue(String tweakName) { return mTweakValues.get(tweakName); } private void declareTweak(String tweakName, Object defaultValue, @TweakType int tweakType) { if (mTweakValues.containsKey(tweakName)) { Log.w(LOGTAG, "Attempt to define a tweak \"" + tweakName + "\" twice with the same name"); return; } final TweakValue value = new TweakValue(tweakType, defaultValue, null, null, defaultValue); mTweakValues.put(tweakName, value); mTweakDefaultValues.put(tweakName, value); final int listenerSize = mTweakDeclaredListeners.size(); for (int i = 0; i < listenerSize; i++) { mTweakDeclaredListeners.get(i).onTweakDeclared(); } } // All access to mTweakValues must be synchronized private final ConcurrentMap<String, TweakValue> mTweakValues; private final ConcurrentMap<String, TweakValue> mTweakDefaultValues; private final List<OnTweakDeclaredListener> mTweakDeclaredListeners; private static final String LOGTAG = "MixpanelAPI.Tweaks"; }
package se.sics.cooja.plugins; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Observable; import java.util.Observer; import java.util.Properties; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ButtonGroup; import javax.swing.JFileChooser; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import org.apache.log4j.Logger; import org.jdom.Element; import se.sics.cooja.ClassDescription; import se.sics.cooja.ConvertedRadioPacket; import se.sics.cooja.GUI; import se.sics.cooja.Plugin; import se.sics.cooja.PluginType; import se.sics.cooja.RadioConnection; import se.sics.cooja.RadioMedium; import se.sics.cooja.RadioPacket; import se.sics.cooja.Simulation; import se.sics.cooja.VisPlugin; import se.sics.cooja.dialogs.TableColumnAdjuster; import se.sics.cooja.interfaces.Radio; import se.sics.cooja.plugins.analyzers.ICMPv6Analyzer; import se.sics.cooja.plugins.analyzers.IEEE802154Analyzer; import se.sics.cooja.plugins.analyzers.IPHCPacketAnalyzer; import se.sics.cooja.plugins.analyzers.IPv6PacketAnalyzer; import se.sics.cooja.plugins.analyzers.PacketAnalyzer; import se.sics.cooja.plugins.analyzers.RadioLoggerAnalyzerSuite; import se.sics.cooja.util.StringUtils; /** * Radio logger listens to the simulation radio medium and lists all transmitted * data in a table. * * @author Fredrik Osterlind */ @ClassDescription("Radio messages...") @PluginType(PluginType.SIM_PLUGIN) public class RadioLogger extends VisPlugin { private static Logger logger = Logger.getLogger(RadioLogger.class); private static final long serialVersionUID = -6927091711697081353L; private final static int COLUMN_TIME = 0; private final static int COLUMN_FROM = 1; private final static int COLUMN_TO = 2; private final static int COLUMN_DATA = 3; private JSplitPane splitPane; private JTextPane verboseBox = null; private final static String[] COLUMN_NAMES = { "Time", "From", "To", "Data" }; private final Simulation simulation; private final JTable dataTable; private ArrayList<RadioConnectionLog> connections = new ArrayList<RadioConnectionLog>(); private RadioMedium radioMedium; private Observer radioMediumObserver; private AbstractTableModel model; private HashMap<String,Action> analyzerMap = new HashMap<String,Action>(); private String analyzerName = null; private ArrayList<PacketAnalyzer> analyzers = null; private JTextField searchField = new JTextField(30); public RadioLogger(final Simulation simulationToControl, final GUI gui) { super("Radio messages", gui); setLayout(new BorderLayout()); simulation = simulationToControl; radioMedium = simulation.getRadioMedium(); /* Menus */ JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu editMenu = new JMenu("Edit"); JMenu analyzerMenu = new JMenu("Analyzer"); JMenu payloadMenu = new JMenu("Payload"); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(analyzerMenu); menuBar.add(payloadMenu); this.setJMenuBar(menuBar); ArrayList<PacketAnalyzer> lowpanAnalyzers = new ArrayList<PacketAnalyzer>(); lowpanAnalyzers.add(new IEEE802154Analyzer(false)); lowpanAnalyzers.add(new IPHCPacketAnalyzer()); lowpanAnalyzers.add(new IPv6PacketAnalyzer()); lowpanAnalyzers.add(new ICMPv6Analyzer()); ArrayList<PacketAnalyzer> lowpanAnalyzersPcap = new ArrayList<PacketAnalyzer>(); lowpanAnalyzersPcap.add(new IEEE802154Analyzer(true)); lowpanAnalyzersPcap.add(new IPHCPacketAnalyzer()); lowpanAnalyzersPcap.add(new IPv6PacketAnalyzer()); lowpanAnalyzersPcap.add(new ICMPv6Analyzer()); model = new AbstractTableModel() { private static final long serialVersionUID = 1692207305977527004L; public String getColumnName(int col) { return COLUMN_NAMES[col]; } public int getRowCount() { return connections.size(); } public int getColumnCount() { return COLUMN_NAMES.length; } public Object getValueAt(int row, int col) { RadioConnectionLog conn = connections.get(row); if (col == COLUMN_TIME) { return Long.toString(conn.startTime / Simulation.MILLISECOND); } else if (col == COLUMN_FROM) { return "" + conn.connection.getSource().getMote().getID(); } else if (col == COLUMN_TO) { Radio[] dests = conn.connection.getDestinations(); if (dests.length == 0) { return "-"; } if (dests.length == 1) { return "" + dests[0].getMote().getID(); } if (dests.length == 2) { return "" + dests[0].getMote().getID() + ',' + dests[1].getMote().getID(); } return "[" + dests.length + " d]"; } else if (col == COLUMN_DATA) { if (conn.data == null) { prepareDataString(connections.get(row)); } if (aliases != null) { /* Check if alias exists */ String alias = (String) aliases.get(conn.data); if (alias != null) { return alias; } } return conn.data; } return null; } public boolean isCellEditable(int row, int col) { if (col == COLUMN_FROM) { /* Highlight source */ gui.signalMoteHighlight(connections.get(row).connection.getSource().getMote()); return false; } if (col == COLUMN_TO) { /* Highlight all destinations */ Radio dests[] = connections.get(row).connection.getDestinations(); for (Radio dest: dests) { gui.signalMoteHighlight(dest.getMote()); } return false; } return false; } public Class<?> getColumnClass(int c) { return getValueAt(0, c).getClass(); } }; dataTable = new JTable(model) { private static final long serialVersionUID = -2199726885069809686L; public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); if (rowIndex < 0 || realColumnIndex < 0) { return super.getToolTipText(e); } RadioConnectionLog conn = connections.get(rowIndex); if (realColumnIndex == COLUMN_TIME) { return "<html>" + "Start time (us): " + conn.startTime + "<br>" + "End time (us): " + conn.endTime + "<br><br>" + "Duration (us): " + (conn.endTime - conn.startTime) + "</html>"; } else if (realColumnIndex == COLUMN_FROM) { return conn.connection.getSource().getMote().toString(); } else if (realColumnIndex == COLUMN_TO) { Radio[] dests = conn.connection.getDestinations(); if (dests.length == 0) { return "No destinations"; } StringBuilder tip = new StringBuilder(); tip.append("<html>"); if (dests.length == 1) { tip.append("One destination:<br>"); } else { tip.append(dests.length).append(" destinations:<br>"); } for (Radio radio: dests) { tip.append(radio.getMote()).append("<br>"); } tip.append("</html>"); return tip.toString(); } else if (realColumnIndex == COLUMN_DATA) { if (conn.tooltip == null) { prepareTooltipString(conn); } return conn.tooltip; } return super.getToolTipText(e); } }; dataTable.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { showInAllAction.actionPerformed(null); } else if (e.getKeyCode() == KeyEvent.VK_F && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) { searchField.setVisible(true); searchField.requestFocus(); searchField.selectAll(); revalidate(); } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { searchField.setVisible(false); dataTable.requestFocus(); revalidate(); } } }); dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int row = dataTable.getSelectedRow(); if (row >= 0) { RadioConnectionLog conn = connections.get(row); if (conn.tooltip == null) { prepareTooltipString(conn); } verboseBox.setText(conn.tooltip); verboseBox.setCaretPosition(0); } } }); // Set data column width greedy dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); dataTable.setFont(new Font("Monospaced", Font.PLAIN, 12)); editMenu.add(new JMenuItem(copyAllAction)); editMenu.add(new JMenuItem(copyAction)); editMenu.add(new JSeparator()); editMenu.add(new JMenuItem(clearAction)); payloadMenu.add(new JMenuItem(aliasAction)); fileMenu.add(new JMenuItem(saveAction)); JPopupMenu popupMenu = new JPopupMenu(); JMenu focusMenu = new JMenu("Show in"); focusMenu.add(new JMenuItem(showInAllAction)); focusMenu.addSeparator(); focusMenu.add(new JMenuItem(timeLineAction)); focusMenu.add(new JMenuItem(logListenerAction)); popupMenu.add(focusMenu); //a group of radio button menu items ButtonGroup group = new ButtonGroup(); JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem( createAnalyzerAction("No Analyzer", "none", null, true)); group.add(rbMenuItem); analyzerMenu.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem(createAnalyzerAction( "6LoWPAN Analyzer", "6lowpan", lowpanAnalyzers, false)); group.add(rbMenuItem); analyzerMenu.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem(createAnalyzerAction( "6LoWPAN Analyzer with PCAP", "6lowpan-pcap", lowpanAnalyzersPcap, false)); group.add(rbMenuItem); analyzerMenu.add(rbMenuItem); /* Load additional analyzers specified by projects (cooja.config) */ String[] projectAnalyzerSuites = gui.getProjectConfig().getStringArrayValue(RadioLogger.class, "ANALYZERS"); if (projectAnalyzerSuites != null) { for (String suiteName: projectAnalyzerSuites) { Class<? extends RadioLoggerAnalyzerSuite> suiteClass = gui.tryLoadClass(RadioLogger.this, RadioLoggerAnalyzerSuite.class, suiteName); try { RadioLoggerAnalyzerSuite suite = suiteClass.newInstance(); ArrayList<PacketAnalyzer> suiteAnalyzers = suite.getAnalyzers(); rbMenuItem = new JRadioButtonMenuItem(createAnalyzerAction( suite.getDescription(), suiteName, suiteAnalyzers, false)); group.add(rbMenuItem); popupMenu.add(rbMenuItem); logger.debug("Loaded radio logger analyzers: " + suite.getDescription()); } catch (InstantiationException e1) { logger.warn("Failed to load analyzer suite '" + suiteName + "': " + e1.getMessage()); } catch (IllegalAccessException e1) { logger.warn("Failed to load analyzer suite '" + suiteName + "': " + e1.getMessage()); } } } dataTable.setComponentPopupMenu(popupMenu); dataTable.setFillsViewportHeight(true); verboseBox = new JTextPane(); verboseBox.setContentType("text/html"); verboseBox.setEditable(false); verboseBox.setComponentPopupMenu(popupMenu); /* Search text field */ searchField.setVisible(false); searchField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { searchSelectNext( searchField.getText(), (e.getModifiers() & KeyEvent.SHIFT_MASK) != 0); } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { searchField.setVisible(false); dataTable.requestFocus(); revalidate(); } } }); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(dataTable), new JScrollPane(verboseBox)); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(150); add(BorderLayout.NORTH, searchField); add(BorderLayout.CENTER, splitPane); TableColumnAdjuster adjuster = new TableColumnAdjuster(dataTable); adjuster.setDynamicAdjustment(true); adjuster.packColumns(); radioMedium.addRadioMediumObserver(radioMediumObserver = new Observer() { public void update(Observable obs, Object obj) { RadioConnection conn = radioMedium.getLastConnection(); if (conn == null) { return; } final RadioConnectionLog loggedConn = new RadioConnectionLog(); loggedConn.startTime = conn.getStartTime(); loggedConn.endTime = simulation.getSimulationTime(); loggedConn.connection = conn; loggedConn.packet = conn.getSource().getLastPacketTransmitted(); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { int lastSize = connections.size(); // Check if the last row is visible boolean isVisible = false; int rowCount = dataTable.getRowCount(); if (rowCount > 0) { Rectangle lastRow = dataTable.getCellRect(rowCount - 1, 0, true); Rectangle visible = dataTable.getVisibleRect(); isVisible = visible.y <= lastRow.y && visible.y + visible.height >= lastRow.y + lastRow.height; } connections.add(loggedConn); if (connections.size() > lastSize) { model.fireTableRowsInserted(lastSize, connections.size() - 1); } if (isVisible) { dataTable.scrollRectToVisible(dataTable.getCellRect(dataTable.getRowCount() - 1, 0, true)); } setTitle("Radio messages: " + dataTable.getRowCount() + " messages seen"); } }); } }); setSize(500, 300); try { setSelected(true); } catch (java.beans.PropertyVetoException e) { // Could not select } } private void searchSelectNext(String text, boolean reverse) { if (text.isEmpty()) { return; } int row = dataTable.getSelectedRow(); if (row < 0) { row = 0; } if (!reverse) { row++; } else { row } int rows = dataTable.getModel().getRowCount(); for (int i=0; i < rows; i++) { int r; if (!reverse) { r = (row + i + rows)%rows; } else { r = (row - i + rows)%rows; } String val = (String) dataTable.getModel().getValueAt(r, COLUMN_DATA); if (!val.contains(text)) { continue; } dataTable.setRowSelectionInterval(r,r); dataTable.scrollRectToVisible(dataTable.getCellRect(r, COLUMN_DATA, true)); searchField.setBackground(Color.WHITE); return; } searchField.setBackground(Color.RED); } /** * Selects a logged radio packet close to the given time. * * @param time Start time */ public void trySelectTime(final long time) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { for (int i=0; i < connections.size(); i++) { if (connections.get(i).endTime < time) { continue; } dataTable.scrollRectToVisible(dataTable.getCellRect(i, 0, true)); dataTable.setRowSelectionInterval(i, i); return; } } }); } private void prepareDataString(RadioConnectionLog conn) { byte[] data; if (conn.packet == null) { data = null; } else if (conn.packet instanceof ConvertedRadioPacket) { data = ((ConvertedRadioPacket)conn.packet).getOriginalPacketData(); } else { data = conn.packet.getPacketData(); } if (data == null) { conn.data = "[unknown data]"; return; } StringBuffer brief = new StringBuffer(); StringBuffer verbose = new StringBuffer(); /* default analyzer */ PacketAnalyzer.Packet packet = new PacketAnalyzer.Packet(data, PacketAnalyzer.MAC_LEVEL); if (analyzePacket(packet, brief, verbose)) { if (packet.hasMoreData()) { byte[] payload = packet.getPayload(); brief.append(StringUtils.toHex(payload, 4)); if (verbose.length() > 0) { verbose.append("<p>"); } verbose.append("<b>Payload (") .append(payload.length).append(" bytes)</b><br><pre>") .append(StringUtils.hexDump(payload)) .append("</pre>"); } conn.data = (data.length < 100 ? (data.length < 10 ? " " : " ") : "") + data.length + ": " + brief; if (verbose.length() > 0) { conn.tooltip = verbose.toString(); } } else { conn.data = data.length + ": 0x" + StringUtils.toHex(data, 4); } } private boolean analyzePacket(PacketAnalyzer.Packet packet, StringBuffer brief, StringBuffer verbose) { if (analyzers == null) return false; try { boolean analyze = true; while (analyze) { analyze = false; for (int i = 0; i < analyzers.size(); i++) { PacketAnalyzer analyzer = analyzers.get(i); if (analyzer.matchPacket(packet)) { int res = analyzer.analyzePacket(packet, brief, verbose); if (packet.hasMoreData() && brief.length() > 0) { brief.append('|'); verbose.append("<br>"); } if (res != PacketAnalyzer.ANALYSIS_OK_CONTINUE) { /* this was the final or the analysis failed - no analyzable payload possible here... */ return brief.length() > 0; } /* continue another round if more bytes left */ analyze = packet.hasMoreData(); break; } } } } catch (Exception e) { logger.debug("Error when analyzing packet: " + e.getMessage(), e); return false; } return brief.length() > 0; } private void prepareTooltipString(RadioConnectionLog conn) { RadioPacket packet = conn.packet; if (packet == null) { conn.tooltip = ""; return; } if (packet instanceof ConvertedRadioPacket && packet.getPacketData().length > 0) { byte[] original = ((ConvertedRadioPacket)packet).getOriginalPacketData(); byte[] converted = ((ConvertedRadioPacket)packet).getPacketData(); conn.tooltip = "<html><font face=\"Monospaced\">" + "<b>Packet data (" + original.length + " bytes)</b><br>" + "<pre>" + StringUtils.hexDump(original) + "</pre>" + "</font><font face=\"Monospaced\">" + "<b>Cross-level packet data (" + converted.length + " bytes)</b><br>" + "<pre>" + StringUtils.hexDump(converted) + "</pre>" + "</font></html>"; } else if (packet instanceof ConvertedRadioPacket) { byte[] original = ((ConvertedRadioPacket)packet).getOriginalPacketData(); conn.tooltip = "<html><font face=\"Monospaced\">" + "<b>Packet data (" + original.length + " bytes)</b><br>" + "<pre>" + StringUtils.hexDump(original) + "</pre>" + "</font><font face=\"Monospaced\">" + "<b>No cross-level conversion available</b><br>" + "</font></html>"; } else { byte[] data = packet.getPacketData(); conn.tooltip = "<html><font face=\"Monospaced\">" + "<b>Packet data (" + data.length + " bytes)</b><br>" + "<pre>" + StringUtils.hexDump(data) + "</pre>" + "</font></html>"; } } public void closePlugin() { if (radioMediumObserver != null) { radioMedium.deleteRadioMediumObserver(radioMediumObserver); } } public Collection<Element> getConfigXML() { ArrayList<Element> config = new ArrayList<Element>(); Element element = new Element("split"); element.addContent(Integer.toString(splitPane.getDividerLocation())); config.add(element); if (analyzerName != null && analyzers != null) { element = new Element("analyzers"); element.setAttribute("name", analyzerName); config.add(element); } if (aliases != null) { for (Object key: aliases.keySet()) { element = new Element("alias"); element.setAttribute("payload", (String) key); element.setAttribute("alias", (String) aliases.get(key)); config.add(element); } } return config; } public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) { for (Element element : configXML) { String name = element.getName(); if ("alias".equals(name)) { String payload = element.getAttributeValue("payload"); String alias = element.getAttributeValue("alias"); if (aliases == null) { aliases = new Properties(); } aliases.put(payload, alias); } else if ("split".equals(name)) { splitPane.setDividerLocation(Integer.parseInt(element.getText())); } else if ("analyzers".equals(name)) { String analyzerName = element.getAttributeValue("name"); final Action action; if (analyzerName != null && ((action = analyzerMap.get(analyzerName)) != null)) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { action.putValue(Action.SELECTED_KEY, Boolean.TRUE); action.actionPerformed(null); } }); } } } return true; } private class RadioConnectionLog { long startTime; long endTime; RadioConnection connection; RadioPacket packet; String data = null; String tooltip = null; public String toString() { if (data == null) { RadioLogger.this.prepareDataString(this); } return Long.toString(startTime / Simulation.MILLISECOND) + "\t" + connection.getSource().getMote().getID() + "\t" + getDestString(this) + "\t" + data; } } private static String getDestString(RadioConnectionLog c) { Radio[] dests = c.connection.getDestinations(); if (dests.length == 0) { return "-"; } if (dests.length == 1) { return "" + dests[0].getMote().getID(); } StringBuilder sb = new StringBuilder(); for (Radio dest: dests) { sb.append(dest.getMote().getID()).append(','); } sb.setLength(sb.length()-1); return sb.toString(); } private Action createAnalyzerAction(String name, final String actionName, final ArrayList<PacketAnalyzer> analyzerList, boolean selected) { Action action = new AbstractAction(name) { private static final long serialVersionUID = -608913700422638454L; public void actionPerformed(ActionEvent event) { if (analyzers != analyzerList) { analyzers = analyzerList; analyzerName = actionName; if (connections.size() > 0) { // Remove the cached values for(int i = 0; i < connections.size(); i++) { RadioConnectionLog conn = connections.get(i); conn.data = null; conn.tooltip = null; } model.fireTableRowsUpdated(0, connections.size() - 1); } verboseBox.setText(""); } } }; action.putValue(Action.SELECTED_KEY, selected ? Boolean.TRUE : Boolean.FALSE); analyzerMap.put(actionName, action); return action; } private Action clearAction = new AbstractAction("Clear") { private static final long serialVersionUID = -6135583266684643117L; public void actionPerformed(ActionEvent e) { int size = connections.size(); if (size > 0) { connections.clear(); model.fireTableRowsDeleted(0, size - 1); setTitle("Radio Logger: " + dataTable.getRowCount() + " packets"); } } }; private Action copyAction = new AbstractAction("Copy selected") { private static final long serialVersionUID = 8412062977916108054L; public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); int[] selectedRows = dataTable.getSelectedRows(); StringBuilder sb = new StringBuilder(); for (int i: selectedRows) { sb.append(dataTable.getValueAt(i, COLUMN_TIME)).append('\t'); sb.append(dataTable.getValueAt(i, COLUMN_FROM)).append('\t'); sb.append(getDestString(connections.get(i))).append('\t'); sb.append(dataTable.getValueAt(i, COLUMN_DATA)).append('\n'); } StringSelection stringSelection = new StringSelection(sb.toString()); clipboard.setContents(stringSelection, null); } }; private Action copyAllAction = new AbstractAction("Copy all") { private static final long serialVersionUID = 1905586689441157304L; public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringBuilder sb = new StringBuilder(); for(int i=0; i < connections.size(); i++) { sb.append("" + dataTable.getValueAt(i, COLUMN_TIME) + '\t'); sb.append("" + dataTable.getValueAt(i, COLUMN_FROM) + '\t'); sb.append("" + getDestString(connections.get(i)) + '\t'); sb.append("" + dataTable.getValueAt(i, COLUMN_DATA) + '\n'); } StringSelection stringSelection = new StringSelection(sb.toString()); clipboard.setContents(stringSelection, null); } }; private Action saveAction = new AbstractAction("Save to file...") { private static final long serialVersionUID = -3942984643211482179L; public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showSaveDialog(GUI.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File saveFile = fc.getSelectedFile(); if (saveFile.exists()) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog( GUI.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } if (saveFile.exists() && !saveFile.canWrite()) { logger.fatal("No write access to file: " + saveFile); return; } try { PrintWriter outStream = new PrintWriter(new FileWriter(saveFile)); for(int i=0; i < connections.size(); i++) { outStream.print("" + dataTable.getValueAt(i, COLUMN_TIME) + '\t'); outStream.print("" + dataTable.getValueAt(i, COLUMN_FROM) + '\t'); outStream.print("" + getDestString(connections.get(i)) + '\t'); outStream.print("" + dataTable.getValueAt(i, COLUMN_DATA) + '\n'); } outStream.close(); } catch (Exception ex) { logger.fatal("Could not write to file: " + saveFile); return; } } }; private Action timeLineAction = new AbstractAction("Timeline") { private static final long serialVersionUID = -4035633464748224192L; public void actionPerformed(ActionEvent e) { int selectedRow = dataTable.getSelectedRow(); if (selectedRow < 0) return; long time = connections.get(selectedRow).startTime; Plugin[] plugins = simulation.getGUI().getStartedPlugins(); for (Plugin p: plugins) { if (!(p instanceof TimeLine)) { continue; } /* Select simulation time */ TimeLine plugin = (TimeLine) p; plugin.trySelectTime(time); } } }; private Action logListenerAction = new AbstractAction("Mote output") { private static final long serialVersionUID = 1985006491187878651L; public void actionPerformed(ActionEvent e) { int selectedRow = dataTable.getSelectedRow(); if (selectedRow < 0) return; long time = connections.get(selectedRow).startTime; Plugin[] plugins = simulation.getGUI().getStartedPlugins(); for (Plugin p: plugins) { if (!(p instanceof LogListener)) { continue; } /* Select simulation time */ LogListener plugin = (LogListener) p; plugin.trySelectTime(time); } } }; private Action showInAllAction = new AbstractAction("Timeline and mote output") { private static final long serialVersionUID = -3888292108886138128L; { putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)); } public void actionPerformed(ActionEvent e) { timeLineAction.actionPerformed(null); logListenerAction.actionPerformed(null); } }; private Properties aliases = null; private Action aliasAction = new AbstractAction("Payload alias...") { private static final long serialVersionUID = -1678771087456128721L; public void actionPerformed(ActionEvent e) { int selectedRow = dataTable.getSelectedRow(); if (selectedRow < 0) return; String current = ""; if (aliases != null && aliases.get(connections.get(selectedRow).data) != null) { current = (String) aliases.get(connections.get(selectedRow).data); } String alias = (String) JOptionPane.showInputDialog( GUI.getTopParentContainer(), "Enter alias for all packets with identical payload.\n" + "An empty string removes the current alias.\n\n" + connections.get(selectedRow).data + "\n", "Create packet payload alias", JOptionPane.QUESTION_MESSAGE, null, null, current); if (alias == null) { /* Cancelled */ return; } /* Should be null if empty */ if (aliases == null) { aliases = new Properties(); } /* Remove current alias */ if (alias.equals("")) { aliases.remove(connections.get(selectedRow).data); /* Should be null if empty */ if (aliases.isEmpty()) { aliases = null; } repaint(); return; } /* (Re)define alias */ aliases.put(connections.get(selectedRow).data, alias); repaint(); } }; public String getConnectionsString() { StringBuilder sb = new StringBuilder(); RadioConnectionLog[] cs = connections.toArray(new RadioConnectionLog[0]); for(RadioConnectionLog c: cs) { sb.append(c.toString() + "\n"); } return sb.toString(); }; public void saveConnectionsToFile(String fileName) { StringUtils.saveToFile(new File(fileName), getConnectionsString()); }; }
package org.pentaho.di.trans.steps.systemdata; import java.util.Calendar; import java.util.Date; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.version.BuildVersion; /** * Get information from the System or the supervising transformation. * * @author Matt * @since 4-aug-2003 */ public class SystemData extends BaseStep implements StepInterface { private SystemDataMeta meta; private SystemDataData data; public SystemData(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); setName(stepMeta.getName()); } private Object[] getSystemData(RowMetaInterface inputRowMeta, Object[] inputRowData) { Object[] row = new Object[data.outputRowMeta.size()]; for (int i=0;i<inputRowMeta.size();i++) { row[i] = inputRowData[i]; // no data is changed, clone is not needed here. } for (int i=0, index=inputRowMeta.size();i<meta.getFieldName().length;i++, index++) { Calendar cal; int argnr=0; switch(meta.getFieldType()[i]) { case SystemDataMeta.TYPE_SYSTEM_INFO_SYSTEM_START: row[index] = getTrans().getCurrentDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_SYSTEM_DATE: row[index] = new Date(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TRANS_DATE_FROM: row[index] = getTrans().getStartDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TRANS_DATE_TO: row[index] = getTrans().getEndDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JOB_DATE_FROM: row[index] = getTrans().getJobStartDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JOB_DATE_TO: row[index] = getTrans().getJobEndDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_DAY_START: cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, -1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_DAY_END: cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, -1); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_DAY_START: cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_DAY_END: cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_DAY_START: cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_DAY_END: cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_MONTH_START: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_PREV_MONTH_END: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_MONTH_START: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_THIS_MONTH_END: cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_MONTH_START: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_NEXT_MONTH_END: cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); row[index] = cal.getTime(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_COPYNR: row[index] = new Long( getCopy() ); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TRANS_NAME: row[index] = getTransMeta().getName(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_MODIFIED_USER: row[index] = getTransMeta().getModifiedUser(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_MODIFIED_DATE: row[index] = getTransMeta().getModifiedDate(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_TRANS_BATCH_ID: row[index] = new Long( getTrans().getBatchId() ); break; case SystemDataMeta.TYPE_SYSTEM_INFO_JOB_BATCH_ID: row[index] = new Long( getTrans().getPassedBatchId() ); break; case SystemDataMeta.TYPE_SYSTEM_INFO_HOSTNAME: row[index] = Const.getHostname(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_IP_ADDRESS: row[index] = Const.getIPAddress(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_FILENAME : row[index] = getTransMeta().getFilename(); break; case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_01: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_02: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_03: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_04: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_05: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_06: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_07: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_08: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_09: case SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_10: argnr = meta.getFieldType()[i]-SystemDataMeta.TYPE_SYSTEM_INFO_ARGUMENT_01; if (argnr<getTransMeta().getArguments().length) { row[index] = getTransMeta().getArguments()[argnr]; } else { row[index] = null; } break; case SystemDataMeta.TYPE_SYSTEM_INFO_KETTLE_VERSION: row[index] = Const.VERSION; break; case SystemDataMeta.TYPE_SYSTEM_INFO_KETTLE_BUILD_VERSION: row[index] = new Long( BuildVersion.getInstance().getVersion() ); break; case SystemDataMeta.TYPE_SYSTEM_INFO_KETTLE_BUILD_DATE: row[index] = BuildVersion.getInstance().getBuildDate(); break; default: break; } } return row; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { Object[] row; if (data.readsRows) { row=getRow(); if (row==null) { setOutputDone(); return false; } if (first) { first=false; data.outputRowMeta = (RowMetaInterface) getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null); } } else { row=new Object[] {}; // empty row linesRead++; if (first) { first=false; data.outputRowMeta = new RowMeta(); meta.getFields(data.outputRowMeta, getStepname(), null); } } RowMetaInterface imeta = getInputRowMeta(); if (imeta==null) { imeta=new RowMeta(); this.setInputRowMeta(imeta); } row = getSystemData(imeta, row); if (log.isRowLevel()) logRowlevel("System info returned: "+row); putRow(data.outputRowMeta, row); if (!data.readsRows) // Just one row and then stop! { setOutputDone(); return false; } return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(SystemDataMeta)smi; data=(SystemDataData)sdi; if (super.init(smi, sdi)) { // Add init code here. data.readsRows = false; StepMeta previous[] = getTransMeta().getPrevSteps(getStepMeta()); if (previous!=null && previous.length>0) { data.readsRows = true; } return true; } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { super.dispose(smi, sdi); } // Run is were the action happens! public void run() { try { logBasic("Starting to run..."); while (processRow(meta, data) && !isStopped()); } catch(Exception e) { logError("Unexpected error : "+e.toString()); logError(Const.getStackTracker(e)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package com.raddle.dlna.swing; import java.awt.Color; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.cybergarage.upnp.Argument; import org.cybergarage.upnp.ArgumentList; import org.cybergarage.upnp.ControlPoint; import org.cybergarage.upnp.Device; import org.cybergarage.upnp.DeviceList; import org.cybergarage.upnp.Service; import org.cybergarage.upnp.device.NotifyListener; import org.cybergarage.upnp.device.SearchResponseListener; import org.cybergarage.upnp.event.EventListener; import org.cybergarage.upnp.ssdp.SSDPPacket; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.raddle.dlna.ctrl.ActionHelper; import com.raddle.dlna.event.DlnaEventParser; import com.raddle.dlna.http.HttpHelper; import com.raddle.dlna.http.LocalFileHttpHandler; import com.raddle.dlna.http.ReceiveSpeedCallback; import com.raddle.dlna.http.RemoteHttpProxyHandler; import com.raddle.dlna.http.RemoteJoinHttpProxyHandler; import com.raddle.dlna.http.join.JoinItem; import com.raddle.dlna.renderer.AVTransport; import com.raddle.dlna.renderer.MediaRenderer; import com.raddle.dlna.url.parser.VideoInfo; import com.raddle.dlna.url.parser.VideoUrlParser; import com.raddle.dlna.util.ByteUtils; import com.raddle.dlna.util.DurationUtils; import com.raddle.dlna.util.KeyValue; import com.raddle.dlna.util.LocalIpUtils; public class DlnaClientSwing { private static final int HTTP_SERVER_PORT = 12173; static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } } private static Logger logger = LoggerFactory.getLogger(DlnaClientSwing.class); private ControlPoint ctrlPoint; private Server server; private DlnaEventParser dlnaEventParser; private List<VideoUrlParser> videoUrlParsers; private List<PlayListItem> playList; private int curVideoIndex = 0; private boolean paused = false; private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5); private int curMousePos = 0; private int quickSyncCount = 0; private boolean hasPlaying = false; private Date urlParseTime = null; private LocalFileHttpHandler localFileHttpHandler = new LocalFileHttpHandler(); private RemoteHttpProxyHandler httpBufferProxyHandler = new RemoteHttpProxyHandler(); private RemoteJoinHttpProxyHandler httpJoinProxyHandler = new RemoteJoinHttpProxyHandler(); private String curUrl = null; private Date lastStoppedEventTime = new Date(); private boolean isDragSplit = false; private JFrame frame; private JTextField urlTxt; private JComboBox deviceComb; private JComboBox addrParseComb; private JComboBox qualityComb; private JButton deviceRefreshBtn; private JButton previousBtn; private JButton nextBtn; private JButton stopBtn; private JSlider progressSlid; private JLabel durationLeb; private JLabel curDurationLeb; private JLabel mouseDurationLeb; private JLabel label_5; private JButton pauseBtn; private JSpinner spinner; private JButton pasteBtn; private JButton parserRefreshBtn; private JLabel lblip; private JComboBox localIpComb; private JButton playBtn2; private JButton stopBtn2; private JCheckBox localBufChk; private JCheckBox localJoinChk; private JButton playBtn; private JCheckBox autoChk; private JCheckBox refreshUrlChk; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { DlnaClientSwing window = new DlnaClientSwing(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public DlnaClientSwing() { initialize(); } /** * Initialize the contents of the frame. */ @SuppressWarnings({ "rawtypes", "unchecked" }) private void initialize() { frame = new JFrame(); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { close(); } @Override public void windowClosing(WindowEvent e) { close(); } private void close() { if (ctrlPoint != null) { ctrlPoint.unsubscribe(); ctrlPoint.stop(); } if (server != null) { try { server.stop(); } catch (Exception e) { } } HttpHelper.close(); scheduledExecutorService.shutdown(); logger.info("DlnaClient closed"); } }); frame.setBounds(100, 100, 793, 286); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblDlna = new JLabel("DLNA"); lblDlna.setBounds(10, 10, 61, 15); frame.getContentPane().add(lblDlna); deviceComb = new JComboBox(); deviceComb.setBounds(72, 7, 200, 21); frame.getContentPane().add(deviceComb); JLabel label = new JLabel(""); label.setBounds(10, 63, 54, 15); frame.getContentPane().add(label); urlTxt = new JTextField(); urlTxt.setToolTipText(""); urlTxt.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { pasteUrlText(); } } }); urlTxt.setBounds(72, 63, 388, 21); frame.getContentPane().add(urlTxt); urlTxt.setColumns(10); playBtn = new JButton(""); playBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { playBtnAction(); } }); playBtn.setBounds(72, 181, 61, 23); frame.getContentPane().add(playBtn); deviceRefreshBtn = new JButton(""); deviceRefreshBtn.setEnabled(false); deviceRefreshBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ctrlPoint.search(); } }); deviceRefreshBtn.setBounds(282, 6, 93, 23); frame.getContentPane().add(deviceRefreshBtn); progressSlid = new JSlider(); progressSlid.setMaximum(0); progressSlid.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { if (!isDragSplit) { updateMouseSpiltValue(false, e); } } @Override public void mouseDragged(MouseEvent e) { updateMouseSpiltValue(true, e); } }); progressSlid.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { isDragSplit = true; } @Override public void mouseReleased(MouseEvent e) { // seek Device selectedDevice = getSelectedDevice(); if (progressSlid.isEnabled() && selectedDevice != null && playList != null && playList.size() > 0) { ActionHelper actionHelper = new ActionHelper(selectedDevice); actionHelper.seak(curMousePos); if (progressSlid.getValue() != curMousePos) { progressSlid.setValue(curMousePos); } quickSyncCount = 5; } isDragSplit = false; } @Override public void mouseEntered(MouseEvent e) { updateMouseSpiltValue(false, e); } @Override public void mouseExited(MouseEvent e) { mouseDurationLeb.setText(""); mouseDurationLeb.setVisible(false); } }); progressSlid.setValue(0); progressSlid.setEnabled(false); progressSlid.setBounds(72, 88, 599, 23); frame.getContentPane().add(progressSlid); JLabel label_1 = new JLabel(""); label_1.setBounds(10, 88, 54, 15); frame.getContentPane().add(label_1); JLabel label_2 = new JLabel(""); label_2.setBounds(10, 35, 54, 15); frame.getContentPane().add(label_2); addrParseComb = new JComboBox(); addrParseComb.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { VideoUrlParser selectedParser = getSelectedParser(); qualityComb.removeAllItems(); for (KeyValue<String, String> keyValue : selectedParser.getVideoQualitys()) { qualityComb.addItem(keyValue.getValue()); } } } }); addrParseComb.setBounds(72, 35, 200, 21); frame.getContentPane().add(addrParseComb); JLabel label_3 = new JLabel(""); label_3.setBounds(282, 39, 54, 15); frame.getContentPane().add(label_3); qualityComb = new JComboBox(); qualityComb.setBounds(334, 35, 126, 21); frame.getContentPane().add(qualityComb); pauseBtn = new JButton(""); pauseBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Device selectedDevice = getSelectedDevice(); if (selectedDevice != null) { ActionHelper actionHelper = new ActionHelper(selectedDevice); if (paused) { actionHelper.resume(); pauseBtn.setText(""); paused = false; } else { actionHelper.pause(); pauseBtn.setText(""); paused = true; } } } }); pauseBtn.setBounds(233, 150, 61, 23); frame.getContentPane().add(pauseBtn); stopBtn = new JButton(""); stopBtn.setEnabled(false); stopBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopBtnAction(); } }); stopBtn.setBounds(316, 181, 61, 23); frame.getContentPane().add(stopBtn); previousBtn = new JButton(""); previousBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (playList != null && playList.size() > 0 && curVideoIndex > 0) { play(curVideoIndex - 1); } } }); previousBtn.setBounds(143, 181, 78, 23); frame.getContentPane().add(previousBtn); nextBtn = new JButton(""); nextBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (playList != null && playList.size() > 0 && curVideoIndex < playList.size() - 1) { play(curVideoIndex + 1); } } }); nextBtn.setBounds(233, 181, 73, 23); frame.getContentPane().add(nextBtn); durationLeb = new JLabel(""); durationLeb.setBounds(674, 88, 93, 21); frame.getContentPane().add(durationLeb); JLabel label_4 = new JLabel(""); label_4.setBounds(72, 129, 55, 15); frame.getContentPane().add(label_4); curDurationLeb = new JLabel(""); curDurationLeb.setBounds(137, 129, 240, 15); frame.getContentPane().add(curDurationLeb); mouseDurationLeb = new JLabel(""); mouseDurationLeb.setBounds(392, 114, 118, 15); frame.getContentPane().add(mouseDurationLeb); label_5 = new JLabel(""); label_5.setBounds(72, 154, 36, 15); frame.getContentPane().add(label_5); spinner = new JSpinner(); spinner.setBounds(104, 149, 36, 22); spinner.setValue(5); frame.getContentPane().add(spinner); JLabel label_6 = new JLabel(""); label_6.setBounds(143, 154, 23, 15); frame.getContentPane().add(label_6); JButton quickForwardBtn = new JButton(""); quickForwardBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Device selectedDevice = getSelectedDevice(); if (progressSlid.isEnabled() && selectedDevice != null && playList != null && playList.size() > 0) { ActionHelper actionHelper = new ActionHelper(selectedDevice); int seekPos = progressSlid.getValue() + (Integer) spinner.getValue(); actionHelper.seak(seekPos); progressSlid.setValue(seekPos); quickSyncCount = 5; } } }); quickForwardBtn.setBounds(304, 150, 61, 23); frame.getContentPane().add(quickForwardBtn); JButton quickBackBtn = new JButton(""); quickBackBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Device selectedDevice = getSelectedDevice(); if (progressSlid.isEnabled() && selectedDevice != null && playList != null && playList.size() > 0) { ActionHelper actionHelper = new ActionHelper(selectedDevice); int seekPos = progressSlid.getValue() - (Integer) spinner.getValue(); actionHelper.seak(seekPos); progressSlid.setValue(seekPos); quickSyncCount = 5; } } }); quickBackBtn.setBounds(165, 150, 61, 23); frame.getContentPane().add(quickBackBtn); pasteBtn = new JButton(""); pasteBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pasteUrlText(); } }); pasteBtn.setBounds(470, 62, 61, 23); frame.getContentPane().add(pasteBtn); parserRefreshBtn = new JButton(""); parserRefreshBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateUrlParsers(); } }); parserRefreshBtn.setBounds(470, 34, 93, 23); frame.getContentPane().add(parserRefreshBtn); lblip = new JLabel("IP"); lblip.setBounds(72, 214, 47, 15); frame.getContentPane().add(lblip); localIpComb = new JComboBox(); localIpComb.setBounds(134, 211, 118, 21); frame.getContentPane().add(localIpComb); JLabel label_7 = new JLabel(""); label_7.setBounds(262, 214, 113, 15); frame.getContentPane().add(label_7); playBtn2 = new JButton(""); playBtn2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { playBtnAction(); } }); playBtn2.setBounds(534, 62, 61, 23); frame.getContentPane().add(playBtn2); stopBtn2 = new JButton(""); stopBtn2.setEnabled(false); stopBtn2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopBtnAction(); } }); stopBtn2.setBounds(598, 62, 61, 23); frame.getContentPane().add(stopBtn2); localBufChk = new JCheckBox(""); localBufChk.setEnabled(false); localBufChk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!localBufChk.isSelected()) { localJoinChk.setSelected(false); } } }); localBufChk.setBounds(392, 6, 93, 23); frame.getContentPane().add(localBufChk); localJoinChk = new JCheckBox(""); localJoinChk.setEnabled(false); localJoinChk.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { localBufChk.setSelected(localJoinChk.isSelected()); } }); localJoinChk.setBounds(492, 6, 87, 23); frame.getContentPane().add(localJoinChk); autoChk = new JCheckBox(""); autoChk.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { localBufChk.setEnabled(!autoChk.isSelected()); localJoinChk.setEnabled(!autoChk.isSelected()); } }); autoChk.setSelected(true); autoChk.setBounds(581, 6, 102, 23); frame.getContentPane().add(autoChk); refreshUrlChk = new JCheckBox(""); refreshUrlChk.setBounds(580, 35, 140, 23); frame.getContentPane().add(refreshUrlChk); dlnaEventParser = new DlnaEventParser(); dlnaEventParser.init(new File("dlna/event.js")); updateUrlParsers(); localIpComb.removeAllItems(); for (String ip : LocalIpUtils.getLocalIpv4()) { localIpComb.addItem(ip); } ctrlPoint = new ControlPoint(); ctrlPoint.addNotifyListener(new NotifyListener() { @Override public void deviceNotifyReceived(SSDPPacket ssdpPacket) { updateDeviceComboList(); } }); ctrlPoint.addSearchResponseListener(new SearchResponseListener() { @Override public void deviceSearchResponseReceived(SSDPPacket ssdpPacket) { updateDeviceComboList(); } }); ctrlPoint.addEventListener(new EventListener() { @Override public void eventNotifyReceived(String uuid, long seq, String varName, String value) { if (value != null && (value.indexOf("RelativeTimePosition") != -1 || value.indexOf("AbsoluteTimePosition") != -1)) { } else { logger.info("eventNotifyReceived , uuid : " + uuid + ",seq : " + seq + ",varName : " + varName + ",value : " + value); } if (dlnaEventParser.isSupportedEvent(getSelectedDevice().getFriendlyName())) { if (AVTransport.PLAYING.equals(dlnaEventParser.parseEvent(getSelectedDevice().getFriendlyName(), varName, value))) { pauseBtn.setText(""); paused = false; hasPlaying = true; progressSlid.setEnabled(true); } else if (AVTransport.PAUSED_PLAYBACK.equals(dlnaEventParser.parseEvent(getSelectedDevice() .getFriendlyName(), varName, value))) { pauseBtn.setText(""); paused = true; } else if (AVTransport.STOPPED.equals(dlnaEventParser.parseEvent(getSelectedDevice() .getFriendlyName(), varName, value))) { if (stopBtn.isEnabled()) { if (playList != null && curVideoIndex < playList.size() - 1) { if (DateUtils.addSeconds(lastStoppedEventTime, 30).before(new Date())) { lastStoppedEventTime = new Date(); logger.info("auto play next video by stopped event , curVideoIndex : " + curVideoIndex); play(curVideoIndex + 1); } } } } } } }); new Thread() { @Override public void run() { // dlna ctrlPoint.start(); ctrlPoint.search(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { deviceRefreshBtn.setText(""); deviceRefreshBtn.setEnabled(true); } }); scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { if (progressSlid.getMaximum() > 0 && progressSlid.getValue() > progressSlid.getMaximum() - 20) { return; } syncPositionInfo(); } }, 5, 10, TimeUnit.SECONDS); scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { if (stopBtn.isEnabled() && progressSlid.isEnabled() && !isDragSplit && !paused && !dlnaEventParser.isSupportedEvent(getSelectedDevice().getFriendlyName())) { if (quickSyncCount > 0 && progressSlid.getValue() < progressSlid.getMaximum() - 10) { quickSyncCount syncPositionInfo(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { showCurrentPos(); } }); } } } }, 1, 1, TimeUnit.SECONDS); scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { if (stopBtn.isEnabled() && progressSlid.isEnabled() && !isDragSplit && !paused && hasPlaying) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressSlid.setValue(progressSlid.getValue() + 1); if (progressSlid.getValue() > progressSlid.getMaximum() - 30 && playList != null && curVideoIndex < playList.size() - 1) { quickSyncCount = 10; } showCurrentPos(); if ((progressSlid.getValue() == 0 || progressSlid.getValue() >= progressSlid .getMaximum()) && playList != null && curVideoIndex < playList.size() - 1 && hasPlaying && !dlnaEventParser.isSupportedEvent(getSelectedDevice().getFriendlyName())) { if (progressSlid.getValue() >= progressSlid.getMaximum()) { try { Thread.sleep(500); } catch (InterruptedException e) { return; } } logger.info("auto play next video by scheduled task , curVideoIndex : " + curVideoIndex); play(curVideoIndex + 1); } } }); } } }, 5, 1, TimeUnit.SECONDS); // urlurl scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { refreshUrls(); } }, 5, 60, TimeUnit.SECONDS); server = new Server(HTTP_SERVER_PORT); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.addHandler(localFileHttpHandler); handlerCollection.addHandler(httpBufferProxyHandler); handlerCollection.addHandler(httpJoinProxyHandler); server.setHandler(handlerCollection); try { server.start(); } catch (Exception e) { logger.error(e.getMessage(), e); } } }.start(); } private void play(int i) { if (playList != null && playList.size() > i) { final Device selectedDevice = getSelectedDevice(); if (selectedDevice != null) { curVideoIndex = i; previousBtn.setEnabled(curVideoIndex > 0); nextBtn.setEnabled(curVideoIndex < playList.size() - 1); updateTitle(null); ActionHelper actionHelper = new ActionHelper(selectedDevice); try { actionHelper.pause(); } catch (Exception e) { } actionHelper.play(playList.get(curVideoIndex).getVideoUrl()); paused = false; hasPlaying = false; stopBtn.setEnabled(true); stopBtn2.setEnabled(true); progressSlid.setEnabled(false); progressSlid.setMaximum(0); progressSlid.setMinimum(0); progressSlid.setValue(0); quickSyncCount = 5; syncPositionInfo(); new Thread() { @Override public void run() { Service service = selectedDevice.getService(AVTransport.SERVICE_TYPE); if (service != null) { logger.info("subscribe :" + selectedDevice.getFriendlyName()); try { ctrlPoint.unsubscribe(service); service.clearSID(); ctrlPoint.subscribe(service); } catch (Exception e) { logger.error("subscribe failed:" + selectedDevice.getFriendlyName(), e); } } try { Thread.sleep(1000); } catch (InterruptedException e1) { return; } for (int j = 0; j < 20; j++) { if (playList != null && playList.size() > curVideoIndex && j % 3 == 0 && (!progressSlid.isEnabled() || progressSlid.getValue() == 0)) { Device selectedDevice = getSelectedDevice(); if (selectedDevice != null) { ActionHelper actionHelper = new ActionHelper(selectedDevice); try { actionHelper.resume(); } catch (Exception e) { } quickSyncCount = 5; syncPositionInfo(); } else { return; } } else { return; } try { Thread.sleep(1000); } catch (InterruptedException e) { return; } } } }.start(); } } } private void updateTitle(String extStr) { if (playList != null && curVideoIndex >= 0 && curVideoIndex < playList.size()) { frame.setTitle(playList.get(curVideoIndex).getVideoInfo().getName() + " - " + (curVideoIndex + 1) + "/" + playList.size() + " - " + playList.get(curVideoIndex).getVideoInfo().getQualityName() + StringUtils.defaultString(extStr)); } } private void updateTitle(VideoInfo videoInfo, String extStr) { frame.setTitle(videoInfo.getName() + " - " + videoInfo.getUrls().size() + " - " + videoInfo.getQualityName() + StringUtils.defaultString(extStr)); } private void updateMouseSpiltValue(boolean isDrag, MouseEvent e) { if (isDrag) { mouseDurationLeb.setText(DurationUtils.getTrackNRFormat(progressSlid.getValue())); mouseDurationLeb.setLocation(e.getX() + progressSlid.getX(), e.getY() + progressSlid.getY() + 20); curMousePos = progressSlid.getValue(); } else { int width = progressSlid.getWidth(); int mouseRelPos = e.getX(); int seconds = (int) Math.ceil(((double) mouseRelPos / width) * progressSlid.getMaximum()); mouseDurationLeb.setText(DurationUtils.getTrackNRFormat(seconds)); mouseDurationLeb.setLocation(e.getX() + progressSlid.getX(), e.getY() + progressSlid.getY() + 20); curMousePos = seconds; } mouseDurationLeb.setForeground(Color.BLUE); mouseDurationLeb.setVisible(true); } @SuppressWarnings("unchecked") private void updateUrlParsers() { videoUrlParsers = VideoUrlParser.getVideoUrlParser(new File("parsers")); addrParseComb.removeAllItems(); for (VideoUrlParser videoUrlParser : videoUrlParsers) { addrParseComb.addItem(videoUrlParser.getName()); } if (videoUrlParsers.size() > 0) { qualityComb.removeAllItems(); for (KeyValue<String, String> keyValue : videoUrlParsers.get(0).getVideoQualitys()) { qualityComb.addItem(keyValue.getValue()); } } dlnaEventParser = new DlnaEventParser(); dlnaEventParser.init(new File("dlna/event.js")); } private VideoUrlParser getSelectedParser() { if (videoUrlParsers != null && addrParseComb.getSelectedItem() != null) { for (VideoUrlParser videoUrlParser : videoUrlParsers) { if (videoUrlParser.getName().equals(addrParseComb.getSelectedItem())) { return videoUrlParser; } } } return null; } @SuppressWarnings("unchecked") private synchronized void updateDeviceComboList() { DeviceList devList = ctrlPoint.getDeviceList(); int devCnt = devList.size(); for (int n = 0; n < devCnt; n++) { Device dev = devList.getDevice(n); if (!dev.isDeviceType(MediaRenderer.DEVICE_TYPE)) { continue; } String devComboName = getDeviceComboName(dev); int itemCnt = deviceComb.getItemCount(); boolean hasSameDeviceName = false; for (int i = 0; i < itemCnt; i++) { String itemName = (String) deviceComb.getItemAt(i); if (itemName == null) { continue; } if (itemName.compareTo(devComboName) == 0) { hasSameDeviceName = true; break; } } if (hasSameDeviceName == false) { deviceComb.addItem(devComboName); } } } private synchronized Device getSelectedDevice() { return getDevice((String) deviceComb.getSelectedItem()); } private String getDeviceComboName(Device dev) { return dev.getFriendlyName(); } private Device getDevice(String devComboName) { if (devComboName == null) { return null; } DeviceList devList = ctrlPoint.getDeviceList(); int devCnt = devList.size(); for (int n = 0; n < devCnt; n++) { Device dev = devList.getDevice(n); if (devComboName.compareTo(getDeviceComboName(dev)) == 0) { return dev; } } return null; } private void syncPositionInfo() { if (playList != null && playList.size() > 0) { Device selectedDevice = getSelectedDevice(); if (selectedDevice != null && !isDragSplit) { ActionHelper actionHelper = new ActionHelper(selectedDevice); try { long start = System.currentTimeMillis(); final ArgumentList positionInfo = actionHelper.getPositionInfo(); final int delay = (int) ((System.currentTimeMillis() - start) / 1000); if (positionInfo != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Argument trackDuration = positionInfo.getArgument(AVTransport.TRACKDURATION); if (trackDuration != null && StringUtils.isNotEmpty(trackDuration.getValue())) { int seconds = DurationUtils.parseTrackNRFormat(trackDuration.getValue()); progressSlid.setMaximum(seconds); progressSlid.setMinimum(0); durationLeb.setText(DurationUtils.getTrackNRFormat(seconds)); } String posTime = null; Argument relTimeDuration = positionInfo.getArgument(AVTransport.RELTIME); Argument absTimeDuration = positionInfo.getArgument(AVTransport.ABSTIME); if (relTimeDuration != null && StringUtils.isNotEmpty(relTimeDuration.getValue())) { posTime = relTimeDuration.getValue(); } else if (absTimeDuration != null && StringUtils.isNotEmpty(absTimeDuration.getValue())) { posTime = absTimeDuration.getValue(); } if (StringUtils.isNotEmpty(posTime)) { int seconds = DurationUtils.parseTrackNRFormat(posTime); if (seconds > 0) { hasPlaying = true; } if (seconds == 0) { progressSlid.setValue(seconds); } else if (Math.abs(progressSlid.getValue() - (seconds + delay)) > 1) { progressSlid.setValue(seconds + delay); } } progressSlid.setEnabled(true); } }); } } catch (Exception e) { logger.error(e.getMessage(), e); } } } } @SuppressWarnings("unchecked") private void pasteUrlText() { Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable contents = sysc.getContents(null); if (contents != null) { if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String text = (String) contents.getTransferData(DataFlavor.stringFlavor); urlTxt.setText(text); } catch (Exception e1) { logger.error(e1.getMessage(), e1); JOptionPane.showMessageDialog(frame, "" + e1.getMessage()); return; } } else if (contents.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { try { List<File> filelist = (List<File>) contents.getTransferData(DataFlavor.javaFileListFlavor); urlTxt.setText(filelist.get(0).getPath()); } catch (Exception e1) { logger.error(e1.getMessage(), e1); JOptionPane.showMessageDialog(frame, "" + e1.getMessage()); return; } } } } private void showCurrentPos() { curDurationLeb.setText(DurationUtils.getTrackNRFormat(Math.min(progressSlid.getValue(), progressSlid.getMaximum())) + " / " + DurationUtils.getTrackNRFormat(progressSlid.getMaximum())); } private void playBtnAction() { playBtn2.setEnabled(false); playBtn2.setEnabled(false); new Thread() { @Override public void run() { try { Device selectedDevice = getSelectedDevice(); if (selectedDevice == null) { JOptionPane.showMessageDialog(frame, "dlna"); return; } VideoUrlParser selectedParser = getSelectedParser(); if (selectedParser == null) { JOptionPane.showMessageDialog(frame, ""); return; } if (qualityComb.getSelectedItem() == null) { JOptionPane.showMessageDialog(frame, ""); return; } String urlText = urlTxt.getText().trim(); if (StringUtils.isBlank(urlText)) { JOptionPane.showMessageDialog(frame, ""); return; } urlParseTime = null; VideoInfo videoInfo = null; if (urlText.indexOf(": frame.setTitle("url"); try { URLConnection openConnection = new URL(urlText).openConnection(); openConnection.connect(); openConnection.getInputStream().close(); } catch (MalformedURLException e1) { logger.error(e1.getMessage(), e1); JOptionPane.showMessageDialog(frame, ""); return; } catch (IOException e1) { logger.error(e1.getMessage(), e1); JOptionPane.showMessageDialog(frame, ""); return; } String baseUrlText = urlText; if (baseUrlText.indexOf(" baseUrlText = baseUrlText.substring(0, baseUrlText.indexOf(" } if (baseUrlText.indexOf("?") != -1) { baseUrlText = baseUrlText.substring(0, baseUrlText.indexOf("?")); } if (baseUrlText.toLowerCase().substring(baseUrlText.lastIndexOf('.')).indexOf("htm") != -1 || StringUtils.isBlank(FilenameUtils.getExtension(baseUrlText))) { try { frame.setTitle(""); videoInfo = selectedParser.fetchVideoUrls(urlText, selectedParser .getVideoQualityByValue(qualityComb.getSelectedItem() + "").getKey()); urlParseTime = new Date(); if (autoChk.isSelected() && videoInfo != null && videoInfo.getUrls() != null) { updateTitle(videoInfo, " , "); if (videoInfo.getUrls().size() == 1) { localBufChk.setSelected(false); localJoinChk.setSelected(false); } else if (videoInfo.getUrls().size() > 1) { JoinItem loadJoinItem = JoinItem.loadJoinItem(videoInfo.getUrls().get(0), null); if (loadJoinItem.getFlvMetaInfo().getFlvHeader() != null) { // flv localBufChk.setSelected(true); localJoinChk.setSelected(true); } } } if (localBufChk.isSelected() && videoInfo != null && videoInfo.getUrls() != null) { httpBufferProxyHandler.setUrls(new ArrayList<String>()); httpBufferProxyHandler.setSpeedCallback(new SpeedCallback()); ArrayList<String> list = new ArrayList<String>(); ArrayList<JoinItem> orgJoinItems = new ArrayList<JoinItem>(); for (int i = 0; i < videoInfo.getUrls().size(); i++) { String videoUrl = videoInfo.getUrls().get(i); httpBufferProxyHandler.getUrls().add(videoUrl); if (localJoinChk.isSelected() && videoInfo.getUrls().size() > 1) { try { updateTitle(videoInfo, " , Meta " + (i + 1) + "/" + videoInfo.getUrls().size()); JoinItem loadJoinItem = JoinItem.loadJoinItem(videoUrl, null); if (loadJoinItem.getFlvMetaInfo().getFlvHeader() == null) { JOptionPane.showMessageDialog(frame, ", flv"); return; } orgJoinItems.add(loadJoinItem); } catch (Exception e) { logger.error(e.getMessage(), e); JOptionPane.showMessageDialog(frame, ", " + e.getMessage()); return; } } else { list.add("http://" + localIpComb.getSelectedItem() + ":" + HTTP_SERVER_PORT + "/remote/" + i); } } if (localJoinChk.isSelected() && videoInfo.getUrls().size() > 1) { list.clear(); list.add("http://" + localIpComb.getSelectedItem() + ":" + HTTP_SERVER_PORT + "/remote/join"); httpJoinProxyHandler.setJoinItems(JoinItem.joinVideo(orgJoinItems)); httpJoinProxyHandler.setSpeedCallback(new SpeedCallback()); } videoInfo.setUrls(list); } } catch (Exception e1) { logger.error(e1.getMessage(), e1); JOptionPane.showMessageDialog(frame, "" + e1.getMessage()); return; } } else { videoInfo = new VideoInfo(); videoInfo.setName(FilenameUtils.getBaseName(urlText)); videoInfo.setQualityName(""); videoInfo.setUrls(new ArrayList<String>()); if (localBufChk.isSelected()) { httpBufferProxyHandler.setSpeedCallback(new SpeedCallback()); httpBufferProxyHandler.setUrls(new ArrayList<String>()); httpBufferProxyHandler.getUrls().add(urlText); videoInfo.getUrls().add( "http://" + localIpComb.getSelectedItem() + ":" + HTTP_SERVER_PORT + "/remote/" + 0); } else { videoInfo.getUrls().add(urlText); } } } else { File file = new File(urlText); if (!file.exists()) { JOptionPane.showMessageDialog(frame, "" + file.getAbsolutePath()); return; } videoInfo = new VideoInfo(); videoInfo.setName(FilenameUtils.getBaseName(urlText)); videoInfo.setQualityName(""); videoInfo.setUrls(new ArrayList<String>()); String videoName = DigestUtils.shaHex(file.getAbsolutePath()) + "." + FilenameUtils.getExtension(urlText); videoInfo.getUrls().add( "http://" + localIpComb.getSelectedItem() + ":" + HTTP_SERVER_PORT + "/file/" + videoName); localFileHttpHandler.setLocalFile(file); localFileHttpHandler.setSpeedCallback(new SpeedCallback()); } if (videoInfo != null) { updateTitle(videoInfo, " - "); playList = new ArrayList<PlayListItem>(); for (String url : videoInfo.getUrls()) { playList.add(new PlayListItem(videoInfo, url)); } if (StringUtils.equals(curUrl, urlText)) { play(curVideoIndex); } else { play(0); } curUrl = urlText; } else { logger.error("videoInfo is null"); JOptionPane.showMessageDialog(frame, ""); return; } } finally { playBtn2.setEnabled(true); playBtn2.setEnabled(true); } } }.start(); } private void stopBtnAction() { Device selectedDevice = getSelectedDevice(); if (selectedDevice != null) { stopBtn.setEnabled(false); stopBtn2.setEnabled(false); ActionHelper actionHelper = new ActionHelper(selectedDevice); try { actionHelper.pause(); } catch (Exception e) { } actionHelper.stop(); curVideoIndex = 0; playList = null; progressSlid.setEnabled(false); progressSlid.setValue(0); progressSlid.setMaximum(0); durationLeb.setText(""); curDurationLeb.setText(""); showCurrentPos(); } } private void refreshUrls() { if (stopBtn.isEnabled() && progressSlid.isEnabled() && hasPlaying && urlParseTime != null && playList != null && playList.size() > 0 && refreshUrlChk.isSelected()) { // 15url if (DateUtils.addMinutes(urlParseTime, 15).before(new Date())) { try { VideoUrlParser selectedParser = getSelectedParser(); String urlText = urlTxt.getText().trim(); VideoInfo videoInfo = selectedParser.fetchVideoUrls(urlText, selectedParser.getVideoQualityByValue(qualityComb.getSelectedItem() + "").getKey()); urlParseTime = new Date(); List<PlayListItem> newPlayList = new ArrayList<PlayListItem>(); for (String url : videoInfo.getUrls()) { newPlayList.add(new PlayListItem(videoInfo, url)); } if (httpJoinProxyHandler.getJoinItems() != null && localJoinChk.isSelected() && videoInfo.getUrls().size() > 1) { for (int i = 0; i < videoInfo.getUrls().size(); i++) { httpJoinProxyHandler.getJoinItems().get(i).setUrl(videoInfo.getUrls().get(i)); } } else if (localBufChk.isSelected()) { httpBufferProxyHandler.setUrls(new ArrayList<String>(videoInfo.getUrls())); } else { playList = newPlayList; } } catch (Exception e1) { logger.error(e1.getMessage(), e1); return; } } } } private class SpeedCallback implements ReceiveSpeedCallback { private long preTime = -1; private long speedReceived = 0; private long totalReceived = 0; @Override public void startReceive(final int videIndex, final int totalSegments) { preTime = -1; speedReceived = 0; totalReceived = 0; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateTitle(" - " + (videIndex + 1) + "/" + totalSegments + " - "); } }); } @Override public void receivedComplete(final int videIndex, final int totalSegments) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateTitle(" - (" + (videIndex + 1) + "/" + totalSegments + " - - " + ByteUtils.readable(totalReceived) + ")"); } }); } @Override public void receivedBytes(final int videIndex, final int totalSegments, final long receivedBytes) { speedReceived += receivedBytes; totalReceived += receivedBytes; if (preTime == -1) { preTime = System.currentTimeMillis(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateTitle(" - (" + (videIndex + 1) + "/" + totalSegments + " - )"); } }); return; } final long spanTime = System.currentTimeMillis() - preTime; if (spanTime > 500) { final long sumReceived = speedReceived; speedReceived = 0; preTime = System.currentTimeMillis(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { double speed = sumReceived * 1000.0 / spanTime; updateTitle(" - (" + (videIndex + 1) + "/" + totalSegments + " - " + ByteUtils.readable((long) speed) + "/s " + ByteUtils.readable(totalReceived) + ")"); } }); } } } }
package org.pikater.shared.database.jpa.daos; import java.util.List; import java.util.logging.Level; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.pikater.shared.database.exceptions.NoResultException; import org.pikater.shared.database.jpa.EntityManagerInstancesCreator; import org.pikater.shared.database.jpa.JPAAbstractEntity; import org.pikater.shared.database.views.base.ITableColumn; import org.pikater.shared.database.views.base.query.SortOrder; import org.pikater.shared.logging.database.PikaterDBLogger; /** * Class {@link AbstractDAO} contains general functions to manipulate with entities. * These general functions are used by classes, that are inherited from this class, * in functions specific to that particular entity. * * * @param <T> class of entity, for which actions are performed. */ public abstract class AbstractDAO<T extends JPAAbstractEntity> { private Class<T> ec; protected AbstractDAO(Class<T> entityClass){ this.ec=entityClass; } public enum EmptyResultAction { /** * Log error if no result is found and return null. */ LOG_NULL, /** * Don't log an error if no result is found and return null. */ NULL, /** * Silently throw a runtime error to handle in the calling code if no result is found. */ THROW; public static EmptyResultAction getDefault() { return LOG_NULL; } } public abstract String getEntityName(); /** * Function retrieving all instances of that spicific entity. * @return list of all entities */ public List<T> getAll(){ return EntityManagerInstancesCreator .getEntityManagerInstance() .createNamedQuery(this.getEntityName()+".getAll", ec) .getResultList(); } /** * Function retrieving an entity based upon the primary key. Currently primary * key is an integer generated at entity persistence. * @param ID of the searched entity * @param era type of action, that should be performed if no entity is found * @return the entity with the given ID */ public T getByID(int ID, EmptyResultAction era){ EntityManager em = EntityManagerInstancesCreator.getEntityManagerInstance(); T item = null; try{ item=em.find(ec, ID); }catch(Exception t){ PikaterDBLogger.logThrowable("Exception while retrieveing entity based on its primary key", t); } if(item!=null){ return item; }else{ switch (era) { case LOG_NULL: PikaterDBLogger.log(Level.WARNING, "Entity not found, returning null"); break; case THROW: throw new NoResultException(); default: break; } return null; } } /** * Function retrieving an entity based upon its ID. If no entity is found * null is returnd and error message is logged. * @param ID of the searched entity * @return the entity with the given ID */ public T getByID(int ID) { return getByID(ID, EmptyResultAction.LOG_NULL); } /** * Checks whether the entity with the given ID is available * @param ID of the entity * @return true if the entity is present */ public boolean existsByID(int ID){ return getByID(ID, EmptyResultAction.NULL)!=null; } /** * Updates the value of an entity with the values from the changedEntity variable. * <p> * This function is used due to the fact, that update operations should be done in * persistence context. * <p> * To simplify the update process all variables of a particular entity are updated * @param changedEntity object with the new values */ public void updateEntity(T changedEntity){ EntityManager em = EntityManagerInstancesCreator.getEntityManagerInstance(); em.getTransaction().begin(); try{ T item=em.find(ec, changedEntity.getId()); item.updateValues(changedEntity); em.getTransaction().commit(); }catch(Exception e){ PikaterDBLogger.logThrowable("Can't update "+changedEntity.getClass().getName()+" object.", e); em.getTransaction().rollback(); }finally{ em.close(); } } /** * Stores a new - not yet persisted - entity to the database. * @param newEntity entity to be stored */ public void storeEntity(Object newEntity){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); em.getTransaction().begin(); try{ em.persist(newEntity); em.getTransaction().commit(); }catch(Exception e){ PikaterDBLogger.logThrowable("Can't persist JPA object.",e); em.getTransaction().rollback(); }finally{ em.close(); } } /** * Deletes an entity from the database. * @param entityToRemove Object to be removed. */ public void deleteEntity(T entityToRemove){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); em.getTransaction().begin(); try{ JPAAbstractEntity entity = em.find(entityToRemove.getClass(), entityToRemove.getId()); em.remove(entity); em.getTransaction().commit(); }catch(Exception e){ PikaterDBLogger.logThrowable("Can't remove JPA object", e); em.getTransaction().rollback(); }finally{ em.close(); } } /** * This function should be used to run named queries that have one integer number * in result set. Usually usage of this function is call of count queries. * @param queryName name of named query * @return number that was query's result */ protected int getByCountQuery(String queryName){ return ((Long)EntityManagerInstancesCreator .getEntityManagerInstance() .createNamedQuery(queryName) .getSingleResult()) .intValue(); } /** * This function should be used to run named queries that have one integer number * in result set and they need one parameter to be set. Usually usage of this function is call of count queries. * @param queryName name of named query * @param paramName name of the parameter in the query * @param param value of the parameter * @return number that was query's result */ protected int getByCountQuery(String queryName, String paramName, Object param){ return ((Long)EntityManagerInstancesCreator .getEntityManagerInstance() .createNamedQuery(queryName) .setParameter(paramName, param) .getSingleResult()) .intValue(); } /** * This function should be used to run named queries that have one integer number * in result set and they need two parameters to be set. Usually usage of this function is call of count queries. * @param queryName name of named query * @param paramOneName name of the first parameter * @param paramOne value of the first parameter * @param paramTwoName name of the second parameter * @param paramTwo value of the second parameter * @return number that was query's result */ protected int getByCountQuery(String queryName, String paramOneName, Object paramOne, String paramTwoName, Object paramTwo){ return ((Long)EntityManagerInstancesCreator .getEntityManagerInstance() .createNamedQuery(queryName) .setParameter(paramOneName, paramOne) .setParameter(paramTwoName, paramTwo) .getSingleResult()) .intValue(); } /** * Runs a named query and returns a list of entities that satisfy the query * @param queryName name of named query * @return list of entities returned by the query */ protected List<T> getByTypedNamedQuery(String queryName){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); try{ return em .createNamedQuery(queryName,ec) .getResultList(); }finally{ em.close(); } } /** * Runs a named query that needs one parameter to be set and returns a list of entities that satisfy the query. * @param queryName name of named query * @param paramName name of the parameter in query * @param param value of the parameter * @return list of entities returned by the query */ protected List<T> getByTypedNamedQuery(String queryName,String paramName,Object param){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); try{ return em .createNamedQuery(queryName,ec) .setParameter(paramName, param) .getResultList(); }finally{ em.close(); } } /** * Runs a named query that needs one parameter to be set. * Returns a list of entities that satisfy the query starting from offset position * and in maximal amount specified. * @param queryName name of named query * @param paramName name of the parameter in the query * @param param value of the parameter * @param offset starting position of entities * @param maxResultSize maximal number of entities returned * @return list of entities returned by the query */ protected List<T> getByTypedNamedQuery(String queryName,String paramName,Object param, int offset,int maxResultSize){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); try{ return em .createNamedQuery(queryName,ec) .setParameter(paramName, param) .setMaxResults(maxResultSize) .setFirstResult(offset) .getResultList(); }finally{ em.close(); } } /** * Runs a named query that needs two parameters to be set and returns a list of entities that satisfy the query. * @param queryName name of named query * @param paramName1 name of the first parameter * @param param1 value of the first parameter * @param paramName2 name of the second parameter * @param param2 value of the second parameter * @return list of entities returned by the query */ protected List<T> getByTypedNamedQueryDouble(String queryName,String paramName1,Object param1,String paramName2,Object param2){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); try{ return em .createNamedQuery(queryName,ec) .setParameter(paramName1, param1) .setParameter(paramName2, param2) .getResultList(); }finally{ em.close(); } } /** * Runs a named query that needs two parameters to be set. * Returns a list of entities that satisfy the query, starting from offset position in specified maximal amount. * @param queryName name of named query * @param paramName1 name of the first parameter * @param param1 value of the first parameter * @param paramName2 name of the second parameter * @param param2 value of the second parameter * @param offset starting position of entities * @param maxResultCount maximal number of entities returned * @return list of entities returned by the query */ protected List<T> getByTypedNamedQueryDouble(String queryName,String paramName1,Object param1,String paramName2,Object param2, int offset, int maxResultCount){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); try{ return em .createNamedQuery(queryName,ec) .setParameter(paramName1, param1) .setParameter(paramName2, param2) .setFirstResult(offset) .setMaxResults(maxResultCount) .getResultList(); }finally{ em.close(); } } /** * Runs a named query and returns the first item returned by the query. If no entity is found null is returned. * @param queryName name of named query * @param paramName name of the parameter * @param param value of the parameter * @return first entity returned by the query */ protected T getSingleResultByTypedNamedQuery(String queryName,String paramName,Object param){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); try { return em .createNamedQuery(queryName,ec) .setParameter(paramName, param) .setMaxResults(1) .getSingleResult(); }catch(Exception e){ return null; }finally{ em.close(); } } protected CriteriaBuilder getCriteriaBuilder(){ return EntityManagerInstancesCreator .getEntityManagerInstance() .getCriteriaBuilder(); } private Root<T> root=null; /** * Creates the new root element for query building specific for particular entity class. * @return root element for query building */ protected Root<T> getRoot(){ if(root==null){ root=getCriteriaBuilder().createQuery(ec).from(ec); } return root; } /** * Creates path to entity's corresponding columns (in database representation) based upon column used in views. * @param column of the table * @return path to entity's corresponding variable */ protected Path<Object> convertColumnToJPAParam(ITableColumn column){ return getRoot().get("id"); } /** * Function returning all entities using criteria query. * @return list of all entities */ protected List<T> getByCriteriaQuery(){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); CriteriaQuery<T> query=getCriteriaBuilder().createQuery(ec); return em .createQuery( query .select(getRoot()) ) .getResultList(); } /** * Performs a criteria query that returns entities satisfying the given predicate. * @param wherePredicate predicate that must be satisfied by the returned entities * @return list of entities */ protected List<T> getByCriteriaQuery(Predicate wherePredicate){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); CriteriaQuery<T> query=getCriteriaBuilder().createQuery(ec); return em .createQuery( query .select(getRoot()) .where(wherePredicate) ) .getResultList(); } /** * Performs a criteria query that returns the number of entities satisfying the given predicate. * @param wherePredicate predicate that must be satisfied by the returned entities * @return number of entities satisfying the predicate */ protected int getByCriteriaQueryCount(Predicate wherePredicate){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); CriteriaQuery<Long> query=getCriteriaBuilder().createQuery(Long.class); return em .createQuery( query .select(getCriteriaBuilder().count(getRoot())) .where(wherePredicate) ) .getSingleResult() .intValue(); } /** * Performs a criteria query that returns all entities from offset position in a specified maximum amount ordered according to the given column in the view. * @param sortColumn column defining the order of entities * @param sortOrder ascending or descending ordering * @param offset start position of the entities * @param maxResultCount maximum number of entities to be returned * @return list of entities */ protected List<T> getByCriteriaQuery(ITableColumn sortColumn, SortOrder sortOrder, int offset, int maxResultCount){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); CriteriaBuilder cb=getCriteriaBuilder(); CriteriaQuery<T> query=cb.createQuery(ec); query = query.select(getRoot()); switch (sortOrder) { case ASCENDING: query.orderBy(cb.asc(convertColumnToJPAParam(sortColumn))); break; case DESCENDING: query.orderBy(cb.desc(convertColumnToJPAParam(sortColumn))); break; default: break; } return em .createQuery(query) .setFirstResult(offset) .setMaxResults(maxResultCount) .getResultList(); } /** * Performs a criteria criteria that returns all entities satisfying the given predicate. * The result list contains entities sorted according to a given column in ascending or descending order. * @param wherePredicate predicate that must be satisfied by the returned entities * @param sortColumn column defining the order of entities * @param sortOrder ascending or descending ordering * @param offset start position of entities * @param maxResultCount maximum number of entities * @return list of entities */ protected List<T> getByCriteriaQuery(Predicate wherePredicate, ITableColumn sortColumn, SortOrder sortOrder, int offset, int maxResultCount){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); CriteriaBuilder cb=getCriteriaBuilder(); CriteriaQuery<T> query=cb.createQuery(ec); query = query.select(getRoot()).where(wherePredicate); switch (sortOrder) { case ASCENDING: query.orderBy(cb.asc(convertColumnToJPAParam(sortColumn))); break; case DESCENDING: query.orderBy(cb.desc(convertColumnToJPAParam(sortColumn))); break; default: break; } return em .createQuery(query) .setFirstResult(offset) .setMaxResults(maxResultCount) .getResultList(); } /** * Deletes an entity with the given ID from the database. * @param id of the entity to be removed */ public void deleteEntityByID(int id){ EntityManager em=EntityManagerInstancesCreator.getEntityManagerInstance(); em.getTransaction().begin(); try{ T entity = em.find(ec, id); em.remove(entity); em.getTransaction().commit(); }catch(Exception e){ PikaterDBLogger.logThrowable("Can't remove JPA object", e); em.getTransaction().rollback(); }finally{ em.close(); } } }
package uk.org.cinquin.mutinack.misc_util; public class VersionNumber { public static final float version = 0.3f; }
package com.raether.watchwordbot; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import jskills.Rating; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.kohsuke.github.GHIssue; import org.kohsuke.github.GHRepository; import com.raether.watchwordbot.feat.UserFeatureRequest; import com.raether.watchwordbot.gh.GitHubHelper; import com.raether.watchwordbot.lex.LexicalDatabaseHelper; import com.raether.watchwordbot.meatsim.AIPlayer; import com.raether.watchwordbot.meatsim.AISlackPlayer; import com.raether.watchwordbot.meatsim.BotThoughtProcess; import com.raether.watchwordbot.meatsim.DesiredBotAction; import com.raether.watchwordbot.meatsim.PotentialGuess; import com.raether.watchwordbot.meatsim.PotentialGuessRow; import com.raether.watchwordbot.message.DefaultMessageGenerator; import com.raether.watchwordbot.message.MessageGenerator; import com.raether.watchwordbot.ranking.RatingHelper; import com.raether.watchwordbot.ranking.RatingPrinter; import com.ullink.slack.simpleslackapi.SlackChannel; import com.ullink.slack.simpleslackapi.SlackPersona.SlackPresence; import com.ullink.slack.simpleslackapi.SlackSession; import com.ullink.slack.simpleslackapi.SlackUser; import com.ullink.slack.simpleslackapi.events.SlackMessagePosted; import com.ullink.slack.simpleslackapi.impl.SlackSessionFactory; import com.ullink.slack.simpleslackapi.listeners.SlackMessagePostedListener; import edu.cmu.lti.jawjaw.db.SynsetDefDAO; import edu.cmu.lti.jawjaw.pobj.Lang; import edu.cmu.lti.jawjaw.pobj.POS; import edu.cmu.lti.jawjaw.pobj.Synset; import edu.cmu.lti.jawjaw.pobj.SynsetDef; import edu.cmu.lti.jawjaw.util.WordNetUtil; public class WatchWordBot implements SlackMessagePostedListener { private String apiKey = ""; private SlackSession slackSession; // Gameplay private GameState currentGameState = GameState.IDLE; private WatchWordLobby watchWordLobby; private WatchWordGame game; private List<String> wordList = null; private List<String> banishedWordList = new ArrayList<String>(); private List<Thread> aiThreads = new ArrayList<Thread>(); private MessageGenerator messageGenerator = new DefaultMessageGenerator(); private static Boolean DEBUG = Boolean.FALSE; // add-ons private Optional<SessionFactory> sessionFactory; private Optional<GHRepository> repo; public WatchWordBot(String apiKey, Optional<SessionFactory> sessionFactory, Optional<GHRepository> repo) { setAPIKey(apiKey); setSessionFactory(sessionFactory); setGHRepo(repo); } private void setGHRepo(Optional<GHRepository> repo) { this.repo = repo; } public Optional<GHRepository> getGHRepo() { return this.repo; } private void setSessionFactory(Optional<SessionFactory> sessionFactory) { this.sessionFactory = sessionFactory; } public Optional<SessionFactory> getSessionFactory() { return sessionFactory; } private void setAPIKey(String apiKey) { this.apiKey = apiKey; } private String getAPIKey() { return this.apiKey; } public void loadWordList() throws IOException { InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream("wordlist.txt"); System.out.println(in); List<String> words = IOUtils.readLines(in, "UTF-8"); System.out.println(words.size()); Set<String> uniqueWords = new TreeSet<String>(); uniqueWords.addAll(words); wordList = new ArrayList<String>(); for (String uniqueWord : uniqueWords) { String formattedUniqueWord = uniqueWord.replaceAll("[\\s]+", "_"); if (!formattedUniqueWord.equals(uniqueWord)) { System.out.println("Transformed " + uniqueWord + "=>" + formattedUniqueWord); } wordList.add(formattedUniqueWord); } } public void connect() throws IOException { SlackSession session = SlackSessionFactory .createWebSocketSlackSession(getAPIKey()); session.connect(); session.addMessagePostedListener(this); updateSession(session); beginHeartbeat(); } public void beginHeartbeat() { ScheduledExecutorService scheduler = Executors .newScheduledThreadPool(1); final Runnable heartBeater = new Runnable() { @Override public void run() { onHeartBeat(getSession()); } }; // final ScheduledFuture<?> heartBeatHandle = scheduler.scheduleAtFixedRate(heartBeater, 1000, 1000, TimeUnit.MILLISECONDS); } private void reconnect(SlackSession session) { try { session.disconnect(); } catch (Exception e) { } finally { try { session.connect(); } catch (Exception e) { e.printStackTrace(); } } } private void updateSession(SlackSession session) { this.slackSession = session; } private SlackSession getSession() { return this.slackSession; } @Override public void onEvent(SlackMessagePosted event, SlackSession session) { updateSession(session); if (event.getSender().getId().equals(session.sessionPersona().getId())) return; try { handleCommand(event, session); } catch (Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); e.printStackTrace(ps); String content; content = baos.toString(); session.sendMessage(event.getChannel(), "Exception Encountered:\n" + content); } } private synchronized void handleCommand(SlackMessagePosted event, SlackSession session) { LinkedList<String> args = new LinkedList<String>(); args.addAll(Arrays.asList(event.getMessageContent().split("\\s+")));// event.getMessageContent().split(" "); String commandText = args.pop().toLowerCase(); List<Command> commands = generateCommands(event, args, session); Command matchingCommand = findMatchingCommand(commandText, commands, event.getChannel()); if (matchingCommand != null) { matchingCommand.run(); } } protected Command findMatchingCommand(String commandText, Collection<Command> commands, SlackChannel channel) { for (Command command : commands) { if (command.matches(commandText)) { if (!isGameCurrentlyInValidGameState(channel, command.getValidGameStates())) { return null; } return command; } } return null; } private List<Command> generateCommands(final SlackMessagePosted event, final LinkedList<String> args, final SlackSession session) { List<Command> commands = new ArrayList<Command>(); commands.add(new Command("lobby", "create a new lobby for players to join", GameState.IDLE) { @Override public void run() { lobbyCommand(event, args, session); } }); commands.add(new Command("define", "define a word", GameState.IDLE, GameState.LOBBY, GameState.GAME) { @Override public void run() { defineCommand(event, args, session); } }); commands.add(new Command("bot", Arrays.asList("bots"), "add a bot to the game", false, GameState.LOBBY, GameState.GAME) { @Override public void run() { botCommand(event, args, session); } }); commands.add(new Command("cancel", "cancel the game and lobby", GameState.LOBBY, GameState.GAME) { @Override public void run() { cancelCommand(event, args, session); } }); commands.add(new Command("list", "show all the players in the game", GameState.LOBBY, GameState.GAME) { @Override public void run() { listCommand(event, args, session); } }); commands.add(new Command("grid", Arrays.asList("board"), "show the WatchWords grid", false, GameState.GAME) { @Override public boolean matches(String command) { return super.matches(command) || command.matches("g+r+i+d+"); } @Override public void run() { gridCommand(event, args, session); } }); commands.add(new Command("join", "join the game", GameState.LOBBY, GameState.GAME) { @Override public void run() { joinCommand(event, args, session); } }); commands.add(new Command("swap", "switch teams or swap two players", GameState.LOBBY, GameState.GAME) { @Override public void run() { swapCommand(event, args, session); } }); commands.add(new Command("time", "shows the remaining time", GameState.GAME) { @Override public void run() { timeCommand(event, args, session); } }); commands.add(new Command("kick", Arrays.asList("remove"), "removes the specified player from the game.", false, GameState.LOBBY, GameState.GAME) { @Override public void run() { kickCommand(event, args, session); } }); commands.add(new Command("start", "starts the game", GameState.LOBBY) { @Override public void run() { startCommand(event, args, session); } }); commands.add(new Command("clue", "give a clue to your team", GameState.GAME) { @Override public void run() { clueCommand(event, args, session); } }); commands.add(new Command("guess", "guess a word", GameState.GAME) { @Override public void run() { guessCommand(event, args, session); } }); if (DEBUG) { commands.add(new Command("win", "win", true, GameState.GAME) { @Override public void run() { winCommand(event, args, session); } }); } commands.add(new Command("end", Arrays.asList("pass"), "end the guessing phase", false, GameState.GAME) { @Override public void run() { endCommand(event, args, session); } }); commands.add(new Command("sync", "synchronization test", true, GameState.IDLE, GameState.LOBBY, GameState.GAME) { @Override public void run() { syncCommand(event, args, session); } }); commands.add(new Command("feat", Arrays.asList("feature"), "submit a feature request", false, GameState.IDLE, GameState.LOBBY, GameState.GAME) { @Override public void run() { featCommand(event, args, session); } }); commands.add(new Command("help", "yes, this is help", true, GameState.IDLE, GameState.LOBBY, GameState.GAME) { @Override public void run() { helpCommand(event, args, session); } }); commands.add(new Command("banish", "banish a word from the game forever", GameState.GAME) { @Override public void run() { banishCommand(event, args, session); } }); return commands; } protected void banishCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (args.isEmpty()) { printUsage(event.getChannel(), "banish [word]"); return; } String banishedWord = args.pop(); boolean match = false; for (String word : wordList) { if (word.equalsIgnoreCase(banishedWord)) { match = true; break; } } if (!match) { session.sendMessage(event.getChannel(), "'" + banishedWord + "' not found in wordlist."); return; } session.sendMessage(event.getChannel(), "Banish command not implemented."); } protected Session createHibernateSession() { if (!this.getSessionFactory().isPresent()) { return null; } Session hibernateSession = null; try { hibernateSession = getSessionFactory().get().openSession(); } catch (Exception e) { e.printStackTrace(); if (hibernateSession != null) { hibernateSession.close(); } } return hibernateSession; } protected void closeHibernateSession(Session session) { try { session.close(); } catch (Exception e) { e.printStackTrace(); } } protected static String printUserFeedbackRequest(GHIssue issue) { return issue.getNumber() + ":" + issue.getTitle() + "(" + issue.getHtmlUrl() + ")"; } protected static String printUserFeedbackRequest(UserFeatureRequest request) { return request.getId() + ": " + request.getDescription(); } protected void featCommand(final SlackMessagePosted event, final LinkedList<String> args, final SlackSession session) { if (!getGHRepo().isPresent()) { session.sendMessage(event.getChannel(), "Could not establish link to github."); return; } List<Command> featCommands = new ArrayList<Command>(); featCommands.add(new Command("list", "list all feature requests", GameState.getAllStates()) { @Override public void run() { if (!args.isEmpty()) { printUsage(event.getChannel(), "feat list"); return; } try { String out = "Feature Requests:\n"; List<GHIssue> issues = GitHubHelper .getSlackIssues(getGHRepo().get()); for (GHIssue issue : issues) { out += printUserFeedbackRequest(issue) + "\n"; } session.sendMessage(event.getChannel(), out); } catch (Exception e) { session.sendMessage(event.getChannel(), "Could not read features"); } } }); featCommands.add(new Command("add", "add a feature request", GameState .getAllStates()) { @Override public void run() { if (args.isEmpty()) { printUsage(event.getChannel(), "feat add [description]"); return; } String description = StringUtils.join(args, " "); try { GHIssue issue = GitHubHelper.createGHIssue(getGHRepo() .get(), description, printFullUserDetails(event .getSender())); session.sendMessage(event.getChannel(), "Successfully created issue:" + printUserFeedbackRequest(issue)); } catch (Exception e) { session.sendMessage(event.getChannel(), "Could not create issue:" + e); } } }); featCommands.add(new Command("close", "close a feature request", GameState.getAllStates()) { @Override public void run() { if (args.isEmpty()) { printUsage(event.getChannel(), "feat close [id]"); return; } Integer id = null; try { id = Integer.parseInt(args.pop()); } catch (Exception e) { session.sendMessage(event.getChannel(), "Could not parse '" + args.pop() + "'"); return; } try { List<GHIssue> issues = GitHubHelper .getSlackIssues(getGHRepo().get()); GHIssue foundIssue = null; for (GHIssue issue : issues) { if (issue.getNumber() == id) { foundIssue = issue; break; } } if (foundIssue == null) { session.sendMessage(event.getChannel(), "Could not find feature with id " + id); return; } GitHubHelper.removeGHIssue(getGHRepo().get(), printFullUserDetails(event.getSender()), id); session.sendMessage(event.getChannel(), "Deleted " + id); } catch (Exception e) { session.sendMessage(event.getChannel(), "Could not delete feature with id " + id); } } }); String featureSubcommandHelp = printCommands("Feature subcommand help", featCommands); if (args.isEmpty()) { printUsage(event.getChannel(), "feat [sub_command] (params)"); session.sendMessage(event.getChannel(), featureSubcommandHelp); return; } String commandText = args.pop(); Command command = this.findMatchingCommand(commandText, featCommands, event.getChannel()); if (command != null) { command.run(); } else { session.sendMessage(event.getChannel(), featureSubcommandHelp); } } private static String printFullUserDetails(SlackUser user) { return user.getUserName() + " (" + user.getRealName() + ")"; } private void defineCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (!LexicalDatabaseHelper.canBeCreated()) { session.sendMessage(event.getChannel(), "Lexical database link could not be established."); return; } if (args.size() != 1) { printUsage(event.getChannel(), "define [word]"); return; } String word = args.pop(); String messageOutput = "Defining *" + word + "*:\n"; for (POS pos : POS.values()) { List<edu.cmu.lti.jawjaw.pobj.Synset> synsets = WordNetUtil .wordToSynsets(word, pos); for (Synset synset : synsets) { SynsetDef def = SynsetDefDAO.findSynsetDefBySynsetAndLang( synset.getSynset(), Lang.eng); messageOutput += def.getSynset() + ":" + def.getDef() + "\n"; } } session.sendMessage(event.getChannel(), messageOutput); } private void winCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { finishGame(Arrays.asList(game.getTurnOrder().getCurrentTurn()), session); } private void botCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { int numberOfBots = 1; if (!args.isEmpty()) { try { numberOfBots = Integer.parseInt(args.pop()); if (numberOfBots <= 0) { throw new IllegalArgumentException( "Number of bots must be > 0"); } } catch (Exception e) { printUsage(event.getChannel(), "bot [# of desired bots]"); return; } } boolean addedBots = false; for (int addedBotCount = 0; addedBotCount < numberOfBots; addedBotCount++) { int maxAIPlayers = 4; int totalAIPlayers = this.getWatchWordLobby().getAIPlayerCount(); if (totalAIPlayers >= maxAIPlayers) { session.sendMessage(event.getChannel(), "Can't add any more bots! You have reached the bot limit (" + maxAIPlayers + " bots)"); break; } if (!AIPlayer.canBeCreated()) { session.sendMessage(event.getChannel(), "Sorry, bots cannot be added due to an environmental error."); break; } AISlackPlayer slackPlayer = new AISlackPlayer("Sim" + (totalAIPlayers + 1)); Player aiPlayer = new Player(true); getWatchWordLobby().addUser(slackPlayer, aiPlayer); addedBots = true; session.sendMessage(getCurrentChannel(), getUsernameString(slackPlayer) + " has joined the game!"); } if (addedBots) { session.sendMessage(getCurrentChannel(), printFactions(getWatchWordLobby())); if (!isAIThreadRunning()) { handleAIGuesses(); } } } private void helpCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { List<Command> commands = generateCommands(event, args, session); session.sendMessage(event.getChannel(), printCommands("Contextual Help", commands)); } private String printCommands(String title, List<Command> commands) { List<Command> filteredCommands = new ArrayList<Command>(); for (Command command : commands) { if (command.getValidGameStates().contains(this.currentGameState) && !command.isHidden()) { filteredCommands.add(command); } } String totalHelpText = title + "\n"; for (Command command : filteredCommands) { String helpText = "*" + command.getPrimaryAlias() + "*"; if (command.hasAdditionalAliases()) { helpText += " (" + command.getAdditionalAliases() + ")"; } helpText += " = " + command.getHelpText() + "\n"; totalHelpText += helpText; } return totalHelpText; } private void lobbyCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (event.getChannel().isDirect()) { session.sendMessage(event.getChannel(), "Cannot start a game in a private message!"); return; } session.sendMessage(event.getChannel(), "Reconnecting to slack service to refresh users, one sec..."); reconnect(getSession()); Faction redFaction = new Faction("Red", null); Faction blueFaction = new Faction("Blue", null); List<Faction> playerFactions = new ArrayList<Faction>(); playerFactions.add(redFaction); playerFactions.add(blueFaction); TurnOrder turnOrder = new TurnOrder(playerFactions); WatchWordLobby watchWordLobby = new WatchWordLobby(event.getChannel(), turnOrder); boolean validStart = false; Set<SlackUser> users = new HashSet<SlackUser>(); SlackUser lobbyStarter = findUserByUsername(event.getSender().getId(), watchWordLobby.getChannel().getMembers()); if (lobbyStarter != null) { users.add(lobbyStarter); } if (args.isEmpty() || args.peek().equals("opt-in")) { validStart = true; } else if (args.peek().equals("opt-out")) { validStart = true; for (SlackUser user : watchWordLobby.getChannel().getMembers()) { SlackPresence presence = session.getPresence(user); if (user.isBot() == false && (presence == SlackPresence.ACTIVE)) { users.add(user); } } } else { printUsage(event.getChannel(), "lobby [(opt-in), opt-out]"); return; } if (validStart) { for (SlackUser user : users) { watchWordLobby.addUser(user); } this.watchWordLobby = watchWordLobby; this.currentGameState = GameState.LOBBY; session.sendMessage(getCurrentChannel(), "Created new WatchWord Lobby!"); session.sendMessage(getCurrentChannel(), printFactions(getWatchWordLobby())); } } private void cancelCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (currentGameState == GameState.GAME) { session.sendMessage( getCurrentChannel(), "Game has been canceled by " + getUsernameString(event.getSender())); partialGameReset(); session.sendMessage(getCurrentChannel(), printFactions(getWatchWordLobby())); } else { session.sendMessage( getCurrentChannel(), "Lobby has been canceled by " + getUsernameString(event.getSender())); fullGameReset(); } } private void syncCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { session.sendMessage(getCurrentChannel(), "Synchronization test..."); try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } session.sendMessage(getCurrentChannel(), "Done!"); } private void listCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { session.sendMessage(event.getChannel(), printFactions(getWatchWordLobby())); } private void gridCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { session.sendMessage(event.getChannel(), printCardGrid()); } private void joinCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (!getWatchWordLobby().hasUser(event.getSender())) { getWatchWordLobby().addUser(event.getSender()); session.sendMessage(getCurrentChannel(), getUsernameString(event.getSender()) + " has joined the game!"); session.sendMessage(getCurrentChannel(), printFactions(getWatchWordLobby())); } else { session.sendMessage(event.getChannel(), getUsernameString(event.getSender()) + ", you're already in the game!"); } } private void swapCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (getWatchWordLobby().getPlayer(event.getSender()) == null) { session.sendMessage(event.getChannel(), getUsernameString(event.getSender()) + ", you are currently not in this game!"); return; } Player player = getWatchWordLobby().getPlayer(event.getSender()); if (args.isEmpty()) { Faction currentFaction = getWatchWordLobby().getTurnOrder() .getFactionFor(player); Faction newFaction = getWatchWordLobby().getTurnOrder() .swapFactions(player); session.sendMessage( getCurrentChannel(), getUsernameString(event.getSender()) + " swapped from " + currentFaction.getName() + " to " + newFaction.getName() + "."); } else { SlackUser firstUser = null; SlackUser secondUser = null; if (args.size() == 2) { firstUser = findUserByUsername(args.pop(), getWatchWordLobby() .getUsers()); secondUser = findUserByUsername(args.pop(), getWatchWordLobby() .getUsers()); } else { printUsage( event.getChannel(), "swap - swap yourself to the other team\nswap <player1> <player2> swap two players"); return; } if (firstUser == null || secondUser == null) { session.sendMessage(event.getChannel(), "Could not find user(s) with those names."); return; } Player firstPlayer = getWatchWordLobby().getPlayer(firstUser); Player secondPlayer = getWatchWordLobby().getPlayer(secondUser); if (firstPlayer == null || secondPlayer == null) { session.sendMessage(event.getChannel(), "One or more of those users are not currently in the game."); return; } getWatchWordLobby().getTurnOrder().swapPlayers(firstPlayer, secondPlayer); session.sendMessage(getCurrentChannel(), getUsernameString(event.getSender()) + " has swapped " + getUsernameString(firstUser) + " with " + getUsernameString(secondUser)); } session.sendMessage(event.getChannel(), printFactions(getWatchWordLobby())); } private void timeCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (game.getActingFaction() == null) { session.sendMessage(event.getChannel(), "Game is currently in an invalid state, there is currently no acting faction!"); return; } CompetitiveTime time = game.getRemainingTime(); if (time == null) { session.sendMessage(event.getChannel(), "There is currently no timer enabled for the " + game.getActingFaction().getName() + " team."); return; } session.sendMessage(event.getChannel(), "Remaining time for the " + game.getActingFaction().getName() + " team: " + time.getTime(TimeUnit.SECONDS) + " secs. (" + time.getOvertime(TimeUnit.SECONDS) + " secs. of overtime)"); } private void kickCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (args.isEmpty()) { printUsage(event.getChannel(), "[kick|remove] <player1, player2, ...>"); return; } while (!args.isEmpty()) { String username = args.pop(); SlackUser user = findUserByUsername(username, getWatchWordLobby() .getUsers()); if (user != null) { getWatchWordLobby().removeUser(user); session.sendMessage(getCurrentChannel(), event.getSender() .getUserName() + " removed " + getUsernameString(user)); } else { session.sendMessage(getCurrentChannel(), "Could not find user already in game with username '" + username + "'."); } } session.sendMessage(watchWordLobby.getChannel(), printFactions(getWatchWordLobby())); } private void guessCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (getWatchWordLobby().getPlayer(event.getSender()) == null) { session.sendMessage(event.getChannel(), getUsernameString(event.getSender()) + ", you are currently not in this game!"); return; } if (args.isEmpty()) { printUsage(event.getChannel(), "guess <word>"); return; } String wordBeingGuessed = args.pop(); makeGuess(wordBeingGuessed, session, event.getChannel(), event.getSender()); } private synchronized void makeGuess(String wordBeingGuessed, SlackSession session, SlackChannel eventChannel, SlackUser eventUser) { List<WordTile> results = this.game.getGrid().getTilesForWord( wordBeingGuessed); if (results.isEmpty()) { session.sendMessage(eventChannel, "Could not find word that matches '" + wordBeingGuessed + "'"); return; } else if (results.size() > 2) { List<String> words = new ArrayList<String>(); for (WordTile tile : results) { words.add(tile.getWord()); } session.sendMessage(eventChannel, "Found multiple words matching '" + wordBeingGuessed + "': " + StringUtils.join(words, ", ") + "'"); return; } else { WordTile guessedTile = results.get(0); Player guesser = getWatchWordLobby().getPlayer(eventUser); Faction guesserFaction = game.getFactionForPlayer(guesser); if (this.game.getTurnOrder().getCurrentTurn() != guesserFaction) { session.sendMessage( eventChannel, getUsernameString(eventUser) + ", it is not currently your turn to guess! (You are on the " + guesserFaction.getName() + " team, it is currently the " + game.getTurnOrder().getCurrentTurn() .getName() + " team's turn.)"); if (DEBUG) { session.sendMessage(eventChannel, "However, I'll allow it for now..."); } else { return; } } else if (guesser == guesserFaction.getLeader()) { session.sendMessage(eventChannel, getUsernameString(eventUser) + ", you're the word smith. You can't guess!"); if (DEBUG) { session.sendMessage(eventChannel, "However, I'll allow it for now..."); } else { return; } } else if (!game.wasClueGivenThisTurn()) { session.sendMessage(eventChannel, getUsernameString(eventUser) + ", hold your horses! A clue has not been given yet!"); return; } session.sendMessage(getCurrentChannel(), getUsernameString(eventUser) + " has guessed *" + results.get(0).getWord() + "*!"); game.guess(); guessedTile.setRevealed(true); Faction victor = null; boolean pickedAssassin = false; boolean pickedOwnCard = false; boolean changeTurns = false; if (guessedTile.getFaction().equals(game.getAssassinFaction())) { victor = game.getTurnOrder().getFactionAfter(guesserFaction); pickedAssassin = true; } if (guesserFaction == guessedTile.getFaction()) { pickedOwnCard = true; } else { changeTurns = true; } if (game.getRemainingGuesses() == 0) { changeTurns = true; } // decide if there's a winner due to no more cards for (Faction faction : game.getTurnOrder().getAllFactions()) { if (game.getGrid().getUnrevealedTilesForFaction(faction) .isEmpty()) { victor = faction; } } // remaining team is the winner if (game.getTurnOrder().getAllFactions().size() == 1) { victor = game.getTurnOrder().getAllFactions().get(0); } if (pickedAssassin) { session.sendMessage(getCurrentChannel(), messageGenerator.getAssassinPickMessage() + " " + getUsernameString(eventUser) + " has picked the assassin! " + guesserFaction.getName() + " loses!"); } else if (pickedOwnCard) { session.sendMessage(getCurrentChannel(), messageGenerator.getCorrectPickMessage() + " " + getUsernameString(eventUser) + " has picked correctly."); } else { session.sendMessage(getCurrentChannel(), messageGenerator.getIncorrectPickMessage() + " " + getUsernameString(eventUser) + " has picked a *" + guessedTile.getFaction().getName() + "* card."); } if (victor != null) { finishGame(Arrays.asList(victor), session); return; } if (changeTurns) { session.sendMessage(getCurrentChannel(), "Out of guesses! Changing turns."); game.changeTurns(); waitForClue(); } else { waitForGuess(); } session.sendMessage(getCurrentChannel(), printCardGrid()); session.sendMessage(getCurrentChannel(), printCurrentTurn()); session.sendMessage(getCurrentChannel(), printGivenClue()); for (Faction faction : game.getTurnOrder().getAllFactions()) { if (faction.hasLeader()) { if (!faction.getLeader().isAIControlled()) { session.sendMessageToUser(this.watchWordLobby .getUser(faction.getLeader()), printCardGrid(true), null); } } } } } private void endCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { endTurn(session, event.getChannel(), event.getSender()); } private void endTurn(SlackSession session, SlackChannel eventChannel, SlackUser eventUser) { if (getWatchWordLobby().getPlayer(eventUser) == null) { session.sendMessage(eventChannel, getUsernameString(eventUser) + ", you are currently not in this game!"); return; } Player guesser = getWatchWordLobby().getPlayer(eventUser); Faction guesserFaction = game.getFactionForPlayer(guesser); if (this.game.getTurnOrder().getCurrentTurn() != guesserFaction) { session.sendMessage(eventChannel, "It is not your turn to end!"); if (DEBUG) { session.sendMessage(eventChannel, "However, I'll allow it for now..."); } else { return; } } else if (guesser == guesserFaction.getLeader()) { session.sendMessage( eventChannel, getUsernameString(eventUser) + ", you're the wordsmith. You can't decide when your team ends their turn!"); if (DEBUG) { session.sendMessage(eventChannel, "However, I'll allow it for now..."); } else { return; } } else if (!game.wasClueGivenThisTurn()) { session.sendMessage(eventChannel, getUsernameString(eventUser) + ", hold your horses! A clue has not been given yet!"); return; } else if (!game.getClue().hasGuessed()) { session.sendMessage(eventChannel, "You must make at least one guess before you can end your turn!"); return; } game.changeTurns(); session.sendMessage(getCurrentChannel(), getUsernameString(eventUser) + " has ended the turn."); session.sendMessage(getCurrentChannel(), printCardGrid()); session.sendMessage(getCurrentChannel(), printCurrentTurn()); session.sendMessage(getCurrentChannel(), printGivenClue()); waitForClue(); } private void clueCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { Player player = getWatchWordLobby().getPlayer(event.getSender()); if (player == null) { session.sendMessage(event.getChannel(), "You are not in the game!"); return; } if (getWatchWordLobby().getTurnOrder().getFactionFor(player) != game .getTurnOrder().getCurrentTurn()) { session.sendMessage(event.getChannel(), "It is not your turn to give a clue!"); if (DEBUG) { session.sendMessage(event.getChannel(), "However, I'll allow it for now..."); } else { return; } } if (player != game.getTurnOrder().getCurrentTurn().getLeader()) { session.sendMessage(event.getChannel(), "Only the current turn's leader can give a clue."); if (DEBUG) { session.sendMessage(event.getChannel(), "However, I'll allow it for now..."); } else { return; } } if (game.getClue() != null) { session.sendMessage(event.getChannel(), "A clue was already given."); session.sendMessage(event.getChannel(), printGivenClue()); return; } if (args.size() != 2) { printUsage(event.getChannel(), "clue <word> [amount|unlimited]"); return; } String word = args.pop(); String unparsedNumber = args.pop(); int totalGuesses = -1; boolean unlimitedGuesses = false; boolean zeroClue = false; if (unparsedNumber.toLowerCase().startsWith("unlimited")) { unlimitedGuesses = true; } else { try { totalGuesses = Integer.parseInt(unparsedNumber); if (totalGuesses == 0) { zeroClue = true; } else if (totalGuesses < 0) { session.sendMessage(event.getChannel(), "You must give a clue with at least one guess!"); return; } totalGuesses += 1;// bonus guess } catch (Exception e) { session.sendMessage(event.getChannel(), "Could not parse '" + unparsedNumber + "' as a number."); return; } ; } List<WordTile> tiles = game.getGrid().getTilesForWord(word); if (!tiles.isEmpty()) { session.sendMessage(event.getChannel(), "Your clue matches tiles on the board! Please give a different clue."); return; } game.giveClue(new WatchWordClue(word, totalGuesses, unlimitedGuesses, zeroClue)); session.sendMessage(getCurrentChannel(), getUsernameString(event.getSender()) + " has given a clue."); session.sendMessage(getCurrentChannel(), printGivenClue()); session.sendMessage(getCurrentChannel(), printCardGrid()); waitForGuess(); } private void refreshGameResources() { refreshBanishedWordList(); } private void refreshBanishedWordList() { } private void startCommand(SlackMessagePosted event, LinkedList<String> args, SlackSession session) { if (args.size() == 1) { if (args.pop().equalsIgnoreCase("debug")) { DEBUG = Boolean.TRUE; } else { DEBUG = Boolean.FALSE; } } refreshGameResources(); currentGameState = GameState.GAME; session.sendMessage(getCurrentChannel(), messageGenerator.getGameStartMessage()); long seed1 = System.nanoTime(); Random random1 = new Random(seed1); int totalRows = 5; int totalCols = 5; List<String> words = generateWords(wordList, banishedWordList, totalRows * totalCols, random1); BuildableWatchWordGrid buildableGrid = new BuildableWatchWordGrid( words, totalRows, totalCols); TurnOrder turnOrder = this.watchWordLobby.getTurnOrder(); turnOrder.shuffle(random1); for (Faction faction : turnOrder.getAllFactions()) { long overtimeDuration = 10; TimeUnit overtimeTimeUnit = TimeUnit.MINUTES; faction.setCompetitiveTimer(new CompetitiveTimer(overtimeDuration, overtimeTimeUnit)); } Faction neutralFaction = new Faction("Neutral", null); Faction assassinFaction = new Faction("Assassin", null); int firstFactionCards = 9; int secondFactionCards = 8; int assassinCards = 1; buildableGrid.randomlyAssign(turnOrder.getCurrentTurn(), firstFactionCards, random1); buildableGrid.randomlyAssign(turnOrder.getNextTurn(), secondFactionCards, random1); buildableGrid.randomlyAssign(assassinFaction, assassinCards, random1); buildableGrid.fillRemainder(neutralFaction); WatchWordGrid grid = buildableGrid.build(); WatchWordGame game = new WatchWordGame(grid, turnOrder, neutralFaction, assassinFaction); this.game = game; session.sendMessage(getCurrentChannel(), printCardGrid()); session.sendMessage(getCurrentChannel(), printFactions(watchWordLobby)); session.sendMessage(getCurrentChannel(), printCurrentTurn()); session.sendMessage(getCurrentChannel(), printGivenClue()); for (Faction faction : game.getTurnOrder().getAllFactions()) { if (faction.hasLeader() && !faction.getLeader().isAIControlled()) { SlackUser user = getWatchWordLobby().getUser( faction.getLeader()); SlackUser opponent = getWatchWordLobby().getUser( game.getTurnOrder().getFactionAfter(faction) .getLeader()); try { session.sendMessageToUser( user, printWordSmithInstructions(user, opponent, faction, game.getAssassinFaction()), null); session.sendMessageToUser(user, printCardGrid(true), null); } catch (Exception e) { e.printStackTrace(); } } } printMatchQuality(); waitForClue(); } private boolean isGameCurrentlyInValidGameState(SlackChannel channel, List<GameState> validStates) { GameState currentState = this.currentGameState; if (validStates.contains(currentState)) { return true; } printIncorrectGameState(channel, validStates); return false; } private void waitForClue() { stopAllAIThreads(); this.game.startCountingDown(4, TimeUnit.MINUTES); } private void waitForGuess() { stopAllAIThreads(); this.game.startCountingDown(2, TimeUnit.MINUTES); handleAIGuesses(); } private boolean isAIThreadRunning() { return !this.aiThreads.isEmpty(); } private void stopAllAIThreads() { for (Thread t : this.aiThreads) { try { t.interrupt(); } catch (Exception e) { e.printStackTrace(); } ; } this.aiThreads.clear(); } private void queueAIThread(Thread t) { this.aiThreads.add(t); t.start(); } private void handleAIGuesses() { if (this.game == null) return; Player aiGuesseeOnCurrentTeam = null; for (Player follower : this.game.getActingFaction().getFollowers()) { if (follower.isAIControlled()) { aiGuesseeOnCurrentTeam = follower; break; } } if (aiGuesseeOnCurrentTeam == null) { return; } final SlackUser aiSlackUser = getWatchWordLobby().getUser( aiGuesseeOnCurrentTeam); sendMessageToCurrentChannel("The AI (" + getUsernameString(aiSlackUser) + ") is attempting to guess using your provided clue!"); final List<WatchWordClue> currentFactionClues = this.game .getAllCluesForFaction(game.getActingFaction()); final List<WatchWordClue> otherFactionClues = new ArrayList<WatchWordClue>(); for (Faction faction : getGame().getTurnOrder() .getAllTurnsExceptCurrent()) { otherFactionClues.addAll(getGame().getAllCluesForFaction(faction)); } queueAIThread(new Thread() { @Override public void run() { sendMessageToCurrentChannel("Sleepin' a bit to give humans a tiny chance to act..."); try { Thread.sleep(5000); } catch (Exception e) { } AIPlayer player = new AIPlayer(); BotThoughtProcess thoughtProcess = player.makeGuess( currentFactionClues, otherFactionClues, getGame() .getGrid(), getGame().getTurnOrder()); if (thoughtProcess.getDesiredAction() == DesiredBotAction.END_TURN) { endTurn(getSession(), getCurrentChannel(), aiSlackUser); } else if (thoughtProcess.getDesiredAction() == DesiredBotAction.GUESS) { List<WordTile> tiles = game.getGrid().getTilesForWord( thoughtProcess.getBestGuess().getWord()); // makes using bots a bit more fun, as they no longer guess // the assassin with as high of a probability. Eventually // this can be removed once bots are a bit better for (WordTile tile : tiles) { if (tile.getFaction() == game.getAssassinFaction()) { PotentialGuess potentialGuess = thoughtProcess .getBestGuess(); potentialGuess.rethinkGuess(2.0, 0.5); } } List<PotentialGuess> allPotentialGuesses = thoughtProcess .getSortedGuessList(); int startingIndex = Math.max(0, allPotentialGuesses.size() - 3); int endingIndex = allPotentialGuesses.size(); List<PotentialGuess> mostProbablePotentialGuesses = allPotentialGuesses .subList(startingIndex, endingIndex); Collections.reverse(mostProbablePotentialGuesses); sendMessageToCurrentChannel(" String out = ""; for (PotentialGuess potentialGuess : mostProbablePotentialGuesses) { out += printPotentialGuess(potentialGuess) + "\n"; } sendMessageToCurrentChannel(out); sendMessageToCurrentChannel(" makeGuess(thoughtProcess.getBestGuess().getWord(), getSession(), getCurrentChannel(), aiSlackUser); } } }); } private String printPotentialGuess(PotentialGuess potentialGuess) { NumberFormat format = NumberFormat.getNumberInstance(); format.setMaximumFractionDigits(2); format.setMinimumFractionDigits(2); format.setMinimumIntegerDigits(0); String output = "Confidence in *" + potentialGuess.getWord() + "*: " + format.format(potentialGuess.getWeightedCertainty()); List<PotentialGuessRow> sortedRows = potentialGuess.getAllGuessRows(); Collections.sort(sortedRows, new Comparator<PotentialGuessRow>() { @Override public int compare(PotentialGuessRow o1, PotentialGuessRow o2) { Double a = Math.abs(o1.getWeightedCertainty()); Double b = Math.abs(o2.getWeightedCertainty()); return b.compareTo(a); } }); List<String> contributors = new ArrayList<String>(); output += " ("; for (PotentialGuessRow row : sortedRows) { boolean inPositive = potentialGuess.getPositiveGuessResults() .contains(row); String prefix = inPositive ? "+" : "-"; contributors.add(format.format(row.getWeightedCertainty()) + "/" + format.format(row.getCertainty()) + " [" + prefix + "" + row.getClue() + "]"); } output += StringUtils.join(contributors, ", "); output += ")"; return output; } private void sendMessageToCurrentChannel(String output) { if (getSession() == null || getCurrentChannel() == null) { System.out.println("Nowhere to send the current message to."); return; } getSession().sendMessage(getCurrentChannel(), output); } private String printAbbreviatedFaction(Faction faction) { return "(" + faction.getName().substring(0, 1) + ")"; } private String printWordSmithInstructions(SlackUser user, SlackUser opponent, Faction yourFaction, Faction assassinFaction) { String out = ""; out += "Hi " + getUsernameString(user) + ", as the Word Smith, try to get your team to guess all of the words marked with " + yourFaction.getName() + " *" + printAbbreviatedFaction(yourFaction) + "*.\n"; out += "The only information you can give your team each turn is a single word, and the number of guesses your team can make. When you're ready, type ```clue``` to give your team a word.\n"; out += "If your team guesses the Assassin card " + printAbbreviatedFaction(assassinFaction) + ", the game is immediately over. Try your best to avoid hinting at the assassin.\n"; out += "If you aren't sure if your clue is legal, feel free to pm " + getUsernameString(opponent, true) + "and ask for clarification.\n"; out += "Good luck!"; return out; } public WatchWordGame getGame() { return this.game; } public WatchWordLobby getWatchWordLobby() { return this.watchWordLobby; } private String printCurrentTurn() { String out = "It is currently *" + game.getTurnOrder().getCurrentTurn().getName() + "*'s turn."; return out; } private String printGivenClue() { if (game.wasClueGivenThisTurn()) { String out = "Current clue: *" + game.getClue().getWord() + "*, guesses remaining: "; if (game.getClue().isUnlimited()) { out += "*Unlimited*"; } else if (game.getClue().isZero()) { out += "*Zero*"; } else { out += "*" + (game.getRemainingGuesses() - 1) + "*"; if (game.getRemainingGuesses() == 1) { out += " (Bonus Guess)"; } } return out; } else { return "A clue has not yet been given. *" + getUsernameString(getWatchWordLobby().getUser( game.getTurnOrder().getCurrentTurn().getLeader())) + "*, please provide a clue."; } } private Rating getUserRating(SlackUser user, boolean isLeader) { if (!this.getSessionFactory().isPresent()) { return null; } Rating rating = null; Session session = null; try { session = getSessionFactory().get().openSession(); session.beginTransaction(); rating = RatingHelper.getRatingForUser(user, isLeader, session); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (session != null) { session.close(); } } return rating; } private String printFactions(WatchWordLobby lobby) { String out = "Here are the teams:\n"; for (Faction faction : lobby.getTurnOrder().getAllFactions()) { String factionString = "[*" + faction.getName() + " team*]\n"; for (Player player : faction.getAllPlayers()) { factionString += getUsernameString(lobby.getUser(player)); String printedRating = RatingPrinter.printRating(getUserRating( lobby.getUser(player), faction.isLeader(player))); System.out.println(printedRating); if (printedRating != null) { factionString += " " + printedRating; } if (faction.isLeader(player)) { factionString += " (Leader)"; } factionString += "\n"; } out += factionString; } return out; } private String printCardGrid(boolean forLeader) { int longestWordLength = 10; for (String word : game.getGrid().getAllWords()) { longestWordLength = Math.max(longestWordLength, word.length()); } String out = "The WatchWords grid so far:\n```"; for (int row = 0; row < game.getGrid().getHeight(); row++) { String line = ""; for (int col = 0; col < game.getGrid().getWidth(); col++) { WordTile tile = game.getGrid().getTileAt(row, col); String tileString = StringUtils.capitalize(tile.getWord()); if (tile.isRevealed()) { tileString = "<" + tile.getFaction().getName() + ">"; } tileString = StringUtils .rightPad(tileString, longestWordLength); if (forLeader) { tileString += " (" + tile.getFaction().getName().substring(0, 1) + ")"; } tileString = "[ " + tileString + " ]"; line += tileString; } line += "\n"; out += line; } out += "```\n"; if (forLeader) { for (Faction faction : game.getEveryKnownFaction()) { out += "*" + faction.getName() + "*: "; List<WordTile> wordTiles = game.getGrid() .getUnrevealedTilesForFaction(faction); List<String> words = new ArrayList<String>(); for (WordTile tile : wordTiles) { words.add(tile.getWord()); } out += StringUtils.join(words, ", ") + "\n"; } } // Print unrevealed tiles for each player faction List<Faction> playerFactions = game.getTurnOrder().getAllFactions(); for (Faction playerFaction : playerFactions) { int unrevealedTiles = game.getGrid() .getUnrevealedTilesForFaction(playerFaction).size(); String conditionallyPluralizedCard = unrevealedTiles == 1 ? "card" : "cards"; out += "\n*" + playerFaction.getName() + "* has *" + unrevealedTiles + "* " + conditionallyPluralizedCard + " left to guess."; } return out; } private String printCardGrid() { return printCardGrid(false); } private void finishGame(List<Faction> victors, SlackSession session) { String finalCardGrid = printCardGrid(true); session.sendMessage(getCurrentChannel(), "Final Card Grid:\n" + finalCardGrid); String victorString = ""; for (Faction victor : victors) { String singleVictorString = messageGenerator.getWinMessage() + " " + victor.getName() + " has won! Congratulations to:\n"; for (Player player : victor.getAllPlayers()) { singleVictorString += getUsernameString(getWatchWordLobby() .getUser(player)) + "\n"; } victorString += singleVictorString + "\n"; } session.sendMessage(getCurrentChannel(), victorString); ArrayList<Faction> losers = new ArrayList<Faction>(game.getTurnOrder() .getAllFactions()); losers.removeAll(victors); updateRankings(victors, losers); partialGameReset(); getWatchWordLobby().getTurnOrder().shuffleFactionLeaders(); getSession().sendMessage(getCurrentChannel(), "\nReturning back to the game lobby..."); getSession().sendMessage(getCurrentChannel(), printFactions(getWatchWordLobby())); } private void printMatchQuality() { if (!this.getSessionFactory().isPresent()) { return; } if (this.game == null) { return; } Session session = null; try { session = getSessionFactory().get().openSession(); session.beginTransaction(); double gameBalance = RatingHelper.getMatchQuality(getGame() .getTurnOrder(), getWatchWordLobby(), session); NumberFormat format = NumberFormat.getInstance(); format.setMaximumFractionDigits(2); format.setMinimumFractionDigits(2); gameBalance *= 100; getSession().sendMessage( getCurrentChannel(), "Current game is *" + format.format(gameBalance) + "*% balanced."); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (session != null) { session.close(); } } } private void updateRankings(List<Faction> victors, List<Faction> losers) { if (!this.getSessionFactory().isPresent()) { System.out .println("No link to any storage available... Not writing results."); return; } Session session = null; try { session = getSessionFactory().get().openSession(); session.beginTransaction(); RatingHelper.updatePlayerRatings(victors, losers, getWatchWordLobby(), session); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (session != null) { session.close(); } } } private void partialGameReset() { this.currentGameState = GameState.LOBBY; stopAllAIThreads(); this.game = null; } private void fullGameReset() { partialGameReset(); this.currentGameState = GameState.IDLE; this.watchWordLobby = null; } private static List<String> generateWords(List<String> wordList, List<String> banishedWordList, int amount, Random rand) { Set<String> words = new HashSet<String>(); while (words.size() < amount) { words.add(getWatchWord(wordList, rand)); words.removeAll(banishedWordList); } List<String> outputWords = new ArrayList<String>(); outputWords.addAll(words); return outputWords; } private static String getWatchWord(List<String> wordList, Random random) { return wordList.get((int) (wordList.size() * random.nextDouble())); } private static String getUsernameString(SlackUser user, boolean verbose) { if (user == null) { return "<No User>"; } if (verbose) { return user.getUserName() + " (" + user.getRealName() + ")"; } else { return user.getUserName(); } } private static String getUsernameString(SlackUser user) { return getUsernameString(user, false); } @SuppressWarnings("unused") private SlackUser findUserById(String id, Collection<SlackUser> members) { for (SlackUser user : members) { if (user.getId().equals(id)) { return user; } } return null; } // first exact match, then lowercase match, then partial match, then // lowercase partial match private static SlackUser findUserByUsername(String username, Collection<SlackUser> users) { List<Boolean> possibilities = Arrays.asList(false, true); for (boolean caseInsensitivity : possibilities) { for (boolean partialMatch : possibilities) { SlackUser user = findUserByUsername(username, caseInsensitivity, partialMatch, users); if (user != null) { return user; } } } return null; } private static SlackUser findUserByUsername(String targetUsername, boolean caseInsensitivity, boolean partialMatch, Collection<SlackUser> users) { for (SlackUser user : users) { String currentUsername = user.getUserName(); if (caseInsensitivity) { targetUsername = targetUsername.toLowerCase(); currentUsername = currentUsername.toLowerCase(); } if (partialMatch) { if (currentUsername.startsWith(targetUsername)) { return user; } } else { if (currentUsername.equals(targetUsername)) { return user; } } } return null; } private void printUsage(SlackChannel channel, String str) { this.getSession().sendMessage(channel, "Usage: " + str); } private void printIncorrectGameState(SlackChannel channel, List<GameState> gameStates) { this.getSession().sendMessage( channel, "This command can only be used during the " + gameStates + " state. It is currently the " + this.currentGameState + " state."); } private SlackChannel getCurrentChannel() { if (this.watchWordLobby == null) { return null; } return this.watchWordLobby.getChannel(); } private void onHeartBeat(SlackSession session) { if (this.game != null && game.getActingFaction() != null) { CompetitiveTime time = game.getRemainingTime(); if (time == null) { return; } long totalTime = time.getTotalTime(TimeUnit.SECONDS); if (totalTime == 0) { session.sendMessage(getCurrentChannel(), "Out of time AND out of overtime! Game over!"); session.sendMessage(getCurrentChannel(), "(psssh...nothin personnel...kid...)"); finishGame(Arrays.asList(game.getTurnOrder().getNextTurn()), session); } else if (totalTime % 60 == 0) { session.sendMessage(getCurrentChannel(), game .getActingFaction().getName() + " team, you have " + time.getTime(TimeUnit.MINUTES) + " min remaining (" + time.getOvertime(TimeUnit.MINUTES) + " min overtime)"); } else if (totalTime < 60 && totalTime % 5 == 0) { session.sendMessage(getCurrentChannel(), game .getActingFaction().getName() + " team, time's running out! " + totalTime + " secs. remaining!"); } } } } enum GameState { IDLE, LOBBY, GAME; public static GameState[] getAllStates() { return GameState.values(); } }
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: package org.sosy_lab.java_smt.test; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; import static org.sosy_lab.java_smt.api.FormulaType.StringType; import com.google.common.collect.ImmutableList; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.sosy_lab.common.UniqueIdGenerator; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.ArrayFormula; import org.sosy_lab.java_smt.api.BitvectorFormula; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.api.StringFormula; import org.sosy_lab.java_smt.api.Tactic; import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor; @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "test code") @RunWith(Parameterized.class) public class QuantifierManagerTest extends SolverBasedTest0 { @Parameters(name = "{0}") public static Object[] getAllSolvers() { return Solvers.values(); } @Parameter(0) public Solvers solverUnderTest; @Override protected Solvers solverToUse() { return solverUnderTest; } private IntegerFormula x; private ArrayFormula<IntegerFormula, IntegerFormula> a; @SuppressWarnings("checkstyle:membername") private BooleanFormula a_at_x_eq_1; @SuppressWarnings("checkstyle:membername") private BooleanFormula a_at_x_eq_0; @SuppressWarnings("checkstyle:membername") private BooleanFormula forall_x_a_at_x_eq_0; private static final int bvWidth = 16; private BitvectorFormula xbv; private ArrayFormula<BitvectorFormula, BitvectorFormula> bvArray; @SuppressWarnings("checkstyle:membername") private BooleanFormula bvArray_at_x_eq_1; @SuppressWarnings("checkstyle:membername") private BooleanFormula bvArray_at_x_eq_0; @SuppressWarnings("checkstyle:membername") private BooleanFormula bv_forall_x_a_at_x_eq_0; @Before public void setUpLIA() { requireIntegers(); requireArrays(); requireQuantifiers(); x = imgr.makeVariable("x"); a = amgr.makeArray("a", FormulaType.IntegerType, FormulaType.IntegerType); a_at_x_eq_1 = imgr.equal(amgr.select(a, x), imgr.makeNumber(1)); a_at_x_eq_0 = imgr.equal(amgr.select(a, x), imgr.makeNumber(0)); forall_x_a_at_x_eq_0 = qmgr.forall(ImmutableList.of(x), a_at_x_eq_0); } @Before public void setUpBV() { if (solverUnderTest == Solvers.PRINCESS || solverUnderTest == Solvers.BOOLECTOR) { // Princess does not support bv in arrays return; } requireBitvectors(); requireArrays(); requireQuantifiers(); xbv = bvmgr.makeVariable(bvWidth, "xbv"); bvArray = amgr.makeArray( "bvArray", FormulaType.getBitvectorTypeWithSize(bvWidth), FormulaType.getBitvectorTypeWithSize(bvWidth)); bvArray_at_x_eq_1 = bvmgr.equal(amgr.select(bvArray, xbv), bvmgr.makeBitvector(bvWidth, 1)); bvArray_at_x_eq_0 = bvmgr.equal(amgr.select(bvArray, xbv), bvmgr.makeBitvector(bvWidth, 0)); bv_forall_x_a_at_x_eq_0 = qmgr.forall(ImmutableList.of(xbv), bvArray_at_x_eq_0); } private SolverException handleSolverException(SolverException e) throws SolverException { // The tests in this class use quantifiers and thus solver failures are expected. // We do not ignore all SolverExceptions in order to not hide bugs, // but only for Princess and CVC4 which are known to not be able to solve all tests here. if (solverUnderTest == Solvers.PRINCESS || solverUnderTest == Solvers.CVC4) { assume().withMessage(e.getMessage()).fail(); } throw e; } private static final UniqueIdGenerator index = new UniqueIdGenerator(); // to get different names @Test public void testLIAForallArrayConjunctUnsat() throws SolverException, InterruptedException { // (forall x . b[x] = 0) AND (b[123] = 1) is UNSAT requireIntegers(); BooleanFormula f = bmgr.and( qmgr.forall(ImmutableList.of(x), a_at_x_eq_0), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1))); assertThatFormula(f).isUnsatisfiable(); } @Test public void testBVForallArrayConjunctUnsat() throws SolverException, InterruptedException { // (forall x . b[x] = 0) AND (b[123] = 1) is UNSAT requireBitvectors(); // Princess does not support bitvectors in arrays assume().that(solverUnderTest).isNotEqualTo(Solvers.PRINCESS); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BooleanFormula f = bmgr.and( qmgr.forall(ImmutableList.of(xbv), bvArray_at_x_eq_0), bvmgr.equal( amgr.select(bvArray, bvmgr.makeBitvector(bvWidth, 123)), bvmgr.makeBitvector(bvWidth, 1))); assertThatFormula(f).isUnsatisfiable(); } @Test public void testLIAForallArrayConjunctSat() throws SolverException, InterruptedException { // (forall x . b[x] = 0) AND (b[123] = 0) is SAT requireIntegers(); BooleanFormula f = bmgr.and( qmgr.forall(ImmutableList.of(x), a_at_x_eq_0), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0))); try { // CVC4 and Princess fail this assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testBVForallArrayConjunctSat() throws SolverException, InterruptedException { // (forall x . b[x] = 0) AND (b[123] = 0) is SAT requireBitvectors(); // Princess does not support bitvectors in arrays assume().that(solverUnderTest).isNotEqualTo(Solvers.PRINCESS); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BooleanFormula f = bmgr.and( qmgr.forall(ImmutableList.of(xbv), bvArray_at_x_eq_0), bvmgr.equal( amgr.select(bvArray, bvmgr.makeBitvector(bvWidth, 123)), bvmgr.makeBitvector(bvWidth, 0))); try { // CVC4 and Princess fail this assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testLIAForallArrayDisjunct1() throws SolverException, InterruptedException { // (forall x . b[x] = 0) AND (b[123] = 1 OR b[123] = 0) is SAT requireIntegers(); BooleanFormula f = bmgr.and( qmgr.forall(ImmutableList.of(x), a_at_x_eq_0), bmgr.or( imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0)))); try { assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testLIAForallArrayDisjunctSat2() throws SolverException, InterruptedException { // (forall x . b[x] = 0) OR (b[123] = 1) is SAT requireIntegers(); BooleanFormula f = bmgr.or( qmgr.forall(ImmutableList.of(x), a_at_x_eq_0), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1))); try { // CVC4 fails this assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testLIANotExistsArrayConjunct1() throws SolverException, InterruptedException { // (not exists x . not b[x] = 0) AND (b[123] = 1) is UNSAT requireIntegers(); BooleanFormula f = bmgr.and( bmgr.not(qmgr.exists(ImmutableList.of(x), bmgr.not(a_at_x_eq_0))), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1))); try { assertThatFormula(f).isUnsatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testLIANotExistsArrayConjunct2() throws SolverException, InterruptedException { // (not exists x . not b[x] = 0) AND (b[123] = 0) is SAT requireIntegers(); BooleanFormula f = bmgr.and( bmgr.not(qmgr.exists(ImmutableList.of(x), bmgr.not(a_at_x_eq_0))), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0))); try { assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testLIANotExistsArrayConjunct3() throws SolverException, InterruptedException { // (not exists x . b[x] = 0) AND (b[123] = 0) is UNSAT requireIntegers(); BooleanFormula f = bmgr.and( bmgr.not(qmgr.exists(ImmutableList.of(x), a_at_x_eq_0)), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0))); assertThatFormula(f).isUnsatisfiable(); } @Test public void testLIANotExistsArrayDisjunct1() throws SolverException, InterruptedException { // (not exists x . not b[x] = 0) AND (b[123] = 1 OR b[123] = 0) is SAT requireIntegers(); BooleanFormula f = bmgr.and( bmgr.not(qmgr.exists(ImmutableList.of(x), bmgr.not(a_at_x_eq_0))), bmgr.or( imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1)), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(0)))); try { // CVC4 and Princess fail this assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testLIANotExistsArrayDisjunct2() throws SolverException, InterruptedException { // (not exists x . not b[x] = 0) OR (b[123] = 1) is SAT requireIntegers(); BooleanFormula f = bmgr.or( bmgr.not(qmgr.exists(ImmutableList.of(x), bmgr.not(a_at_x_eq_0))), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1))); try { // CVC4 fails this assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testLIAExistsArrayConjunct1() throws SolverException, InterruptedException { // (exists x . b[x] = 0) AND (b[123] = 1) is SAT requireIntegers(); BooleanFormula f = bmgr.and( qmgr.exists(ImmutableList.of(x), a_at_x_eq_0), imgr.equal(amgr.select(a, imgr.makeNumber(123)), imgr.makeNumber(1))); assertThatFormula(f).isSatisfiable(); } @Test public void testBVExistsArrayConjunct1() throws SolverException, InterruptedException { // (exists x . b[x] = 0) AND (b[123] = 1) is SAT requireBitvectors(); // Princess does not support bitvectors in arrays assume().that(solverUnderTest).isNotEqualTo(Solvers.PRINCESS); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BooleanFormula f = bmgr.and( qmgr.exists(ImmutableList.of(x), a_at_x_eq_0), bvmgr.equal( amgr.select(bvArray, bvmgr.makeBitvector(bvWidth, 123)), bvmgr.makeBitvector(bvWidth, 1))); assertThatFormula(f).isSatisfiable(); } @Test public void testLIAExistsArrayConjunct2() throws SolverException, InterruptedException { // (exists x . b[x] = 1) AND (forall x . b[x] = 0) is UNSAT requireIntegers(); BooleanFormula f = bmgr.and(qmgr.exists(ImmutableList.of(x), a_at_x_eq_1), forall_x_a_at_x_eq_0); assertThatFormula(f).isUnsatisfiable(); } @Test public void testBVExistsArrayConjunct2() throws SolverException, InterruptedException { // (exists x . b[x] = 1) AND (forall x . b[x] = 0) is UNSAT requireBitvectors(); // Princess does not support bitvectors in arrays assume().that(solverUnderTest).isNotEqualTo(Solvers.PRINCESS); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BooleanFormula f = bmgr.and(qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_1), bv_forall_x_a_at_x_eq_0); assertThatFormula(f).isUnsatisfiable(); } @Test public void testLIAExistsArrayConjunct3() throws SolverException, InterruptedException { // (exists x . b[x] = 0) AND (forall x . b[x] = 0) is SAT requireIntegers(); BooleanFormula f = bmgr.and(qmgr.exists(ImmutableList.of(x), a_at_x_eq_0), forall_x_a_at_x_eq_0); try { // CVC4 and Princess fail this assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testBVExistsArrayConjunct3() throws SolverException, InterruptedException { // (exists x . b[x] = 0) AND (forall x . b[x] = 0) is SAT requireBitvectors(); // Princess does not support bitvectors in arrays assume().that(solverUnderTest).isNotEqualTo(Solvers.PRINCESS); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BooleanFormula f = bmgr.and(qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_0), bv_forall_x_a_at_x_eq_0); try { // CVC4 and Princess fail this assertThatFormula(f).isSatisfiable(); } catch (SolverException e) { throw handleSolverException(e); } } @Test public void testLIAExistsArrayDisjunct1() throws SolverException, InterruptedException { // (exists x . b[x] = 0) OR (forall x . b[x] = 1) is SAT requireIntegers(); BooleanFormula f = bmgr.or( qmgr.exists(ImmutableList.of(x), a_at_x_eq_0), qmgr.forall(ImmutableList.of(x), a_at_x_eq_1)); assertThatFormula(f).isSatisfiable(); } @Test public void testBVExistsArrayDisjunct1() throws SolverException, InterruptedException { // (exists x . b[x] = 0) OR (forall x . b[x] = 1) is SAT requireBitvectors(); // Princess does not support bitvectors in arrays assume().that(solverUnderTest).isNotEqualTo(Solvers.PRINCESS); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BooleanFormula f = bmgr.or( qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_0), qmgr.forall(ImmutableList.of(xbv), bvArray_at_x_eq_1)); assertThatFormula(f).isSatisfiable(); } @Test public void testLIAExistsArrayDisjunct2() throws SolverException, InterruptedException { // (exists x . b[x] = 1) OR (exists x . b[x] = 1) is SAT requireIntegers(); BooleanFormula f = bmgr.or( qmgr.exists(ImmutableList.of(x), a_at_x_eq_1), qmgr.exists(ImmutableList.of(x), a_at_x_eq_1)); assertThatFormula(f).isSatisfiable(); } @Test public void testBVExistsArrayDisjunct2() throws SolverException, InterruptedException { // (exists x . b[x] = 1) OR (exists x . b[x] = 1) is SAT requireBitvectors(); // Princess does not support bitvectors in arrays assume().that(solverUnderTest).isNotEqualTo(Solvers.PRINCESS); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BooleanFormula f = bmgr.or( qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_1), qmgr.exists(ImmutableList.of(xbv), bvArray_at_x_eq_1)); assertThatFormula(f).isSatisfiable(); } @Test public void testLIAContradiction() throws SolverException, InterruptedException { // forall x . x = x+1 is UNSAT requireIntegers(); BooleanFormula f = qmgr.forall(ImmutableList.of(x), imgr.equal(x, imgr.add(x, imgr.makeNumber(1)))); assertThatFormula(f).isUnsatisfiable(); } @Test public void testBVContradiction() throws SolverException, InterruptedException { // forall x . x = x+1 is UNSAT requireBitvectors(); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); int width = 16; BitvectorFormula z = bvmgr.makeVariable(width, "z"); BooleanFormula f = qmgr.forall( ImmutableList.of(z), bvmgr.equal(z, bvmgr.add(z, bvmgr.makeBitvector(width, 1)))); assertThatFormula(f).isUnsatisfiable(); } @Test public void testLIASimple() throws SolverException, InterruptedException { // forall x . x+2 = x+1+1 is SAT requireIntegers(); BooleanFormula f = qmgr.forall( ImmutableList.of(x), imgr.equal( imgr.add(x, imgr.makeNumber(2)), imgr.add(imgr.add(x, imgr.makeNumber(1)), imgr.makeNumber(1)))); assertThatFormula(f).isSatisfiable(); } @Test public void testBVSimple() throws SolverException, InterruptedException { // forall z . z+2 = z+1+1 is SAT requireBitvectors(); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); int width = 16; BitvectorFormula z = bvmgr.makeVariable(width, "z"); BooleanFormula f = qmgr.forall( ImmutableList.of(z), bvmgr.equal( bvmgr.add(z, bvmgr.makeBitvector(width, 2)), bvmgr.add( bvmgr.add(z, bvmgr.makeBitvector(width, 1)), bvmgr.makeBitvector(width, 1)))); assertThatFormula(f).isSatisfiable(); } @Test public void testLIAEquality() throws SolverException, InterruptedException { requireIntegers(); // Note that due to the variable cache we simply get the existing var x here! IntegerFormula z = imgr.makeVariable("x"); IntegerFormula y = imgr.makeVariable("y"); BooleanFormula f = qmgr.forall(ImmutableList.of(z), qmgr.exists(ImmutableList.of(y), imgr.equal(z, y))); assertThatFormula(f).isSatisfiable(); } @Test public void testBVEquality() throws SolverException, InterruptedException { requireBitvectors(); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BitvectorFormula z = bvmgr.makeVariable(bvWidth, "z"); BitvectorFormula y = bvmgr.makeVariable(bvWidth, "y"); BooleanFormula f = qmgr.forall(ImmutableList.of(z), qmgr.exists(ImmutableList.of(y), bvmgr.equal(z, y))); assertThatFormula(f).isSatisfiable(); } @Test public void testBVEquality2() throws SolverException, InterruptedException { requireBitvectors(); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BitvectorFormula z = bvmgr.makeVariable(bvWidth, "z"); BitvectorFormula y = bvmgr.makeVariable(bvWidth, "y"); BooleanFormula f = qmgr.forall(ImmutableList.of(z, y), bvmgr.equal(z, y)); assertThatFormula(f).isUnsatisfiable(); } @Test public void testBVEquality3() throws SolverException, InterruptedException { // exists z . (forall y . z = y && z + 2 > z) // UNSAT because of bv behaviour requireBitvectors(); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); BitvectorFormula z = bvmgr.makeVariable(bvWidth, "z"); BitvectorFormula zPlusTwo = bvmgr.add(bvmgr.makeVariable(bvWidth, "z"), bvmgr.makeBitvector(bvWidth, 2)); BitvectorFormula y = bvmgr.makeVariable(bvWidth, "y"); BooleanFormula f = qmgr.exists( ImmutableList.of(z), qmgr.forall( ImmutableList.of(y), bmgr.and(bvmgr.equal(z, y), bvmgr.greaterThan(zPlusTwo, z, false)))); assertThatFormula(f).isUnsatisfiable(); } @Test public void testLIABoundVariables() throws SolverException, InterruptedException { // If the free and bound vars are equal, this will be UNSAT requireIntegers(); IntegerFormula aa = imgr.makeVariable("aa"); IntegerFormula one = imgr.makeNumber(1); BooleanFormula restrict = bmgr.not(imgr.equal(aa, one)); // x != 1 && exists x . (x == 1) BooleanFormula f = qmgr.exists(ImmutableList.of(aa), imgr.equal(aa, one)); assertThatFormula(bmgr.and(f, restrict)).isSatisfiable(); } @Test public void testBVBoundVariables() throws SolverException, InterruptedException { // If the free and bound vars are equal, this will be UNSAT requireBitvectors(); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); int width = 2; BitvectorFormula aa = bvmgr.makeVariable(width, "aa"); BitvectorFormula one = bvmgr.makeBitvector(width, 1); BooleanFormula restrict = bmgr.not(bvmgr.equal(aa, one)); // x != 1 && exists x . (x == 1) BooleanFormula f = qmgr.exists(ImmutableList.of(aa), bvmgr.equal(aa, one)); assertThatFormula(bmgr.and(f, restrict)).isSatisfiable(); } @Test public void testQELight() throws InterruptedException { requireIntegers(); assume().that(solverToUse()).isEqualTo(Solvers.Z3); // exists y : (y=4 && x=y+3) --> simplified: x=7 IntegerFormula y = imgr.makeVariable("y"); BooleanFormula f1 = qmgr.exists( y, bmgr.and( imgr.equal(y, imgr.makeNumber(4)), imgr.equal(x, imgr.add(y, imgr.makeNumber(3))))); BooleanFormula out = mgr.applyTactic(f1, Tactic.QE_LIGHT); assertThat(out).isEqualTo(imgr.equal(x, imgr.makeNumber(7))); } @Test public void testIntrospectionForall() { requireIntegers(); BooleanFormula forall = qmgr.forall(ImmutableList.of(x), a_at_x_eq_0); final AtomicBoolean isQuantifier = new AtomicBoolean(false); final AtomicBoolean isForall = new AtomicBoolean(false); final AtomicInteger numBound = new AtomicInteger(0); // Test introspection with visitors. mgr.visit( forall, new DefaultFormulaVisitor<Void>() { @Override protected Void visitDefault(Formula f) { return null; } @Override public Void visitQuantifier( BooleanFormula f, Quantifier quantifier, List<Formula> boundVariables, BooleanFormula body) { isForall.set(quantifier == Quantifier.FORALL); isQuantifier.set(true); numBound.set(boundVariables.size()); return null; } }); } @Test public void testIntrospectionExists() { requireIntegers(); BooleanFormula exists = qmgr.exists(ImmutableList.of(x), a_at_x_eq_0); final AtomicBoolean isQuantifier = new AtomicBoolean(false); final AtomicBoolean isForall = new AtomicBoolean(false); final List<Formula> boundVars = new ArrayList<>(); // Test introspection with visitors. mgr.visit( exists, new DefaultFormulaVisitor<Void>() { @Override protected Void visitDefault(Formula f) { return null; } @Override public Void visitQuantifier( BooleanFormula f, Quantifier quantifier, List<Formula> boundVariables, BooleanFormula body) { assertThat(isQuantifier.get()).isFalse(); isForall.set(quantifier == Quantifier.FORALL); isQuantifier.set(true); boundVars.addAll(boundVariables); return null; } }); assertThat(isQuantifier.get()).isTrue(); assertThat(isForall.get()).isFalse(); assume() .withMessage("Quantifier introspection in JavaSMT for Princess is currently not complete.") .that(solverToUse()) .isNotEqualTo(Solvers.PRINCESS); assertThat(boundVars).hasSize(1); } @Test(expected = IllegalArgumentException.class) public void testEmpty() { assume() .withMessage("TODO: The JavaSMT code for Princess explicitly allows this.") .that(solverToUse()) .isNotEqualTo(Solvers.PRINCESS); // An empty list of quantified variables throws an exception. @SuppressWarnings("unused") BooleanFormula quantified = qmgr.exists(ImmutableList.of(), bmgr.makeVariable("b")); } @Test public void checkLIAQuantifierElimination() throws InterruptedException, SolverException { // build formula: (forall x . ((x < 5) | (7 < x + y))) // quantifier-free equivalent: (2 < y) requireIntegers(); IntegerFormula xx = imgr.makeVariable("x"); IntegerFormula yy = imgr.makeVariable("y"); BooleanFormula f = qmgr.forall( xx, bmgr.or( imgr.lessThan(xx, imgr.makeNumber(5)), imgr.lessThan(imgr.makeNumber(7), imgr.add(xx, yy)))); BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f); assertThatFormula(qFreeF).isEquivalentTo(imgr.lessThan(imgr.makeNumber(2), yy)); } @Test public void checkLIAQuantifierEliminationFail() throws InterruptedException, SolverException { // build formula: (exists x : arr[x] = 3) && (forall y: arr[y] = 2) // as there is no quantifier free equivalent, it should return the input formula. requireIntegers(); IntegerFormula xx = imgr.makeVariable("x"); IntegerFormula yy = imgr.makeVariable("y"); ArrayFormula<IntegerFormula, IntegerFormula> a1 = amgr.makeArray("a1", FormulaType.IntegerType, FormulaType.IntegerType); BooleanFormula f = bmgr.and( qmgr.exists(xx, imgr.equal(amgr.select(a1, xx), imgr.makeNumber(3))), qmgr.forall(yy, imgr.equal(amgr.select(a1, yy), imgr.makeNumber(2)))); BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f); assertThatFormula(qFreeF).isEquivalentTo(f); } @Test public void checkBVQuantifierEliminationFail() throws InterruptedException, SolverException { // build formula: (exists x : arr[x] = 3) && (forall y: arr[y] = 2) // as there is no quantifier free equivalent, it should return the input formula. requireBitvectors(); // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); // Princess does not support bitvectors in arrays assume().that(solverUnderTest).isNotEqualTo(Solvers.PRINCESS); int width = 2; BitvectorFormula xx = bvmgr.makeVariable(width, "x_bv"); BitvectorFormula yy = bvmgr.makeVariable(width, "y_bv"); ArrayFormula<BitvectorFormula, BitvectorFormula> array = amgr.makeArray( "array", FormulaType.getBitvectorTypeWithSize(width), FormulaType.getBitvectorTypeWithSize(width)); BooleanFormula f = bmgr.and( qmgr.exists(xx, bvmgr.equal(amgr.select(array, xx), bvmgr.makeBitvector(width, 3))), qmgr.forall(yy, bvmgr.equal(amgr.select(array, yy), bvmgr.makeBitvector(width, 2)))); BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f); assertThatFormula(qFreeF).isEquivalentTo(f); } @Test public void checkBVQuantifierElimination() throws InterruptedException, SolverException { requireBitvectors(); // build formula: exists y : bv[2]. x * y = 1 // quantifier-free equivalent: x = 1 | x = 3 // or extract_0_0 x = 1 // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); int i = index.getFreshId(); int width = 2; BitvectorFormula xx = bvmgr.makeVariable(width, "x" + i); BitvectorFormula yy = bvmgr.makeVariable(width, "y" + i); BooleanFormula f = qmgr.exists(yy, bvmgr.equal(bvmgr.multiply(xx, yy), bvmgr.makeBitvector(width, 1))); BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f); assertThatFormula(qFreeF) .isEquivalentTo(bvmgr.equal(bvmgr.extract(xx, 0, 0, false), bvmgr.makeBitvector(1, 1))); } /** Quant elim test based on a crash in Z3. */ @Test public void checkBVQuantifierElimination2() throws InterruptedException, SolverException { requireBitvectors(); // build formula: exists a2 : (and (= a2 #x00000006) // (= b2 #x00000006) // (= a3 #x00000000)) // quantifier-free equivalent: (and (= b2 #x00000006) // (= a3 #x00000000)) // Boolector quants need to be reworked assume().that(solverUnderTest).isNotEqualTo(Solvers.BOOLECTOR); // Z3 fails this currently. Remove once thats not longer the case! assume().that(solverUnderTest).isNotEqualTo(Solvers.Z3); int width = 32; BitvectorFormula a2 = bvmgr.makeVariable(width, "a2"); BitvectorFormula b2 = bvmgr.makeVariable(width, "b2"); BitvectorFormula a3 = bvmgr.makeVariable(width, "a3"); BooleanFormula fAnd = bmgr.and( bvmgr.equal(a2, bvmgr.makeBitvector(width, 6)), bvmgr.equal(b2, bvmgr.makeBitvector(width, 6)), bvmgr.equal(a3, bvmgr.makeBitvector(width, 0))); BooleanFormula f = qmgr.exists(a2, fAnd); BooleanFormula qFreeF = qmgr.eliminateQuantifiers(f); assertThatFormula(qFreeF) .isEquivalentTo( bmgr.and( bvmgr.equal(b2, bvmgr.makeBitvector(width, 6)), bvmgr.equal(a3, bvmgr.makeBitvector(width, 0)))); } @Test public void testExistsRestrictedRange() throws SolverException, InterruptedException { ArrayFormula<IntegerFormula, IntegerFormula> b = amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType); BooleanFormula bAtXEq1 = imgr.equal(amgr.select(b, x), imgr.makeNumber(1)); BooleanFormula bAtXEq0 = imgr.equal(amgr.select(b, x), imgr.makeNumber(0)); BooleanFormula exists10to20bx1 = exists(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq1); BooleanFormula forallXbx0 = qmgr.forall(x, bAtXEq0); // (exists x in [10..20] . b[x] = 1) AND (forall x . b[x] = 0) is UNSAT assertThatFormula(bmgr.and(exists10to20bx1, forallXbx0)).isUnsatisfiable(); // (exists x in [10..20] . b[x] = 1) AND (b[10] = 0) is SAT assertThatFormula( bmgr.and( exists10to20bx1, imgr.equal(amgr.select(b, imgr.makeNumber(10)), imgr.makeNumber(0)))) .isSatisfiable(); // (exists x in [10..20] . b[x] = 1) AND (b[1000] = 0) is SAT assertThatFormula( bmgr.and( exists10to20bx1, imgr.equal(amgr.select(b, imgr.makeNumber(1000)), imgr.makeNumber(0)))) .isSatisfiable(); } @Test public void testExistsRestrictedRangeWithoutInconclusiveSolvers() throws SolverException, InterruptedException { assume() .withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse()) .that(solverToUse()) .isNoneOf(Solvers.CVC4, Solvers.PRINCESS); ArrayFormula<IntegerFormula, IntegerFormula> b = amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType); BooleanFormula bAtXEq1 = imgr.equal(amgr.select(b, x), imgr.makeNumber(1)); BooleanFormula bAtXEq0 = imgr.equal(amgr.select(b, x), imgr.makeNumber(0)); BooleanFormula exists10to20bx0 = exists(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq0); BooleanFormula exists10to20bx1 = exists(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq1); BooleanFormula forallXbx1 = qmgr.forall(x, bAtXEq1); BooleanFormula forallXbx0 = qmgr.forall(x, bAtXEq0); // (exists x in [10..20] . b[x] = 0) AND (forall x . b[x] = 0) is SAT assertThatFormula(bmgr.and(exists10to20bx0, forallXbx0)).isSatisfiable(); // (exists x in [10..20] . b[x] = 1) AND (forall x . b[x] = 1) is SAT assertThatFormula(bmgr.and(exists10to20bx1, forallXbx1)).isSatisfiable(); } @Test public void testForallRestrictedRange() throws SolverException, InterruptedException { ArrayFormula<IntegerFormula, IntegerFormula> b = amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType); BooleanFormula bAtXEq1 = imgr.equal(amgr.select(b, x), imgr.makeNumber(1)); BooleanFormula bAtXEq0 = imgr.equal(amgr.select(b, x), imgr.makeNumber(0)); BooleanFormula forall10to20bx1 = forall(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq1); // (forall x in [10..20] . b[x] = 1) AND (exits x in [15..17] . b[x] = 0) is UNSAT assertThatFormula( bmgr.and(forall10to20bx1, exists(x, imgr.makeNumber(15), imgr.makeNumber(17), bAtXEq0))) .isUnsatisfiable(); // (forall x in [10..20] . b[x] = 1) AND b[10] = 0 is UNSAT assertThatFormula( bmgr.and( forall10to20bx1, imgr.equal(amgr.select(b, imgr.makeNumber(10)), imgr.makeNumber(0)))) .isUnsatisfiable(); // (forall x in [10..20] . b[x] = 1) AND b[20] = 0 is UNSAT assertThatFormula( bmgr.and( forall10to20bx1, imgr.equal(amgr.select(b, imgr.makeNumber(20)), imgr.makeNumber(0)))) .isUnsatisfiable(); } @Test public void testForallRestrictedRangeWithoutConclusiveSolvers() throws SolverException, InterruptedException { assume() .withMessage("Solver %s does not support the complete theory of quantifiers", solverToUse()) .that(solverToUse()) .isNoneOf(Solvers.CVC4, Solvers.PRINCESS); ArrayFormula<IntegerFormula, IntegerFormula> b = amgr.makeArray("b", FormulaType.IntegerType, FormulaType.IntegerType); BooleanFormula bAtXEq1 = imgr.equal(amgr.select(b, x), imgr.makeNumber(1)); BooleanFormula bAtXEq0 = imgr.equal(amgr.select(b, x), imgr.makeNumber(0)); BooleanFormula forall10to20bx0 = forall(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq0); BooleanFormula forall10to20bx1 = forall(x, imgr.makeNumber(10), imgr.makeNumber(20), bAtXEq1); // (forall x in [10..20] . b[x] = 0) AND (forall x . b[x] = 0) is SAT assertThatFormula(bmgr.and(forall10to20bx0, qmgr.forall(x, bAtXEq0))).isSatisfiable(); // (forall x in [10..20] . b[x] = 1) AND b[9] = 0 is SAT assertThatFormula( bmgr.and( forall10to20bx1, imgr.equal(amgr.select(b, imgr.makeNumber(9)), imgr.makeNumber(0)))) .isSatisfiable(); // (forall x in [10..20] . b[x] = 1) AND b[21] = 0 is SAT assertThatFormula( bmgr.and( forall10to20bx1, imgr.equal(amgr.select(b, imgr.makeNumber(21)), imgr.makeNumber(0)))) .isSatisfiable(); // (forall x in [10..20] . b[x] = 1) AND (forall x in [0..20] . b[x] = 0) is UNSAT assertThatFormula( bmgr.and(forall10to20bx1, forall(x, imgr.makeNumber(0), imgr.makeNumber(20), bAtXEq0))) .isUnsatisfiable(); // (forall x in [10..20] . b[x] = 1) AND (forall x in [0..9] . b[x] = 0) is SAT assertThatFormula( bmgr.and(forall10to20bx1, forall(x, imgr.makeNumber(0), imgr.makeNumber(9), bAtXEq0))) .isSatisfiable(); } @Test public void testExistsBasicStringTheorie() throws SolverException, InterruptedException { requireStrings(); requireIntegers(); // exists var ("a" < var < "c") & length var == 1 -> var == "b" StringFormula stringA = smgr.makeString("a"); StringFormula stringC = smgr.makeString("c"); StringFormula var = smgr.makeVariable("var"); BooleanFormula query = qmgr.exists( var, bmgr.and( imgr.equal(smgr.length(var), imgr.makeNumber(1)), smgr.lessThan(stringA, var), smgr.lessThan(var, stringC))); assertThatFormula(query).isSatisfiable(); } @Test public void testForallBasicStringTheorie() throws SolverException, InterruptedException { requireStrings(); requireIntegers(); // forall var ("a" < var < "c") & length var == 1 StringFormula stringA = smgr.makeString("a"); StringFormula stringC = smgr.makeString("c"); StringFormula var = smgr.makeVariable("var"); BooleanFormula query = qmgr.forall( var, bmgr.and( imgr.equal(smgr.length(var), imgr.makeNumber(1)), smgr.lessThan(stringA, var), smgr.lessThan(var, stringC))); assertThatFormula(query).isUnsatisfiable(); } @Test public void testExistsBasicStringArray() throws SolverException, InterruptedException { requireStrings(); requireIntegers(); // exists var (var = select(store(arr, 2, "bla"), 2) IntegerFormula two = imgr.makeNumber(2); StringFormula string = smgr.makeString("bla"); StringFormula var = smgr.makeVariable("var"); ArrayFormula<IntegerFormula, StringFormula> arr = amgr.makeArray("arr", FormulaType.IntegerType, StringType); BooleanFormula query = qmgr.exists(var, smgr.equal(var, amgr.select(amgr.store(arr, two, string), two))); assertThatFormula(query).isSatisfiable(); } @Test public void testForallBasicStringArray() throws SolverException, InterruptedException { requireStrings(); requireIntegers(); // forall var (var = select(store(arr, 2, "bla"), 2) IntegerFormula two = imgr.makeNumber(2); StringFormula string = smgr.makeString("bla"); StringFormula var = smgr.makeVariable("var"); ArrayFormula<IntegerFormula, StringFormula> arr = amgr.makeArray("arr", FormulaType.IntegerType, StringType); BooleanFormula query = qmgr.forall(var, smgr.equal(var, amgr.select(amgr.store(arr, two, string), two))); assertThatFormula(query).isUnsatisfiable(); } private BooleanFormula forall( final IntegerFormula pVariable, final IntegerFormula pLowerBound, final IntegerFormula pUpperBound, final BooleanFormula pBody) { return qmgr.forall( pVariable, bmgr.implication( bmgr.and( imgr.greaterOrEquals(pVariable, pLowerBound), imgr.lessOrEquals(pVariable, pUpperBound)), pBody)); } private BooleanFormula exists( final IntegerFormula pVariable, final IntegerFormula pLowerBound, final IntegerFormula pUpperBound, final BooleanFormula pBody) { List<BooleanFormula> constraintsAndBody = ImmutableList.of( imgr.greaterOrEquals(pVariable, pLowerBound), imgr.lessOrEquals(pVariable, pUpperBound), pBody); return qmgr.exists(pVariable, bmgr.and(constraintsAndBody)); } }
package de.akg_bensheim.akgbensheim; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.AdapterView; import android.widget.Spinner; import android.widget.Toast; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import de.akg_bensheim.akgbensheim.adapter.ToolBarSpinnerAdapter; import de.akg_bensheim.akgbensheim.preferences.SettingsActivity; import de.akg_bensheim.akgbensheim.utils.ConnectionDetector; public class MainActivity extends ActionBarActivity implements Spinner.OnItemSelectedListener, SwipeRefreshLayout.OnRefreshListener { private static final String KEY_SELECTED_INDEX = "selected_index"; private static final String URL_FIXED = "http: private int selectedIndex = 0; private boolean fromSavedInstanceState; private int week; private SwipeRefreshLayout swipeRefreshLayout; private Spinner spinner; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* State check */ if(savedInstanceState != null) { selectedIndex = savedInstanceState.getInt(KEY_SELECTED_INDEX, 0); fromSavedInstanceState = true; } /* View id lookup */ Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); webView = (WebView) findViewById(R.id.webView); /* Toolbar setup */ setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); /* Inflate spinner layout and add it to the toolbar*/ View spinnerContainer = LayoutInflater.from(this) .inflate(R.layout.toolbar_spinner, toolbar, false); ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); toolbar.addView(spinnerContainer, layoutParams); /* Set up Spinner data */ ToolBarSpinnerAdapter adapter = new ToolBarSpinnerAdapter(getResources().getString(R.string.title_substitute)); adapter.addItems(getResources().getStringArray(R.array.toolbar_spinner_items)); /* Set up the Spinner */ spinner = (Spinner) spinnerContainer.findViewById(R.id.spinner); spinner.setAdapter(adapter); if(!fromSavedInstanceState) spinner.setSelection(selectedIndex); spinner.setOnItemSelectedListener(this); /* Set up swipeToRefreshLayout */ swipeRefreshLayout.setColorSchemeResources(R.color.primary, R.color.accent, R.color.primaryDark); swipeRefreshLayout.setOnRefreshListener(this); /* Set up webView */ webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { swipeRefreshLayout.setRefreshing(false); spinner.setEnabled(true); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return !url.startsWith(" } }); webView.getSettings().setUseWideViewPort(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setJavaScriptEnabled(false); webView.getSettings().setSupportZoom(true); webView.getSettings().setBuiltInZoomControls(true); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) webView.getSettings().setDisplayZoomControls(false); webView.post(new Runnable() { @Override public void run() { webView.zoomOut(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.action_settings: startActivity( new Intent(MainActivity.this, SettingsActivity.class) ); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onPause() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) webView.onPause(); else webView.pauseTimers(); super.onPause(); } @Override public void onResume() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) webView.onResume(); else webView.resumeTimers(); super.onResume(); } @Override public void onDestroy() { if (webView != null) { webView.destroy(); webView = null; } super.onDestroy(); } @Override public void onRestoreInstanceState(@NonNull Bundle inState) { super.onRestoreInstanceState(inState); webView.restoreState(inState); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); webView.saveState(outState); outState.putInt(KEY_SELECTED_INDEX, selectedIndex); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.d("MainActivity", "Spinner item at index: " + position + " selected."); if(fromSavedInstanceState) { fromSavedInstanceState = false; return; } selectedIndex = position; Calendar calendar = Calendar.getInstance(Locale.getDefault()); switch (selectedIndex) { case 0: week = calendar.get(Calendar.WEEK_OF_YEAR); break; case 1: calendar.add(Calendar.DATE, 7); week = calendar.get(Calendar.WEEK_OF_YEAR); break; } if(ConnectionDetector.getInstance(getApplicationContext()) .allowedToUseConnection("pref_key_only_wifi")) new Loader().execute( String.format(URL_FIXED, week) ); else webView.loadUrl(Loader.CODE_1); } @Override public void onNothingSelected(AdapterView<?> parent) { Log.d("MainActivity", "No spinner item item selected."); } @Override public void onRefresh() { if(ConnectionDetector.getInstance(getApplicationContext()) .allowedToUseConnection("pref_key_only_wifi")) new Loader().execute( String.format(URL_FIXED, week) ); else swipeRefreshLayout.setRefreshing(false); } protected class Loader extends AsyncTask<String, Void, Loader.Response> { private String url; class Response { int code; long lastModified; @Override public String toString() { return getClass().getSimpleName() + " [code=" + code + ", lastModified=" + lastModified + "]"; } } private static final String CODE_301 = "file:///android_asset/error/301.html"; private static final String CODE_404 = "file:///android_asset/error/404.html"; private static final String CODE_1 = "file:///android_asset/error/offline.html"; private static final String CODE_UNKNOWN = "file:///android_asset/error/unknown.html"; @Override protected void onPreExecute() { Log.d("MainActivity", "Starting Loader..."); swipeRefreshLayout.setRefreshing(true); spinner.setEnabled(false); } @Override protected Loader.Response doInBackground(String... params) { url = params[0]; Loader.Response response = new Loader.Response(); try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(1000); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(false); connection.connect(); response.code = connection.getResponseCode(); response.lastModified = connection.getLastModified(); connection.disconnect(); } catch (IOException e) { Log.e("Loader", "IOException occurred while connecting to: \"" + url + "\"", e); response.code = 1; } return response; } @Override protected void onPostExecute(Loader.Response response) { Log.d("MainActivity", "Loader finished with result: " + response.toString()); switch (response.code) { case 200: webView.loadUrl(url); Toast.makeText( MainActivity.this, new SimpleDateFormat(getResources().getString(R.string.last_modification), Locale.getDefault()) .format(new Date(response.lastModified)), Toast.LENGTH_SHORT ).show(); break; case 301: webView.loadUrl(CODE_301); break; case 404: webView.loadUrl(CODE_404); break; case 1: webView.loadUrl(CODE_1); break; default: webView.loadUrl(CODE_UNKNOWN); break; } } } }
package org.domokit.oknet; import android.util.Log; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Headers; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import com.squareup.okhttp.ResponseBody; import org.chromium.base.TraceEvent; import org.chromium.mojo.system.Core; import org.chromium.mojo.system.DataPipe; import org.chromium.mojo.system.MojoException; import org.chromium.mojo.system.MojoResult; import org.chromium.mojo.system.Pair; import org.chromium.mojom.mojo.HttpHeader; import org.chromium.mojom.mojo.NetworkError; import org.chromium.mojom.mojo.UrlLoader; import org.chromium.mojom.mojo.UrlLoaderStatus; import org.chromium.mojom.mojo.UrlRequest; import org.chromium.mojom.mojo.UrlResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.util.concurrent.Executor; import okio.BufferedSource; /** * OkHttp implementation of UrlLoader. */ public class UrlLoaderImpl implements UrlLoader { private static final String TAG = "UrlLoaderImpl"; private final Core mCore; private final OkHttpClient mClient; private final Executor mExecutor; private boolean mIsLoading; private NetworkError mError; private static long sNextTracingId = 1; private final long mTracingId; class CopyToPipeJob implements Runnable { private ResponseBody mBody; private BufferedSource mSource; private DataPipe.ProducerHandle mProducer; public CopyToPipeJob(ResponseBody body, DataPipe.ProducerHandle producerHandle) { mBody = body; mSource = body.source(); mProducer = producerHandle; } @Override public void run() { TraceEvent.begin("UrlLoaderImpl::CopyToPipeJob::copy"); int result = 0; do { try { ByteBuffer buffer = mProducer.beginWriteData(0, DataPipe.WriteFlags.none()); // TODO(abarth): There must be a way to do this without the temporary buffer. byte[] tmp = new byte[buffer.capacity()]; result = mSource.read(tmp); buffer.put(tmp); mProducer.endWriteData(result == -1 ? 0 : result); } catch (MojoException e) { // No one read the pipe, they just closed it. if (e.getMojoResult() == MojoResult.FAILED_PRECONDITION) { break; } else if (e.getMojoResult() == MojoResult.SHOULD_WAIT) { mCore.wait(mProducer, Core.HandleSignals.WRITABLE, -1); } else { throw e; } } catch (IOException e) { Log.e(TAG, "mSource.read failed", e); break; } } while (result != -1); mIsLoading = false; mProducer.close(); try { mBody.close(); } catch (IOException e) { Log.e(TAG, "mBody.close failed", e); } TraceEvent.finishAsync("UrlLoaderImpl", mTracingId); TraceEvent.end("UrlLoaderImpl::CopyToPipeJob::copy"); } } public UrlLoaderImpl(Core core, OkHttpClient client, Executor executor) { assert core != null; mCore = core; mClient = client; mExecutor = executor; mIsLoading = false; mError = null; mTracingId = sNextTracingId++; } @Override public void close() {} @Override public void onConnectionError(MojoException e) {} @Override public void start(UrlRequest request, StartResponse callback) { TraceEvent.startAsync("UrlLoaderImpl", mTracingId); mIsLoading = true; mError = null; URL url = null; try { url = new URL(request.url); } catch (MalformedURLException e) { Log.w(TAG, "Failed to parse url " + request.url); mError = new NetworkError(); // TODO(abarth): Which mError.code should we set? mError.description = e.toString(); UrlResponse urlResponse = new UrlResponse(); urlResponse.url = request.url; urlResponse.error = mError; callback.call(urlResponse); return; } RequestBody body = null; if (request.body != null && request.body[0] != null) { DataPipe.ConsumerHandle consumer = request.body[0]; ByteArrayOutputStream bodyStream = new ByteArrayOutputStream(); WritableByteChannel dest = Channels.newChannel(bodyStream); do { try { ByteBuffer buffer = consumer.beginReadData(0, DataPipe.ReadFlags.NONE); if (buffer.capacity() == 0) break; dest.write(buffer); consumer.endReadData(buffer.capacity()); } catch (IOException e) { throw new MojoException(e); } catch (MojoException e) { // No one read the pipe, they just closed it. if (e.getMojoResult() == MojoResult.FAILED_PRECONDITION) { break; } else if (e.getMojoResult() == MojoResult.SHOULD_WAIT) { mCore.wait(consumer, Core.HandleSignals.READABLE, -1); } else { throw e; } } } while (true); String contentType = "application/x-www-form-urlencoded; charset=utf8"; MediaType mediaType = MediaType.parse(contentType); body = RequestBody.create(mediaType, bodyStream.toByteArray()); } Request.Builder builder = new Request.Builder().url(url).method(request.method, body); if (request.headers != null) { for (HttpHeader header : request.headers) { builder.addHeader(header.name, header.value); } } // TODO(abarth): body, responseBodyBufferSize, autoFollowRedirects, bypassCache. final StartResponse responseCallback = callback; Call call = mClient.newCall(builder.build()); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.w(TAG, "Network failure loading " + request.urlString()); mError = new NetworkError(); // TODO(abarth): Which mError.code should we set? mError.description = e.toString(); UrlResponse urlResponse = new UrlResponse(); urlResponse.url = request.urlString(); urlResponse.error = mError; responseCallback.call(urlResponse); mIsLoading = false; TraceEvent.finishAsync("UrlLoaderImpl", mTracingId); } @Override public void onResponse(Response response) { UrlResponse urlResponse = new UrlResponse(); urlResponse.url = response.request().urlString(); urlResponse.statusCode = response.code(); urlResponse.statusLine = response.message(); if (urlResponse.statusCode >= 400) { Log.w(TAG, "Failed to load: " + urlResponse.url + " (" + urlResponse.statusCode + ")"); } Headers headers = response.headers(); urlResponse.headers = new HttpHeader[headers.size()]; for (int i = 0; i < headers.size(); ++i) { HttpHeader header = new HttpHeader(); header.name = headers.name(i); header.value = headers.value(i); urlResponse.headers[i] = header; } ResponseBody body = response.body(); MediaType mediaType = body.contentType(); if (mediaType != null) { urlResponse.mimeType = mediaType.type() + "/" + mediaType.subtype(); Charset charset = mediaType.charset(); if (charset != null) { urlResponse.charset = charset.displayName(); } } Pair<DataPipe.ProducerHandle, DataPipe.ConsumerHandle> handles = mCore.createDataPipe(null); DataPipe.ProducerHandle producerHandle = handles.first; DataPipe.ConsumerHandle consumerHandle = handles.second; urlResponse.body = consumerHandle; responseCallback.call(urlResponse); mExecutor.execute(new CopyToPipeJob(body, producerHandle)); } }); } @Override public void followRedirect(FollowRedirectResponse callback) { // TODO(abarth): Implement redirects. callback.call(new UrlResponse()); } @Override public void queryStatus(QueryStatusResponse callback) { UrlLoaderStatus status = new UrlLoaderStatus(); status.error = mError; status.isLoading = mIsLoading; callback.call(status); } }
package de.mpg.mpdl.labcam.Model.LocalModel; import com.google.gson.annotations.Expose; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import java.util.List; import java.util.ArrayList; @Table(name = "Notes") public class Note extends Model{ @Expose @Column(name = "noteId") String noteId; @Expose @Column(name = "noteContent") String noteContent; @Expose @Column(name = "createTime") String createTime; @Expose @Column(name = "imageIds") List<String> imageIds = new ArrayList<String>(); public Note(String noteId, String noteContent, String createTime, ArrayList<String> imageIds){ this.noteId = noteId; this.noteContent = noteContent; this.createTime = createTime; this.imageIds = imageIds; } public Note() { super(); } public String getNoteId() { return noteId; } public void setNoteId(String noteId) { this.noteId = noteId; } public String getNoteContent() { return noteContent; } public void setNoteContent(String noteContent) { this.noteContent = noteContent; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public List<String> getImageIds() { return imageIds; } public void setImageIds(List<String> imageIds) { this.imageIds = imageIds; } }
package org.slc.sli.util; /** * This class is for constants that are used in multiple places throughout the application. * Constants used only in one class should be kept in that class. * * @author dwu * */ public final class Constants { // API related URLs public static final String API_PREFIX = "api/rest"; public static final String SESSION_CHECK_PREFIX = "api/rest/system/session/check"; public static final String PROGRAM_ELL = "limitedEnglishProficiency"; public static final String PROGRAM_FRE = "schoolFoodServicesEligibility"; /* * \"name\": \"limitedEnglishProficiency\", * \"name\": \"ELL_FORMER\", * \"name\": \"504\", * \"name\": \"504_FORMER\", * \"name\": \"IEP\", * \"name\": \"IEP_FORMER\", * \"name\": \"LEA\", * \"name\": \"RPT\", * \"name\": \"RED\", * \"name\": \"schoolFoodServiceEligibility\", */ // view config strings - TODO: should these be changed to enums? public static final String VIEW_TYPE_STUDENT_LIST = "listOfStudents"; public static final String VIEW_TYPE_STUDENT_PROFILE_PAGE = "studentProfilePage"; public static final String FIELD_TYPE_ASSESSMENT = "assessment"; public static final String FIELD_TYPE_STUDENT_INFO = "studentInfo"; public static final String FIELD_LOZENGES_POSITION_FRONT = "pre"; public static final String FIELD_LOZENGES_POSITION_BACK = "post"; public static final String FIELD_TYPE_HISTORICAL_GRADE = "historicalGrade"; public static final String FIELD_TYPE_HISTORICAL_COURSE = "historicalCourse"; public static final String FIELD_TYPE_UNIT_GRADE = "unitTestGrade"; public static final String FIELD_TYPE_CURRENT_TERM_GRADE = "currentTermGrade"; public static final String CONFIG_ASSESSMENT_FILTER = "assessmentFilter"; // model map keys public static final String MM_KEY_LOZENGE_CONFIG = "lozengeConfigs"; public static final String MM_KEY_VIEW_CONFIG = "viewConfig"; public static final String MM_KEY_VIEW_CONFIGS = "viewConfigs"; public static final String MM_KEY_VIEW_CONFIGS_JSON = "viewConfigsJson"; public static final String MM_KEY_WIDGET_CONFIGS_JSON = "widgetConfig"; public static final String MM_KEY_LAYOUT = "layout"; public static final String MM_KEY_DATA = "data"; public static final String MM_KEY_DATA_JSON = "dataJson"; public static final String MM_KEY_ASSESSMENTS = "assessments"; public static final String MM_KEY_STUDENTS = "students"; public static final String MM_KEY_WIDGET_FACTORY = "widgetFactory"; public static final String MM_KEY_CONSTANTS = "constants"; public static final String MM_KEY_ATTENDANCE = "attendances"; public static final String MM_KEY_HISTORICAL = "historicaldata"; public static final String MM_KEY_GRADEBOOK_ENTRY_DATA = "gradebookEntryData"; // entity attributes public static final String ATTR_COURSES = "courses"; public static final String ATTR_SCHOOL_ID = "schoolId"; public static final String ATTR_SCHOOLS = "schools"; public static final String ATTR_SECTIONS = "sections"; public static final String ATTR_COURSE = "course"; public static final String ATTR_SECTION_NAME = "sectionName"; public static final String ATTR_LINK = "link"; public static final String ATTR_HREF = "href"; public static final String ATTR_SELF = "self"; public static final String ATTR_REL = "rel"; public static final String ATTR_LINKS = "links"; public static final String ATTR_STUDENT_UIDS = "studentUIDs"; public static final String ATTR_ID = "id"; public static final String ATTR_CUSTOM_DATA = "customData"; public static final String ATTR_ASSESSMENT_NAME = "assessmentName"; public static final String ATTR_ASSESSMENT_ID = "assessmentId"; public static final String ATTR_ADMIN_DATE = "administrationDate"; public static final String ATTR_ASSESSMENT_PERF_LEVEL = "assessmentPerformanceLevel"; public static final String ATTR_ASSESSMENT_REPORTING_METHOD = "assessmentReportingMethod"; public static final String ATTR_ASSESSMENT_TITLE = "assessmentTitle"; public static final String ATTR_ASSESSMENT_FAMILY_HIERARCHY_NAME = "assessmentFamilyHierarchyName"; public static final String ATTR_ASSESSMENT_PERIOD_DESCRIPTOR = "assessmentPeriodDescriptor"; public static final String ATTR_PERFORMANCE_LEVEL_DESCRIPTOR = "performanceLevelDescriptors"; public static final String ATTR_CODE_VALUE = "codeValue"; public static final String ATTR_ASSESSMENT_PERIOD_BEGIN_DATE = "beginDate"; public static final String ATTR_ASSESSMENT_PERIOD_END_DATE = "endDate"; public static final String ATTR_STUDENT_OBJECTIVE_ASSESSMENTS = "studentObjectiveAssessments"; public static final String ATTR_OBJECTIVE_ASSESSMENT = "objectiveAssessment"; public static final String ATTR_IDENTIFICATIONCODE = "identificationCode"; public static final String ATTR_DESCRIPTION = "description"; public static final String ATTR_RESULT = "result"; public static final String ATTR_SCORE_RESULTS = "scoreResults"; public static final String ATTR_MINIMUM_SCORE = "minimumScore"; public static final String ATTR_MAXIMUM_SCORE = "maximumScore"; public static final String ATTR_STUDENT_ID = "studentId"; public static final String ATTR_NAME = "name"; public static final String ATTR_FIRST_NAME = "firstName"; public static final String ATTR_LAST_SURNAME = "lastSurname"; public static final String ATTR_MIDDLE_NAME = "middleName"; public static final String ATTR_FULL_NAME = "fullName"; public static final String ATTR_PROGRAMS = "programs"; public static final String ATTR_YEAR = "year"; public static final String ATTR_SCALE_SCORE = "Scale score"; public static final String ATTR_RAW_SCORE = "Raw score"; public static final String ATTR_MASTERY_LEVEL = "Mastery level"; public static final String ATTR_PERF_LEVEL = "perfLevel"; public static final String ATTR_PERCENTILE = "Percentile"; public static final String ATTR_LEXILE_SCORE = "Other"; public static final String ATTR_ED_ORG_ID = "educationOrganizationId"; public static final String ATTR_ED_ORG_CHILD_ID = "educationOrganizationChildId"; public static final String ATTR_ED_ORG_PARENT_ID = "educationOrganizationParentId"; public static final String ATTR_NAME_OF_INST = "nameOfInstitution"; public static final String ATTR_ASSESSMENT_FAMILY = "assessmentFamily"; public static final String ATTR_ASSESSMENTS = "assessments"; public static final String ATTR_COHORT_YEAR = "cohortYear"; public static final String ATTR_UNIQUE_SECTION_CODE = "uniqueSectionCode"; public static final String ATTR_STUDENT_ASSESSMENTS = "studentAssessments"; public static final String ATTR_COURSE_ID = "courseId"; public static final String ATTR_STUDENT_ATTENDANCES = "attendances"; public static final String ATTR_PARENT_EDORG = "parentEducationAgencyReference"; public static final String ATTR_TEACHER_ID = "teacherId"; public static final String ATTR_TEACHER_NAME = "teacherName"; public static final String ATTR_SECTION_ID = "sectionId"; public static final String ATTR_SUBJECTAREA = "subjectArea"; public static final String ATTR_COURSE_TITLE = "courseTitle"; public static final String ATTR_SCHOOL_YEAR = "schoolYear"; public static final String ATTR_SESSION_ID = "sessionId"; public static final String ATTR_FINAL_LETTER_GRADE = "finalLetterGradeEarned"; public static final String ATTR_SESSIONS = "sessions"; public static final String ATTR_CLASSROOM_POSITION = "classroomPosition"; public static final String ATTR_TERM = "term"; public static final String ATTR_NUMERIC_GRADE_EARNED = "numericGradeEarned"; public static final String ATTR_DATE_FULFILLED = "dateFulfilled"; public static final String ATTR_HOMEROOM_INDICATOR = "homeroomIndicator"; public static final String ATTR_PERSONAL_TITLE_PREFIX = "personalTitlePrefix"; public static final String ATTR_GRADEBOOK_ENTRY_ID = "gradebookEntryId"; public static final String ATTR_GRADEBOOK_ENTRY_TYPE = "gradebookEntryType"; public static final String ATTR_GRADEBOOK_ENTRIES = "gradebookEntries"; public static final String ATTR_GRADE_LEVEL = "gradeLevel"; public static final String ATTR_GRADE_LEVELS = "gradeLevels"; public static final String ATTR_STUDENT_ENROLLMENT = "studentEnrollment"; public static final String ATTR_SCHOOL = "school"; public static final String ATTR_HEADER_STRING = "headerString"; public static final String ATTR_FOOTER_STRING = "footerString"; public static final String ATTR_OPTIONAL_FIELDS = "optionalFields"; public static final String ATTR_GRADEBOOK_VIEW = "gradebookView"; public static final String ATTR_STUDENT_SECTION_GRADEBOOK = "studentGradebookEntries"; public static final String ATTR_ATTENDANCE_EVENT_CATEGORY = "attendanceEventCategory"; public static final String ATTR_ABSENCE_COUNT = "absenceCount"; public static final String ATTR_TARDY_COUNT = "tardyCount"; public static final String ATTR_ATTENDANCE_RATE = "attendanceRate"; public static final String ATTR_TARDY_RATE = "tardyRate"; public static final String ATTR_STUDENTS = "students"; public static final String ATTR_TRANSCRIPT = "transcript"; public static final String ATTR_STUDENT_TRANSCRIPT_ASSOC = "courseTranscripts"; public static final String ATTR_STUDENT_SECTION_ASSOC = "studentSectionAssociations"; public static final String ATTR_INTERNAL_METADATA = "meta"; // Teacher constants public static final String TEACHER_OF_RECORD = "Teacher of Record"; public static final String HISTORICAL_DATA_VIEW = "Historical Data"; public static final String MIDDLE_SCHOOL_VIEW = "Middle School ELA View"; public static final String ATTR_NAME_WITH_LINK = "name_w_link"; public static final String PARAM_INCLUDE_FIELDS = "includeFields"; // Program Participation Constants public static final String SHOW_ELL_LOZENGE = "Limited"; // AddressType Constants public static final String TYPE_ADDRESS_HOME = "Home"; public static final String TYPE_ADDRESS_PHYSICAL = "Physical"; public static final String TYPE_ADDRESS_BILLING = "Billing"; public static final String TYPE_ADDRESS_MAILING = "Mailing"; public static final String TYPE_ADDRESS_OTHER = "Other"; public static final String TYPE_ADDRESS_TEMPORARY = "Temporary"; public static final String TYPE_ADDRESS_WORK = "Work"; // TelephoneType Constants public static final String TYPE_TELEPHONE_HOME = "Home"; public static final String TYPE_TELEPHONE_WORK = "Work"; public static final String TYPE_TELEPHONE_MOBILE = "Mobile"; public static final String TYPE_TELEPHONE_EMERGENCY_1 = "Emergency 1"; public static final String TYPE_TELEPHONE_EMERGENCY_2 = "Emergency 2"; public static final String TYPE_TELEPHONE_FAX = "Fax"; public static final String TYPE_TELEPHONE_OTHER = "Other"; public static final String TYPE_TELEPHONE_UNLISTED = "Unlisted"; // EmailType Constants public static final String TYPE_EMAIL_HOME_PERSONAL = "Home/Personal"; public static final String TYPE_EMAIL_WORK = "Work"; public static final String TYPE_EMAIL_ORGANIZATION = "Organization"; public static final String TYPE_EMAIL_OTHER = "Other"; public static final String CONTEXT_ROOT_PATH = "CONTEXT_ROOT_PATH"; // extra elements added by API public static final String METADATA = "metaData"; public static final String EXTERNAL_ID = "externalId"; /** * Contains the possible values for FRE participation */ public static enum FREParticipation { FREE("Free"), REDUCED_PRICE("Reduced Price"); private final String value; FREParticipation(String value) { this.value = value; } public String getValue() { return value; } } }
package com.rultor.agents.github.qtn; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Tv; import com.jcabi.github.Comment; import com.jcabi.log.Logger; import com.jcabi.ssh.SSH; import com.jcabi.ssh.Shell; import com.jcabi.xml.XML; import com.jcabi.xml.XSL; import com.jcabi.xml.XSLDocument; import com.rultor.agents.github.Answer; import com.rultor.agents.github.Question; import com.rultor.agents.github.Req; import com.rultor.agents.shells.TalkShells; import com.rultor.spi.Talk; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.ResourceBundle; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.lang3.StringUtils; /** * Show current status. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.5 */ @Immutable @ToString @EqualsAndHashCode(of = "talk") public final class QnStatus implements Question { /** * Message bundle. */ private static final ResourceBundle PHRASES = ResourceBundle.getBundle("phrases"); /** * XSL to generate report. */ private static final XSL REPORT = XSLDocument.make( QnStatus.class.getResourceAsStream("status.xsl") ); /** * Talk. */ private final transient Talk talk; /** * Ctor. * @param tlk Talk */ public QnStatus(final Talk tlk) { this.talk = tlk; } @Override public Req understand(final Comment.Smart comment, final URI home) throws IOException { final XML xml = this.talk.read(); final Collection<String> lines = new LinkedList<>(); if (!xml.nodes("/talk[shell/host and daemon/dir]").isEmpty()) { final String dir = xml.xpath("/talk/daemon/dir/text()").get(0); final Shell.Plain shell = new Shell.Plain( new Shell.Safe(new TalkShells(xml).get()) ); lines.add( String.format( " * Docker container ID: `%s...`", StringUtils.substring( shell.exec( String.format( // @checkstyle LineLength (1 line) "dir=%s; if [ -e \"${dir}/cid\" ]; then cat \"${dir}/cid\"; fi", SSH.escape(dir) ) ), 0, Tv.TWENTY ) ) ); lines.add( String.format( " * working directory size: %s", shell.exec( String.format("du -hs \"%s\" | cut -f1", dir) ).trim() ) ); lines.add( String.format( " * server load average: %s", shell.exec( "uptime | awk '{print $12}' | cut -d ',' -f 1" ).trim() ) ); } new Answer(comment).post( String.format( QnStatus.PHRASES.getString("QnStatus.response"), Joiner.on('\n').join( Iterables.concat( //Collections.singleton( // QnStatus.REPORT.applyTo(xml).trim() Collections.emptyList(), lines ) ) ) ); Logger.info(this, "status request in #%d", comment.issue().number()); return Req.DONE; } }
package me.devsaki.hentoid.workers; import android.annotation.SuppressLint; import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Data; import androidx.work.WorkerParameters; import java.util.List; import java.util.Locale; import java.util.concurrent.LinkedBlockingQueue; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; import me.devsaki.hentoid.R; import me.devsaki.hentoid.core.AppStartup; import me.devsaki.hentoid.database.DatabaseMaintenance; import me.devsaki.hentoid.notification.startup.StartupCompleteNotification; import me.devsaki.hentoid.notification.startup.StartupProgressNotification; import me.devsaki.hentoid.util.notification.Notification; import timber.log.Timber; /** * Worker responsible for running post-startup tasks */ public class StartupWorker extends BaseWorker { private final CompositeDisposable launchDisposable = new CompositeDisposable(); private List<Observable<Float>> launchTasks; public StartupWorker( @NonNull Context context, @NonNull WorkerParameters parameters) { super(context, parameters, R.id.startup_service, null); } @Override Notification getStartNotification() { return new StartupProgressNotification("Startup progress", 0, 0); } @Override void onInterrupt() { launchDisposable.dispose(); } @Override void onClear() { launchTasks.clear(); launchDisposable.dispose(); } @SuppressLint("TimberArgCount") @Override void getToWork(@NonNull Data input) { launchTasks = AppStartup.getPostLaunchTasks(getApplicationContext()); launchTasks.addAll(DatabaseMaintenance.getPostLaunchCleanupTasks(getApplicationContext())); int step = 0; for (Observable<Float> o : launchTasks) { String message = String.format(Locale.ENGLISH, "Startup progress : step %d / %d", ++step, launchTasks.size()); Timber.d(message); notificationManager.notify(new StartupProgressNotification(message, Math.round(step * 1f / launchTasks.size() * 100), 100)); runTask(o); } notificationManager.notify(new StartupCompleteNotification()); } private void runTask(Observable<Float> o) { // Tasks are used to execute Rx's observeOn on current thread // See https://github.com/square/retrofit/issues/370#issuecomment-315868381 LinkedBlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>(); launchDisposable.add(o .observeOn(Schedulers.from(tasks::add)) .subscribe() ); try { tasks.take().run(); } catch (InterruptedException e) { Timber.w(e); Thread.currentThread().interrupt(); } } }
package twitter4j; import static twitter4j.DAOTest.assertDeserializedFormIsEqual; import static twitter4j.DAOTest.assertDeserializedFormIsNotEqual; import java.io.File; import java.net.URL; import java.util.Date; import java.util.List; /** * @author Yusuke Yamamoto - yusuke at mac.com */ public class TwitterTest extends TwitterTestBase { public TwitterTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testGetPublicTimeline() throws Exception { List<Status> statuses; statuses = twitterAPI1.getPublicTimeline(); assertTrue("size", 5 < statuses.size()); } public void testGetHomeTimeline() throws Exception { List<Status> status = twitterAPI1.getHomeTimeline(); assertTrue(0 < status.size()); } public void testSerializability() throws Exception { Twitter twitter = new TwitterFactory().getInstance("foo", "bar"); Twitter deserialized = (Twitter)assertDeserializedFormIsEqual(twitter); assertEquals(deserialized.getScreenName(), twitter.getScreenName()); assertEquals(deserialized.auth, twitter.auth); twitter = new TwitterFactory().getInstance(); deserialized = (Twitter)assertDeserializedFormIsEqual(twitter); assertEquals(deserialized.auth, twitter.auth); } public void testGetScreenName() throws Exception { assertEquals(id1.screenName, twitterAPI1.getScreenName()); assertEquals(id1.id, twitterAPI1.getId()); } public void testGetFriendsTimeline() throws Exception { List<Status> actualReturn; actualReturn = twitterAPI1.getFriendsTimeline(); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI1.getFriendsTimeline(new Paging(1l)); assertTrue(actualReturn.size() > 0); //this is necessary because the twitter server's clock tends to delay actualReturn = twitterAPI1.getFriendsTimeline(new Paging(1000l)); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI1.getFriendsTimeline(new Paging(1)); assertTrue(actualReturn.size() > 0); } public void testShowUser() throws Exception { User user = twitterAPI1.showUser(id1.screenName); assertEquals(id1.screenName, user.getScreenName()); assertNotNull(user.getLocation()); assertNotNull(user.getDescription()); assertNotNull(user.getProfileImageURL()); assertNotNull(user.getURL()); assertFalse(user.isProtected()); assertTrue(0 <= user.getFavouritesCount()); assertTrue(0 <= user.getFollowersCount()); assertTrue(0 <= user.getFriendsCount()); assertNotNull(user.getCreatedAt()); assertNotNull(user.getTimeZone()); assertNotNull(user.getProfileBackgroundImageUrl()); assertTrue(0 <= user.getStatusesCount()); assertNotNull(user.getProfileBackgroundColor()); assertNotNull(user.getProfileTextColor()); assertNotNull(user.getProfileLinkColor()); assertNotNull(user.getProfileSidebarBorderColor()); assertNotNull(user.getProfileSidebarFillColor()); assertNotNull(user.getProfileTextColor()); assertTrue(1 < user.getFollowersCount()); assertNotNull(user.getStatusCreatedAt()); assertNotNull(user.getStatusText()); assertNotNull(user.getStatusSource()); assertFalse(user.isStatusFavorited()); assertEquals(-1, user.getStatusInReplyToStatusId()); assertEquals(-1, user.getStatusInReplyToUserId()); assertFalse(user.isStatusFavorited()); assertNull(user.getStatusInReplyToScreenName()); assertTrue(1 < user.getListedCount()); assertFalse(user.isFollowRequestSent()); //test case for TFJ-91 null pointer exception getting user detail on users with no statuses twitterAPI1.showUser("twit4jnoupdate"); twitterAPI1.showUser("tigertest"); user = twitterAPI1.showUser(numberId); assertEquals(numberIdId, user.getId()); user = twitterAPI1.showUser(numberIdId); assertEquals(numberIdId, user.getId()); } public void testLookupUsers() throws TwitterException { ResponseList<User> users = twitterAPI1.lookupUsers(new String[]{id1.screenName, id2.screenName}); assertEquals(2, users.size()); assertContains(users, id1); assertContains(users, id2); users = twitterAPI1.lookupUsers(new int[]{id1.id, id2.id}); assertEquals(2, users.size()); assertContains(users, id1); assertContains(users, id2); assertNull(users.getFeatureSpecificRateLimitStatus()); } private void assertContains(ResponseList<User> users, TestUserInfo user) { boolean found = false; for(User aUser : users){ if(aUser.getId() == user.id && aUser.getScreenName().equals(user.screenName)){ found = true; break; } } if(!found){ fail(user.screenName + " not found in the result."); } } public void testSearchUser() throws TwitterException { ResponseList<User> users = twitterAPI1.searchUsers("Doug Williams",1); assertTrue(4 < users.size()); assertNotNull(users.getFeatureSpecificRateLimitStatus()); } public void testSuggestion() throws Exception { ResponseList<Category> categories = twitterAPI1.getSuggestedUserCategories(); assertTrue(categories.size() > 0); ResponseList<User> users = twitterAPI1.getUserSuggestions(categories.get(0).getSlug()); assertTrue(users.size() > 0); } // list deletion doesn't work now. public void testList() throws Exception { PagableResponseList<UserList> userLists; userLists = twitterAPI1.getUserLists(id1.screenName,-1l); for(UserList alist : userLists){ twitterAPI1.destroyUserList(alist.getId()); } /*List Methods*/ UserList userList; //ensuring createUserList works in the case an email is specified a userid userList = twitterAPI3.createUserList("api3 is email", false, null); assertFalse(userList.isPublic()); twitterAPI3.destroyUserList(userList.getId()); userList = twitterAPI1.createUserList("testpoint1", false, "description1"); assertNotNull(userList); assertEquals("testpoint1", userList.getName()); assertEquals("description1", userList.getDescription()); userList = twitterAPI1.updateUserList(userList.getId(), "testpoint2", true, "description2"); assertTrue(userList.isPublic()); assertNotNull(userList); assertEquals("testpoint2", userList.getName()); assertEquals("description2", userList.getDescription()); userLists = twitterAPI1.getUserLists(id1.screenName, -1l); assertFalse(userLists.size() == 0); userList = twitterAPI1.showUserList(id1.screenName, userList.getId()); assertNotNull(userList); List<Status> statuses = twitterAPI1.getUserListStatuses(id1.screenName, userList.getId(), new Paging()); assertNotNull(statuses); /*List Member Methods*/ User user; try { user = twitterAPI1.checkUserListMembership(id1.screenName, id2.id, userList.getId()); fail("id2 shouldn't be a member of the userList yet. expecting a TwitterException"); } catch (TwitterException te) { assertEquals(404, te.getStatusCode()); } userList = twitterAPI1.addUserListMember(userList.getId(), id2.id); userList = twitterAPI1.addUserListMember(userList.getId(), id4.id); assertNotNull(userList); List<User> users = twitterAPI1.getUserListMembers(id1.screenName, userList.getId(), -1); // workaround issue 1301 // assertEquals(userList.getMemberCount(), users.size()); assertTrue(0 < users.size());// workaround issue 1301 userList = twitterAPI1.deleteUserListMember(userList.getId(), id2.id); assertNotNull(userList); // assertEquals(1, userList.getMemberCount()); user = twitterAPI1.checkUserListMembership(id1.screenName, userList.getId(), id4.id); assertEquals(id4.id, user.getId()); userLists = twitterAPI1.getUserListMemberships(id1.screenName, -1l); assertNotNull(userLists); userLists = twitterAPI1.getUserListSubscriptions(id1.screenName, -1l); assertNotNull(userLists); assertEquals(0, userLists.size()); /*List Subscribers Methods*/ users = twitterAPI1.getUserListSubscribers(id1.screenName, userList.getId(), -1); assertEquals(0, users.size()); try { twitterAPI2.subscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { // workarounding issue 1300 assertEquals(404,te.getStatusCode()); } // expected subscribers: id2 try { twitterAPI4.subscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { // workarounding issue 1300 assertEquals(404, te.getStatusCode()); } // expected subscribers: id2 and id4 try { twitterAPI2.unsubscribeUserList(id1.screenName, userList.getId()); } catch (TwitterException te) { // workarounding issue 1300 assertEquals(404, te.getStatusCode()); } // expected subscribers: id4 users = twitterAPI1.getUserListSubscribers(id1.screenName, userList.getId(), -1); // assertEquals(1, users.size()); //only id4 should be subscribing the userList assertTrue(0 <= users.size()); // workarounding issue 1300 try { user = twitterAPI1.checkUserListSubscription(id1.screenName, userList.getId(), id4.id); assertEquals(id4.id, user.getId()); } catch (TwitterException te) { // workarounding issue 1300 assertEquals(404, te.getStatusCode()); } userLists = twitterAPI1.getUserListSubscriptions(id4.screenName, -1l); assertNotNull(userLists); // assertEquals(1, userLists.size()); workarounding issue 1300 try { user = twitterAPI1.checkUserListSubscription(id1.screenName, id2.id, userList.getId()); fail("id2 shouldn't be a subscriber the userList. expecting a TwitterException"); } catch (TwitterException ignore) { assertEquals(404, ignore.getStatusCode()); } userList = twitterAPI1.destroyUserList(userList.getId()); assertNotNull(userList); } public void testUserTimeline() throws Exception { List<Status> statuses; statuses = twitterAPI1.getUserTimeline(); assertTrue("size", 0 < statuses.size()); try { statuses = unauthenticated.getUserTimeline("1000"); assertTrue("size", 0 < statuses.size()); assertEquals(9737332, statuses.get(0).getUser().getId()); statuses = unauthenticated.getUserTimeline(1000); assertTrue("size", 0 < statuses.size()); assertEquals(1000, statuses.get(0).getUser().getId()); statuses = unauthenticated.getUserTimeline(id1.screenName, new Paging().count(10)); assertTrue("size", 0 < statuses.size()); statuses = unauthenticated.getUserTimeline(id1.screenName, new Paging(999383469l)); assertTrue("size", 0 < statuses.size()); } catch (TwitterException te) { // is being rate limited assertEquals(400, te.getStatusCode()); } statuses = twitterAPI1.getUserTimeline(new Paging(999383469l)); assertTrue("size", 0 < statuses.size()); statuses = twitterAPI1.getUserTimeline(new Paging(999383469l).count(15)); assertTrue("size", 0 < statuses.size()); statuses = twitterAPI1.getUserTimeline(new Paging(1).count(30)); List<Status> statuses2 = twitterAPI1.getUserTimeline(new Paging(2).count(15)); assertEquals(statuses.get(statuses.size() - 1), statuses2.get(statuses2.size() - 1)); } public void testShowStatus() throws Exception { Status status = twitterAPI2.showStatus(1000l); assertEquals(52, status.getUser().getId()); try { Status status2 = unauthenticated.showStatus(1000l); assertEquals(52, status2.getUser().getId()); assertNotNull(status.getRateLimitStatus()); status2 = unauthenticated.showStatus(999383469l); assertEquals("01010100 01110010 01101001 01110101 01101101 01110000 01101000 <3", status2.getText()); status2 = unauthenticated.showStatus(7185737372l); assertEquals("\\u5e30%u5e30 <%}& foobar", status2.getText()); } catch (TwitterException te) { assertEquals(400, te.getStatusCode()); } status = twitterAPI2.showStatus(1000l); assertTrue(-1 <= status.getRetweetCount()); assertFalse(status.isRetweetedByMe()); } public void testStatusMethods() throws Exception { String date = new java.util.Date().toString() + "test"; Status status = twitterAPI1.updateStatus(date); assertEquals(date, status.getText()); Status status2 = twitterAPI2.updateStatus("@" + id1.screenName + " " + date, status.getId()); assertEquals("@" + id1.screenName + " " + date, status2.getText()); assertEquals(status.getId(), status2.getInReplyToStatusId()); assertEquals(twitterAPI1.verifyCredentials().getId(), status2.getInReplyToUserId()); twitterAPI1.destroyStatus(status.getId()); } public void testRetweetMethods() throws Exception { List<Status> statuses = twitterAPI1.getRetweetedByMe(); assertIsRetweet(statuses); statuses = twitterAPI1.getRetweetedByMe(new Paging(1)); assertIsRetweet(statuses); statuses = twitterAPI1.getRetweetedToMe(); assertIsRetweet(statuses); statuses = twitterAPI1.getRetweetedToMe(new Paging(1)); assertIsRetweet(statuses); statuses = twitterAPI1.getRetweetsOfMe(); // assertIsRetweet(statuses); statuses = twitterAPI1.getRetweetsOfMe(new Paging(1)); // assertIsRetweet(statuses); statuses = twitterAPI1.getRetweets(18594701629l); assertIsRetweet(statuses); assertTrue(20 < statuses.size()); } private void assertIsRetweet(List<Status> statuses) { for(Status status : statuses){ assertTrue(status.isRetweet()); } } public void testGeoLocation() throws Exception { final double LATITUDE = 12.3456; final double LONGITUDE = -34.5678; Status withgeo = twitterAPI1.updateStatus(new java.util.Date().toString() + ": updating geo location", new GeoLocation(LATITUDE, LONGITUDE)); assertTrue(withgeo.getUser().isGeoEnabled()); assertEquals(LATITUDE, withgeo.getGeoLocation().getLatitude()); assertEquals(LONGITUDE, withgeo.getGeoLocation().getLongitude()); assertFalse(twitterAPI2.verifyCredentials().isGeoEnabled()); } // public void testAnnotations() throws Exception { // final String failMessage = // "Annotations were not added to the status, please make sure that your account is whitelisted for Annotations by Twitter"; // Annotation annotation = new Annotation("review"); // annotation.attribute("content", "Yahoo! landing page"). // StatusUpdate update = new StatusUpdate(new java.util.Date().toString() + ": annotated status"); // update.addAnnotation(annotation); // Status withAnnos = twitterAPI1.updateStatus(update); // Annotations annotations = withAnnos.getAnnotations(); // assertNotNull(failMessage, annotations); // List<Annotation> annos = annotations.getAnnotations(); // assertEquals(1, annos.size()); // assertEquals(annotation, annos.get(0)); public void testGetFriendsStatuses() throws Exception { PagableResponseList<User> users = twitterAPI1.getFriendsStatuses(); assertNotNull("friendsStatuses", users); users = twitterAPI1.getFriendsStatuses(numberId); assertNotNull("friendsStatuses", users); assertEquals(id1.screenName, users.get(0).getScreenName()); users = twitterAPI1.getFriendsStatuses(numberIdId); assertNotNull("friendsStatuses", users); assertEquals(id1.screenName, users.get(0).getScreenName()); try { users = unauthenticated.getFriendsStatuses("yusukey"); assertNotNull("friendsStatuses", users); } catch (TwitterException te) { // is being rate limited assertEquals(400, te.getStatusCode()); } } public void testRelationship() throws Exception { // TESTING PRECONDITIONS: // 1) id1 is followed by "followsOneWay", but not following "followsOneWay" Relationship rel1 = twitterAPI1.showFriendship(id1.screenName, followsOneWay); // test second precondition assertNotNull(rel1); assertTrue(rel1.isSourceFollowedByTarget()); assertFalse(rel1.isSourceFollowingTarget()); assertTrue(rel1.isTargetFollowingSource()); assertFalse(rel1.isTargetFollowedBySource()); // 2) best_friend1 is following and followed by best_friend2 Relationship rel2 = twitterAPI1.showFriendship(bestFriend1.screenName, bestFriend2.screenName); // test second precondition assertNotNull(rel2); assertTrue(rel2.isSourceFollowedByTarget()); assertTrue(rel2.isSourceFollowingTarget()); assertTrue(rel2.isTargetFollowingSource()); assertTrue(rel2.isTargetFollowedBySource()); // test equality Relationship rel3 = twitterAPI1.showFriendship(id1.screenName, followsOneWay); assertEquals(rel1, rel3); assertFalse(rel1.equals(rel2)); } private void assertIDExsits(String assertion, IDs ids, int idToFind) { boolean found = false; for (int id : ids.getIDs()) { if (id == idToFind) { found = true; break; } } assertTrue(assertion, found); } public void testFriendships() throws Exception { IDs ids; ids = twitterAPI4.getIncomingFriendships(-1); assertTrue(ids.getIDs().length > 0); ids = twitterAPI2.getOutgoingFriendships(-1); assertTrue(ids.getIDs().length > 0); } public void testSocialGraphMethods() throws Exception { IDs ids; ids = twitterAPI1.getFriendsIDs(); int yusukey = 4933401; assertIDExsits("twit4j is following yusukey", ids, yusukey); int ryunosukey = 48528137; ids = twitterAPI1.getFriendsIDs(ryunosukey); assertEquals("ryunosukey is not following anyone", 0, ids.getIDs().length); ids = twitterAPI1.getFriendsIDs("yusukey"); assertIDExsits("yusukey is following ryunosukey", ids, ryunosukey); IDs obamaFollowers; obamaFollowers = twitterAPI1.getFollowersIDs("barackobama"); assertTrue(obamaFollowers.hasNext()); assertFalse(obamaFollowers.hasPrevious()); obamaFollowers = twitterAPI1.getFollowersIDs("barackobama", obamaFollowers.getNextCursor()); assertTrue(obamaFollowers.hasNext()); assertTrue(obamaFollowers.hasPrevious()); obamaFollowers = twitterAPI1.getFollowersIDs(813286); assertTrue(obamaFollowers.hasNext()); assertFalse(obamaFollowers.hasPrevious()); obamaFollowers = twitterAPI1.getFollowersIDs(813286, obamaFollowers.getNextCursor()); assertTrue(obamaFollowers.hasNext()); assertTrue(obamaFollowers.hasPrevious()); IDs obamaFriends; obamaFriends = twitterAPI1.getFriendsIDs("barackobama"); assertTrue(obamaFriends.hasNext()); assertFalse(obamaFriends.hasPrevious()); obamaFriends = twitterAPI1.getFriendsIDs("barackobama", obamaFriends.getNextCursor()); assertTrue(obamaFriends.hasNext()); assertTrue(obamaFriends.hasPrevious()); obamaFriends = twitterAPI1.getFriendsIDs(813286); assertTrue(obamaFriends.hasNext()); assertFalse(obamaFriends.hasPrevious()); obamaFriends = twitterAPI1.getFriendsIDs(813286, obamaFriends.getNextCursor()); assertTrue(obamaFriends.hasNext()); assertTrue(obamaFriends.hasPrevious()); try { twitterAPI2.createFriendship(id1.screenName); } catch (TwitterException ignore) { } ids = twitterAPI1.getFollowersIDs(); assertIDExsits("twit4j2 is following twit4j", ids, 6377362); ids = twitterAPI1.getFollowersIDs(ryunosukey); assertIDExsits("yusukey is following ryunosukey", ids, yusukey); ids = twitterAPI1.getFollowersIDs("ryunosukey"); assertIDExsits("yusukey is following ryunosukey", ids, yusukey); } public void testAccountMethods() throws Exception { User original = twitterAPI1.verifyCredentials(); if (original.getScreenName().endsWith("new") || original.getName().endsWith("new")) { original = twitterAPI1.updateProfile( "twit4j", null, "http://yusuke.homeip.net/twitter4j/" , "location:", "Hi there, I do test a lot!new"); } String newName, newURL, newLocation, newDescription; String neu = "new"; newName = original.getName() + neu; newURL = original.getURL() + neu; newLocation = original.getLocation() + neu; newDescription = original.getDescription() + neu; User altered = twitterAPI1.updateProfile( newName, null, newURL, newLocation, newDescription); twitterAPI1.updateProfile(original.getName() , null, original.getURL().toString(), original.getLocation(), original.getDescription()); assertEquals(newName, altered.getName()); assertEquals(newURL, altered.getURL().toString()); assertEquals(newLocation, altered.getLocation()); assertEquals(newDescription, altered.getDescription()); try { new TwitterFactory().getInstance("doesnotexist--", "foobar").verifyCredentials(); fail("should throw TwitterException"); } catch (TwitterException te) { } assertTrue(twitterAPIBestFriend1.existsFriendship(bestFriend1.screenName, bestFriend2.screenName)); assertFalse(twitterAPI1.existsFriendship(id1.screenName, "al3x")); User eu; eu = twitterAPI1.updateProfileColors("f00", "f0f", "0ff", "0f0", "f0f"); assertEquals("f00", eu.getProfileBackgroundColor()); assertEquals("f0f", eu.getProfileTextColor()); assertEquals("0ff", eu.getProfileLinkColor()); assertEquals("0f0", eu.getProfileSidebarFillColor()); assertEquals("f0f", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors("f0f", "f00", "f0f", "0ff", "0f0"); assertEquals("f0f", eu.getProfileBackgroundColor()); assertEquals("f00", eu.getProfileTextColor()); assertEquals("f0f", eu.getProfileLinkColor()); assertEquals("0ff", eu.getProfileSidebarFillColor()); assertEquals("0f0", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors("87bc44", "9ae4e8", "000000", "0000ff", "e0ff92"); assertEquals("87bc44", eu.getProfileBackgroundColor()); assertEquals("9ae4e8", eu.getProfileTextColor()); assertEquals("000000", eu.getProfileLinkColor()); assertEquals("0000ff", eu.getProfileSidebarFillColor()); assertEquals("e0ff92", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors("f0f", null, "f0f", null, "0f0"); assertEquals("f0f", eu.getProfileBackgroundColor()); assertEquals("9ae4e8", eu.getProfileTextColor()); assertEquals("f0f", eu.getProfileLinkColor()); assertEquals("0000ff", eu.getProfileSidebarFillColor()); assertEquals("0f0", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors(null, "f00", null, "0ff", null); assertEquals("f0f", eu.getProfileBackgroundColor()); assertEquals("f00", eu.getProfileTextColor()); assertEquals("f0f", eu.getProfileLinkColor()); assertEquals("0ff", eu.getProfileSidebarFillColor()); assertEquals("0f0", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors("9ae4e8", "000000", "0000ff", "e0ff92", "87bc44"); assertEquals("9ae4e8", eu.getProfileBackgroundColor()); assertEquals("000000", eu.getProfileTextColor()); assertEquals("0000ff", eu.getProfileLinkColor()); assertEquals("e0ff92", eu.getProfileSidebarFillColor()); assertEquals("87bc44", eu.getProfileSidebarBorderColor()); } public void testAccountProfileImageUpdates() throws Exception { twitterAPI1.updateProfileImage(getRandomlyChosenFile()); // tile randomly twitterAPI1.updateProfileBackgroundImage(getRandomlyChosenFile(), (5 < System.currentTimeMillis() % 5)); } static final String[] files = {"src/test/resources/t4j-reverse.jpeg", "src/test/resources/t4j-reverse.png", "src/test/resources/t4j-reverse.gif", "src/test/resources/t4j.jpeg", "src/test/resources/t4j.png", "src/test/resources/t4j.gif", }; public static File getRandomlyChosenFile(){ int rand = (int) (System.currentTimeMillis() % 6); File file = new File(files[rand]); if(!file.exists()){ file = new File("twitter4j-core/"+ files[rand]); } return file; } public void testFavoriteMethods() throws Exception { Status status = twitterAPI1.getHomeTimeline(new Paging().count(1)).get(0); twitterAPI2.createFavorite(status.getId()); assertTrue(twitterAPI2.getFavorites().size() > 0); try { twitterAPI2.destroyFavorite(status.getId()); } catch (TwitterException te) { // sometimes destorying favorite fails with 404 assertEquals(404, te.getStatusCode()); } } public void testFollowers() throws Exception { PagableResponseList<User> actualReturn = twitterAPI1.getFollowersStatuses(); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI1.getFollowersStatuses(); assertTrue(actualReturn.size() > 0); assertFalse(actualReturn.hasNext()); assertFalse(actualReturn.hasPrevious()); actualReturn = twitterAPI1.getFollowersStatuses(actualReturn.getNextCursor()); assertEquals(0, actualReturn.size()); actualReturn = twitterAPI2.getFollowersStatuses(); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI2.getFollowersStatuses("yusukey"); assertTrue(actualReturn.size() > 60); actualReturn = twitterAPI2.getFollowersStatuses("yusukey", actualReturn.getNextCursor()); assertTrue(actualReturn.size() > 10); // - Issue 1572: Lists previous cursor returns empty results // actualReturn = twitterAPI2.getFollowersStatuses("yusukey", actualReturn.getPreviousCursor()); // assertTrue(actualReturn.size() > 10); } public void testDirectMessages() throws Exception { String expectedReturn = new Date() + ":directmessage test"; DirectMessage actualReturn = twitterAPI1.sendDirectMessage("twit4jnoupdate", expectedReturn); assertEquals(expectedReturn, actualReturn.getText()); assertEquals(id1.screenName, actualReturn.getSender().getScreenName()); assertEquals("twit4jnoupdate", actualReturn.getRecipient().getScreenName()); List<DirectMessage> actualReturnList = twitterAPI1.getDirectMessages(); assertTrue(1 <= actualReturnList.size()); } public void testCreateDestroyFriend() throws Exception { User user; try { user = twitterAPI2.destroyFriendship(id1.screenName); } catch (TwitterException te) { //ensure destory id1 before the actual test //ensure destory id1 before the actual test } try { user = twitterAPI2.destroyFriendship(id1.screenName); } catch (TwitterException te) { assertEquals(403, te.getStatusCode()); } user = twitterAPI2.createFriendship(id1.screenName, true); assertEquals(id1.screenName, user.getScreenName()); // the Twitter API is not returning appropriate notifications value // User detail = twitterAPI2.showUser(id1); // assertTrue(detail.isNotificationEnabled()); try { user = twitterAPI2.createFriendship(id2.screenName); fail("shouldn't be able to befrinend yourself"); } catch (TwitterException te) { assertEquals(403, te.getStatusCode()); } try { user = twitterAPI2.createFriendship("doesnotexist fail("non-existing user"); } catch (TwitterException te) { //now befriending with non-existing user returns 404 assertEquals(404, te.getStatusCode()); } } public void testGetMentions() throws Exception { twitterAPI2.updateStatus("@" + id1.screenName + " reply to id1 " + new java.util.Date()); List<Status> statuses = twitterAPI1.getMentions(); assertTrue(statuses.size() > 0); statuses = twitterAPI1.getMentions(new Paging(1)); assertTrue(statuses.size() > 0); statuses = twitterAPI1.getMentions(new Paging(1)); assertTrue(statuses.size() > 0); statuses = twitterAPI1.getMentions(new Paging(1, 1l)); assertTrue(statuses.size() > 0); statuses = twitterAPI1.getMentions(new Paging(1l)); assertTrue(statuses.size() > 0); } public void testNotification() throws Exception { try { twitterAPI1.disableNotification("twit4jprotected"); } catch (TwitterException te) { } twitterAPI1.enableNotification("twit4jprotected"); twitterAPI1.disableNotification("twit4jprotected"); } public void testBlock() throws Exception { twitterAPI2.createBlock(id1.screenName); twitterAPI2.destroyBlock(id1.screenName); assertFalse(twitterAPI1.existsBlock("twit4j2")); assertTrue(twitterAPI1.existsBlock("twit4jblock")); List<User> users = twitterAPI1.getBlockingUsers(); assertEquals(1, users.size()); assertEquals(39771963, users.get(0).getId()); users = twitterAPI1.getBlockingUsers(1); assertEquals(1, users.size()); assertEquals(39771963, users.get(0).getId()); IDs ids = twitterAPI1.getBlockingUsersIDs(); assertEquals(1, ids.getIDs().length); assertEquals(39771963, ids.getIDs()[0]); } public void testLocalTrendsMethods() throws Exception { ResponseList<Location> locations; locations = twitterAPI1.getAvailableTrends(); assertTrue(locations.size() > 0); locations = twitterAPI1.getAvailableTrends(new GeoLocation(0,0)); assertTrue(locations.size() > 0); Trends trends = twitterAPI1.getLocationTrends(locations.get(0).getWoeid()); assertEquals(locations.get(0), trends.getLocation()); assertTrue(trends.getTrends().length > 0); } RateLimitStatus rateLimitStatus = null; boolean accountLimitStatusAcquired; boolean ipLimitStatusAcquired; //need to think of a way to test this, perhaps mocking out Twitter is the way to go public void testRateLimitStatus() throws Exception { RateLimitStatus status = twitterAPI1.getRateLimitStatus(); assertTrue(10 < status.getHourlyLimit()); assertTrue(10 < status.getRemainingHits()); twitterAPI1.setRateLimitStatusListener(new RateLimitStatusListener() { public void onRateLimitStatus(RateLimitStatusEvent event) { System.out.println("onRateLimitStatus"+event); accountLimitStatusAcquired = event.isAccountRateLimitStatus(); ipLimitStatusAcquired = event.isIPRateLimitStatus(); rateLimitStatus = event.getRateLimitStatus(); } public void onRateLimitReached(RateLimitStatusEvent event) { } }); // the listener doesn't implement serializable and deserialized form should not be equal to the original object assertDeserializedFormIsNotEqual(twitterAPI1); unauthenticated.setRateLimitStatusListener(new RateLimitStatusListener() { public void onRateLimitStatus(RateLimitStatusEvent event) { accountLimitStatusAcquired = event.isAccountRateLimitStatus(); ipLimitStatusAcquired = event.isIPRateLimitStatus(); rateLimitStatus = event.getRateLimitStatus(); } public void onRateLimitReached(RateLimitStatusEvent event){ } }); // the listener doesn't implement serializable and deserialized form should not be equal to the original object assertDeserializedFormIsNotEqual(unauthenticated); twitterAPI1.getMentions(); assertTrue(accountLimitStatusAcquired); assertFalse(ipLimitStatusAcquired); RateLimitStatus previous = rateLimitStatus; twitterAPI1.getMentions(); assertTrue(accountLimitStatusAcquired); assertFalse(ipLimitStatusAcquired); assertTrue(previous.getRemainingHits() > rateLimitStatus.getRemainingHits()); assertEquals(previous.getHourlyLimit(), rateLimitStatus.getHourlyLimit()); try { unauthenticated.getPublicTimeline(); assertFalse(accountLimitStatusAcquired); assertTrue(ipLimitStatusAcquired); previous = rateLimitStatus; unauthenticated.getPublicTimeline(); assertFalse(accountLimitStatusAcquired); assertTrue(ipLimitStatusAcquired); assertTrue(previous.getRemainingHits() > rateLimitStatus.getRemainingHits()); assertEquals(previous.getHourlyLimit(), rateLimitStatus.getHourlyLimit()); } catch (TwitterException te) { // is being rate limited; assertEquals(400, te.getStatusCode()); } } /* Spam Reporting Methods */ public void testReportSpammerSavedSearches() throws Exception { // Not sure they're accepting multiple spam reports for the same user. // Do we really need to test this method? How? } /* Saved Searches Methods */ public void testSavedSearches() throws Exception { List<SavedSearch> list = twitterAPI1.getSavedSearches(); for (SavedSearch savedSearch : list) { twitterAPI1.destroySavedSearch(savedSearch.getId()); } SavedSearch ss1 = twitterAPI1.createSavedSearch("my search"); assertEquals("my search", ss1.getQuery()); assertEquals(-1, ss1.getPosition()); list = twitterAPI1.getSavedSearches(); // the saved search may not be immediately available assertTrue(0 <= list.size()); try { SavedSearch ss2 = twitterAPI1.destroySavedSearch(ss1.getId()); assertEquals(ss1, ss2); } catch (TwitterException te) { // sometimes it returns 404 or 500 when its out of sync. assertTrue(404 == te.getStatusCode() || 500 == te.getStatusCode()); } } public void testGeoMethods() throws Exception { GeoQuery query; ResponseList<Place> places; query = new GeoQuery(new GeoLocation(0, 0)); places = twitterAPI1.reverseGeoCode(query); assertEquals(0, places.size()); query = new GeoQuery(new GeoLocation(37.78215, -122.40060)); places = twitterAPI1.reverseGeoCode(query); assertTrue(places.size() > 0); places = twitterAPI1.getNearbyPlaces(query); assertTrue(places.size() > 0); try{ Place place = this.unauthenticated.getGeoDetails("5a110d312052166f"); assertEquals("San Francisco, CA", place.getFullName()); assertEquals("California, US", place.getContainedWithIn()[0].getFullName()); } catch (TwitterException te) { // is being rate limited assertEquals(400, te.getStatusCode()); } String sanFrancisco = "5a110d312052166f"; Status status = twitterAPI1.updateStatus(new StatusUpdate(new java.util.Date() + " status with place"). placeId(sanFrancisco)); assertEquals(sanFrancisco, status.getPlace().getId()); assertEquals(null, status.getContributors()); } public void testTest() throws Exception { assertTrue(twitterAPI2.test()); } /** * @since Twitter4J 2.1.3 */ public void testRetweetedBy() throws Exception { // this is the test status id used in the api docs final long testStatusId = 9548214222l; ResponseList<User> users; users = twitterAPI1.getRetweetedBy(testStatusId); assertNotNull(users); assertTrue(users.size() == 3); assertEquals("anilparmar", users.get(0).getScreenName()); Paging paging = new Paging(); paging.setPage(3); paging.setCount(1); users = twitterAPI1.getRetweetedBy(testStatusId, paging); assertTrue(users.size() == 1); assertEquals("mtodd", users.get(0).getScreenName()); IDs ids = twitterAPI1.getRetweetedByIDs(testStatusId); assertNotNull(ids); assertTrue(ids.getIDs().length == 3); assertEquals(ids.getIDs()[0], 16758065); ids = twitterAPI1.getRetweetedByIDs(testStatusId, paging); assertTrue(ids.getIDs().length == 1); assertEquals(ids.getIDs()[0], 5933482); } public void testEntities() throws Exception { Status status = twitterAPI2.showStatus(22035985122L); assertEquals(2, status.getUserMentions().length); assertEquals(1, status.getURLs().length); User user1 = status.getUserMentions()[0]; assertEquals(20263710, user1.getId()); assertEquals("rabois", user1.getScreenName()); assertEquals("Keith Rabois", user1.getName()); assertEquals(new URL("http://j.mp/cHv0VS"), status.getURLs()[0]); status = twitterAPI2.showStatus(22043496385L); assertEquals(2, status.getHashtags().length); assertEquals("pilaf", status.getHashtags()[0]); assertEquals("recipe", status.getHashtags()[1]); } }
package com.rultor.agents.github.qtn; import com.jcabi.aspects.Immutable; import com.jcabi.github.Comment; import com.jcabi.github.Content; import com.jcabi.github.Contents; import com.jcabi.log.Logger; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; import com.rultor.agents.github.Answer; import com.rultor.agents.github.Question; import com.rultor.agents.github.Req; import java.io.IOException; import java.net.URI; import java.util.ResourceBundle; import javax.json.Json; import lombok.EqualsAndHashCode; import lombok.ToString; import org.xembly.Directive; import org.xembly.Directives; import org.xembly.Xembler; /** * Unlock branch. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.53 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @Immutable @ToString @EqualsAndHashCode public final class QnUnlock implements Question { /** * Message bundle. */ private static final String PATH = ".rultor.lock"; /** * Message bundle. */ private static final ResourceBundle PHRASES = ResourceBundle.getBundle("phrases"); @Override public Req understand(final Comment.Smart comment, final URI home) throws IOException { final XML args = QnUnlock.args(comment, home); final String branch; if (args.nodes("//arg[@name='branch']").isEmpty()) { branch = "master"; } else { branch = args.xpath("//arg[@name='branch']/text()").get(0); } final Contents contents = comment.issue().repo().contents(); if (contents.exists(QnUnlock.PATH, branch)) { contents.remove( Json.createObjectBuilder() .add("path", QnUnlock.PATH) .add( "sha", new Content.Smart( contents.get(QnUnlock.PATH, branch) ).sha() ) .add( "message", String.format( "#%d branch \"%s\" unlocked, by request of @%s", comment.issue().number(), branch, comment.author().login() ) ) .add("branch", branch) .build() ); new Answer(comment).post( String.format( QnUnlock.PHRASES.getString("QnUnlock.response"), branch ) ); } else { new Answer(comment).post( String.format( QnUnlock.PHRASES.getString("QnUnlock.does-not-exist"), branch ) ); } Logger.info(this, "unlock request in #%d", comment.issue().number()); return Req.DONE; } /** * Get args. * @param comment The comment * @param home Home * @return Args * @throws IOException If fails */ private static XML args(final Comment.Smart comment, final URI home) throws IOException { return new XMLDocument( new Xembler( new Directives().add("args").up().append( new QnParametrized( new Question() { @Override public Req understand(final Comment.Smart cmt, final URI hme) { return new Req() { @Override public Iterable<Directive> dirs() { return new Directives().xpath("/"); } }; } } ).understand(comment, home).dirs() ) ).xmlQuietly() ); } }
package mx.ambmultimedia.brillamexico; import android.content.Context; import android.content.Intent; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.UiLifecycleHelper; import com.facebook.model.GraphUser; import com.facebook.widget.LoginButton; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.apache.http.Header; import org.json.JSONObject; import java.util.Arrays; public class LoginStep5 extends FragmentActivity { Context ctx; Config config; private String Nombre; private int CampoDeAccion; private Boolean isReturn; private UiLifecycleHelper uiHelper; private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session session, SessionState sessionState, Exception e) { onSessionChange (session, sessionState, e); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_step5); ctx = this; config = new Config(ctx); /*** * Obteniendo datos del activity anterior */ Bundle bundle = getIntent().getExtras(); CampoDeAccion = bundle.getInt("CampoDeAccion"); Nombre = bundle.getString("Nombre"); isReturn = Boolean.valueOf(bundle.getString("ReturnUser")); String pHiText = getString(R.string.l_text_11); pHiText = pHiText.replaceAll("__username__", Nombre); TextView hiText = (TextView) findViewById(R.id.hiText); if (isReturn) { hiText.setText("¡Hola de nuevo!, por favor vuelve a iniciar sesión"); } else { hiText.setText(Html.fromHtml(pHiText)); } /*** * Creando Login de facebook */ uiHelper = new UiLifecycleHelper(this, callback); uiHelper.onCreate(savedInstanceState); LoginButton loginBtn = (LoginButton) findViewById(R.id.authButton); loginBtn.setPublishPermissions(Arrays.asList("email", "public_profile", "publish_actions")); } @Override protected void onResume() { super.onResume(); Session session = Session.getActiveSession(); if (session != null && (session.isClosed() || session.isOpened())) { onSessionChange(session, session.getState(), null); } uiHelper.onResume(); } @Override protected void onPause() { super.onPause(); uiHelper.onPause(); } @Override protected void onDestroy() { super.onDestroy(); uiHelper.onDestroy(); } @Override protected void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); uiHelper.onSaveInstanceState(bundle); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data); } // Facebook Methods public void onSessionChange (Session session, SessionState sessionState, Exception e) { if (session != null && session.isOpened()) { Log.i("Script", "Dentro"); Request.newMeRequest(session, new Request.GraphUserCallback() { @Override public void onCompleted(GraphUser user, Response response) { if (user != null) { Toast.makeText(ctx, "Bienvenido " + user.getName(), Toast.LENGTH_SHORT).show(); final String fbID = user.getId(); if (!isReturn) { String email = user.getProperty("email").toString(); if (Nombre.isEmpty()) { Nombre = user.getFirstName(); } RequestParams nuevoUsuario = new RequestParams(); nuevoUsuario.put("fbid", fbID); nuevoUsuario.put("twid", ""); nuevoUsuario.put("name", Nombre); nuevoUsuario.put("email", email); nuevoUsuario.put("fieldaction_id", CampoDeAccion); nuevoUsuario.put("gender", user.getProperty("gender").toString()); nuevoUsuario.put("age", ""); String hostname = getString(R.string.hostname); AsyncHttpClient client = new AsyncHttpClient(); client.post(hostname + "/user/register", nuevoUsuario, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { config.set("isLogin", "true"); config.set("fbID", fbID); config.set("Nombre", Nombre); config.set("CampoDeAccion", String.valueOf(CampoDeAccion)); config.set("Puntos", "0"); Intent intent = new Intent(LoginStep5.this, UserProfile.class); startActivity(intent); } @Override public void onFailure(int statusCode, Header[] headers, String response, Throwable e) { Toast.makeText(ctx, "Algo salió mal: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } else { config.set("isLogin", "true"); config.set("fbID", fbID); config.set("Nombre", "unknown"); config.set("CampoDeAccion", ""); config.set("Puntos", "0"); Intent intent = new Intent(LoginStep5.this, UserProfile.class); startActivity(intent); } } } }).executeAsync(); } else { Log.i("Script", "Fuera"); config.set("isLogin", "false"); config.set("fbID", ""); } } }
package com.sdl.bootstrap.button; import com.sdl.selenium.web.WebDriverConfig; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.utils.FileUtils; import org.openqa.selenium.WebDriver; import org.openqa.selenium.interactions.Actions; import java.io.File; public class DownloadFile extends WebLocator implements Download { public DownloadFile() { setClassName("DownloadFile"); setBaseCls("btn"); setTag("button"); } /** * @param container parent */ public DownloadFile(WebLocator container) { this(); setContainer(container); } public DownloadFile(WebLocator container, String label) { this(container); setLabel(label); } /** * if WebDriverConfig.isSilentDownload() is true, se face silentDownload, is is false se face download with AutoIT. * Download file with AutoIT, works only on FireFox. SilentDownload works FireFox and Chrome * Use only this: button.download("C:\\TestSet.tmx"); * return true if the downloaded file is the same one that is meant to be downloaded, otherwise returns false. * * @param fileName e.g. "TestSet.tmx" */ @Override public boolean download(String fileName) { openBrowse(); if (WebDriverConfig.isSilentDownload()) { fileName = WebDriverConfig.getDownloadPath() + File.separator + fileName; File file = new File(fileName); return FileUtils.waitFileIfIsEmpty(file) && fileName.equals(file.getAbsolutePath()); } else { return RunExe.getInstance().download(fileName); } } public void openBrowse() { WebDriver driver = WebDriverConfig.getDriver(); driver.switchTo().window(driver.getWindowHandle()); focus(); Actions builder = new Actions(driver); builder.moveToElement(currentElement).build().perform(); builder.click().build().perform(); driver.switchTo().defaultContent(); } public boolean isDisabled(){ return getAttribute("disabled") != null || getAttributeClass().contains("disabled"); } }
package net.bloople.stories; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE; public class ReadingStoryActivity extends Activity { private RecyclerView nodesView; private LinearLayoutManager layoutManager; private NodesAdapter adapter; private DrawerLayout drawer; private RecyclerView sidebar; private LinearLayoutManager sidebarLayoutManager; private OutlineAdapter outlineAdapter; private Book book; private int savedReadPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reading_story); nodesView = (RecyclerView)findViewById(R.id.nodes_view); nodesView.setItemAnimator(null); layoutManager = new LinearLayoutManager(this); nodesView.setLayoutManager(layoutManager); adapter = new NodesAdapter(); nodesView.setAdapter(adapter); nodesView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if(newState == SCROLL_STATE_IDLE) savePosition(); } }); sidebar = (RecyclerView)findViewById(R.id.sidebar); sidebarLayoutManager = new LinearLayoutManager(this); sidebar.setLayoutManager(sidebarLayoutManager); outlineAdapter = new OutlineAdapter(); sidebar.setAdapter(outlineAdapter); drawer = (DrawerLayout)findViewById(R.id.drawer_layout); Intent intent = getIntent(); book = Book.findById(this, intent.getLongExtra("_id", -1)); ParseStoryTask parser = new ParseStoryTask(); parser.execute(book); } @Override protected void onStop() { super.onStop(); savePosition(); } public void savePosition() { int currentReadPosition = layoutManager.findFirstVisibleItemPosition(); if(savedReadPosition != currentReadPosition) { book.lastReadPosition(currentReadPosition); book.save(this); savedReadPosition = currentReadPosition; } } public void scrollToPosition(int position) { layoutManager.scrollToPositionWithOffset(position, 0); } public void closeDrawers() { drawer.closeDrawers(); } private class ParseStoryTask extends AsyncTask<Book, List<String>, Void> { int BATCH_SIZE = 50; private boolean setPosition = false; protected Void doInBackground(Book... bookArgs) { Book book = bookArgs[0]; try { StoryParser parser = new StoryParser(new BufferedReader(new FileReader(book.path()))); List<String> accumulator = new ArrayList<>(); while(parser.hasNext()) { accumulator.add(parser.next()); if(accumulator.size() >= BATCH_SIZE) { publishProgress(accumulator); accumulator = new ArrayList<>(); } } publishProgress(accumulator); } catch(IOException e) { e.printStackTrace(); } return null; } protected void onProgressUpdate(List<String>... nodesArgs) { int countBefore = adapter.getItemCount(); adapter.addAll(nodesArgs[0]); List<String> outlineNodes = new ArrayList<>(); List<Integer> outlineNodesMap = new ArrayList<>(); for(int i = 0; i < nodesArgs[0].size(); i++) { String node = nodesArgs[0].get(i); if(NodeRenderer.isOutline(node)) { outlineNodes.add(node); outlineNodesMap.add(countBefore + i); } } outlineAdapter.addAll(outlineNodes, outlineNodesMap); if(!setPosition && (adapter.getItemCount() >= book.lastReadPosition())) { setPosition = true; int lastReadPosition = book.lastReadPosition(); savedReadPosition = lastReadPosition; scrollToPosition(lastReadPosition); } } protected void onPostExecute(Void result) { } } }
package com.secret.fastalign.main; import jaligner.Alignment; import jaligner.SmithWatermanGotoh; import jaligner.matrix.MatrixLoader; import jaligner.matrix.MatrixLoaderException; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import com.secret.fastalign.general.FastaData; import com.secret.fastalign.general.Sequence; import com.secret.fastalign.utils.IntervalTree; import com.secret.fastalign.utils.Utils; public class EstimateROC { private static final double MIN_IDENTITY = 0.70; private static final double MIN_REF_IDENTITY = MIN_IDENTITY + 0.10; private static final int DEFAULT_NUM_TRIALS = 10000; private static final int DEFAULT_MIN_OVL = 500; private static final boolean DEFAULT_DO_DP = false; private static boolean DEBUG = false; private static class Pair { public int first; public int second; public Pair(int startInRef, int endInRef) { this.first = startInRef; this.second = endInRef; } @SuppressWarnings("unused") public int size() { return (Math.max(this.first, this.second) - Math.min(this.first, this.second) + 1); } } private static class Overlap { public int afirst; public int bfirst; public int asecond; public int bsecond; public boolean isFwd; public String id1; public String id2; public Overlap() { // do nothing } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Overlap Fwd=" + this.isFwd); stringBuilder.append(" Aid="); stringBuilder.append(this.id1); stringBuilder.append(" ("); stringBuilder.append(this.afirst); stringBuilder.append(", "); stringBuilder.append(this.asecond); stringBuilder.append("), Bid="); stringBuilder.append(this.id2); stringBuilder.append(" ("); stringBuilder.append(this.bfirst); stringBuilder.append(", "); stringBuilder.append(this.bsecond); stringBuilder.append(")"); return stringBuilder.toString(); } } private static Random generator = null; public static int seed = 0; private HashMap<String, IntervalTree<Integer>> clusters = new HashMap<String, IntervalTree<Integer>>(); private HashMap<String, String> seqToChr = new HashMap<String, String>(10000000); private HashMap<String, Integer> seqToScore = new HashMap<String, Integer>(10000000); private HashMap<String, Pair> seqToPosition = new HashMap<String, Pair>(10000000); private HashMap<Integer, String> seqToName = new HashMap<Integer, String>(10000000); private HashMap<String, Integer> seqNameToIndex = new HashMap<String, Integer>(10000000); private HashSet<String> ovlNames = new HashSet<String>(10000000*10); private HashMap<String, Overlap> ovlInfo = new HashMap<String, Overlap>(10000000*10); private HashMap<Integer, String> ovlToName = new HashMap<Integer, String>(10000000*10); private int minOvlLen = DEFAULT_MIN_OVL; private int numTrials = DEFAULT_NUM_TRIALS; private boolean doDP = false; private long tp = 0; private long fn = 0; private long tn = 0; private long fp = 0; private double ppv = 0; private Sequence[] dataSeq = null; public static void printUsage() { System.err .println("This program uses random sampling to estimate PPV/Sensitivity/Specificity"); System.err.println("The program requires 2 arguments:"); System.err .println("\t1. A blasr M4 file mapping sequences to a reference (or reference subset)"); System.err .println("\t2. All-vs-all mappings of same sequences in CA ovl format"); System.err .println("\t3. Fasta sequences"); System.err.println("\t4. Minimum overlap length (default: " + DEFAULT_MIN_OVL); System.err.println("\t5. Number of random trials, 0 means full compute (default : " + DEFAULT_NUM_TRIALS); System.err.println("\t6. Compute DP during PPV true/false"); System.err.println("\t7. Debug output true/false"); } public static void main(String[] args) throws Exception { if (args.length < 3) { printUsage(); System.exit(1); } EstimateROC g = null; if (args.length > 5) { g = new EstimateROC(Integer.parseInt(args[3]), Integer.parseInt(args[4]), Boolean.parseBoolean(args[5])); } else if (args.length > 4) { g = new EstimateROC(Integer.parseInt(args[3]), Integer.parseInt(args[4])); } else if (args.length > 3) { g = new EstimateROC(Integer.parseInt(args[3])); } else { g = new EstimateROC(); } if (args.length > 6) { DEBUG = Boolean.parseBoolean(args[6]); } System.err.println("Running, reference: " + args[0] + " matches: " + args[1]); System.err.println("Number trials: " + (g.numTrials == 0 ? "all" : g.numTrials)); System.err.println("Minimum ovl: " + g.minOvlLen); // load and cluster reference System.err.print("Loading reference..."); long startTime = System.nanoTime(); long totalTime = startTime; g.processReference(args[0]); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); // load fasta System.err.print("Loading fasta..."); startTime = System.nanoTime(); g.loadFasta(args[2]); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); // load matches System.err.print("Loading matches..."); startTime = System.nanoTime(); g.processOverlaps(args[1]); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); if (g.numTrials == 0) { System.err.print("Computing full statistics O(" + g.seqToName.size() + "^2) operations!..."); startTime = System.nanoTime(); g.fullEstimate(); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); } else { System.err.print("Computing sensitivity..."); startTime = System.nanoTime(); g.estimateSensitivity(); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); // now estimate FP/TN by picking random match and checking reference // mapping System.err.print("Computing specificity..."); startTime = System.nanoTime(); g.estimateSpecificity(); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); // last but not least PPV, pick random subset of our matches and see what percentage are true System.err.print("Computing PPV..."); startTime = System.nanoTime(); g.estimatePPV(); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); } System.err.println("Total time: " + (System.nanoTime() - totalTime) * 1.0e-9 + "s."); System.out.println("Estimated sensitivity:\t" + Utils.DECIMAL_FORMAT.format((double) g.tp / (double)(g.tp + g.fn))); System.out.println("Estimated specificity:\t" + Utils.DECIMAL_FORMAT.format((double) g.tn / (double)(g.fp + g.tn))); System.out.println("Estimated PPV:\t " + Utils.DECIMAL_FORMAT.format(g.ppv)); } public EstimateROC() { this(DEFAULT_MIN_OVL, DEFAULT_NUM_TRIALS); } public EstimateROC(int minOvlLen) { this(minOvlLen, DEFAULT_NUM_TRIALS); } public EstimateROC(int minOvlLen, int numTrials) { this(minOvlLen, numTrials, DEFAULT_DO_DP); } @SuppressWarnings("unused") public EstimateROC(int minOvlLen, int numTrials, boolean doDP) { this.minOvlLen = minOvlLen; this.numTrials = numTrials; this.doDP = doDP; if (false) { GregorianCalendar t = new GregorianCalendar(); int t1 = t.get(Calendar.SECOND); int t2 = t.get(Calendar.MINUTE); int t3 = t.get(Calendar.HOUR_OF_DAY); int t4 = t.get(Calendar.DAY_OF_MONTH); int t5 = t.get(Calendar.MONTH); int t6 = t.get(Calendar.YEAR); seed = t6 + 65 * (t5 + 12 * (t4 + 31 * (t3 + 24 * (t2 + 60 * t1)))); } generator = new Random(seed); } private static String getOvlName(String id, String id2) { return (id.compareTo(id2) <= 0 ? id + "_" + id2 : id2 + "_" + id); } private String pickRandomSequence() { int val = generator.nextInt(this.seqToName.size()); return this.seqToName.get(val); } private String pickRandomMatch() { int val = generator.nextInt(this.ovlToName.size()); return this.ovlToName.get(val); } private int getOverlapSize(String id, String id2) { String chr = this.seqToChr.get(id); String chr2 = this.seqToChr.get(id2); Pair p1 = this.seqToPosition.get(id); Pair p2 = this.seqToPosition.get(id2); if (!chr.equalsIgnoreCase(chr2)) { System.err.println("Error: comparing wrong chromosomes betweeen sequences " + id + " and sequence " + id2); System.exit(1); } return Utils.getRangeOverlap(p1.first, p1.second, p2.first, p2.second); } private HashSet<String> getSequenceMatches(String id, int min) { String chr = this.seqToChr.get(id); Pair p1 = this.seqToPosition.get(id); List<Integer> intersect = this.clusters.get(chr).get(p1.first, p1.second); HashSet<String> result = new HashSet<String>(); Iterator<Integer> it = intersect.iterator(); while (it.hasNext()) { String id2 = this.seqToName.get(it.next()); Pair p2 = this.seqToPosition.get(id2); String chr2 = this.seqToChr.get(id2); if (!chr.equalsIgnoreCase(chr2)) { System.err.println("Error: comparing wrong chromosomes betweeen sequences " + id + " and sequence in its cluster " + id2); System.exit(1); } int overlap = Utils.getRangeOverlap(p1.first, p1.second, p2.first, p2.second); if (overlap >= min && !id.equalsIgnoreCase(id2)) { result.add(id2); } } return result; } private Overlap getOverlapInfo(String line) { Overlap overlap = new Overlap(); String[] splitLine = line.trim().split("\\s+"); try { if (splitLine.length == 7 || splitLine.length == 6) { overlap.id1 = splitLine[0]; overlap.id2 = splitLine[1]; @SuppressWarnings("unused") double score = Double.parseDouble(splitLine[5]) * 5; int aoffset = Integer.parseInt(splitLine[3]); int boffset = Integer.parseInt(splitLine[4]); overlap.isFwd = "N".equalsIgnoreCase(splitLine[2]); if (this.dataSeq != null) { int alen = this.dataSeq[Integer.parseInt(overlap.id1)-1].length(); int blen = this.dataSeq[Integer.parseInt(overlap.id2)-1].length(); overlap.afirst = Math.max(0, aoffset); overlap.asecond = Math.min(alen, alen + boffset); overlap.bfirst = -1*Math.min(0, aoffset); overlap.bsecond = Math.min(blen, blen - boffset); } } else if (splitLine.length == 13) { overlap.afirst = Integer.parseInt(splitLine[5]); overlap.asecond = Integer.parseInt(splitLine[6]); overlap.bfirst = Integer.parseInt(splitLine[9]); overlap.bsecond = Integer.parseInt(splitLine[10]); overlap.isFwd = (Integer.parseInt(splitLine[8]) == 0); if (!overlap.isFwd) { overlap.bsecond = Integer.parseInt(splitLine[11]) - Integer.parseInt(splitLine[9]); overlap.bfirst = Integer.parseInt(splitLine[11]) - Integer.parseInt(splitLine[10]); } overlap.id1 = splitLine[0]; if (overlap.id1.indexOf("/") != -1) { overlap.id1 = overlap.id1.substring(0, splitLine[0].indexOf("/")); } if (overlap.id1.indexOf(",") != -1) { overlap.id1 = overlap.id1.split(",")[1]; } overlap.id2 = splitLine[1]; if (overlap.id2.indexOf(",") != -1) { overlap.id2 = overlap.id2.split(",")[1]; } } } catch (NumberFormatException e) { System.err.println("Warning: could not parse input line: " + line + " " + e.getMessage()); } return overlap; } private void loadFasta(String file) throws IOException { FastaData data = new FastaData(file, 0); data.enqueueFullFile(); this.dataSeq = data.toArray(); } private void processOverlaps(String file) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader( new FileInputStream(file))); String line = null; int counter = 0; while ((line = bf.readLine()) != null) { Overlap ovl = getOverlapInfo(line); String id = ovl.id1; String id2 = ovl.id2; if (id == null || id2 == null) { continue; } if (id.equalsIgnoreCase(id2)) { continue; } if (this.seqToChr.get(id) == null || this.seqToChr.get(id2) == null) { continue; } String ovlName = getOvlName(id, id2); if (this.ovlNames.contains(ovlName)) { continue; } this.ovlNames.add(ovlName); this.ovlToName.put(counter, ovlName); this.ovlInfo.put(ovlName, ovl); counter++; if (counter % 100000 == 0) { System.err.println("Loaded " + counter); } } System.err.print("Processed " + this.ovlNames.size() + " overlaps"); if (this.ovlNames.isEmpty()) { System.err .println("Error: No sequence matches to reference loaded!"); System.exit(1); } bf.close(); } /** * We are parsing file of the format 18903/0_100 ref000001|lambda_NEB3011 * -462 96.9697 0 0 99 100 0 2 101 48502 254 21589/0_100 * ref000001|lambda_NEB3011 -500 100 0 0 100 100 1 4 104 48502 254 * 15630/0_100 ref000001|lambda_NEB3011 -478 98 0 0 100 100 0 5 105 48502 * 254 **/ @SuppressWarnings("unused") private void processReference(String file) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader( new FileInputStream(file))); String line = null; int counter = 0; while ((line = bf.readLine()) != null) { String[] splitLine = line.trim().split("\\s+"); String id = splitLine[0]; if (id.indexOf("/") != -1) { id = id.substring(0, splitLine[0].indexOf("/")); } if (id.indexOf(",") != -1) { id = id.split(",")[1]; } double idy = Double.parseDouble(splitLine[3]); int start = Integer.parseInt(splitLine[5]); int end = Integer.parseInt(splitLine[6]); int length = Integer.parseInt(splitLine[7]); int seqIsFwd = Integer.parseInt(splitLine[4]); if (seqIsFwd != 0) { System.err.println("Error: malformed line, first sequences should always be in fwd orientation"); System.exit(1); } int startInRef = Integer.parseInt(splitLine[9]); int endInRef = Integer.parseInt(splitLine[10]); int refLen = Integer.parseInt(splitLine[11]); int isRev = Integer.parseInt(splitLine[8]); int score = Integer.parseInt(splitLine[2]); if (isRev == 1) { int tmp = refLen - endInRef; endInRef = refLen - startInRef; startInRef = tmp; } if (idy < MIN_REF_IDENTITY) { continue; } String chr = splitLine[1]; if (!this.clusters.containsKey(chr)) { this.clusters.put(chr, new IntervalTree<Integer>()); } if (this.seqToPosition.containsKey(id)) { if (score < this.seqToScore.get(id)) { // replace this.seqToPosition.put(id, new Pair(startInRef, endInRef)); this.seqToChr.put(id, chr); this.seqToScore.put(id, score); } } else { this.seqToPosition.put(id, new Pair(startInRef, endInRef)); this.seqToChr.put(id, chr); this.seqToName.put(counter, id); this.seqNameToIndex.put(id, counter); this.seqToScore.put(id, score); counter++; } } bf.close(); for (String id : this.seqToPosition.keySet()) { String chr = this.seqToChr.get(id); if (!this.clusters.containsKey(chr)) { this.clusters.put(chr, new IntervalTree<Integer>()); } Pair p = this.seqToPosition.get(id); this.clusters.get(chr).addInterval(p.first, p.second, this.seqNameToIndex.get(id)); } System.err.print("Processed " + this.clusters.size() + " chromosomes, " + this.seqToPosition.size() + " sequences matching ref"); if (this.seqToPosition.isEmpty()) { System.err .println("Error: No sequence matches to reference loaded!"); System.exit(1); } } private boolean overlapExists(String id, String id2) { return this.ovlNames.contains(getOvlName(id, id2)); } private boolean overlapMatches(String id, String m) { int refOverlap = getOverlapSize(id, m); Overlap ovl = this.ovlInfo.get(getOvlName(id, m)); if (ovl == null) { return false; } int observedOverlap = Utils.getRangeOverlap(ovl.afirst, ovl.asecond, ovl.bfirst, ovl.bsecond); int diff = Math.abs(observedOverlap - refOverlap); double overlapRatio = (double)diff / (double) refOverlap; return (overlapRatio < 0.3); } private void checkMatches(String id, HashSet<String> matches) { for (String m : matches) { if (overlapMatches(id, m)) { this.tp++; } else { this.fn++; if (DEBUG) { System.err.println("Overlap between sequences: " + id + ", " + m + " is missing."); System.err.println(">" + id + " reference location " + this.seqToChr.get(id) + " " + this.seqToPosition.get(id).first + ", " + this.seqToPosition.get(id).second); System.err.println(this.dataSeq[Integer.parseInt(id)-1].getString()); System.err.println(">" + m + " reference location " + this.seqToChr.get(m) + " " + this.seqToPosition.get(m).first + ", " + this.seqToPosition.get(m).second); System.err.println(this.dataSeq[Integer.parseInt(m)-1].getString()); } } } } private boolean computeDP(String id, String id2) { if (this.doDP == false) { return false; } Logger logger = Logger.getLogger(SmithWatermanGotoh.class.getName()); logger.setLevel(Level.OFF); logger = Logger.getLogger(MatrixLoader.class.getName()); logger.setLevel(Level.OFF); Overlap ovl = this.ovlInfo.get(getOvlName(id, id2)); jaligner.Sequence s1 = new jaligner.Sequence(this.dataSeq[Integer.parseInt(ovl.id1)-1].getString().substring(ovl.afirst, ovl.asecond)); jaligner.Sequence s2 = null; if (ovl.isFwd) { s2 = new jaligner.Sequence(this.dataSeq[Integer.parseInt(ovl.id2)-1].getString().substring(ovl.bfirst, ovl.bsecond)); } else { s2 = new jaligner.Sequence(this.dataSeq[Integer.parseInt(ovl.id2)-1].getReverseCompliment().getString().substring(ovl.bfirst, ovl.bsecond)); } Alignment alignment; try { alignment = SmithWatermanGotoh.align(s1, s2, MatrixLoader.load("IDENTITY"), 2f, 1f); } catch (MatrixLoaderException e) { return false; } return (AlignmentHashRun.getScoreWithNoTerminalGaps(alignment) > MIN_IDENTITY); } private void estimateSensitivity() { // we estimate TP/FN by randomly picking a sequence, getting its // cluster, and checking our matches for (int i = 0; i < this.numTrials; i++) { String id = null; HashSet<String> matches = null; while (matches == null || matches.size() == 0) { // pick cluster id = pickRandomSequence(); matches = getSequenceMatches(id, this.minOvlLen); } if (DEBUG) { System.err.println("Estimated sensitivity trial #" + i + " " + id + " matches " + matches); } checkMatches(id, matches); } } private void estimateSpecificity() { // we estimate FP/TN by randomly picking two sequences for (int i = 0; i < this.numTrials; i++) { // pick cluster String id = pickRandomSequence(); String other = pickRandomSequence(); while (id.equalsIgnoreCase(other)) { other = pickRandomSequence(); } HashSet<String> matches = getSequenceMatches(id, 0); if (overlapExists(id, other)) { if (!matches.contains(other)) { this.fp++; } } else { if (!matches.contains(other)) { this.tn++; } } } } private void estimatePPV() { int numTP = 0; for (int i = 0; i < this.numTrials; i++) { int ovlLen = 0; String[] ovl = null; String ovlName = null; while (ovlLen < this.minOvlLen) { // pick an overlap ovlName = pickRandomMatch(); Overlap o = this.ovlInfo.get(ovlName); ovlLen = Utils.getRangeOverlap(o.afirst, o.asecond, o.bfirst, o.bsecond); } if (ovlName == null) { System.err.println("Could not find any computed overlaps > " + this.minOvlLen); System.exit(1); } else { ovl = ovlName.split("_"); String id = ovl[0]; String id2 = ovl[1]; HashSet<String> matches = getSequenceMatches(id, 0); if (matches.contains(id2)) { numTP++; } else { if (computeDP(id, id2)) { numTP++; } else { if (DEBUG) { System.err.println("Overlap between sequences: " + id + ", " + id2 + " is not correct."); } } } } } // now our formula for PPV. Estimate percent of our matches which are true this.ppv = (double)numTP / (double)this.numTrials; } @SuppressWarnings("cast") private void fullEstimate() { for (int i = 0; i < this.seqToName.size(); i++) { String id = this.seqToName.get(i); for (int j = i+1; j < this.seqToName.size(); j++) { String id2 = this.seqToName.get(j); if (id == null || id2 == null) { continue; } HashSet<String> matches = getSequenceMatches(id, 0); if (!overlapMatches(id, id2)) { if (!matches.contains(id2)) { this.tn++; } else if (getOverlapSize(id, id2) > this.minOvlLen) { this.fn++; } } else { if (matches.contains(id2)) { this.tp++; } else { if (computeDP(id, id2)) { this.tp++; } else { this.fp++; } } } } } this.ppv = (double) this.tp / ((double)this.tp+(double)this.fp); } }
package com.spaceapplications.yamcs.scpi; import static pl.touk.throwing.ThrowingSupplier.unchecked; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; public class Main { public static Integer DEFAULT_PORT = 1337; public static Integer MAX_INOMING_CONNECTIONS = 5; public static void main(String[] args) { EventLoopGroup bossEventLoop = new NioEventLoopGroup(); EventLoopGroup workerEventLoop = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossEventLoop, workerEventLoop) .channel(NioServerSocketChannel.class) // Set up a TCP server .option(ChannelOption.SO_BACKLOG, MAX_INOMING_CONNECTIONS) .handler(new LoggingHandler(LogLevel.INFO)) // Handler for boss channel (incl. port binding, accepting // connections, etc.) .childHandler(new ServerInitializer()); // Handler for worker channel (incl. receiving new data, etc.) ChannelFuture f = unchecked(bootstrap.bind(DEFAULT_PORT)::sync).get(); unchecked(f.channel().closeFuture()::sync).get(); } finally { bossEventLoop.shutdownGracefully(); workerEventLoop.shutdownGracefully(); } } }
package thomasc.loananalyzer.loans; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import thomasc.loananalyzer.common.LoanMath; import thomasc.loananalyzer.common.LoanUtils; public class PrincipalLoan extends BaseLoan { public PrincipalLoan() { super(); setLoanType(LoanType.PRINCIPAL); } @Override public LoanError compute() { LoanError error = validate(); if (error != LoanError.SUCCESS) { return error; } switch (getPaymentType()) { case AMOUNT: double f = (getIntervals() * getAmount()) - getPrincipal(); setPeriodicRate(f / getIntervals() / getPrincipal()); setAnnualRate(getPeriodicRate() * getPeriodsPerYear()); break; case ANNUAL_RATE: setPeriodicRate(getAnnualRate() / getPeriodsPerYear()); setAmount((getPrincipal() / getIntervals()) + (getPrincipal() * getPeriodicRate())); break; case PERIODIC_RATE: setAnnualRate(getPeriodicRate() * getPeriodsPerYear()); setAmount((getPrincipal() / getIntervals()) + (getPrincipal() * getPeriodicRate())); break; } setEap(LoanMath.calcPeriodicRate( getPrincipal(), getAmount() + getPeriodicFee(), getIntervals()) * getPeriodsPerYear()); return LoanError.SUCCESS; } @Override public List<Payment> getPayments() { ArrayList<Payment> payments = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); calendar.setTime(getFirstPayment()); double balance = getAmount() * getIntervals(); for (int no = 0; no <= getIntervals(); no++) { Payment p = new Payment(); p.setNo(no); if (p.getNo() == 0) { p.setDate(new Date(0)); p.setAmount(0); } else { p.setDate(calendar.getTime()); p.setAmount(getAmount()); } p.setInterest(0); p.setBalance(balance - p.getNo() * getAmount()); payments.add(p); if (p.getNo() > 0) { LoanUtils.calendarAdd(calendar, getIntervalType(), getIntervalTypeTimes()); } } return payments; } }
package zero.zd.zquestionnaire; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; import zero.zd.zquestionnaire.model.QnA; public class QnaAnswerActivity extends AppCompatActivity { private static final String TAG = QnaAnswerActivity.class.getSimpleName(); private static final String EXTRA_IS_MISTAKE_LOADED = "EXTRA_IS_MISTAKE_LOADED"; private static final String SAVED_QNA_INDEX = "SAVED_QNA_INDEX"; private static final String SAVED_ANSWER_LOCATION_INDEX = "SAVED_ANSWER_LOCATION_INDEX"; private static final String SAVED_CORRECT_ANSWER = "SAVED_CORRECT_ANSWER"; private static final String SAVED_MISTAKE_ANSWER = "SAVED_MISTAKE_ANSWER"; private static final String SAVED_IS_INITIALIZED = "SAVED_IS_INITIALIZED"; RadioGroup mRadioGroup; Button mOkButton; TextView mTextQuestion; private ArrayList<QnA> mQnaList; private ArrayList<QnA> mMistakeQnaList; private int mQnaIndex; private int mAnswerLocationIndex; private int mCorrect; private int mMistake; private boolean isInitialized; public static Intent getStartIntent(Context context, boolean isMistakesLoaded) { Intent intent = new Intent(context, QnaAnswerActivity.class); intent.putExtra(EXTRA_IS_MISTAKE_LOADED, isMistakesLoaded); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qna_answer); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(QnaState.getInstance().getQnaSubject().getSubjectName()); actionBar.setDisplayHomeAsUpEnabled(true); } mOkButton = (Button) findViewById(R.id.btn_ok); mRadioGroup = (RadioGroup) findViewById(R.id.radio_group); mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { if (isInitialized) mOkButton.setEnabled(true); } }); mTextQuestion = (TextView) findViewById(R.id.text_question); mQnaList = new ArrayList<>(); mMistakeQnaList = new ArrayList<>(); // check if mistake is loaded boolean isMistakesLoaded = getIntent() .getBooleanExtra(EXTRA_IS_MISTAKE_LOADED, false); if (isMistakesLoaded) { mQnaList = new ArrayList<>(QnaState.getInstance().getMistakeQnaList()); QnaState.getInstance().setQnaList(mQnaList); Log.d(TAG, "mQnaList Size: " + mQnaList.size()); mMistakeQnaList.clear(); Log.d(TAG, "Clean mistakeList"); Log.d(TAG, "mQnaList Size: " + mQnaList.size()); Log.d(TAG, "Mistakes Loaded!"); } // set qna list mQnaList = QnaState.getInstance().getQnaList(!isMistakesLoaded); Collections.shuffle(mQnaList); // retrieve saved instances if (savedInstanceState != null) { mMistakeQnaList = new ArrayList<>(); mQnaList = new ArrayList<>(); mMistakeQnaList = QnaState.getInstance().getMistakeQnaList(); mQnaList = QnaState.getInstance().getQnaList(false); mQnaIndex = savedInstanceState.getInt(SAVED_QNA_INDEX); mAnswerLocationIndex = savedInstanceState.getInt(SAVED_ANSWER_LOCATION_INDEX); mCorrect = savedInstanceState.getInt(SAVED_CORRECT_ANSWER); mMistake = savedInstanceState.getInt(SAVED_MISTAKE_ANSWER); isInitialized = savedInstanceState.getBoolean(SAVED_IS_INITIALIZED); updateQuestionText(); Log.d(TAG, "Activity recreated."); } else { mQnaIndex = 0; initQnA(); Log.d(TAG, "Activity initialized."); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); QnaState.getInstance().setQnaList(mQnaList); QnaState.getInstance().setMistakeQnaList(mMistakeQnaList); outState.putInt(SAVED_QNA_INDEX, mQnaIndex); outState.putInt(SAVED_ANSWER_LOCATION_INDEX, mAnswerLocationIndex); outState.putInt(SAVED_CORRECT_ANSWER, mCorrect); outState.putInt(SAVED_MISTAKE_ANSWER, mMistake); outState.putBoolean(SAVED_IS_INITIALIZED, isInitialized); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_qna_answer, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.action_reset: resetQnA(); break; case R.id.action_quit: Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); break; } return super.onOptionsItemSelected(item); } /** * Methods for to check if answer is correct, * and update QnA */ public void onClickOk(View view) { // get radio location RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group); int selectedRadioButton = radioGroup.indexOfChild(radioGroup .findViewById(radioGroup.getCheckedRadioButtonId())); if (selectedRadioButton != mAnswerLocationIndex) { // add QnA to mistake list mMistakeQnaList.add(mQnaList.get(mQnaIndex)); showMistakeDialog(); mMistake++; } else { Snackbar.make(view, R.string.msg_correct, Snackbar.LENGTH_SHORT).show(); mCorrect++; updateQna(); } } /** * Method to initialize a question and answer, * updates GUI and will run on every increment of mQnaIndex */ private void initQnA() { updateQuestionText(); int[] randIndices = new int[3]; randIndices[0] = getRandomIndex(); for (int i = 1; i < 3; i++) { while (true) { int x = getRandomIndex(); if (!isRandomIndexExists(randIndices, x)) { randIndices[i] = x; break; } } } Log.i(TAG, "Random Indices: " + Arrays.toString(randIndices)); Random random = new Random(); mAnswerLocationIndex = random.nextInt(4); RadioButton btnOne = (RadioButton) findViewById(R.id.radio_one); RadioButton btnTwo = (RadioButton) findViewById(R.id.radio_two); RadioButton btnThree = (RadioButton) findViewById(R.id.radio_three); RadioButton btnFour = (RadioButton) findViewById(R.id.radio_four); ArrayList<RadioButton> radioList = new ArrayList<>(); radioList.add(btnOne); radioList.add(btnTwo); radioList.add(btnThree); radioList.add(btnFour); // Log.i(TAG, "AnswerLoc: " + mAnswerLocationIndex); radioList.get(mAnswerLocationIndex).setText(mQnaList.get(mQnaIndex).getAnswer()); int randIndex = 0; for (int i = 0; i < 4; i++) { if (i == mAnswerLocationIndex) continue; radioList.get(i).setText(mQnaList.get(randIndices[randIndex]).getAnswer()); randIndex++; } TextView txtProgress = (TextView) findViewById(R.id.text_progress); txtProgress.setText(String.format(getResources().getString(R.string.msg_progress), mQnaIndex + 1, mQnaList.size(), mCorrect, mMistake)); mRadioGroup.clearCheck(); isInitialized = true; } /** * Checks if the answer index generated from {@code getRandomIndex()} * if the index already exists on the generated index on array * {@code randIndices} for 3 invalid answers * * @param arr the array of 3 index of invalid answers to check * @param target the newly generated index to compare to {@code arr} * @return {@code true} if the array randIndices already contains the * newly generated index of answer * {@code false} no same index or answer already existed at {@code randIndices} * @see #getRandomIndex() */ private boolean isRandomIndexExists(int[] arr, int target) { for (int x : arr) if (x == target || mQnaList.get(x).getAnswer() .equalsIgnoreCase(mQnaList.get(target).getAnswer())) return true; return false; } /** * Generates an invalid random answer index and returns an index * which is not the same as the answer * * @return random index */ private int getRandomIndex() { // @TODO: if list is < 4 app crashes if (mQnaList.size() < 4) throw new AssertionError("List must be at least 4"); Random random = new Random(); while (true) { int x = random.nextInt(mQnaList.size()); if (x != mQnaIndex && !mQnaList.get(x).getAnswer() .equalsIgnoreCase(mQnaList.get(mQnaIndex).getAnswer())) return x; } } /** * Resets the states of the variables, for resetting QnA */ private void resetQnA() { mQnaIndex = 0; mCorrect = 0; mMistake = 0; mQnaList = QnaState.getInstance().getQnaList(true); initQnA(); Snackbar.make(getWindow().getDecorView().getRootView(), R.string.msg_reset, Snackbar.LENGTH_SHORT).show(); } private void updateQna() { mQnaIndex++; if (mQnaIndex == mQnaList.size()) { showResultActivity(); return; } initQnA(); mOkButton.setEnabled(false); } private void updateQuestionText() { mTextQuestion.setText(mQnaList.get(mQnaIndex).getQuestion()); } private void showMistakeDialog() { String msg = "Correct Answer: \n" + mQnaList.get(mQnaIndex).getAnswer(); new AlertDialog.Builder(QnaAnswerActivity.this) .setTitle(R.string.msg_mistake) .setMessage(msg) .setCancelable(false) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { updateQna(); dialog.dismiss(); } }) .show(); } private void showResultActivity() { // update mistake list QnaState.getInstance().setQnaList(mQnaList); QnaState.getInstance().setMistakeQnaList(mMistakeQnaList); // get passing String assessment = "Failed!"; int passingCorrectPoints = mQnaList.size() / 2; if (mCorrect >= passingCorrectPoints) assessment = "Passed!"; startActivity(QnaResultActivity .getStartIntent(this, assessment, mCorrect)); finish(); } }
package com.taskadapter.redmineapi.bean; import com.taskadapter.redmineapi.Include; import com.taskadapter.redmineapi.NotFoundException; import com.taskadapter.redmineapi.RedmineAuthenticationException; import com.taskadapter.redmineapi.RedmineException; import com.taskadapter.redmineapi.internal.RequestParam; import com.taskadapter.redmineapi.internal.Transport; import java.util.*; public class Issue implements Identifiable, FluentStyle { private final PropertyStorage storage = new PropertyStorage(); public final static Property<Integer> DATABASE_ID = new Property<>(Integer.class, "id"); public final static Property<String> SUBJECT = new Property<>(String.class, "subject"); public final static Property<Date> START_DATE = new Property<>(Date.class, "startDate"); public final static Property<Date> DUE_DATE = new Property<>(Date.class, "dueDate"); public final static Property<Date> CREATED_ON = new Property<>(Date.class, "createdOn"); public final static Property<Date> UPDATED_ON = new Property<>(Date.class, "updatedOn"); public final static Property<Integer> DONE_RATIO = new Property<>(Integer.class, "doneRatio"); public final static Property<Integer> PARENT_ID = new Property<>(Integer.class, "parentId"); public final static Property<Integer> PRIORITY_ID = new Property<>(Integer.class, "priorityId"); public final static Property<Float> ESTIMATED_HOURS = new Property<>(Float.class, "estimatedHours"); public final static Property<Float> SPENT_HOURS = new Property<>(Float.class, "spentHours"); public final static Property<Integer> ASSIGNEE_ID = new Property<>(Integer.class, "assigneeId"); public final static Property<String> ASSIGNEE_NAME = new Property<>(String.class, "assigneeName"); /** * Some comment describing an issue update. */ public final static Property<String> NOTES = new Property<String>(String.class, "notes"); public final static Property<Boolean> PRIVATE_NOTES = new Property<>(Boolean.class, "notes"); public final static Property<String> PRIORITY_TEXT = new Property<>(String.class, "priorityText"); public final static Property<Integer> PROJECT_ID = new Property<>(Integer.class, "projectId"); public final static Property<String> PROJECT_NAME = new Property<>(String.class, "projectName"); public final static Property<Integer> AUTHOR_ID = new Property<>(Integer.class, "authorId"); public final static Property<String> AUTHOR_NAME = new Property<>(String.class, "authorName"); public final static Property<Tracker> TRACKER = new Property<>(Tracker.class, "tracker"); public final static Property<String> DESCRIPTION = new Property<>(String.class, "description"); public final static Property<Date> CLOSED_ON = new Property<>(Date.class, "closedOn"); public final static Property<Integer> STATUS_ID = new Property<>(Integer.class, "statusId"); public final static Property<String> STATUS_NAME = new Property<>(String.class, "statusName"); public final static Property<Version> TARGET_VERSION = new Property<>(Version.class, "targetVersion"); public final static Property<IssueCategory> ISSUE_CATEGORY = new Property<>(IssueCategory.class, "issueCategory"); public final static Property<Boolean> PRIVATE_ISSUE = new Property<>(Boolean.class, "privateIssue"); /** * can't have two custom fields with the same ID in the collection, that's why it is declared * as a Set, not a List. */ public final static Property<Set<CustomField>> CUSTOM_FIELDS = (Property<Set<CustomField>>) new Property(Set.class, "customFields"); public final static Property<Set<Journal>> JOURNALS = (Property<Set<Journal>>) new Property(Set.class, "journals"); public final static Property<Set<IssueRelation>> RELATIONS = (Property<Set<IssueRelation>>) new Property(Set.class, "relations"); public final static Property<Set<Attachment>> ATTACHMENTS = (Property<Set<Attachment>>) new Property(Set.class, "attachments"); public final static Property<Set<Changeset>> CHANGESETS = (Property<Set<Changeset>>) new Property(Set.class, "changesets"); public final static Property<Set<Watcher>> WATCHERS = (Property<Set<Watcher>>) new Property(Set.class, "watchers"); public final static Property<Set<Issue>> CHILDREN = (Property<Set<Issue>>) new Property(Set.class, "children"); private Transport transport; public Issue() { initCollections(storage); } public Issue(Transport transport) { this(); setTransport(transport); } /** * Each Issue object must have project Id set in order for Redmine 3.x to accept it via REST API. */ public Issue(Transport transport, int projectId) { this(); this.transport = transport; setProjectId(projectId); } /** * @param projectId Each Issue object must have project Id set in order for Redmine 3.x to accept it via REST API. */ public Issue(Transport transport, int projectId, String subject) { this(); this.transport = transport; setSubject(subject); setProjectId(projectId); } private void initCollections(PropertyStorage storage) { storage.set(CUSTOM_FIELDS, new HashSet<>()); storage.set(CHILDREN, new HashSet<>()); storage.set(WATCHERS, new HashSet<>()); storage.set(CHANGESETS, new HashSet<>()); storage.set(ATTACHMENTS, new HashSet<>()); storage.set(RELATIONS, new HashSet<>()); storage.set(JOURNALS, new HashSet<>()); } public Integer getProjectId() { return storage.get(PROJECT_ID); } public Issue setProjectId(Integer projectId) { storage.set(PROJECT_ID, projectId); return this; } public String getProjectName() { return storage.get(PROJECT_NAME); } public Issue setProjectName(String name) { storage.set(PROJECT_NAME, name); return this; } /** * @param id database ID. */ public Issue setId(Integer id) { storage.set(DATABASE_ID, id); return this; } public Integer getDoneRatio() { return storage.get(DONE_RATIO); } public Issue setDoneRatio(Integer doneRatio) { storage.set(DONE_RATIO, doneRatio); return this; } public String getPriorityText() { return storage.get(PRIORITY_TEXT); } /** * @deprecated This method has no effect when creating issues on Redmine Server, so we might as well just delete it * in the future releases. */ public void setPriorityText(String priority) { storage.set(PRIORITY_TEXT, priority); } /** * Redmine can be configured to allow group assignments for issues: * Configuration option: Settings -> Issue Tracking -> Allow issue assignment to groups * * <p>An assignee can be a user or a group</p> */ public Integer getAssigneeId() { return storage.get(ASSIGNEE_ID); } public Issue setAssigneeId(Integer assigneeId) { storage.set(ASSIGNEE_ID, assigneeId); return this; } public String getAssigneeName() { return storage.get(ASSIGNEE_NAME); } public Issue setAssigneeName(String assigneeName) { storage.set(ASSIGNEE_NAME, assigneeName); return this; } public Float getEstimatedHours() { return storage.get(ESTIMATED_HOURS); } public Issue setEstimatedHours(Float estimatedTime) { storage.set(ESTIMATED_HOURS, estimatedTime); return this; } public Float getSpentHours() { return storage.get(SPENT_HOURS); } public Issue setSpentHours(Float spentHours) { storage.set(SPENT_HOURS, spentHours); return this; } /** * Parent Issue ID, or NULL for issues without a parent. * * @return NULL, if there's no parent */ public Integer getParentId() { return storage.get(PARENT_ID); } public Issue setParentId(Integer parentId) { storage.set(PARENT_ID, parentId); return this; } /** * @return database id for this object. can be NULL for Issues not added to Redmine yet */ @Override public Integer getId() { return storage.get(DATABASE_ID); } public String getSubject() { return storage.get(SUBJECT); } public Issue setSubject(String subject) { storage.set(SUBJECT, subject); return this; } public Date getStartDate() { return storage.get(START_DATE); } public Issue setStartDate(Date startDate) { storage.set(START_DATE, startDate); return this; } public Date getDueDate() { return storage.get(DUE_DATE); } public Issue setDueDate(Date dueDate) { storage.set(DUE_DATE, dueDate); return this; } public Integer getAuthorId() { return storage.get(AUTHOR_ID); } @Deprecated public Issue setAuthorId(Integer id) { storage.set(AUTHOR_ID, id); return this; } public String getAuthorName() { return storage.get(AUTHOR_NAME); } @Deprecated public Issue setAuthorName(String name) { storage.set(AUTHOR_NAME, name); return this; } public Tracker getTracker() { return storage.get(TRACKER); } public Issue setTracker(Tracker tracker) { storage.set(TRACKER, tracker); return this; } public String getDescription() { return storage.get(DESCRIPTION); } public Issue setDescription(String description) { storage.set(DESCRIPTION, description); return this; } public Date getCreatedOn() { return storage.get(CREATED_ON); } public Issue setCreatedOn(Date createdOn) { storage.set(CREATED_ON, createdOn); return this; } public Date getUpdatedOn() { return storage.get(UPDATED_ON); } public Issue setUpdatedOn(Date updatedOn) { storage.set(UPDATED_ON, updatedOn); return this; } public Date getClosedOn() { return storage.get(CLOSED_ON); } public Issue setClosedOn(Date closedOn) { storage.set(CLOSED_ON, closedOn); return this; } public Integer getStatusId() { return storage.get(STATUS_ID); } public Issue setStatusId(Integer statusId) { storage.set(STATUS_ID, statusId); return this; } public String getStatusName() { return storage.get(STATUS_NAME); } public Issue setStatusName(String statusName) { storage.set(STATUS_NAME, statusName); return this; } /** * @return unmodifiable collection of Custom Field objects. the collection may be empty, but it is never NULL. */ public Collection<CustomField> getCustomFields() { return Collections.unmodifiableCollection(storage.get(CUSTOM_FIELDS)); } public Issue clearCustomFields() { storage.set(CUSTOM_FIELDS, new HashSet<>()); return this; } /** * NOTE: The custom field(s) <strong>must have correct database ID set</strong> to be saved to Redmine. * This is Redmine REST API's requirement. */ public Issue addCustomFields(Collection<CustomField> customFields) { storage.get(CUSTOM_FIELDS).addAll(customFields); return this; } /** * If there is a custom field with the same ID already present in the Issue, * the new field replaces the old one. * * @param customField the field to add to the issue. */ public Issue addCustomField(CustomField customField) { storage.get(CUSTOM_FIELDS).add(customField); return this; } @Deprecated /** * This method should not be used by clients. "notes" only makes sense when creating/updating an issue - that is the * string value added along with the update. * <p> * use {@link #getJournals()} if you want to access previously saved notes. feel free to submit an enhancement * request to Redmine developers if you think this "notes - journals" separation looks weird... */ public String getNotes() { return storage.get(NOTES); } /** * @param notes Some comment describing the issue update */ public Issue setNotes(String notes) { storage.set(NOTES, notes); return this; } public boolean isPrivateNotes() { return storage.get(PRIVATE_NOTES); } /** * @param privateNotes mark note as private */ public Issue setPrivateNotes(boolean privateNotes) { storage.set(PRIVATE_NOTES, privateNotes); return this; } /** * Don't forget to use Include.journals flag when loading issue from Redmine server: * <pre> * Issue issue = issueManager.getIssueById(3205, Include.journals); * </pre> * @return unmodifiable collection of Journal entries or empty collection if no objects found. Never NULL. * @see com.taskadapter.redmineapi.Include#journals */ public Collection<Journal> getJournals() { return Collections.unmodifiableCollection(storage.get(JOURNALS)); } public void addJournals(Collection<Journal> journals) { storage.get(JOURNALS).addAll(journals); } /** * Don't forget to use Include.changesets flag when loading issue from Redmine server: * <pre> * Issue issue = issueManager.getIssueById(3205, Include.changesets); * </pre> * @return unmodifiable collection of entries or empty collection if no objects found. * @see com.taskadapter.redmineapi.Include#changesets */ public Collection<Changeset> getChangesets() { return Collections.unmodifiableCollection(storage.get(CHANGESETS)); } public Issue addChangesets(Collection<Changeset> changesets) { storage.get(CHANGESETS).addAll(changesets); return this; } /** * Don't forget to use Include.watchers flag when loading issue from Redmine server: * <pre> * Issue issue = issueManager.getIssueById(3205, Include.watchers); * </pre> * @return unmodifiable collection of entries or empty collection if no objects found. * @see com.taskadapter.redmineapi.Include#watchers */ public Collection<Watcher> getWatchers() { return Collections.unmodifiableCollection(storage.get(WATCHERS)); } public Issue addWatchers(Collection<Watcher> watchers) { storage.get(WATCHERS).addAll(watchers); return this; } /** * Don't forget to use Include.children flag when loading issue from Redmine server: * <pre> * Issue issue = issueManager.getIssueById(3205, Include.children); * </pre> * @return Collection of entries or empty collection if no objects found. * @see com.taskadapter.redmineapi.Include#children */ public Collection<Issue> getChildren() { return Collections.unmodifiableCollection(storage.get(CHILDREN)); } public Issue addChildren(Collection<Issue> children) { storage.get(CHILDREN).addAll(children); return this; } /** * Issues are considered equal if their IDs are equal. what about two issues with null ids? */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Issue issue = (Issue) o; if (getId() != null ? !getId().equals(issue.getId()) : issue.getId() != null) return false; return true; } @Override public int hashCode() { return getId() != null ? getId().hashCode() : 0; } /** * @return the custom field with given Id or NULL if the field is not found */ public CustomField getCustomFieldById(int customFieldId) { for (CustomField customField : storage.get(CUSTOM_FIELDS)) { if (customFieldId == customField.getId()) { return customField; } } return null; } /** * @return the custom field with given name or NULL if the field is not found */ public CustomField getCustomFieldByName(String customFieldName) { for (CustomField customField : storage.get(CUSTOM_FIELDS)) { if (customFieldName.equals(customField.getName())) { return customField; } } return null; } @Override public String toString() { return "Issue [id=" + getId() + ", subject=" + getSubject() + "]"; } /** * Relations are only loaded if you include Include.relations when loading the Issue. * <pre> * Issue issue = issueManager.getIssueById(3205, Include.relations); * </pre> * <p>Since the returned collection is not modifiable, you need to use addRelations() method * if you want to add elements, e.g.: * <pre> * issue.addRelations(Collections.singletonList(relation)); * </pre> * @return unmodifiable collection of Relations or EMPTY collection if none found. Never returns NULL. * @see com.taskadapter.redmineapi.Include#relations */ public Collection<IssueRelation> getRelations() { return Collections.unmodifiableCollection(storage.get(RELATIONS)); } public Issue addRelations(Collection<IssueRelation> collection) { storage.get(RELATIONS).addAll(collection); return this; } public Integer getPriorityId() { return storage.get(PRIORITY_ID); } public Issue setPriorityId(Integer priorityId) { storage.set(PRIORITY_ID, priorityId); return this; } public Version getTargetVersion() { return storage.get(TARGET_VERSION); } /** * Don't forget to use <i>Include.attachments</i> flag when loading issue from Redmine server: * <pre> * Issue issue = issueManager.getIssueById(3205, Include.attachments); * </pre> * @return unmodifiable collection of entries or empty collection if no objects found. * @see com.taskadapter.redmineapi.Include#attachments */ public Collection<Attachment> getAttachments() { return Collections.unmodifiableCollection(storage.get(ATTACHMENTS)); } public Issue addAttachments(Collection<Attachment> collection) { storage.get(ATTACHMENTS).addAll(collection); return this; } public Issue addAttachment(Attachment attachment) { storage.get(ATTACHMENTS).add(attachment); return this; } public Issue setTargetVersion(Version version) { storage.set(TARGET_VERSION, version); return this; } public IssueCategory getCategory() { return storage.get(ISSUE_CATEGORY); } public Issue setCategory(IssueCategory category) { storage.set(ISSUE_CATEGORY, category); return this; } /** * Default value is not determines. it's up to the server what it thinks the default value is if not set. */ public boolean isPrivateIssue() { return storage.get(PRIVATE_ISSUE); } public Issue setPrivateIssue(boolean privateIssue) { storage.set(PRIVATE_ISSUE, privateIssue); return this; } public PropertyStorage getStorage() { return storage; } /** * @return the newly created Issue. * * @throws RedmineAuthenticationException invalid or no API access key is used with the server, which * requires authorization. Check the constructor arguments. * @throws NotFoundException the required project is not found * @throws RedmineException */ public Issue create(RequestParam... params) throws RedmineException { RequestParam[] enrichParams = Arrays.copyOf(params, params.length + 1); enrichParams[params.length] = new RequestParam("include", Include.attachments.toString()); return transport.addObject(this, enrichParams); } public void update(RequestParam... params) throws RedmineException { transport.updateObject(this, params); } public void delete() throws RedmineException { transport.deleteObject(Issue.class, Integer.toString(this.getId())); } public void addWatcher(int watcherId) throws RedmineException { transport.addWatcherToIssue(watcherId, getId()); } public void deleteWatcher(int watcherId) throws RedmineException { transport.deleteChildId(Issue.class, Integer.toString(getId()), new Watcher(), watcherId); } @Override public void setTransport(Transport transport) { this.transport = transport; PropertyStorageUtil.updateCollections(storage, transport); } }
package de.gymnew.sudoku.gui; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import de.gymnew.sudoku.algorithm.Standard; import de.gymnew.sudoku.core.Solver; import de.gymnew.sudoku.core.SolverWatcher; import de.gymnew.sudoku.model.Field; import de.gymnew.sudoku.model.Sudoku; import static de.gymnew.sudoku.gui.SudokuPanel.*; public class MainFrameHandler extends MouseAdapter implements SolverWatcher{ private MainFrame frame; public MainFrameHandler(MainFrame frame) { this.frame = frame; } // From DrawPanel @Override public void mouseClicked(MouseEvent event) { Point click = event.getPoint(); int x = (int) click.getX(); int y = (int) click.getY(); x -= (OFFSET_SIDE + BLOCK_SEPARATOR_WIDTH) * frame.getScale(); y -= (OFFSET_TOP + BLOCK_SEPARATOR_WIDTH) * frame.getScale(); if (x <= 0 || y <= 0) return; int block_x = (int) x / ((FIELD_SIZE * 3 + BLOCK_SEPARATOR_WIDTH) * frame.getScale()); int block_y = (int) y / ((FIELD_SIZE * 3 + BLOCK_SEPARATOR_WIDTH) * frame.getScale()); if (block_x > 2 || block_y > 2) return; x -= block_x * (FIELD_SIZE * 3 + BLOCK_SEPARATOR_WIDTH) * frame.getScale(); y -= block_y * (FIELD_SIZE * 3 + BLOCK_SEPARATOR_WIDTH) * frame.getScale(); int field_x = (int) x / (FIELD_SIZE * frame.getScale()); int field_y = (int) y / (FIELD_SIZE * frame.getScale()); if (field_x > 2 || field_y > 2) return; Field field = frame.getSudoku().getField(block_x * 3 + field_x, block_y * 3 + field_y); if (event.getButton() == MouseEvent.BUTTON2) { field.setLocked((!field.isLocked()) && field.getValue() != 0); frame.repaint(); return; } if (field.isLocked()) return; if (event.getButton() == MouseEvent.BUTTON1) { String s = JOptionPane.showInputDialog(frame, "Wert: (0 = leer)", field.getValue()); byte b; try { b = Byte.parseByte(s); } catch (NumberFormatException e) { b = -1; } if (b > -1 && b < 10) field.setValue(b); } else if (event.getButton() == MouseEvent.BUTTON3) { Set<Byte> notes = field.getNotes(); String n = ""; for (byte f : notes) { n = n + f; } String s = JOptionPane.showInputDialog(frame, "Notizen:", n); if (s == null) return; Set<Byte> newNotes = new HashSet<Byte>(); for (char c : s.toCharArray()) { try { byte b = Byte.parseByte("" + c); if (b != 0) newNotes.add(b); } catch (NumberFormatException e) { return; // TODO error } } field.clearNotes(); field.addNotes(newNotes); } frame.repaint(); } @Override public void mouseEntered(MouseEvent event) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent event) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent event) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent event) { // TODO Auto-generated method stub } // From MainFrame public void onMenuQuit() { System.exit(0); } public void onMenuLoad() { JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); File file = chooser.getSelectedFile(); if (file != null) { try { frame.setSudoku(Sudoku.load(file)); } catch (IOException e) { JOptionPane.showMessageDialog(frame, "Sudoku konnte nicht geladen werden!", "Fehler beim Laden!", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { JOptionPane.showMessageDialog(frame, "Keine Datei ausgew\u00E4hlt", "Fehler beim Laden!", JOptionPane.ERROR_MESSAGE); } } public void onMenuSave() { JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); File file = chooser.getSelectedFile(); if (file != null) { try { frame.getSudoku().save(file); } catch (IOException e) { JOptionPane.showMessageDialog(frame, "Sudoku konnte nicht gespeichert werden!", "Fehler beim Speichern!", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { JOptionPane.showMessageDialog(frame, "Kein Speicherort ausgew\u00E4hlt", "Fehler beim Speichern!", JOptionPane.ERROR_MESSAGE); } } public void onMenuCredits() { JOptionPane.showMessageDialog(frame, "Tobias Bodensteiner, Sven Gebauer, Tobias Gr\u00F6mer, Katharina Hauer, Valentin Kellner, Elena Menzl, Jonas Piehler, Alexander Puff, Maximilian Rauch, Catrin Schnupfhagn, Rudolf Wimmer, Matthias Zetzl", "Credits", JOptionPane.INFORMATION_MESSAGE); } public void onMenuStartSolver() { if(frame.getSolver() != null && frame.getSolver().isAlive()){ JOptionPane.showMessageDialog(frame, "Solver l&auml;uft bereits"); return; } frame.setSolver(new Solver(new Standard(frame.getSudoku(), true), this)); frame.getSolver().start(); } public void onMenuStopSolver() { // TODO Auto-generated method stub } // SolverWatcher methods @Override public void onUpdate(Solver solver, Sudoku sudoku) { frame.setSudoku(sudoku); frame.getContentPane().repaint(); JOptionPane.showMessageDialog(frame, "Pause!"); // TODO Debug } @Override public void onFinised(Solver solver) { if(solver.getResult() == null) { JOptionPane.showMessageDialog(frame, "Der Solver konnte kein Ergebnis finden!"); } else { frame.setSudoku(solver.getResult()); frame.getContentPane().repaint(); JOptionPane.showMessageDialog(frame, "Der Solver hat ein Ergebnis gefunden!"); } } }
package de.prob2.ui.animations; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob.model.representation.AbstractElement; import de.prob.model.representation.AbstractModel; import de.prob.statespace.AnimationSelector; import de.prob.statespace.IAnimationChangeListener; import de.prob.statespace.Trace; import de.prob.statespace.Transition; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.util.Callback; @Singleton public class AnimationsView extends AnchorPane implements IAnimationChangeListener { @FXML private TableView<Animation> animationsTable; @FXML private TableColumn<Animation, String> machine; @FXML private TableColumn<Animation, String> lastop; @FXML private TableColumn<Animation, String> tracelength; private final AnimationSelector animations; private int currentIndex; private int previousSize = 0; @Inject private AnimationsView(final AnimationSelector animations, final FXMLLoader loader) { this.animations = animations; this.animations.registerAnimationChangeListener(this); try { loader.setLocation(getClass().getResource("animations_view.fxml")); loader.setRoot(this); loader.setController(this); loader.load(); } catch (IOException e) { e.printStackTrace(); } } @FXML public void initialize() { machine.setCellValueFactory(new PropertyValueFactory<>("modelName")); lastop.setCellValueFactory(new PropertyValueFactory<>("lastOperation")); tracelength.setCellValueFactory(new PropertyValueFactory<>("steps")); animationsTable.setRowFactory(new Callback<TableView<Animation>, TableRow<Animation>>() { @Override public TableRow<Animation> call(TableView<Animation> tableView) { final TableRow<Animation> row = new TableRow<>(); final ContextMenu contextMenu = new ContextMenu(); final MenuItem removeMenuItem = new MenuItem("Remove Trace"); removeMenuItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Animation a = row.getItem(); animations.removeTrace(a.getTrace()); animationsTable.getItems().remove(a); } }); contextMenu.getItems().add(removeMenuItem); row.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getButton().equals(MouseButton.PRIMARY)) { currentIndex = row.getIndex(); Trace trace = row.getItem().getTrace(); animations.changeCurrentAnimation(trace); } if (event.getButton().equals(MouseButton.SECONDARY) && !row.isEmpty()) { contextMenu.show(row, event.getScreenX(), event.getScreenY()); } } }); return row; } }); } @Override public void traceChange(Trace currentTrace, boolean currentAnimationChanged) { List<Trace> traces = animations.getTraces(); List<Animation> animList = new ArrayList<Animation>(); for (Trace t : traces) { AbstractModel model = t.getModel(); AbstractElement mainComponent = t.getStateSpace().getMainComponent(); String modelName = mainComponent != null ? mainComponent.toString() : model.getModelFile().getName(); Transition op = t.getCurrentTransition(); String lastOp = op != null ? op.getPrettyRep() : ""; String steps = t.getTransitionList().size() + ""; boolean isCurrent = t.equals(currentTrace); boolean isProtected = animations.getProtectedTraces().contains(t.getUUID()); Animation a = new Animation(modelName, lastOp, steps, t, isCurrent, isProtected); animList.add(a); } Platform.runLater(() -> { ObservableList<Animation> animationsList = animationsTable.getItems(); animationsList.clear(); animationsList.addAll(animList); if(previousSize < animationsList.size()) currentIndex = animationsList.size()-1; else if(previousSize > animationsList.size() && currentIndex > 0) currentIndex animationsTable.getFocusModel().focus(currentIndex); previousSize = animationsList.size(); }); } @Override public void animatorStatus(boolean busy) { } }
package de.prob2.ui.operations; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Pattern; import java.util.stream.Collectors; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon; import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView; import de.prob.animator.domainobjects.FormulaExpand; import de.prob.model.representation.AbstractModel; import de.prob.statespace.LoadedMachine; import de.prob.statespace.OperationInfo; import de.prob.statespace.Trace; import de.prob.statespace.Transition; import de.prob2.ui.config.Config; import de.prob2.ui.config.ConfigData; import de.prob2.ui.config.ConfigListener; import de.prob2.ui.helpsystem.HelpButton; import de.prob2.ui.internal.FXMLInjected; import de.prob2.ui.internal.StageManager; import de.prob2.ui.internal.StopActions; import de.prob2.ui.layout.FontSize; import de.prob2.ui.prob2fx.CurrentTrace; import de.prob2.ui.statusbar.StatusBar; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.StringProperty; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.CustomMenuItem; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.MenuButton; import javafx.scene.control.MenuItem; import javafx.scene.control.TextField; import javafx.scene.control.ToggleButton; import javafx.scene.control.Tooltip; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseButton; import javafx.scene.layout.VBox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.sawano.java.text.AlphanumericComparator; @FXMLInjected @Singleton public final class OperationsView extends VBox { public enum SortMode { MODEL_ORDER, A_TO_Z, Z_TO_A } private final class OperationsCell extends ListCell<OperationItem> { public OperationsCell() { super(); getStyleClass().add("operations-cell"); this.setOnMouseClicked(event -> { if (event.getButton() == MouseButton.PRIMARY && !event.isControlDown()) { executeOperationIfPossible(this.getItem()); } }); final MenuItem showDetailsItem = new MenuItem(bundle.getString("operations.operationsView.contextMenu.items.showDetails")); showDetailsItem.setOnAction(event -> { final OperationDetailsStage stage = injector.getInstance(OperationDetailsStage.class); stage.setItem(this.getItem()); stage.show(); }); final MenuItem executeByPredicateItem = new MenuItem(bundle.getString("operations.operationsView.contextMenu.items.executeByPredicate")); executeByPredicateItem.setOnAction(event -> { final ExecuteByPredicateStage stage = injector.getInstance(ExecuteByPredicateStage.class); stage.setItem(this.getItem()); stage.show(); }); this.setContextMenu(new ContextMenu(showDetailsItem, executeByPredicateItem)); } @Override protected void updateItem(OperationItem item, boolean empty) { super.updateItem(item, empty); getStyleClass().removeAll("enabled", "timeout", "unexplored", "errored", "skip", "normal", "disabled"); if (item != null && !empty) { setText(item.toPrettyString()); setDisable(true); final FontAwesomeIconView icon; switch (item.getStatus()) { case TIMEOUT: icon = new FontAwesomeIconView(FontAwesomeIcon.CLOCK_ALT); getStyleClass().add("timeout"); setTooltip(new Tooltip(bundle.getString("operations.operationsView.tooltips.timeout"))); break; case ENABLED: icon = new FontAwesomeIconView(item.isSkip() ? FontAwesomeIcon.REPEAT : FontAwesomeIcon.PLAY); setDisable(false); getStyleClass().add("enabled"); if (!item.isExplored()) { getStyleClass().add("unexplored"); setTooltip(new Tooltip(bundle.getString("operations.operationsView.tooltips.reachesUnexplored"))); } else if (item.isErrored()) { getStyleClass().add("errored"); setTooltip(new Tooltip(bundle.getString("operations.operationsView.tooltips.reachesErrored"))); } else if (item.isSkip()) { getStyleClass().add("skip"); setTooltip(new Tooltip(bundle.getString("operations.operationsView.tooltips.reachesSame"))); } else { getStyleClass().add("normal"); setTooltip(null); } break; case DISABLED: icon = new FontAwesomeIconView(FontAwesomeIcon.MINUS_CIRCLE); getStyleClass().add("disabled"); setTooltip(null); break; default: throw new IllegalStateException("Unhandled status: " + item.getStatus()); } FontSize fontsize = injector.getInstance(FontSize.class); icon.glyphSizeProperty().bind(fontsize.fontSizeProperty()); setGraphic(icon); } else { setDisable(true); setGraphic(null); setText(null); } } } private static final Logger LOGGER = LoggerFactory.getLogger(OperationsView.class); // Matches empty string or number private static final Pattern NUMBER_OR_EMPTY_PATTERN = Pattern.compile("^$|^\\d+$"); @FXML private ListView<OperationItem> opsListView; @FXML private Label warningLabel; @FXML private Button sortButton; @FXML private ToggleButton disabledOpsToggle; @FXML private TextField searchBar; @FXML private TextField randomText; @FXML private MenuButton randomButton; @FXML private MenuItem oneRandomEvent; @FXML private MenuItem fiveRandomEvents; @FXML private MenuItem tenRandomEvents; @FXML private CustomMenuItem someRandomEvents; @FXML private HelpButton helpButton; @FXML private Button cancelButton; private AbstractModel currentModel; private final List<String> opNames = new ArrayList<>(); private final Map<String, List<String>> opToParams = new HashMap<>(); private final List<OperationItem> events = new ArrayList<>(); private final BooleanProperty showDisabledOps; private final ObjectProperty<OperationsView.SortMode> sortMode; private final CurrentTrace currentTrace; private final Injector injector; private final ResourceBundle bundle; private final StatusBar statusBar; private final StageManager stageManager; private final Config config; private final Comparator<CharSequence> alphanumericComparator; private final ExecutorService updater; private final ObjectProperty<Thread> randomExecutionThread; @Inject private OperationsView(final CurrentTrace currentTrace, final Locale locale, final StageManager stageManager, final Injector injector, final ResourceBundle bundle, final StatusBar statusBar, final StopActions stopActions, final Config config) { this.showDisabledOps = new SimpleBooleanProperty(this, "showDisabledOps", true); this.sortMode = new SimpleObjectProperty<>(this, "sortMode", OperationsView.SortMode.MODEL_ORDER); this.currentTrace = currentTrace; this.alphanumericComparator = new AlphanumericComparator(locale); this.injector = injector; this.bundle = bundle; this.statusBar = statusBar; this.stageManager = stageManager; this.config = config; this.updater = Executors.newSingleThreadExecutor(r -> new Thread(r, "OperationsView Updater")); this.randomExecutionThread = new SimpleObjectProperty<>(this, "randomExecutionThread", null); stopActions.add(this.updater::shutdownNow); stageManager.loadFXML(this, "ops_view.fxml"); } @FXML public void initialize() { helpButton.setHelpContent(this.getClass()); opsListView.setCellFactory(lv -> new OperationsCell()); opsListView.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { executeOperationIfPossible(opsListView.getSelectionModel().getSelectedItem()); } }); searchBar.textProperty().addListener((o, from, to) -> opsListView.getItems().setAll(applyFilter(to))); randomButton.disableProperty().bind(Bindings.or(currentTrace.existsProperty().not(), randomExecutionThread.isNotNull())); randomText.textProperty().addListener((observable, from, to) -> { if (!NUMBER_OR_EMPTY_PATTERN.matcher(to).matches() && NUMBER_OR_EMPTY_PATTERN.matcher(from).matches()) { ((StringProperty) observable).set(from); } }); this.update(currentTrace.get()); currentTrace.addListener((observable, from, to) -> update(to)); cancelButton.disableProperty().bind(randomExecutionThread.isNull()); showDisabledOps.addListener((o, from, to) -> { ((FontAwesomeIconView)disabledOpsToggle.getGraphic()).setIcon(to ? FontAwesomeIcon.EYE : FontAwesomeIcon.EYE_SLASH); disabledOpsToggle.setSelected(to); update(currentTrace.get()); }); sortMode.addListener((o, from, to) -> { final FontAwesomeIcon icon; switch (to) { case A_TO_Z: icon = FontAwesomeIcon.SORT_ALPHA_ASC; break; case Z_TO_A: icon = FontAwesomeIcon.SORT_ALPHA_DESC; break; case MODEL_ORDER: icon = FontAwesomeIcon.SORT; break; default: throw new IllegalStateException("Unhandled sort mode: " + to); } ((FontAwesomeIconView)sortButton.getGraphic()).setIcon(icon); doSort(); opsListView.getItems().setAll(applyFilter(searchBar.getText())); }); config.addListener(new ConfigListener() { @Override public void loadConfig(final ConfigData configData) { if (configData.operationsSortMode != null) { setSortMode(configData.operationsSortMode); } setShowDisabledOps(configData.operationsShowNotEnabled); } @Override public void saveConfig(final ConfigData configData) { configData.operationsSortMode = getSortMode(); configData.operationsShowNotEnabled = getShowDisabledOps(); } }); } private void executeOperationIfPossible(final OperationItem item) { if ( item != null && item.getStatus() == OperationItem.Status.ENABLED && item.getTrace().equals(currentTrace.get()) ) { Trace forward = currentTrace.forward(); if(forward != null && item.getTransition().equals(forward.getCurrentTransition())) { currentTrace.set(currentTrace.forward()); return; } currentTrace.set(currentTrace.get().add(item.getTransition().getId())); } } public void update(final Trace trace) { if (trace == null) { currentModel = null; opNames.clear(); opToParams.clear(); opsListView.getItems().clear(); } else { this.updater.execute(() -> this.updateBG(trace)); } } private void updateBG(final Trace trace) { Platform.runLater(() -> { this.statusBar.setOperationsViewUpdating(true); this.opsListView.setDisable(true); }); if (!trace.getModel().equals(currentModel)) { updateModel(trace); } events.clear(); final Set<Transition> operations = trace.getNextTransitions(true, FormulaExpand.TRUNCATE); final Set<String> disabled = new HashSet<>(opNames); final Set<String> withTimeout = trace.getCurrentState().getTransitionsWithTimeout(); for (Transition transition : operations) { disabled.remove(transition.getName()); events.add(OperationItem.forTransition(trace, transition)); } showDisabledAndWithTimeout(trace, disabled, withTimeout); doSort(); final String text; if (trace.getCurrentState().isMaxTransitionsCalculated()) { text = bundle.getString("operations.operationsView.warningLabel.maxReached"); } else if (!trace.getCurrentState().isInitialised() && operations.isEmpty()) { text = bundle.getString("operations.operationsView.warningLabel.noSetupConstantsOrInit"); } else { text = ""; } Platform.runLater(() -> warningLabel.setText(text)); final List<OperationItem> filtered = applyFilter(searchBar.getText()); Platform.runLater(() -> { opsListView.getItems().setAll(filtered); this.opsListView.setDisable(false); this.statusBar.setOperationsViewUpdating(false); }); } private void showDisabledAndWithTimeout(final Trace trace, final Set<String> notEnabled, final Set<String> withTimeout) { if (this.getShowDisabledOps()) { for (String s : notEnabled) { if (!"$initialise_machine".equals(s)) { events.add(OperationItem.forDisabled( trace, s, withTimeout.contains(s) ? OperationItem.Status.TIMEOUT : OperationItem.Status.DISABLED, opToParams.get(s) )); } } } for (String s : withTimeout) { if (!notEnabled.contains(s)) { events.add(OperationItem.forDisabled(trace, s, OperationItem.Status.TIMEOUT, Collections.emptyList())); } } } private int compareParams(final List<String> left, final List<String> right) { int minSize = left.size() < right.size() ? left.size() : right.size(); for (int i = 0; i < minSize; i++) { int cmp = alphanumericComparator.compare(left.get(i), right.get(i)); if (cmp != 0) { return cmp; } } // All elements are equal up to the end of the smaller list, order based // on which one has more elements. return Integer.compare(left.size(), right.size()); } private int compareAlphanumeric(final OperationItem left, final OperationItem right) { if (left.getName().equals(right.getName())) { return compareParams(left.getParameterValues(), right.getParameterValues()); } else { return alphanumericComparator.compare(left.getName(), right.getName()); } } private int compareModelOrder(final OperationItem left, final OperationItem right) { if (left.getName().equals(right.getName())) { return compareParams(left.getParameterValues(), right.getParameterValues()); } else { final int leftIndex = opNames.indexOf(left.getName()); final int rightIndex = opNames.indexOf(right.getName()); if (leftIndex == -1 && rightIndex == -1) { return left.getName().compareTo(right.getName()); } else { return Integer.compare(leftIndex, rightIndex); } } } @FXML private void handleDisabledOpsToggle() { this.setShowDisabledOps(disabledOpsToggle.isSelected()); } private List<OperationItem> applyFilter(final String filter) { return events.stream().filter(op -> op.getName().toLowerCase().contains(filter.toLowerCase())) .collect(Collectors.toList()); } private void doSort() { final Comparator<OperationItem> comparator; switch (this.getSortMode()) { case MODEL_ORDER: comparator = this::compareModelOrder; break; case A_TO_Z: comparator = this::compareAlphanumeric; break; case Z_TO_A: comparator = ((Comparator<OperationItem>) this::compareAlphanumeric).reversed(); break; default: throw new IllegalStateException("Unhandled sort mode: " + this.getSortMode()); } events.sort(comparator); } @FXML private void handleSortButton() { switch (this.getSortMode()) { case MODEL_ORDER: this.setSortMode(OperationsView.SortMode.A_TO_Z); break; case A_TO_Z: this.setSortMode(OperationsView.SortMode.Z_TO_A); break; case Z_TO_A: this.setSortMode(OperationsView.SortMode.MODEL_ORDER); break; default: throw new IllegalStateException("Unhandled sort mode: " + this.getSortMode()); } } @FXML public void random(ActionEvent event) { if (currentTrace.exists()) { Thread executionThread = new Thread(() -> { String randomInput = randomText.getText(); try { Trace newTrace = null; if (event.getSource().equals(randomText)) { if (randomInput.isEmpty()) { return; } newTrace = currentTrace.get().randomAnimation(Integer.parseInt(randomInput)); } else if (event.getSource().equals(oneRandomEvent)) { newTrace = currentTrace.get().randomAnimation(1); } else if (event.getSource().equals(fiveRandomEvents)) { newTrace = currentTrace.get().randomAnimation(5); } else if (event.getSource().equals(tenRandomEvents)) { newTrace = currentTrace.get().randomAnimation(10); } currentTrace.set(newTrace); randomExecutionThread.set(null); } catch (NumberFormatException e) { LOGGER.error("Invalid input for executing random number of events",e); Platform.runLater(() -> stageManager .makeAlert(Alert.AlertType.WARNING, "operations.operationsView.alerts.invalidNumberOfOparations.header", "operations.operationsView.alerts.invalidNumberOfOparations.content", randomInput) .showAndWait()); randomExecutionThread.set(null); } }); randomExecutionThread.set(executionThread); executionThread.start(); } } @FXML private void cancel() { currentTrace.getStateSpace().sendInterrupt(); if(randomExecutionThread.get() != null) { randomExecutionThread.get().interrupt(); randomExecutionThread.set(null); } } private void updateModel(final Trace trace) { currentModel = trace.getModel(); opNames.clear(); opToParams.clear(); LoadedMachine loadedMachine = trace.getStateSpace().getLoadedMachine(); for (String opName : loadedMachine.getOperationNames()) { OperationInfo machineOperationInfo = loadedMachine.getMachineOperationInfo(opName); opNames.add(opName); opToParams.put(opName, machineOperationInfo.getParameterNames()); } } private OperationsView.SortMode getSortMode() { return this.sortMode.get(); } private void setSortMode(final OperationsView.SortMode sortMode) { this.sortMode.set(sortMode); } private boolean getShowDisabledOps() { return this.showDisabledOps.get(); } private void setShowDisabledOps(boolean showDisabledOps) { this.showDisabledOps.set(showDisabledOps); } }
package edu.harvard.iq.dataverse; /** * * @author skraffmiller */ import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Transient; import org.apache.commons.lang.StringUtils; @Entity @ValidateDatasetFieldType public class DatasetField implements Serializable { private static final long serialVersionUID = 1L; /** * Orders dataset fields by their display order. */ public static final Comparator<DatasetField> DisplayOrder = new Comparator<DatasetField>() { @Override public int compare(DatasetField o1, DatasetField o2) { return Integer.compare( o1.getDatasetFieldType().getDisplayOrder(), o2.getDatasetFieldType().getDisplayOrder() ); }}; public static DatasetField createNewEmptyDatasetField(DatasetFieldType dsfType, DatasetVersion dsv) { DatasetField dsfv = createNewEmptyDatasetField(dsfType); dsfv.setDatasetVersion(dsv); return dsfv; } // originally this was an overloaded method, but we renamed it to get around an issue with Bean Validation // (that looked t overloaded methods, when it meant to look at overriden methods public static DatasetField createNewEmptyChildDatasetField(DatasetFieldType dsfType, DatasetFieldCompoundValue compoundValue) { DatasetField dsfv = createNewEmptyDatasetField(dsfType); dsfv.setParentDatasetFieldCompoundValue(compoundValue); return dsfv; } private static DatasetField createNewEmptyDatasetField(DatasetFieldType dsfType) { DatasetField dsfv = new DatasetField(); dsfv.setDatasetFieldType(dsfType); if (dsfType.isPrimitive()) { if (!dsfType.isControlledVocabulary()) { dsfv.getDatasetFieldValues().add(new DatasetFieldValue(dsfv)); } } else { // compound field dsfv.getDatasetFieldCompoundValues().add(DatasetFieldCompoundValue.createNewEmptyDatasetFieldCompoundValue(dsfv)); } return dsfv; } /** * Groups a list of fields by the block they belong to. * @param fields well, duh. * @return a map, mapping each block to the fields that belong to it. */ public static Map<MetadataBlock, List<DatasetField>> groupByBlock(List<DatasetField> fields) { Map<MetadataBlock, List<DatasetField>> retVal = new HashMap<>(); for (DatasetField f : fields) { MetadataBlock metadataBlock = f.getDatasetFieldType().getMetadataBlock(); List<DatasetField> lst = retVal.get(metadataBlock); if (lst == null) { retVal.put(metadataBlock, new LinkedList<>(Collections.singleton(f))); } else { lst.add(f); } } return retVal; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne @JoinColumn(nullable = false) private DatasetFieldType datasetFieldType; public DatasetFieldType getDatasetFieldType() { return datasetFieldType; } public void setDatasetFieldType(DatasetFieldType datasetField) { this.datasetFieldType = datasetField; } @ManyToOne private DatasetVersion datasetVersion; public DatasetVersion getDatasetVersion() { return datasetVersion; } public void setDatasetVersion(DatasetVersion datasetVersion) { this.datasetVersion = datasetVersion; } @ManyToOne(cascade = CascadeType.MERGE) private DatasetFieldCompoundValue parentDatasetFieldCompoundValue; public DatasetFieldCompoundValue getParentDatasetFieldCompoundValue() { return parentDatasetFieldCompoundValue; } public void setParentDatasetFieldCompoundValue(DatasetFieldCompoundValue parentDatasetFieldCompoundValue) { this.parentDatasetFieldCompoundValue = parentDatasetFieldCompoundValue; } @OneToMany(mappedBy = "parentDatasetField", orphanRemoval = true, cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) @OrderBy("displayOrder ASC") private List<DatasetFieldCompoundValue> datasetFieldCompoundValues = new ArrayList(); public List<DatasetFieldCompoundValue> getDatasetFieldCompoundValues() { return datasetFieldCompoundValues; } public void setDatasetFieldCompoundValues(List<DatasetFieldCompoundValue> datasetFieldCompoundValues) { this.datasetFieldCompoundValues = datasetFieldCompoundValues; } @OneToMany(mappedBy = "datasetField", orphanRemoval = true, cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) @OrderBy("displayOrder ASC") private List<DatasetFieldValue> datasetFieldValues = new ArrayList(); public List<DatasetFieldValue> getDatasetFieldValues() { return this.datasetFieldValues; } public void setDatasetFieldValues(List<DatasetFieldValue> datasetFieldValues) { this.datasetFieldValues = datasetFieldValues; } @OneToMany(cascade = {CascadeType.MERGE}) private List<ControlledVocabularyValue> controlledVocabularyValues = new ArrayList(); public List<ControlledVocabularyValue> getControlledVocabularyValues() { return controlledVocabularyValues; } public void setControlledVocabularyValues(List<ControlledVocabularyValue> controlledVocabularyValues) { this.controlledVocabularyValues = controlledVocabularyValues; } // HELPER METHODS public DatasetFieldValue getSingleValue() { if (!datasetFieldValues.isEmpty()) { return datasetFieldValues.get(0); } else { return new DatasetFieldValue(this); } } public ControlledVocabularyValue getSingleControlledVocabularyValue() { if (!controlledVocabularyValues.isEmpty()) { return controlledVocabularyValues.get(0); } else { return null; } } public void setSingleControlledVocabularyValue(ControlledVocabularyValue cvv) { if (!controlledVocabularyValues.isEmpty()) { controlledVocabularyValues.set(0, cvv); } else { controlledVocabularyValues.add(cvv); } } public String getValue() { if (!datasetFieldValues.isEmpty()) { return datasetFieldValues.get(0).getValue(); } else if (!controlledVocabularyValues.isEmpty()) { return controlledVocabularyValues.get(0).getStrValue(); } return null; } public String getDisplayValue() { String returnString = ""; for (String value : getValues()) { returnString += (returnString.equals("") ? "" : "; ") + value; } return returnString; } public List<String> getValues() { List returnList = new ArrayList(); if (!datasetFieldValues.isEmpty()) { for (DatasetFieldValue dsfv : datasetFieldValues) { returnList.add(dsfv.getValue()); } } else { for (ControlledVocabularyValue cvv : controlledVocabularyValues) { if (cvv != null && cvv.getStrValue() != null){ returnList.add(cvv.getStrValue()); } } } return returnList; } public boolean isEmpty() { if (datasetFieldType.isPrimitive()) { // primitive for (String value : getValues()) { if (value != null && !value.trim().isEmpty() ) { return false; } } } else { // compound for (DatasetFieldCompoundValue cv : datasetFieldCompoundValues) { for (DatasetField subField : cv.getChildDatasetFields()) { if (!subField.isEmpty()) { return false; } } } } return true; } @Transient private String validationMessage; public String getValidationMessage() { return validationMessage; } public void setValidationMessage(String validationMessage) { this.validationMessage = validationMessage; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DatasetField)) { return false; } DatasetField other = (DatasetField) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "edu.harvard.iq.dataverse.DatasetField[ id=" + id + " ]"; } public DatasetField copy(DatasetVersion version) { return copy(version, null); } // originally this was an overloaded method, but we renamed it to get around an issue with Bean Validation // (that looked t overloaded methods, when it meant to look at overriden methods public DatasetField copyChild(DatasetFieldCompoundValue parent) { return copy(null, parent); } private DatasetField copy(DatasetVersion version, DatasetFieldCompoundValue parent) { DatasetField dsf = new DatasetField(); dsf.setDatasetFieldType(datasetFieldType); dsf.setDatasetVersion(version); dsf.setParentDatasetFieldCompoundValue(parent); dsf.setControlledVocabularyValues(controlledVocabularyValues); for (DatasetFieldValue dsfv : datasetFieldValues) { dsf.getDatasetFieldValues().add(dsfv.copy(dsf)); } for (DatasetFieldCompoundValue compoundValue : datasetFieldCompoundValues) { dsf.getDatasetFieldCompoundValues().add(compoundValue.copy(dsf)); } return dsf; } public boolean removeBlankDatasetFieldValues() { if (this.getDatasetFieldType().isPrimitive() && !this.getDatasetFieldType().isControlledVocabulary()) { Iterator<DatasetFieldValue> dsfvIt = this.getDatasetFieldValues().iterator(); while (dsfvIt.hasNext()) { DatasetFieldValue dsfv = dsfvIt.next(); if (StringUtils.isBlank(dsfv.getValue())) { dsfvIt.remove(); } } if (this.getDatasetFieldValues().isEmpty()) { return true; } } else if (this.getDatasetFieldType().isCompound()) { Iterator<DatasetFieldCompoundValue> cvIt = this.getDatasetFieldCompoundValues().iterator(); while (cvIt.hasNext()) { DatasetFieldCompoundValue cv = cvIt.next(); Iterator<DatasetField> dsfIt = cv.getChildDatasetFields().iterator(); while (dsfIt.hasNext()) { if (dsfIt.next().removeBlankDatasetFieldValues()) { dsfIt.remove(); } } if (cv.getChildDatasetFields().isEmpty()) { cvIt.remove(); } } if (this.getDatasetFieldCompoundValues().isEmpty()) { return true; } } return false; } public void setValueDisplayOrder() { if (this.getDatasetFieldType().isPrimitive() && !this.getDatasetFieldType().isControlledVocabulary()) { for (int i = 0; i < datasetFieldValues.size(); i++) { datasetFieldValues.get(i).setDisplayOrder(i); } } else if (this.getDatasetFieldType().isCompound()) { for (int i = 0; i < datasetFieldCompoundValues.size(); i++) { DatasetFieldCompoundValue compoundValue = datasetFieldCompoundValues.get(i); compoundValue.setDisplayOrder(i); for (DatasetField dsf : compoundValue.getChildDatasetFields()) { dsf.setValueDisplayOrder(); } } } } public void addDatasetFieldValue(int index) { datasetFieldValues.add(index, new DatasetFieldValue(this)); } public void removeDatasetFieldValue(int index) { datasetFieldValues.remove(index); } public void addDatasetFieldCompoundValue(int index) { datasetFieldCompoundValues.add(index, DatasetFieldCompoundValue.createNewEmptyDatasetFieldCompoundValue(this)); } public void removeDatasetFieldCompoundValue(int index) { datasetFieldCompoundValues.remove(index); } }
package com.github.kevinsawicki.http; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static java.net.HttpURLConnection.HTTP_CREATED; import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED; import static java.net.HttpURLConnection.HTTP_OK; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.security.AccessController; import java.security.GeneralSecurityException; import java.security.PrivilegedAction; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * A fluid interface for making HTTP requests using an underlying * {@link HttpURLConnection} (or sub-class). * <p> * Each instance supports making a single request and cannot be reused for * further requests. */ public class HttpRequest { /** * 'UTF-8' charset name */ public static final String CHARSET_UTF8 = "UTF-8"; /** * 'Accept' header name */ public static final String HEADER_ACCEPT = "Accept"; /** * 'Accept-Charset' header name */ public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset"; /** * 'Accept-Encoding' header name */ public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; /** * 'Authorization' header name */ public static final String HEADER_AUTHORIZATION = "Authorization"; /** * 'Cache-Control' header name */ public static final String HEADER_CACHE_CONTROL = "Cache-Control"; /** * 'Content-Encoding' header name */ public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; /** * 'Content-Length' header name */ public static final String HEADER_CONTENT_LENGTH = "Content-Length"; /** * 'Content-Type' header name */ public static final String HEADER_CONTENT_TYPE = "Content-Type"; /** * 'Date' header name */ public static final String HEADER_DATE = "Date"; /** * 'ETag' header name */ public static final String HEADER_ETAG = "ETag"; /** * 'Expires' header name */ public static final String HEADER_EXPIRES = "Expires"; /** * 'If-None-Match' header name */ public static final String HEADER_IF_NONE_MATCH = "If-None-Match"; /** * 'Last-Modified' header name */ public static final String HEADER_LAST_MODIFIED = "Last-Modified"; /** * 'Location' header name */ public static final String HEADER_LOCATION = "Location"; /** * 'Server' header name */ public static final String HEADER_SERVER = "Server"; /** * 'User-Agent' header name */ public static final String HEADER_USER_AGENT = "User-Agent"; /** * 'DELETE' request method */ public static final String METHOD_DELETE = "DELETE"; /** * 'GET' request method */ public static final String METHOD_GET = "GET"; /** * 'HEAD' request method */ public static final String METHOD_HEAD = "HEAD"; /** * 'OPTIONS' options method */ public static final String METHOD_OPTIONS = "OPTIONS"; /** * 'POST' request method */ public static final String METHOD_POST = "POST"; /** * 'PUT' request method */ public static final String METHOD_PUT = "PUT"; /** * 'TRACE' request method */ public static final String METHOD_TRACE = "TRACE"; /** * 'charset' header value parameter */ public static final String PARAM_CHARSET = "charset"; private static final String BOUNDARY = "00content0boundary00"; private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary=" + BOUNDARY; private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"; public static class Base64 { /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "US-ASCII"; /** The 64 valid Base64 values. */ private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; /** Defeats instantiation. */ private Base64() { } /** * <p> * Encodes up to three bytes of the array <var>source</var> and writes * the resulting four Base64 bytes to <var>destination</var>. The source * and destination arrays can be manipulated anywhere along their length * by specifying <var>srcOffset</var> and <var>destOffset</var>. This * method does not check to make sure your arrays are large enough to * accomodate <var>srcOffset</var> + 3 for the <var>source</var> array * or <var>destOffset</var> + 4 for the <var>destination</var> array. * The actual number of significant bytes in your array is given by * <var>numSigBytes</var>. * </p> * <p> * This is the lowest level of the encoding methods with all possible * parameters. * </p> * * @param source * the array to convert * @param srcOffset * the index where conversion begins * @param numSigBytes * the number of significant bytes in your array * @param destination * the array to hold the conversion * @param destOffset * the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { byte[] ALPHABET = _STANDARD_ALPHABET; int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } } /** * Encode string as a byte array in Base64 annotation. * * @param string * @return The Base64-encoded data as a string */ public static String encode(String string) { byte[] bytes; try { bytes = string.getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { bytes = string.getBytes(); } return encodeBytes(bytes); } public static String encodeBytes(byte[] source) { return encodeBytes(source, 0, source.length); } public static String encodeBytes(byte[] source, int off, int len) { byte[] encoded = encodeBytesToBytes(source, off, len); try { return new String(encoded, PREFERRED_ENCODING); } catch (UnsupportedEncodingException uue) { return new String(encoded); } } public static byte[] encodeBytesToBytes(byte[] source, int off, int len) { if (source == null) throw new NullPointerException("Cannot serialize a null array."); if (off < 0) throw new IllegalArgumentException( "Cannot have negative offset: " + off); if (len < 0) throw new IllegalArgumentException( "Cannot have length offset: " + len); if (off + len > source.length) throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); // Bytes needed for actual encoding int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); byte[] outBuff = new byte[encLen]; int d = 0; int e = 0; int len2 = len - 2; for (; d < len2; d += 3, e += 4) encode3to4(source, d + off, 3, outBuff, e); if (d < len) { encode3to4(source, d + off, len - d, outBuff, e); e += 4; } if (e <= outBuff.length - 1) { byte[] finalOut = new byte[e]; System.arraycopy(outBuff, 0, finalOut, 0, e); return finalOut; } else return outBuff; } } /** * HTTP request exception whose cause is always an {@link IOException} */ public static class HttpRequestException extends RuntimeException { /** serialVersionUID */ private static final long serialVersionUID = -1170466989781746231L; /** * @param cause */ protected HttpRequestException(final IOException cause) { super(cause); } /** * Get {@link IOException} that triggered this request exception * * @return {@link IOException} cause */ public IOException getCause() { return (IOException) super.getCause(); } } /** * Operation that handles executing a callback once complete and handling * nested exceptions * * @param <V> */ protected static abstract class Operation<V> implements Callable<V> { /** * Run operation * * @return result * @throws HttpRequestException * @throws IOException */ protected abstract V run() throws HttpRequestException, IOException; /** * Operation complete callback * * @throws IOException */ protected abstract void done() throws IOException; public V call() throws HttpRequestException { boolean thrown = false; try { return run(); } catch (HttpRequestException e) { thrown = true; throw e; } catch (IOException e) { thrown = true; throw new HttpRequestException(e); } finally { try { done(); } catch (IOException e) { if (!thrown) throw new HttpRequestException(e); } } } } /** * Class that ensures a {@link Closeable} gets closed with proper exception * handling. * * @param <V> */ protected static abstract class CloseOperation<V> extends Operation<V> { private final Closeable closeable; private final boolean ignoreCloseExceptions; /** * Create closer for operation * * @param closeable * @param ignoreCloseExceptions */ protected CloseOperation(final Closeable closeable, final boolean ignoreCloseExceptions) { this.closeable = closeable; this.ignoreCloseExceptions = ignoreCloseExceptions; } protected void done() throws IOException { if (closeable instanceof Flushable) ((Flushable) closeable).flush(); if (ignoreCloseExceptions) try { closeable.close(); } catch (IOException e) { // Ignored } else closeable.close(); } } /** * Class that and ensures a {@link Flushable} gets flushed with proper * exception handling. * * @param <V> */ protected static abstract class FlushOperation<V> extends Operation<V> { private final Flushable flushable; /** * Create flush operation * * @param flushable */ protected FlushOperation(final Flushable flushable) { this.flushable = flushable; } protected void done() throws IOException { flushable.flush(); } } /** * Request output stream */ public static class RequestOutputStream extends BufferedOutputStream { private final CharsetEncoder encoder; /** * Create request output stream * * @param stream * @param charsetName * @param bufferSize */ public RequestOutputStream(OutputStream stream, String charsetName, int bufferSize) { super(stream, bufferSize); if (charsetName == null) charsetName = CHARSET_UTF8; encoder = Charset.forName(charsetName).newEncoder(); } /** * Write string to stream * * @param value * @return this stream * @throws IOException */ public RequestOutputStream write(final String value) throws IOException { final ByteBuffer bytes = encoder.encode(CharBuffer.wrap(value)); super.write(bytes.array(), 0, bytes.limit()); return this; } } /** * Start a 'GET' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest get(String url) throws HttpRequestException { return new HttpRequest(url, METHOD_GET); } /** * Start a 'GET' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest get(URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_GET); } /** * Start a 'POST' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest post(String url) throws HttpRequestException { return new HttpRequest(url, METHOD_POST); } /** * Start a 'POST' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest post(URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_POST); } /** * Start a 'PUT' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest put(String url) throws HttpRequestException { return new HttpRequest(url, METHOD_PUT); } /** * Start a 'PUT' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest put(URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_PUT); } /** * Start a 'DELETE' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest delete(String url) throws HttpRequestException { return new HttpRequest(url, METHOD_DELETE); } /** * Start a 'DELETE' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest delete(URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_DELETE); } /** * Start a 'HEAD' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest head(String url) throws HttpRequestException { return new HttpRequest(url, METHOD_HEAD); } /** * Start a 'HEAD' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest head(URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_HEAD); } /** * Start a 'OPTIONS' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest options(String url) throws HttpRequestException { return new HttpRequest(url, METHOD_OPTIONS); } /** * Start a 'OPTIONS' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest options(URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_OPTIONS); } /** * Start a 'TRACE' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest trace(String url) throws HttpRequestException { return new HttpRequest(url, METHOD_TRACE); } /** * Start a 'TRACE' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest trace(URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_TRACE); } /** * Set the 'http.keepAlive' property to the given value. * <p> * This setting will apply to requests. * * @param keepAlive */ public static void keepAlive(boolean keepAlive) { setProperty("http.keepAlive", Boolean.toString(keepAlive)); } /** * Set the 'http.proxyHost' & 'https.proxyHost' properties to the given * value. * <p> * This setting will apply to requests. * * @param host */ public static void proxyHost(final String host) { setProperty("http.proxyHost", host); setProperty("https.proxyHost", host); } /** * Set the 'http.proxyPort' & 'https.proxyPort' properties to the given * value. * <p> * This setting will apply to requests. * * @param port */ public static void proxyPort(final int port) { final String portValue = Integer.toString(port); setProperty("http.proxyPort", portValue); setProperty("https.proxyPort", portValue); } /** * Set the 'http.nonProxyHosts' properties to the given value. Hosts will be * separated by a '|' character. * <p> * This setting will apply to requests. * * @param hosts */ public static void nonProxyHosts(String... hosts) { if (hosts == null) hosts = new String[0]; if (hosts.length > 0) { StringBuilder separated = new StringBuilder(); int last = hosts.length - 1; for (int i = 0; i < last; i++) separated.append(hosts[i]).append('|'); separated.append(hosts[last]); setProperty("http.nonProxyHosts", separated.toString()); } else setProperty("http.nonProxyHosts", null); } /** * Set property to given value. * <p> * Specifying a null value will cause the property to be cleared * * @param name * @param value * @return previous value */ private static final String setProperty(final String name, final String value) { if (value != null) return AccessController .doPrivileged(new PrivilegedAction<String>() { public String run() { return System.setProperty(name, value); } }); else return AccessController .doPrivileged(new PrivilegedAction<String>() { public String run() { return System.clearProperty(name); } }); } private final HttpURLConnection connection; private RequestOutputStream output; private boolean multipart; private boolean form; private boolean ignoreCloseExceptions = true; private int bufferSize = 8192; /** * Create HTTP connection wrapper * * @param url * @param method * @throws HttpRequestException */ public HttpRequest(final String url, final String method) throws HttpRequestException { try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod(method); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Create HTTP connection wrapper * * @param url * @param method * @throws HttpRequestException */ public HttpRequest(final URL url, final String method) throws HttpRequestException { try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); } catch (IOException e) { throw new HttpRequestException(e); } } public String toString() { return connection.getRequestMethod() + " " + connection.getURL(); } /** * Get underlying connection * * @return connection */ public HttpURLConnection getConnection() { return connection; } /** * Set whether or not to ignore exceptions that occur from calling * {@link OutputStream#close()} * <p> * The default value of this setting is <code>true</code> * * @param ignore * @return this request */ public HttpRequest ignoreCloseExceptions(final boolean ignore) { ignoreCloseExceptions = ignore; return this; } /** * Get the status code of the response * * @return the response code * @throws HttpRequestException */ public int code() throws HttpRequestException { try { closeOutput(); return connection.getResponseCode(); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Set the value of the given {@link AtomicInteger} to the status code of * the response * * @param output * @return this request * @throws HttpRequestException */ public HttpRequest code(final AtomicInteger output) throws HttpRequestException { output.set(code()); return this; } /** * Is the response code a 200 OK? * * @return true if 200, false otherwise * @throws HttpRequestException */ public boolean ok() throws HttpRequestException { return HTTP_OK == code(); } /** * Is the response code a 201 Created? * * @return true if 201, false otherwise * @throws HttpRequestException */ public boolean created() throws HttpRequestException { return HTTP_CREATED == code(); } /** * Is the response code a 500 Internal Server Error? * * @return true if 500, false otherwise * @throws HttpRequestException */ public boolean serverError() throws HttpRequestException { return HTTP_INTERNAL_ERROR == code(); } /** * Is the response code a 400 Bad Request? * * @return true if 400, false otherwise * @throws HttpRequestException */ public boolean badRequest() throws HttpRequestException { return HTTP_BAD_REQUEST == code(); } /** * Is the response code a 404 Not Found? * * @return true if 404, false otherwise * @throws HttpRequestException */ public boolean notFound() throws HttpRequestException { return HTTP_NOT_FOUND == code(); } /** * Is the response code a 304 Not Modified? * * @return true if 304, false otherwise * @throws HttpRequestException */ public boolean notModified() throws HttpRequestException { return HTTP_NOT_MODIFIED == code(); } /** * Get status message of the response * * @return message * @throws HttpRequestException */ public String message() throws HttpRequestException { try { closeOutput(); return connection.getResponseMessage(); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Disconnect the connection * * @return this request */ public HttpRequest disconnect() { connection.disconnect(); return this; } /** * Set chunked streaming mode to the given size * * @param size * @return this request */ public HttpRequest chunk(final int size) { connection.setChunkedStreamingMode(size); return this; } /** * Set the size used when buffering and copying between streams * * @param size * @return this request */ public HttpRequest bufferSize(final int size) { if (size < 1) throw new IllegalArgumentException("Size must be greater than zero"); bufferSize = size; return this; } /** * Create byte array output stream * * @return stream */ protected ByteArrayOutputStream byteStream() { final int size = contentLength(); if (size > 0) return new ByteArrayOutputStream(size); else return new ByteArrayOutputStream(); } /** * Get response as String in given charset. * <p> * This will fallback to using the platform's default character if the given * charset is null. * * @param charset * @return string * @throws HttpRequestException */ public String body(final String charset) throws HttpRequestException { final ByteArrayOutputStream output = byteStream(); try { copy(buffer(), output); } catch (IOException e) { throw new HttpRequestException(e); } if (charset != null) try { return output.toString(charset); } catch (UnsupportedEncodingException e) { throw new HttpRequestException(e); } else return output.toString(); } /** * Get response as String using character returned from {@link #charset()} * * @return string * @throws HttpRequestException */ public String body() throws HttpRequestException { return body(charset()); } /** * Get response as byte array * * @return byte array * @throws HttpRequestException */ public byte[] bytes() throws HttpRequestException { final ByteArrayOutputStream output = byteStream(); try { copy(buffer(), output); } catch (IOException e) { throw new HttpRequestException(e); } return output.toByteArray(); } /** * Get response in a buffered stream * * @return stream * @throws HttpRequestException */ public BufferedInputStream buffer() throws HttpRequestException { return new BufferedInputStream(stream(), bufferSize); } /** * Get stream to response body * * @return stream * @throws HttpRequestException */ public InputStream stream() throws HttpRequestException { if (code() < HTTP_BAD_REQUEST) try { return connection.getInputStream(); } catch (IOException e) { throw new HttpRequestException(e); } else { InputStream stream = connection.getErrorStream(); if (stream != null) return stream; try { return connection.getInputStream(); } catch (IOException e) { throw new HttpRequestException(e); } } } /** * Get reader to response body using given character set. * <p> * This will fallback to using the platform's default character if the given * charset is null. * * @param charset * @return reader * @throws HttpRequestException */ public InputStreamReader reader(final String charset) throws HttpRequestException { final InputStream stream = stream(); if (charset != null) try { return new InputStreamReader(stream, charset); } catch (UnsupportedEncodingException e) { throw new HttpRequestException(e); } else return new InputStreamReader(stream); } /** * Get response to response body using the character set returned from * {@link #charset()} * * @return reader * @throws HttpRequestException */ public InputStreamReader reader() throws HttpRequestException { return reader(charset()); } /** * Stream response body to file * * @param file * @return this request */ public HttpRequest receive(final File file) { final OutputStream output; try { output = new BufferedOutputStream(new FileOutputStream(file), bufferSize); } catch (FileNotFoundException e) { throw new HttpRequestException(e); } return new CloseOperation<HttpRequest>(output, ignoreCloseExceptions) { protected HttpRequest run() throws HttpRequestException, IOException { return receive(output); } }.call(); } /** * Stream response to given output stream * * @param output * @return this request * @throws HttpRequestException */ public HttpRequest receive(final OutputStream output) throws HttpRequestException { try { return copy(buffer(), output); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Receive response into the given appendable * * @param appendable * @return this request * @throws HttpRequestException */ public HttpRequest receive(final Appendable appendable) throws HttpRequestException { final BufferedReader reader = new BufferedReader(reader(), bufferSize); return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) { public HttpRequest run() throws IOException { final CharBuffer buffer = CharBuffer.allocate(bufferSize); int read; while ((read = reader.read(buffer)) != -1) { buffer.rewind(); appendable.append(buffer, 0, read); buffer.rewind(); } return HttpRequest.this; } }.call(); } /** * Receive response into the given writer * * @param writer * @return this request * @throws HttpRequestException */ public HttpRequest receive(final Writer writer) throws HttpRequestException { final BufferedReader reader = new BufferedReader(reader(), bufferSize); return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) { public HttpRequest run() throws IOException { return copy(reader, writer); } }.call(); } /** * Set read timeout on connection to given value * * @param timeout * @return this request */ public HttpRequest readTimeout(final int timeout) { connection.setReadTimeout(timeout); return this; } /** * Set connect timeout on connection to given value * * @param timeout * @return this request */ public HttpRequest connectTimeout(final int timeout) { connection.setConnectTimeout(timeout); return this; } /** * Set header name to given value * * @param name * @param value * @return this request */ public HttpRequest header(final String name, final String value) { connection.setRequestProperty(name, value); return this; } /** * Set header name to given value * * @param name * @param value * @return this request */ public HttpRequest header(final String name, final Number value) { return header(name, value != null ? value.toString() : null); } /** * Set header names to given values. * <p> * Each name should be followed by the corresponding value and the number of * arguments must be divisible by 2. * * @param headers * @return this request */ public HttpRequest headers(final String... headers) { if (headers == null) throw new IllegalArgumentException("Headers cannot be null"); final int length = headers.length; if (length == 0) throw new IllegalArgumentException("Headers cannot be empty"); if (length % 2 != 0) throw new IllegalArgumentException( "Headers length must be divisible by two"); for (int i = 0; i < length; i += 2) header(headers[i], headers[i + 1]); return this; } /** * Get a response header * * @param name * @return response header */ public String header(final String name) { return connection.getHeaderField(name); } /** * Get a date header from the response * * @param name * @return date, -1 on failures */ public long dateHeader(final String name) { return connection.getHeaderFieldDate(name, -1L); } /** * Get an integer header from the response * * @param name * @return integer, -1 on failures */ public int intHeader(final String name) { return connection.getHeaderFieldInt(name, -1); } /** * Get parameter value from header * * @param value * @param paramName * @return parameter value or null if none */ protected String getParam(final String value, final String paramName) { if (value == null || value.length() == 0) return null; int postSemi = value.indexOf(';') + 1; if (postSemi == 0 || postSemi == value.length()) return null; String[] params = value.substring(postSemi).split(";"); for (String param : params) { String[] split = param.split("="); if (split.length != 2) continue; if (!paramName.equals(split[0].trim())) continue; String charset = split[1].trim(); int length = charset.length(); if (length == 0) continue; if (length > 2 && '"' == charset.charAt(0) && '"' == charset.charAt(length - 1)) charset = charset.substring(1, length - 1); return charset; } return null; } /** * Get 'charset' parameter from 'Content-Type' response header * * @return charset or null if none */ public String charset() { return getParam(contentType(), PARAM_CHARSET); } /** * Set the 'User-Agent' header to given value * * @param value * @return this request */ public HttpRequest userAgent(final String value) { return header(HEADER_USER_AGENT, value); } /** * Set value of {@link HttpURLConnection#setUseCaches(boolean)} * * @param useCaches * @return this request */ public HttpRequest useCaches(final boolean useCaches) { connection.setUseCaches(useCaches); return this; } /** * Set the 'Accept-Encoding' header to given value * * @param value * @return this request */ public HttpRequest acceptEncoding(final String value) { return header(HEADER_ACCEPT_ENCODING, value); } /** * Set the 'Accept-Charset' header to given value * * @param value * @return this request */ public HttpRequest acceptCharset(final String value) { return header(HEADER_ACCEPT_CHARSET, value); } /** * Get the 'Content-Encoding' header from the response * * @return this request */ public String contentEncoding() { return header(HEADER_CONTENT_ENCODING); } /** * Get the 'Server' header from the response * * @return server */ public String server() { return header(HEADER_SERVER); } /** * Get the 'Date' header from the response * * @return date value, -1 on failures */ public long date() { return dateHeader(HEADER_DATE); } /** * Get the 'Cache-Control' header from the response * * @return cache control */ public String cacheControl() { return header(HEADER_CACHE_CONTROL); } /** * Get the 'ETag' header from the response * * @return entity tag */ public String eTag() { return header(HEADER_ETAG); } /** * Get the 'Expires' header from the response * * @return expires value, -1 on failures */ public long expires() { return dateHeader(HEADER_EXPIRES); } /** * Get the 'Last-Modified' header from the response * * @return last modified value, -1 on failures */ public long lastModified() { return dateHeader(HEADER_LAST_MODIFIED); } /** * Get the 'Location' header from the response * * @return location */ public String location() { return header(HEADER_LOCATION); } /** * Set the 'Authorization' header to given value * * @param value * @return this request */ public HttpRequest authorization(final String value) { return header(HEADER_AUTHORIZATION, value); } /** * Set the 'Authorization' header to given values in Basic authentication * format * * @param name * @param password * @return this request */ public HttpRequest basic(final String name, final String password) { return authorization("Basic " + Base64.encode(name + ':' + password)); } /** * Set the 'If-Modified-Since' request header to the given value * * @param value * @return this request */ public HttpRequest ifModifiedSince(final long value) { connection.setIfModifiedSince(value); return this; } /** * Set the 'If-None-Match' request header to the given value * * @param value * @return this request */ public HttpRequest ifNoneMatch(final String value) { return header(HEADER_IF_NONE_MATCH, value); } /** * Set the 'Content-Type' request header to the given value * * @param value * @return this request */ public HttpRequest contentType(final String value) { return contentType(value, null); } /** * Set the 'Content-Type' request header to the given value and charset * * @param value * @param charset * @return this request */ public HttpRequest contentType(final String value, final String charset) { if (charset != null) { final String separator = "; " + PARAM_CHARSET + '='; return header(HEADER_CONTENT_TYPE, value + separator + charset); } else return header(HEADER_CONTENT_TYPE, value); } /** * Get the 'Content-Type' header from the response * * @return response header value */ public String contentType() { return header(HEADER_CONTENT_TYPE); } /** * Get the 'Content-Type' header from the response * * @return response header value */ public int contentLength() { return intHeader(HEADER_CONTENT_LENGTH); } /** * Set the 'Content-Length' request header to the given value * * @param value * @return this request */ public HttpRequest contentLength(final String value) { return contentLength(Integer.parseInt(value)); } /** * Set the 'Content-Length' request header to the given value * * @param value * @return this request */ public HttpRequest contentLength(final int value) { connection.setFixedLengthStreamingMode(value); return this; } /** * Set the 'Accept' header to given value * * @param value * @return this request */ public HttpRequest accept(final String value) { return header(HEADER_ACCEPT, value); } /** * Copy from input stream to output stream * * @param input * @param output * @return this request * @throws IOException */ protected HttpRequest copy(final InputStream input, final OutputStream output) throws IOException { return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) { public HttpRequest run() throws IOException { final byte[] buffer = new byte[bufferSize]; int read; while ((read = input.read(buffer)) != -1) output.write(buffer, 0, read); return HttpRequest.this; } }.call(); } /** * Copy from reader to writer * * @param input * @param output * @return this request * @throws IOException */ protected HttpRequest copy(final Reader input, final Writer output) throws IOException { return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) { public HttpRequest run() throws IOException { final char[] buffer = new char[bufferSize]; int read; while ((read = input.read(buffer)) != -1) output.write(buffer, 0, read); return HttpRequest.this; } }.call(); } /** * Close output stream * * @return this request * @throws HttpRequestException * @throws IOException */ protected HttpRequest closeOutput() throws IOException { if (output == null) return this; if (multipart) output.write("\r\n--" + BOUNDARY + "--\r\n"); output.flush(); if (ignoreCloseExceptions) try { output.close(); } catch (IOException ignored) { // Ignored } else output.close(); output = null; return this; } /** * Open output stream * * @return this request * @throws IOException */ protected HttpRequest openOutput() throws IOException { if (output != null) return this; connection.setDoOutput(true); final String charset = getParam( connection.getRequestProperty(HEADER_CONTENT_TYPE), PARAM_CHARSET); output = new RequestOutputStream(connection.getOutputStream(), charset, bufferSize); return this; } /** * Start part of a multipart * * @return this request * @throws IOException */ protected HttpRequest startPart() throws IOException { if (!multipart) { multipart = true; contentType(CONTENT_TYPE_MULTIPART).openOutput(); output.write("--" + BOUNDARY + "\r\n"); } else output.write("\r\n--" + BOUNDARY + "\r\n"); return this; } /** * Write part header * * @param name * @param filename * @return this request * @throws IOException */ protected HttpRequest writePartHeader(final String name, final String filename) throws IOException { final StringBuilder partBuffer = new StringBuilder(); partBuffer.append("form-data; name=\"").append(name); if (filename != null) partBuffer.append("\"; filename=\"").append(filename); partBuffer.append('"'); return partHeader("Content-Disposition", partBuffer.toString()); } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request */ public HttpRequest part(final String name, final String part) { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final String part) throws HttpRequestException { try { startPart(); writePartHeader(name, filename); output.write(part); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final Number part) throws HttpRequestException { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final Number part) throws HttpRequestException { return part(name, filename, part != null ? part.toString() : null); } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final File part) throws HttpRequestException { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final File part) throws HttpRequestException { final InputStream stream; try { stream = new BufferedInputStream(new FileInputStream(part)); } catch (IOException e) { throw new HttpRequestException(e); } return part(name, filename, stream); } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final InputStream part) throws HttpRequestException { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final InputStream part) throws HttpRequestException { try { startPart(); writePartHeader(name, filename); copy(part, output); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Write a multipart header to the response body * * @param name * @param value * @return this request * @throws HttpRequestException */ public HttpRequest partHeader(String name, String value) throws HttpRequestException { return send(name).send(": ").send(value).send("\r\n\r\n"); } /** * Write contents of file to request body * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final File input) throws HttpRequestException { final InputStream stream; try { stream = new BufferedInputStream(new FileInputStream(input)); } catch (FileNotFoundException e) { throw new HttpRequestException(e); } return send(stream); } /** * Write byte array to request body * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final byte[] input) throws HttpRequestException { return send(new ByteArrayInputStream(input)); } /** * Write stream to request body * <p> * The given stream will be closed once sending completes * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final InputStream input) throws HttpRequestException { try { openOutput(); copy(input, output); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Write reader to request body * <p> * The given reader will be closed once sending completes * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final Reader input) throws HttpRequestException { try { openOutput(); } catch (IOException e) { throw new HttpRequestException(e); } final Writer writer = new OutputStreamWriter(output, output.encoder.charset()); return new FlushOperation<HttpRequest>(writer) { protected HttpRequest run() throws IOException { return copy(input, writer); } }.call(); } /** * Write string to request body * <p> * The charset configured via {@link #contentType(String)} will be used and * UTF-8 will be used if it is unset. * * @param value * @return this request * @throws HttpRequestException */ public HttpRequest send(final String value) throws HttpRequestException { try { openOutput(); output.write(value); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Write the values in the map as form data to the request body * <p> * The pairs specified will be URL-encoded and sent with the * 'application/x-www-form-urlencoded' content-type * * @param values * @return this request * @throws HttpRequestException */ public HttpRequest form(final Map<?, ?> values) throws HttpRequestException { return form(values, CHARSET_UTF8); } /** * Write the name/value pair as form data to the request body * <p> * The pair specified will be URL-encoded and sent with the * 'application/x-www-form-urlencoded' content-type * * @param name * @param value * @return this request * @throws HttpRequestException */ public HttpRequest form(final Object name, final Object value) { return form(name, value, CHARSET_UTF8); } /** * Write the name/value pair as form data to the request body * <p> * The values specified will be URL-encoded and sent with the * 'application/x-www-form-urlencoded' content-type * * @param name * @param value * @param charset * @return this request * @throws HttpRequestException */ public HttpRequest form(final Object name, final Object value, final String charset) { return form(Collections.singletonMap(name, value), charset); } /** * Write the values in the map as encoded form data to the request body * * @param values * @param charset * @return this request * @throws HttpRequestException */ public HttpRequest form(final Map<?, ?> values, final String charset) throws HttpRequestException { if (!form) { contentType(CONTENT_TYPE_FORM, charset); form = true; } if (values.isEmpty()) return this; final Set<?> set = values.entrySet(); @SuppressWarnings({ "unchecked", "rawtypes" }) final Iterator<Entry> entries = (Iterator<Entry>) set.iterator(); try { openOutput(); @SuppressWarnings("rawtypes") Entry entry = entries.next(); output.write(URLEncoder.encode(entry.getKey().toString(), charset)); output.write('='); Object value = entry.getValue(); if (value != null) output.write(URLEncoder.encode(value.toString(), charset)); while (entries.hasNext()) { entry = entries.next(); output.write('&'); output.write(URLEncoder.encode(entry.getKey().toString(), charset)); output.write('='); value = entry.getValue(); if (value != null) output.write(URLEncoder.encode(value.toString(), charset)); } } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Configure HTTPS connection to trust all certificates * * @return this request * @throws HttpRequestException */ public HttpRequest trustAllCerts() throws HttpRequestException { if (!(connection instanceof HttpsURLConnection)) return this; final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; final SSLContext context; try { context = SSLContext.getInstance("TLS"); context.init(null, trustAllCerts, new SecureRandom()); } catch (GeneralSecurityException e) { throw new HttpRequestException(new IOException( e.getLocalizedMessage())); } ((HttpsURLConnection) connection).setSSLSocketFactory(context .getSocketFactory()); return this; } /** * Configured HTTPS connection to trust all hosts * * @return this request */ public HttpRequest trustAllHosts() { if (!(connection instanceof HttpsURLConnection)) return this; ((HttpsURLConnection) connection) .setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return this; } }
package edu.ucsf.mousedatabase; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import com.google.gson.Gson; import edu.ucsf.mousedatabase.admin.EmailRecipientManager; import edu.ucsf.mousedatabase.admin.EmailRecipientManager.EmailRecipient; import edu.ucsf.mousedatabase.objects.ChangeRequest; import edu.ucsf.mousedatabase.objects.EmailTemplate; import edu.ucsf.mousedatabase.objects.Facility; import edu.ucsf.mousedatabase.objects.Gene; import edu.ucsf.mousedatabase.objects.Holder; import edu.ucsf.mousedatabase.objects.IHolder; import edu.ucsf.mousedatabase.objects.ImportReport; import edu.ucsf.mousedatabase.objects.MGIResult; import edu.ucsf.mousedatabase.objects.MouseHolder; import edu.ucsf.mousedatabase.objects.MouseRecord; import edu.ucsf.mousedatabase.objects.MouseType; import edu.ucsf.mousedatabase.objects.Setting; import edu.ucsf.mousedatabase.objects.SubmittedMouse; public class HTMLGeneration { public static final String siteRoot = "/mouseinventory/"; public static final String adminRoot = siteRoot + "admin/"; public static final String imageRoot = siteRoot + "img/"; public static final String scriptRoot = siteRoot + "js/"; public static final String styleRoot = siteRoot + "css/"; public static final String dataRoot = siteRoot + "rawdata/"; public static void setGoogleAnalyticsId(String id, String domainSuffix) { googleAnalyticsScript = "<script type=\"text/javascript\">\r\n" + " var _gaq = _gaq || [];\r\n" + " _gaq.push(['_setAccount', '" + id + "']);\r\n" + " _gaq.push(['_setDomainName', '"+ domainSuffix + "']);\r\n" + " _gaq.push(['_trackPageview']);\r\n" + " (function() {\r\n" + " var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\r\n" + " ga.src = ('https:' == document.location.protocol ? 'https: + " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\r\n" + " })();" + "</script>\r\n"; } public static String googleAnalyticsScript; private static final Pattern jaxPattern = Pattern.compile("[^\\d]*([\\d]+)"); /* Page utility methods */ public static String getPageHeader(String additionalJavaScript, boolean disableCache, boolean isAdminPage) { return getPageHeader(additionalJavaScript, disableCache, isAdminPage, null); } public static String getPageHeader(String additionalJavaScript, boolean disableCache, boolean isAdminPage, String bodyParams) { StringBuffer buf = new StringBuffer(); buf.append("<!DOCTYPE html>\r\n"); buf.append("<html>\r\n"); buf.append("<head>\r\n"); buf.append("<meta name='robots' content='noindex, nofollow'>"); if (disableCache) { buf.append("<meta http-equiv='cache-control' content='no-cache'>\r\n"); buf.append("<meta http-equiv='expires' content='0'>\r\n"); buf.append("<meta http-equiv='pragma' content='no-cache'>\r\n"); } buf.append("<title>" + DBConnect.loadSetting("general_site_name").value + "</title>\r\n"); buf.append("<link href='" + styleRoot + "bootstrap.css' rel='stylesheet' type='text/css'>\r\n"); buf.append("<link href='" + styleRoot + "chosen.css' rel='stylesheet' type='text/css'>\r\n"); buf.append("<link href='" + styleRoot + "MouseInventory.css' rel='stylesheet' type='text/css'>\r\n"); buf.append("<link href='" + styleRoot + "jquery-ui.css 'rel='stylesheet' type='text/css' />"); buf.append("<script src='" + scriptRoot + "jquery.min.js'></script>\r\n"); buf.append("<script src='" + scriptRoot + "jquery-ui.min.js'></script>\r\n"); buf.append("<script src='" + scriptRoot + "chosen.jquery.min.js'></script>\r\n"); buf.append("<script src='" + scriptRoot + "jquery.ba-bbq.min.js'></script>\r\n"); buf.append("<script src='" + scriptRoot + "uiHelperFunctions.js'></script>\r\n"); buf.append("<script src='" + scriptRoot + "ajaxFunctions.js'></script>\r\n"); buf.append("<script src='" + scriptRoot + "validationFunctions.js'></script>\r\n"); buf.append("<script src='" + scriptRoot + "application.js'></script>\r\n"); buf.append("<script src='" + scriptRoot + "respond.min.js'></script>\r\n"); //ie8 fix if (isAdminPage) { buf.append("<link href='" + styleRoot + "jquery.cleditor.css' type='text/css' rel='stylesheet'>"); buf.append("<script src='" + scriptRoot + "bootstrap.min.js'></script>"); buf.append("<script src='" + scriptRoot + "jquery.cleditor.js'></script>"); } buf.append(googleAnalyticsScript + "\r\n"); if (additionalJavaScript != null) { buf.append(additionalJavaScript); } buf.append("</head>\r\n"); buf.append("<body " + (bodyParams == null ? "" : bodyParams) + " >\r\n"); return buf.toString(); } public static String getPageFooter() { StringBuffer buf = new StringBuffer(); buf.append("</body>"); buf.append("</html>"); return buf.toString(); } public static String getNavBar(String currentPageFilename, boolean isAdminPage) { return getNavBar(currentPageFilename, isAdminPage, true); } public static String getNavBar(String currentPageFilename, boolean isAdminPage, boolean showAdminControls) { StringBuffer table = new StringBuffer(); table.append("<div id=\"navBarContainer\">"); // Page header table.append("<div id=\"pageHeaderContainer\" class='clearfix'>"); table.append("<div class='site_container'>"); table.append("<div id=\"pageTitleContainer\">"); table.append("<div>"); //pagetitle table.append("<span id=\"pageTitle\">" + "<a href='" + siteRoot + "'>" + DBConnect.loadSetting("general_site_name").value + "</a></span>"); table.append("</div>"); table.append("<div>"); // About, faq, contact links table.append("<span class=\"titleSubText\">"); table.append("<a href=\"" + siteRoot + "about.jsp\">Home</a>&nbsp;"); // table.append("&nbsp;<a href=\""+siteRoot+"faq.jsp\">FAQ</a>&nbsp;"); table.append("&nbsp;<a href=\"" + siteRoot + "contact.jsp\">Submit Feedback</a>"); table.append("</span>"); table.append("</div>"); // About, faq, contact links table.append("</div>"); //pagetitle // Quick Search bar if (currentPageFilename == null || !currentPageFilename.equals("search.jsp")) { table.append("<div id=\"quickSearchContainer\">"); table.append("<form id=\"quickSearchForm\"action=\"" + siteRoot + "search.jsp\" method=\"get\">\r\n"); table.append("<input type=\"text\" class=\"input-medium search-query\" name=\"searchterms\" >\r\n"); table.append("<input type='hidden' name='search-source' value='quicksearch:" + currentPageFilename + "'>\r\n"); table.append("<input id='quicksearchbutton' class=\"btn search-query\" type=\"submit\" value=\"Quick Search\">\r\n"); table.append("<script type='text/javascript'>\r\n$('input[name=searchterms]').focus()\r\n"); table.append("$(\"#quicksearchbutton\").click(function(){ \r\n"); table.append("window.location.href = '" + siteRoot + "search.jsp#' + $(\"#quickSearchForm\").serialize();\r\nreturn false; });"); table.append("</script>\r\n"); table.append("</form>"); table.append("</div>"); } table.append("</div>"); //pagetitlecontainer table.append("</div>"); //pageheader table.append("</div>"); //pageheadercontainer // Navigation Bar table.append("<div id=\"navigationLinksContainer\" class='clearfix'>"); table.append("<div id='navigationLinks' class='site_container'>"); table.append("<ul class=\"navLinkUL\">"); table.append(addNavLink("Search", "search.jsp", null, currentPageFilename, false,"nav-search-link")); table.append(addNavLink("Mouse Records", "MouseReport.jsp", null, currentPageFilename, false,"nav-mouselist")); table.append(addNavLink("Gene List", "GeneReport.jsp", null, currentPageFilename, false)); table.append(addNavLink("Holder List", "HolderReport.jsp", null, currentPageFilename, false)); table.append(addNavLink("Facility List", "FacilityReport.jsp", null, currentPageFilename, false)); // table.append(addNavLink("Endangered Mice", "EndangeredReport.jsp", // null,currentPageFilename,false)); table.append(addNavLink("Submit Mice", "submitforminit.jsp", null, currentPageFilename, false)); if (isAdminPage && showAdminControls){ table.append(addNavLink("Log out", "logout.jsp", null, currentPageFilename, false,"pull-right small")); } else { table.append(addNavLink("Admin use only", "admin.jsp", null, isAdminPage ? "admin.jsp" : currentPageFilename, true, "pull-right small")); } table.append("</ul>"); table.append("</div>"); //navigationlinks table.append("</div>"); //navigationlinkscontainer // Admin Row if (isAdminPage && showAdminControls) { table.append("<div id=\"adminLinksContainer\" class='clearfix'>"); table.append("<div id='adminLinks' class='site_container'>"); table.append("<ul class=\"navLinkUL\">"); table.append(addNavLink("Admin Home", "admin.jsp", null, currentPageFilename, true)); table.append(addNavLink("Change Requests", "ManageChangeRequests.jsp", null, currentPageFilename, true)); table.append(addNavLink("Submissions", "ListSubmissions.jsp", null, currentPageFilename, true)); table.append(addNavLink("Edit Records", "EditMouseSelection.jsp", null, currentPageFilename, true)); table.append(addNavLink("Edit Holders", "EditHolderChooser.jsp", null, currentPageFilename, true)); table.append(addNavLink("Edit Facilities","EditFacilityChooser.jsp", null, currentPageFilename, true)); table.append(addNavLink("Data Upload", "ImportReports.jsp", null, currentPageFilename, true)); table.append(addNavLink("Reports", "Reports.jsp", null, currentPageFilename, true)); table.append(addNavLink("Notes", "ManageAdminNotes.jsp", null, currentPageFilename, true)); table.append(addNavLink("Options", "Options.jsp", null, currentPageFilename, true)); table.append("</ul>"); table.append("</div>"); //adminlinks table.append("</div>"); //adminlinkscontainer } table.append("</div>"); //navbarcontainer Setting alert = DBConnect.loadSetting("general_site_alert"); if (alert.value != null && !alert.value.trim().isEmpty()) { table.append("<div class='site_container'><div class='alert alert-error' style='margin-top: 15px'><b>" + alert.value + "</b></div></div>"); } return table.toString(); } private static String addNavLink(String targetNiceName, String targetPageFilename, String targetPageArguments, String currentPageFilename, boolean isAdminPage) { return addNavLink(targetNiceName, targetPageFilename, targetPageArguments, currentPageFilename, isAdminPage,""); } private static String addNavLink(String targetNiceName, String targetPageFilename, String targetPageArguments, String currentPageFilename, boolean isAdminPage, String cssClass) { cssClass += targetPageFilename.equals(currentPageFilename) ? " current" : ""; cssClass += " NavLinkItem"; String url = (isAdminPage ? adminRoot : siteRoot) + targetPageFilename; if (targetPageArguments != null) { url += targetPageArguments; } return "<li class=\"" + cssClass + "\"><a class=\"navBarAnchor\" href=\"" + url + "\">" + targetNiceName + "</a></li>\r\n"; } public static String getNewMouseForm(MouseRecord r) { return getEditMouseForm(r, null, null, true); } public static String getEditMouseForm(MouseRecord r) { return getEditMouseForm(r, null, null); } public static String getEditMouseForm(MouseRecord r, SubmittedMouse sub) { return getEditMouseForm(r, sub, null); } public static String getEditMouseForm(MouseRecord r, ChangeRequest req) { return getEditMouseForm(r, null, req); } public static String getEditMouseForm(MouseRecord r, SubmittedMouse sub, ChangeRequest req) { return getEditMouseForm(r, sub, req, false); } public static String getEditMouseForm(MouseRecord r, SubmittedMouse sub, ChangeRequest req, boolean isAdminCreating) { int size = 35; // default field size String field = ""; StringBuilder buf = new StringBuilder(); buf.append("<div class=\"mouseTable\">\r\n"); if (sub != null) {// sub is null when editing existing mice, not null // when this is a new submission buf.append("<form name=\"mouseDetails\" action=\"UpdateSubmission.jsp\" method=\"post\">\r\n"); buf.append("<input type=\"hidden\" name=\"submittedMouseID\" value=\"" + sub.getSubmissionID() + "\">"); if (req != null) { return null; } } else if (req != null) { buf.append("<form name=\"mouseDetails\" action=\"UpdateChangeRequest.jsp\" method=\"post\">\r\n"); buf.append("<input type=\"hidden\" name=\"changeRequestID\" value=\"" + req.getRequestID() + "\">"); } else if (isAdminCreating) { buf.append("<form name=\"mouseDetails\" action=\"CreateRecord.jsp\" method=\"post\">\r\n"); } else { buf.append("<form name=\"mouseDetails\" action=\"UpdateMouse.jsp\" method=\"post\">\r\n"); } buf.append("<input type=\"hidden\" name=\"mouseID\" value=\"" + r.getMouseID() + "\">"); buf.append("<input type=\"hidden\" name=\"mouseType\" value=\"" + r.getMouseType() + "\">"); buf.append("<input type=\"hidden\" name=\"repositoryTypeID\" value=\"5\">"); // everything is MGI now buf.append("<div class=\"editMouseFormContainer\">\r\n"); // buf.append("<tr>\r\n"); // buf.append("<td valign=\"top\" style=\"padding: 0px\">\r\n"); buf.append("<div class=\"editMouseFormLeftColumn\">"); buf.append("<table class=\"editMouseColumn\">\r\n"); // holders ArrayList<MouseHolder> holderList = r.getHolders(); if (holderList == null) { holderList = new ArrayList<MouseHolder>(); } if (req != null && req.Properties() != null) { int addHolderID = -1; int addFacilityId = -1; //if there is a holder and facility in the change requests, add it to the list for(String propName : req.Properties().stringPropertyNames()) { String propertyValue = req.Properties().getProperty(propName); if (propName.equals("Add Holder")) { int splitterIndex = propertyValue.indexOf('|'); if (splitterIndex > 0) { try { addHolderID = Integer.parseInt(propertyValue.substring(0,splitterIndex)); } catch (Exception e) { Log.Error("Unable to parse int from holder property value in change request #" + req.getRequestID() + ": " + propertyValue,e); } } } else if (propName.equals("Add Facility")) { int splitterIndex = propertyValue.indexOf('|'); if (splitterIndex > 0) { try { addFacilityId = Integer.parseInt(propertyValue.substring(0,splitterIndex)); } catch (Exception e) { Log.Error("Unable to parse int from facility property value in change request #" + req.getRequestID() + ": " + propertyValue,e); } } } else if (propName.equals("Add Holder Name")) { IHolder holder = DBConnect.findHolder(propertyValue); if (holder != null) { addHolderID = holder.getHolderID(); } } else if (propName.equals("Add Facility Name")) { Facility facility = DBConnect.findFacility(propertyValue); if (facility != null) { addFacilityId = facility.getFacilityID(); } } } if (addHolderID > 0) { MouseHolder addedHolder = new MouseHolder(); addedHolder.setNewlyAdded(true); addedHolder.setHolderID(addHolderID); if (addFacilityId > 0) { addedHolder.setFacilityID(addFacilityId); } holderList.add(addedHolder); } } // TODO finish this - auto populate multiple holders on the submission - need a way to deal with holders that don't yet exisit // if (sub != null) // int i = 2; // Properties props = sub.getProperties(); // String key = "Recipient PI Name-" + i; // while (props.containsKey(key)) // String holderName = props.getProperty(key); // String holderFacility = props.getProperty("Recipient Facility-" + i); holderList.add(new MouseHolder()); ArrayList<Holder> allHoldersObjs = DBConnect.getAllHolders(); ArrayList<Facility> allFacilitiesObjs = DBConnect.getAllFacilities(); String[] holderIDs = new String[allHoldersObjs.size()]; String[] holderNames = new String[allHoldersObjs.size()]; String[] facilityIDs = new String[allFacilitiesObjs.size()]; String[] facilityNames = new String[allFacilitiesObjs.size()]; int k = 0; for (IHolder holder : allHoldersObjs) { holderIDs[k] = String.valueOf(holder.getHolderID()); if (holder.getHolderID() == 1) { holderNames[k] = "NA"; } else { holderNames[k] = holder.getLastname() + ", " + holder.getFirstname() + " - " + holder.getDept(); } k++; } k = 0; for (Facility facility : allFacilitiesObjs) { facilityIDs[k] = String.valueOf(facility.getFacilityID()); facilityNames[k] = facility.getFacilityName(); k++; } String[] covertOptions = { "Covert" }; k = 0; for (MouseHolder holder : holderList) { if (holder.isNewlyAdded()) { buf.append("<tr class=\"editMouseRow\">"); buf.append("<td colspan=\"2\"><b>Auto-filled from change request:</b></td></tr>"); } buf.append("<tr class=\"editMouseRow\">"); buf.append("<td colspan=\"2\"><div style=\"position: relative\">Holder:&nbsp;"); buf.append(HTMLGeneration.genSelect("holder_id-" + k, holderIDs, holderNames, String.valueOf(holder.getHolderID()), null)); buf.append("&nbsp;<a class='btn btn-mini btn-warning' href=\"javascript:\" onclick=\"clearHolder('" + k + "')\"><i class='icon-remove icon-white'></i></a>"); buf.append("<br>Facility:"); buf.append("&nbsp;"); buf.append(HTMLGeneration.genSelect("facility_id-" + k, facilityIDs, facilityNames, String.valueOf(holder.getFacilityID()), null)); buf.append("&nbsp;"); buf.append("&nbsp;"); buf.append(HTMLGeneration.genFlatRadio("cryoLiveStatus-" + k, new String[] { "Live only", "Live and Cryo", "Cryo only" }, new String[] { "Live only", "Live and Cryo", "Cryo only" }, holder.getCryoLiveStatus(), null)); buf.append("&nbsp;"); buf.append("&nbsp;"); buf.append("&nbsp;"); buf.append(HTMLGeneration.genCheckbox("covertHolder_-" + k, covertOptions, (holder.isCovert() ? "Covert" : ""))); buf.append("</div>"); buf.append("</td>"); buf.append("</tr>\n"); if (holder.isNewlyAdded()) { buf.append("<tr><td>&nbsp;</td></tr>"); } k++; } getTextInputRow(buf, "Mouse Name", "mouseName", r.getMouseName(), size, 255, null, null, "editMouseRow"); // boolean MGIConnectionAvailable = true; // Mutant Allele and Transgene mice if (r.isMA() || r.isTG()) { if (r.isMA()) { // Gene Section String mgiID = r.getGeneID(); if ((mgiID == null || mgiID.isEmpty()) && sub != null && (sub.getMAMgiGeneID() != null && !sub.getMAMgiGeneID().isEmpty())) { mgiID = sub.getMAMgiGeneID(); } field = getTextInput( "geneMGIID", emptyIfNull(mgiID), size, 11, "id=\"geneMGIID\" onkeyup=\"validateInput('geneMGIID', 'geneMGIIDValidation', 'mgiModifiedGeneId', '')\""); if (mgiID != null && !mgiID.isEmpty()) { String geneURL = HTMLGeneration.formatMGI(mgiID); String resultString = ""; String validationStyle = ""; String manualNameSymbolEntry = "<br>MGI SQL connection unavailable. To continue editing this record, the gene Symbol and Name must be manually entered. <br>Symbol:&nbsp;" + getTextInput("geneManualSymbol", "", 15, 25, null) + "&nbsp;&nbsp;Name:&nbsp;" + getTextInput("geneManualName", "", 15, 25, null); Gene knownGene = DBConnect.findGene(mgiID); if (knownGene != null) { resultString = knownGene.getSymbol() + " - " + knownGene.getFullname(); validationStyle = "bp_valid"; replaceBrackets(resultString); } else { MGIResult geneResult = MGIConnect.doMGIQuery(mgiID, MGIConnect.MGI_MARKER, "This MGI ID does not correspond to a Gene", false); validationStyle = geneResult.isValid() ? "bp_valid" : "bp_invalid"; if (geneResult.isValid()) { resultString = geneResult.getSymbol() + " - " + geneResult.getName(); } else if (geneResult.isMgiConnectionTimedout() || geneResult.isMgiOffline()) { resultString = manualNameSymbolEntry; } else { resultString = geneResult.getErrorString(); } } field += "<span class='" + validationStyle + "' id='geneMGIIDValidation'>" + resultString + " (MGI:" + geneURL + ")</span>"; } else { field += "<span id='geneMGIIDValidation'></span>"; } getInputRow(buf, "Gene MGI ID", field, null, "editMouseRow"); } // Modification type section String[] values = { "targeted disruption", "conditional allele (loxP/frt)", "targeted knock-in", "gene trap insertion", "Chemically induced (ENU)", "spontaneous mutation", "other (info in comment)" }; getInputRow( buf, "Modification Type", genRadio("modificationType", values, r.getModificationType(), "onChange=\"UpdateModificationTypeEdit()\""), "style=\"" + rowVisibility(r.isMA()) + "\"", "editMouseRow"); // Expressed Sequence section String[] exprSeqValues = { "Reporter", "Cre", "Mouse Gene (unmodified)", "Modified mouse gene or Other" }; getInputRow( buf, "Expressed Sequence", genRadio("expressedSequence", exprSeqValues, r.getExpressedSequence(), "onChange=\"UpdateExpressedSequenceEdit()\""), "id=\"trExprSeqRow\" style=\"" + rowVisibility(r.isTG() || (r.getModificationType() != null && r.getModificationType().equalsIgnoreCase("targeted knock-in"))) + "\"", "editMouseRow"); String mgiID = r.getTargetGeneID(); if ((mgiID == null || mgiID.isEmpty()) && sub != null && (sub.getTGMouseGene() != null && !sub.getTGMouseGene().isEmpty())) { mgiID = sub.getTGMouseGene(); } // Mouse Gene section field = getTextInput( "targetGeneMGIID", emptyIfNull(mgiID), size, 11, "id=\"targetGeneMGIID\" onkeyup=\"validateInput('targetGeneMGIID', 'targetGeneMGIIDValidation', 'mgiModifiedGeneId', '')\""); if (mgiID != null && !mgiID.isEmpty()) { String geneURL = HTMLGeneration.formatMGI(mgiID); String resultString = ""; String validationStyle = ""; String manualNameSymbolEntry = "<br>MGI SQL connection unavailable. To continue editing this record, the gene Symbol and Name must be manually entered. <br>Symbol:&nbsp;" + getTextInput("targetGeneManualSymbol", "", size, 25, null) + "&nbsp;&nbsp;Name:&nbsp;" + getTextInput("targetGeneManualName", "", size, 25, null); Gene knownGene = DBConnect.findGene(mgiID); if (knownGene != null) { resultString = knownGene.getSymbol() + " - " + knownGene.getFullname(); validationStyle = "bp_valid"; replaceBrackets(resultString); } else { MGIResult geneResult = MGIConnect.doMGIQuery(mgiID, MGIConnect.MGI_MARKER, "This MGI ID does not correspond to a Gene", false); validationStyle = geneResult.isValid() ? "bp_valid" : "bp_invalid"; if (geneResult.isValid()) { resultString = geneResult.getSymbol() + " - " + geneResult.getName(); } else if (geneResult.isMgiConnectionTimedout() || geneResult.isMgiOffline()) { resultString = manualNameSymbolEntry; } else { resultString = geneResult.getErrorString(); } } field += "<span class='" + validationStyle + "' id='targetGeneMGIIDValidation'>" + replaceBrackets(resultString) + " (MGI:" + geneURL + ")</span>"; } else { field += "<span id='targetGeneMGIIDValidation'></span>"; } getInputRow( buf, "Expr. Gene MGI ID:", field, "id=\"trGeneRow\" style=\"" + rowVisibility(r.getExpressedSequence() != null && (r.getExpressedSequence() .equalsIgnoreCase("mouse gene") || r .getExpressedSequence() .equalsIgnoreCase( "Mouse Gene (unmodified)"))) + "\"", "editMouseRow"); // getTextInputRow(buf, "Reporter", "reporter", // emptyIfNull(r.getReporter()), size, 255, null, // "id=\"trRepRow\" " // , "editMouseRow"); field = "<textarea id=\"reporterTextArea\" name=\"reporter\" rows=\"4\" cols=\"40\" onkeypress=\"return imposeMaxLength(this,255);\" >" + emptyIfNull(r.getReporter()) + "</textarea>\r\n"; getInputRow(buf, "Reporter", field, "style=\"" + rowVisibility(r.getExpressedSequence() != null && r.getExpressedSequence() .equalsIgnoreCase("reporter")) + "\"", "editMouseRow", "trRepRow"); // getTextInputRow(buf, "Other", "otherComment", // emptyIfNull(r.getOtherComment()), size, 255, null, // "id=\"trDescRow\" " + // "style=\"" + rowVisibility(r.getExpressedSequence() != null && // r.getExpressedSequence().equalsIgnoreCase("other")) + "\"", // "editMouseRow"); field = "<textarea id=\"otherCommentTextArea\" name=\"otherComment\" rows=\"4\" cols=\"40\" onkeypress=\"return imposeMaxLength(this,255);\" >" + emptyIfNull(r.getOtherComment()) + "</textarea>\r\n"; getInputRow( buf, "Modified mouse gene or Other", field, "style=\"" + rowVisibility(r.getExpressedSequence() != null && (r.getExpressedSequence() .equalsIgnoreCase("other") || r .getExpressedSequence() .equalsIgnoreCase( "Modified mouse gene or Other"))) + "\"", "editMouseRow", "trDescRow"); // Regulatory Element if (r.isTG()) { field = "<textarea id=\"regulatoryElement\" name=\"regulatoryElement\" rows=\"2\" cols=\"40\" >" + emptyIfNull(r.getRegulatoryElement()) + "</textarea>\r\n"; getInputRow(buf, "Regulatory Element", field,null, "editMouseRow"); } } buf.append("</table>\r\n"); buf.append("</div>\r\n"); buf.append("<div class=\"editMouseFormRightColumn\">"); buf.append("<table class=\"editMouseColumn\">\r\n"); if (r.isMA() || r.isTG()) { // Allele or Transgene MGI ID String mgiType = r.isMA() ? "Allele" : "Transgene"; String mgiID = r.getRepositoryCatalogNumber(); if ((mgiID == null || mgiID.isEmpty()) && sub != null && (sub.getMouseMGIID() != null && !sub.getMouseMGIID() .isEmpty())) { mgiID = sub.getMouseMGIID(); } String officialSymbol = r.getSource(); String officialMouseName = r.getOfficialMouseName(); field = getTextInput( "repositoryCatalogNumber", emptyIfNull(mgiID), size, 11, "id=\"repositoryCatalogNumber\" onkeyup=\"validateInput('repositoryCatalogNumber', 'repositoryCatalogNumberValidation', 'mgi" + mgiType + "Id', 'none')\""); if (mgiID != null && !mgiID.isEmpty() && !mgiID.equalsIgnoreCase("none")) { MGIResult mouseResult = null; String validationStyle = ""; String resultString = ""; String geneURL = HTMLGeneration.formatMGI(mgiID); if (r.getSource() == null || r.getSource().isEmpty() || officialMouseName == null || officialMouseName.isEmpty()) { if (r.isMA()) { mouseResult = MGIConnect .doMGIQuery( mgiID, MGIConnect.MGI_ALLELE, "This MGI ID does not correspond to an Allele Detail Page", false); } else { mouseResult = MGIConnect .doMGIQuery( mgiID, MGIConnect.MGI_ALLELE, "This MGI ID does not correspond to an Allele Detail Page", false); } if (mouseResult.isMgiConnectionTimedout() || mouseResult.isMgiOffline()) { // buf = new StringBuilder(); // buf // .append("<br><span class='error'>Unable to edit record because the MGI Connection is unavailable. Please try again later</span>"); // return buf.toString(); } validationStyle = mouseResult.isValid() ? "bp_valid" : "bp_invalid"; if (mouseResult.isValid()) { resultString = mouseResult.getSymbol(); officialSymbol = mouseResult.getSymbol(); officialMouseName = mouseResult.getName(); r.setOfficialMouseName(officialMouseName); r.setSource(officialSymbol); // bad programmer! } else { resultString = mouseResult.getErrorString(); } } field += "<span class='" + validationStyle + "' id='repositoryCatalogNumberValidation'>" + replaceBrackets(resultString) + " (MGI:" + geneURL + ")</span>"; } else { field += "<span id='repositoryCatalogNumberValidation'></span>"; } getInputRow(buf, mgiType + " MGI ID", field, null, "editMouseRow"); getTextInputRow(buf, "Official Symbol", "source", emptyIfNull(officialSymbol), size, 255, "id=\"officialSymbol\"", null, "editMouseRow"); getTextInputRow(buf, "Official Name", "officialMouseName", officialMouseName, size, 255, null, null, "editMouseRow"); // PubMed ID(s) int pubMedNum = 1; for (String pmID : r.getPubmedIDs()) { if (pmID == null || pmID.isEmpty()) continue; MGIResult pubmedResult = MGIConnect.DoReferenceQuery(pmID); if (pubmedResult.isMgiConnectionTimedout() || pubmedResult.isMgiOffline()) { // buf = new StringBuilder(); // buf // .append("<br><span class='error'>Unable to edit record because the MGI Connection is unavailable. Please try again later</span>"); // return buf.toString(); } String resultString = ""; if (pubmedResult.isValid()) { resultString = pubmedResult.getTitle() + " (" + pubmedResult.getAuthors() + ")"; } else { resultString = pubmedResult.getErrorString(); } field = getTextInput("pmid" + pubMedNum, pmID, 20, 32, "id=\"" + "pmid" + pubMedNum + "\" onkeyup=\"validateInput('pmid" + pubMedNum + "', 'pmID" + pubMedNum + "Validation', 'pmId', ',')\""); field += "<span class=\"" + (pubmedResult.isValid() ? "bp_valid" : "bp_invalid") + "\" id=\"pmID" + pubMedNum + "Validation\">" + resultString + " (PubMed:" + formatPubMedID(pmID) + ")</span>"; getInputRow(buf, "PubMed ID #" + pubMedNum, field, null, "editMouseRow"); pubMedNum++; } field = getTextInput("pmid" + pubMedNum, null, 20, 32, "id=\"" + "pmid" + pubMedNum + "\" onkeyup=\"validateInput('pmid" + pubMedNum + "', 'pmid" + pubMedNum + "Validation', 'pmId', ',')\" id=\"pmid" + pubMedNum + "\""); field += "<span id=\"pmid" + pubMedNum + "Validation\"></span>"; getInputRow(buf, "PubMed ID #" + pubMedNum, field, null, "editMouseRow"); // String[] mtaValues = { "Y", "N", "D" }; // String[] mtaNiceNames = { "Yes", "No", "Don't Know" }; // field = genSelect("mtaRequired", mtaValues, mtaNiceNames, // r.getMtaRequired(), null); // field = genCheckbox("mtaRequired", mtaValues, // r.getMtaRequired()); // getInputRow(buf, "MTA Required?", field, null, "editMouseRow"); // field = "<input type=\"checkbox\" value=\"true\" name=\"endangered\" " // + (r.isEndangered() ? "checked=\"checked\"" : "") + " >"; // getInputRow(buf, "Endangered?", field, null, "editMouseRow"); } if (r.getMouseType().equalsIgnoreCase("inbred strain")) { buf.append("<tr class=\"editMouseRow\">\r\n"); buf.append("<td valign=\"top\">\r\n"); buf.append("Supplier and catalog link:</td>\r\n"); buf.append("<td valign=\"top\">\r\n"); buf.append("<input name=\"source\" type=\"text\" size=\"80\" value=\"" + emptyIfNull(r.getSource()) + "\">\r\n"); buf.append("<br>Jax format: JAX Mice, catalog number"); buf.append("<br>Non-Jax format: supplier || url"); buf.append("</td>\r\n"); buf.append("</tr>\r\n"); } if (sub != null && sub.getRawMGIComment() != null && !sub.getRawMGIComment().equals("") && sub.getComment() != null && !(sub.getComment().equals(sub.getRawMGIComment()))) { buf.append("<tr class=editMouseRow><td colspan=2>"); buf.append("<span class=red>The submitter modified the description from MGI</span> (Original below)"); buf.append("<p style='font-style: italic;'>" + sub.getRawMGIComment() + "</p>"); buf.append("</td></tr>"); } field = "<textarea name=\"generalComment\" rows=\"10\" cols=\"60\">" + emptyIfNull(r.getGeneralComment()) + "</textarea>\r\n"; getInputRow(buf, "Comment", field, null, "editMouseRow"); buf.append("<tr class=editMouseRow><td colspan=2>To make links, use [URL]http://example.com[/URL]. For bold, use [B]bold text here[/B]</td></tr>"); // if (r.isTG()) // String[] transgenicTypes = { "Random Insertion" }; // field = genSelect("transgenicType", transgenicTypes, // "Random Insertion"); // getInputRow(buf, "Transgenic Type", field, null, "editMouseRow"); // else buf.append("<input type=\"hidden\" name=\"transgenicType\" value=\""+ "Random Insertion" + "\">"); // String[] cryoValues = { "Y" }; // field = genCheckbox("cryopreserved", cryoValues, // r.getCryopreserved()); // getInputRow(buf, "Cryopreserved only? (DEPRECATED)", field, null, // "editMouseRow"); if (r.isMA() || r.isTG()) { field = "<textarea name=\"backgroundStrain\" rows=\"10\" cols=\"60\" >" + emptyIfNull(r.getBackgroundStrain()) + "</textarea>\r\n"; getInputRow(buf, "Background Strain", field, null, "editMouseRow"); field = getTextInput("gensat", r.getGensat(), size, 100, null); getInputRow(buf, "Gensat Founder Line", field, null, "editMouseRow"); } if (r.getStatus() != null) { if (r.getStatus().equalsIgnoreCase("live") || r.getStatus().equalsIgnoreCase("deleted")) { String[] statusValues = { "live", "deleted" }; field = genRadio("status", statusValues, r.getStatus()); getInputRow(buf, "Record Status", field, null, "editMouseRow"); } else if (r.getStatus().equalsIgnoreCase("incomplete")) { buf.append("<input type=\"hidden\" name=\"status\" value=\"incomplete\">"); } } buf.append("</table>"); buf.append("</div>\r\n"); buf.append("<div style=\"clear: both;\">\r\n"); if (sub != null) { buf.append("<table style=\"width: 100%;\">"); field = "<textarea name=\"submissionNotes\" rows=\"10\" cols=\"60\">" + emptyIfNull(sub.getAdminComment()) + "</textarea>\r\n"; getInputRow(buf, "Submission Admin Comment", field, null, "editMouseRow"); buf.append("</table>"); } if (req != null) { buf.append("<table style=\"width: 100%;\">"); field = "<textarea name=\"requestNotes\" rows=\"10\" cols=\"60\">" + emptyIfNull(req.getAdminComment()) + "</textarea>\r\n"; getInputRow(buf, "Change Request Admin Comment", field, null, "editMouseRow"); buf.append("</table>"); } if (sub != null) { buf.append("<input type=\"submit\" class='btn btn-success' name=\"submitButton\" value=\"Convert to Record\">"); buf.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "<input type=\"submit\" class='btn btn-warning' name=\"submitButton\" value=\"Move to Hold\">"); buf.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "<input type=\"submit\" class='btn btn-danger' name=\"submitButton\" value=\"Reject Submission\">"); } else if (req != null) { buf.append("<input type=\"submit\" class='btn btn-primary' name=\"submitButton\" value=\"Complete Change Request\">"); buf.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "<input type=\"submit\" class='btn btn-warning' name=\"submitButton\" value=\"Move to Pending\">"); } else if (isAdminCreating) { buf.append("<input type=\"submit\" class='btn btn-success' name=\"submitButton\" value=\"Create Record\">"); buf.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "<input type=\"submit\" class='btn btn-warning' name=\"submitButton\" value=\"Save as Incomplete\">"); } else { buf.append("<input type=\"submit\" class='btn btn-primary' name=\"submitButton\" value=\"Save Changes to Record\">"); } buf.append("</form>\r\n"); if (r.getMouseID() != null && req == null) { ArrayList<MouseType> mouseTypes = DBConnect.getMouseTypes(); String[] mouseTypeIDs = new String[mouseTypes.size()]; String[] mouseTypeNames = new String[mouseTypes.size()]; String currentTypeIDstr = ""; for (int i = 0; i < mouseTypes.size(); i++) { mouseTypeIDs[i] = Integer.toString((mouseTypes.get(i) .getMouseTypeID())); mouseTypeNames[i] = mouseTypes.get(i).getTypeName(); if (mouseTypeNames[i].equalsIgnoreCase(r.getMouseType())) { currentTypeIDstr = mouseTypeIDs[i]; } } String mouseTypeOptions = genSelect("mousetype_id", mouseTypeIDs, mouseTypeNames, currentTypeIDstr, "style='width:150px'"); buf.append("<form name='changeMouseType' action='ChangeMouseType.jsp' method='post'>\r\n"); buf.append("<input type='hidden' name='mouse_id' value='" + r.getMouseID() + "'>"); buf.append("<br><p>Change Mouse Category to: " + mouseTypeOptions); buf.append("&nbsp;&nbsp;<input type='submit' class='btn btn-small' value='Change Category'>"); buf.append("</form>\r\n"); } if (req != null){ buf.append("<p>Should a change in mouse category be necessary, it can be made using the 'Edit Record' feature.</p>"); } buf.append("</div>\r\n"); buf.append("</div>\r\n"); return buf.toString(); } private static void getTextInputRow(StringBuilder buf, String label, String name, String current, int size, int maxLength, String inputParams, String rowParams, String cssClass) { buf.append("<tr " + (cssClass != null ? "class=\"" + cssClass + "\"" : "") + (rowParams != null ? rowParams : "") + ">\r\n"); buf.append("<td>" + label + "</td>\r\n"); buf.append("<td>" + getTextInput(name, current, size, maxLength, inputParams) + "</td>"); buf.append("</tr>\r\n"); } private static void getInputRow(StringBuilder buf, String label, String field, String params, String cssClass) { getInputRow(buf, label, field, params, cssClass, null); } private static void getInputRow(StringBuilder buf, String label, String field, String params, String cssClass, String rowId) { buf.append("<tr " + (cssClass != null ? "class=\"" + cssClass + "\"" : "") + (rowId != null ? "id=\"" + rowId + "\"" : "") + (params != null ? params : "") + ">\r\n"); buf.append("<td>" + label + "</td>\r\n"); buf.append("<td>" + field + "</td>"); buf.append("</tr>\r\n"); } /* Table creation methods */ public static String getRowStyle(int rowNum, String style, String altStyle) { return ((rowNum % 2) == 0) ? style : altStyle; } private static String getSubmissionTableHeaders() { StringBuffer table = new StringBuffer(); table.append("<tr class='submissionlistH'>\r\n"); table.append("<td style='min-width:130px'\">\r\n"); table.append("Status "); table.append("</td>\r\n"); table.append("<td style='min-width:250px'>\r\n"); table.append("Submission info"); table.append("<td style='min-width:110px'>\r\n"); table.append("Category"); table.append("</td>\r\n"); table.append("<td style='min-width:150px'>\r\n"); table.append("Details"); table.append("</td style='min-width:200px'>\r\n"); table.append("<td>\r\n"); table.append("Comment "); table.append("</td>\r\n"); table.append("<td >\r\n"); table.append("Holders "); table.append("</td style='width:120px'>\r\n"); table.append("</tr>\r\n"); return table.toString(); } public static String getSubmissionTable(ArrayList<SubmittedMouse> submissions, String currentPageStatus, String currentPageEntered) { return getSubmissionTable(submissions, currentPageStatus, currentPageEntered, true); } public static String getSubmissionTable(ArrayList<SubmittedMouse> submissions, String currentPageStatus, String currentPageEntered, boolean showStatusChangeLinks) { StringBuffer table = new StringBuffer(); table.append("<div class=\"mouseTable\">\r\n"); table.append("<table style='width:100%'>\r\n"); int numSubmissions = 0; for (SubmittedMouse nextSubmission : submissions) { nextSubmission.prepareForSerialization(); if (numSubmissions % 20 == 0) table.append(getSubmissionTableHeaders()); String rowStyle = getRowStyle(numSubmissions, "submissionlist", "submissionlistAlt"); table.append("<tr class='" + rowStyle + "'>\r\n"); // FIRST COLUMN - status table.append("<td valign='top'>\r\n"); table.append("<dl>\r\n"); table.append("<dt>\r\n"); table.append("Submission #" + nextSubmission.getSubmissionID()); table.append("</dt>\r\n"); table.append("<dt>\r\n"); String statusString = nextSubmission.getStatus(); if (statusString.equalsIgnoreCase("need more info")) { statusString = "on hold"; } table.append("Status: <b>" + statusString + "</b>"); table.append("</dt>\r\n"); if (nextSubmission.isEntered() && !nextSubmission.getStatus().equalsIgnoreCase( "need more info")) { table.append("<dt>\r\n"); table.append("<a href='" + adminRoot + "EditMouseSelection.jsp?searchterms=%23"+ nextSubmission.getMouseRecordID() + "'>Record #<b>" + nextSubmission.getMouseRecordID() + "</b></a>"); table.append("</dt>\r\n"); } if (showStatusChangeLinks) { if (!nextSubmission.isEntered()) { table.append("<dt>\r\n"); table.append("<a href=\"CreateNewRecord.jsp?id=" + nextSubmission.getSubmissionID() + "\">Convert to record</a>"); table.append("</dt>\r\n"); } if (nextSubmission.getStatus().equalsIgnoreCase("rejected")) { table.append("<dt>\r\n"); table.append("<a href=\"DeleteSubmission.jsp?submissionID=" + nextSubmission.getSubmissionID() + "\">Delete...</a>"); table.append("</dt>\r\n"); } } table.append("</dl>\r\n"); table.append("</td>"); // COLUMN - submitter data table.append("<td valign='top'>\r\n"); table.append("<dl>\r\n"); table.append("<dt>\r\n"); table.append(nextSubmission.getFirstName() + " " + nextSubmission.getLastName()); table.append("</dt>\r\n"); table.append("<dt>\r\n"); table.append(nextSubmission.getDepartment()); table.append("</dt>\r\n"); table.append("<dt>\r\n"); table.append(nextSubmission.getTelephoneNumber()); table.append("</dt>\r\n"); table.append("<dt>\r\n"); for(IHolder holder: nextSubmission.getHolders()){ EmailRecipient rec = EmailRecipientManager.recipientsForRequestorAndHolder(nextSubmission.getEmail(), holder); table.append(getAdminMailLink(rec.recipients,rec.ccs, EmailTemplate.SUBMISSION, nextSubmission.getSubmissionID(),-1,Integer.toString(nextSubmission.getMouseRecordID()),-1) + " (" + holder.getFullname() + ")<br>"); } table.append("</dt>\r\n"); table.append("<dt>"); table.append("Submission date: " + nextSubmission.getSubmissionDate()); table.append("</dt></dl>"); table.append("<div style='font-size:14px;font-weight:700'>Admin Comments:</div>"); table.append("<span class=\"mouseComment\">" + emptyIfNull(HTMLUtilities.getCommentForDisplay(nextSubmission.getAdminComment())) + "</span>"); table.append("</td>\r\n"); // COLUMN - details table.append("<td valign='top'><dl>\r\n"); if (nextSubmission.getMouseName() != null && !nextSubmission.getMouseName().isEmpty()) { table.append("<dt class='mouseName'>\r\n"); table.append(nextSubmission.getMouseName()); table.append("</dt>\r\n"); } if (nextSubmission.getMouseType() != null) { table.append("<dt class='mouseType'>\r\n" + nextSubmission.getMouseType()); if (nextSubmission.isTG()) { if (nextSubmission.getTransgenicType().equalsIgnoreCase("knock-in")) { table.append(" - <b>Knock-in</b></dt>\r\n"); } else if (nextSubmission.getTransgenicType() .equalsIgnoreCase("random insertion")) { table.append(" - <b>Random insertion</b></dt>\r\n"); } if (nextSubmission.getTGExpressedSequence() .equalsIgnoreCase("mouse gene") || nextSubmission .getTGExpressedSequence() .equalsIgnoreCase("Mouse Gene (unmodified)")) { table.append("<dt><b>Expressed Sequence:</b></dt>\r\n"); table.append("<dd>" + formatMGI(nextSubmission.getTGMouseGene()) + "</dd>\r\n"); if (nextSubmission.getTGMouseGeneValid() != null && nextSubmission.getTGMouseGeneValid() .equalsIgnoreCase("true")) { table.append("<dd>" + nextSubmission .getTGMouseGeneValidationString() + "</dd>\r\n"); } // formatGene(nextSubmission.getGeneSymbol(), // nextSubmission.getGeneName(), // nextSubmission.getGeneID())); } else if (nextSubmission.getTGExpressedSequence() .equalsIgnoreCase("reporter")) { table.append("<dt><b>Expressed Sequence:</b>\r\n"); table.append(nextSubmission.getTGReporter() + "</dt>\r\n"); } else if (nextSubmission.getTGExpressedSequence() .equalsIgnoreCase("other") || nextSubmission.getTGExpressedSequence() .equalsIgnoreCase( "Modified mouse gene or Other")) { table.append("<dt><b>Expressed Sequence:</b>\r\n"); table.append(nextSubmission.getTGOther() + "</dt>\r\n"); } else { table.append("<dt><b>Expressed Sequence:</b> " + nextSubmission.getTGExpressedSequence() + "</dt>\r\n"); } if (nextSubmission.getTransgenicType().equalsIgnoreCase( "knock-in")) { table.append("<dt><b>Knocked-in to:</b></dt>\r\n"); table.append("<dd>" + formatMGI(nextSubmission.getTGKnockedInGene()) + "</dd>"); // formatGene(nextSubmission // .getTargetGeneSymbol(), nextSubmission // .getTargetGeneName(), nextSubmission // .getTargetGeneID())); } else if (nextSubmission.getTransgenicType().equalsIgnoreCase("random insertion")) { table.append("<dt><b>Regulatory element:</b> " + nextSubmission.getTGRegulatoryElement() + "</dt>\r\n"); } } else if (nextSubmission.isMA()) { table.append("</dt>\r\n"); table.append("<dd>" + formatMGI(nextSubmission.getMAMgiGeneID()) + "</dd>"); // formatGene(nextSubmission.getGeneSymbol(), if (nextSubmission.getMAMgiGeneIDValid() != null && nextSubmission.getMAMgiGeneIDValid() .equalsIgnoreCase("true")) { table.append("<dd>" + nextSubmission .getMAMgiGeneIDValidationString() + "</dd>\r\n"); } // nextSubmission.getGeneName(), nextSubmission // .getGeneID())); table.append("<dt><b>Modification Type:</b> " + nextSubmission.getMAModificationType() + "</dt>\r\n"); if (nextSubmission.getMAModificationType() != null && nextSubmission.getMAModificationType() .equalsIgnoreCase("targeted knock-in")) { if (nextSubmission.getTGExpressedSequence() != null) { if (nextSubmission.getTGExpressedSequence() .equalsIgnoreCase("mouse gene") || nextSubmission.getTGExpressedSequence() .equalsIgnoreCase( "Mouse Gene (unmodified)")) { table.append("<dt><b>Expressed Sequence:</b></dt>\r\n"); table.append("<dd>" + formatMGI(nextSubmission .getTGMouseGene()) + "</dd>");// formatGene(nextSubmission.getGeneSymbol(), if (nextSubmission.getTGMouseGeneValid() != null && nextSubmission.getTGMouseGeneValid() .equalsIgnoreCase("true")) { table.append("<dd>" + nextSubmission .getTGMouseGeneValidationString() + "</dd>\r\n"); } // nextSubmission.getGeneName(), // nextSubmission.getGeneID())); } else if (nextSubmission.getTGExpressedSequence() .equalsIgnoreCase("reporter")) { table.append("<dt><b>Expressed Sequence:</b>\r\n"); table.append(nextSubmission.getTGReporter() + "</dt>\r\n"); } else if (nextSubmission.getTGExpressedSequence() .equalsIgnoreCase("other") || nextSubmission .getTGExpressedSequence() .equalsIgnoreCase( "Modified mouse gene or Other")) { table.append("<dt><b>Expressed Sequence:</b>\r\n"); table.append(nextSubmission.getTGOther() + "</dt>\r\n"); } else { table.append("<dt><b>Expressed Sequence:</b> " + nextSubmission .getTGExpressedSequence() + "</dt>\r\n"); } } } } else if (nextSubmission.getMouseType().equalsIgnoreCase( "inbred strain")) { String supplier = nextSubmission.getISSupplier(); if (nextSubmission.getISSupplierCatalogNumber() != null) { supplier += ", " + nextSubmission.getISSupplierCatalogNumber(); } String formattedUrl = null; if (nextSubmission.getISSupplierCatalogUrl() != null) { formattedUrl = formatInbredStrainURL(supplier, nextSubmission.getISSupplierCatalogUrl()); } else { formattedUrl = formatInbredStrainURL(supplier); } table.append("</dt>\r\n"); table.append("<dt>Supplier (and Catalog#, if available): " + formattedUrl + "</dt>\r\n"); } } else { table.append("<dt>MISSING MOUSE TYPE</dt>"); } if (nextSubmission.getProducedInLabOfHolder() != null) { table.append("<dt>Produced in lab of holder: " + nextSubmission.getProducedInLabOfHolder() + "</dt>\r\n"); } // if (nextSubmission.getCryoLiveStatus() != null) { // table.append("<dt>Mouse Status: " // + nextSubmission.getCryoLiveStatus() + "</dt>\r\n"); // } else { // table.append("<dt>Mouse Status: Unspecified</dt>\r\n"); table.append("</dl></td>\r\n"); // COLUMN - mouse info (transgenic and mutant allele) table.append("<td valign='top'>\r\n"); table.append("<dl>\r\n"); if (nextSubmission.getMouseType() != null && (nextSubmission.isTG() || nextSubmission.isMA())) { String source = ""; if (nextSubmission.getOfficialSymbol() == null || nextSubmission.getOfficialSymbol().equals("")) { source = "none"; } else { source = "<b>" + replaceBrackets(nextSubmission .getOfficialSymbol()) + "</b>"; } String repositoryCatalogNumber = nextSubmission.getMouseMGIID(); if (repositoryCatalogNumber == null || repositoryCatalogNumber.equals("") || repositoryCatalogNumber.equals("null")) { repositoryCatalogNumber = "none"; } else { repositoryCatalogNumber = formatMGI(repositoryCatalogNumber); } table.append("<dt>Official Symbol: " + source + "</dt>\r\n"); if (nextSubmission.getOfficialMouseName() != null && !nextSubmission.getOfficialMouseName().isEmpty()) { table.append("<dt>("); table.append(nextSubmission.getOfficialMouseName()); table.append(")</dt>\r\n"); } table.append("<dt>MGI: " + repositoryCatalogNumber + "</dt>\r\n"); if (nextSubmission.getPMID() == null) { // unpublished mice table.append("<dt>Unpublished</dt>\r\n"); } else { table.append("<dt>PubMed: " + formatPubMedID(nextSubmission.getPMID()) + "</dt>\r\n"); } if (nextSubmission.getBackgroundStrain() != null && !nextSubmission.getBackgroundStrain().isEmpty()) { table.append("<dt>Background Strain: " + nextSubmission.getBackgroundStrain() + "</dt>\r\n"); } if (nextSubmission.getMtaRequired() != null) { if (nextSubmission.getMtaRequired().equalsIgnoreCase("Y")) { // table.append("<dt>MTA is required.</dt>\r\n"); } else if (nextSubmission.getMtaRequired() .equalsIgnoreCase("D")) { // table.append("<dt>Unknown if MTA required.</dt>\r\n"); } } if (nextSubmission.getGensatFounderLine() != null && !nextSubmission.getGensatFounderLine().isEmpty()) { table.append("<dt>Gensat founder line: " + formatGensat(nextSubmission .getGensatFounderLine()) + "</dt>\r\n"); } } table.append("</dl>\r\n"); table.append("</td>\r\n"); // column - comment table.append("<td valign='top'>\r\n"); table.append("<span class=\"mouseComment\">" + emptyIfNull(HTMLUtilities.getCommentForDisplay(nextSubmission.getComment())) + "</span>"); table.append("</td>\r\n"); // COLUMN - Holder table.append("<td valign='top'>\r\n"); for (MouseHolder mouseHolder : nextSubmission.getHolders()) { table.append("<dt>\r\n"); table.append(mouseHolder.getFullname()); table.append("</dt>\r\n"); table.append("<dt>\r\n"); table.append("Facility: " + mouseHolder.getFacilityName()); table.append("</dt>\r\n"); } if (nextSubmission.getCryoLiveStatus() != null) table.append("<dt>Status: " + nextSubmission.getCryoLiveStatus()+ "</dt>"); table.append("</td>\r\n"); table.append("</tr>\r\n"); numSubmissions++; } table.append("</table>\r\n"); table.append("<script type='text/javascript'>\r\n"); table.append("MouseConf.addSubmissions(" + new Gson().toJson(submissions) + ")"); table.append("</script>"); table.append("</div>\r\n"); if (numSubmissions <= 0) return "No results found"; return table.toString(); } private static String getMouseTableHeaders() { StringBuffer table = new StringBuffer(); table.append("<tr class='mouselistH'>\r\n"); table.append("<td class='mouselistcolumn-name' >\r\n"); table.append("Name"); table.append("<td class='mouselistcolumn-category'>\r\n"); table.append("Category"); table.append("</td>\r\n"); table.append("<td class='mouselistcolumn-details'>\r\n"); table.append("Details"); table.append("</td>\r\n"); table.append("<td class='mouselistcolumn-comment'>\r\n"); table.append("Comment "); table.append("</td>\r\n"); table.append("<td class='mouselistcolumn-holders' >\r\n"); table.append("Holders "); table.append("</td>\r\n"); table.append("</tr>\r\n"); return table.toString(); } public static String getMouseTable(ArrayList<MouseRecord> mice, boolean edit, boolean showChangeRequest, boolean showAllHolders) { return getMouseTable(mice, edit, showChangeRequest, showAllHolders, true); } public static String getMouseTable(ArrayList<MouseRecord> mice, boolean edit, boolean showChangeRequest, boolean showAllHolders, boolean showHeader) { return getMouseTable(mice, edit, showChangeRequest, showAllHolders, showHeader, edit); } public static String getMouseTable(ArrayList<MouseRecord> mice, boolean edit, boolean showChangeRequest, boolean showAllHolders, boolean showHeader, boolean includeJson) { StringBuffer table = new StringBuffer(); table.append("<div class=\"mouseTable\">\r\n"); table.append("<table style='width:100%'>\r\n"); int numMice = 0; for (MouseRecord nextRecord : mice) { String rowStyle = getRowStyle(numMice, "mouselist", "mouselistAlt"); if (numMice % 25 == 0 && showHeader) table.append(getMouseTableHeaders()); table.append("<tr class='" + rowStyle + "'>\r\n"); // FIRST COLUMN - name and record number table.append("<td class='mouselistcolumn-name'><dl>"); if (nextRecord.getMouseName() != null) { table.append("<dt class='mouseName'>\r\n"); table.append(nextRecord.getMouseName()); table.append("</dt>\r\n"); } if (edit) { table.append("<dt><a href=\"EditMouseForm.jsp?id=" + nextRecord.getMouseID() + "\">Edit record + nextRecord.getMouseID() + "</a></dt>\r\n"); } else { table.append("<dt><span class='lbl'>Record</span> #" + nextRecord.getMouseID() + "</dt>\r\n"); } if (showChangeRequest) { table.append("<dt><span class='changerequest'><a href=ChangeRequestForm.jsp?mouseID=" + nextRecord.getMouseID() + "><span class='lbl'>request change in record</span></a></span></dt>\r\n"); } if (edit && nextRecord.getStatus() != null) { String style = ""; if (nextRecord.getStatus().equalsIgnoreCase("live")) { style = "style=\"color: green; font-weight: bold;\""; } else if (nextRecord.getStatus().equalsIgnoreCase("deleted")) { style = "style=\"color: red; font-weight: bold;\""; } table.append("<dt>Record status: <span " + style + ">" + nextRecord.getStatus() + "</span></dt>"); } table.append("</dl></td>\r\n"); // SECOND COLUMN - category table.append("<td class='mouselistcolumn-category'><dl>\r\n"); table.append("<dt class='mouseType'>\r\n<span class='lbl'>" + nextRecord.getMouseType() + "</span>"); if (nextRecord.isTG()) { if (nextRecord.getExpressedSequence() != null) { if (nextRecord.getExpressedSequence().equalsIgnoreCase( "mouse gene") || nextRecord .getExpressedSequence() .equalsIgnoreCase("Mouse Gene (unmodified)")) { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b></dt>\r\n"); table.append(formatGene( nextRecord.getTargetGeneSymbol(), nextRecord.getTargetGeneName(), nextRecord.getTargetGeneID())); } else if (nextRecord.getExpressedSequence() .equalsIgnoreCase("reporter")) { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b>\r\n"); table.append(nextRecord.getReporter() + "</dt>\r\n"); } else if (nextRecord.getExpressedSequence() .equalsIgnoreCase("other") || nextRecord.getExpressedSequence() .equalsIgnoreCase( "Modified mouse gene or Other")) { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b>\r\n"); table.append(nextRecord.getOtherComment() + "</dt>\r\n"); } else { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b> " + nextRecord.getExpressedSequence() + "</dt>\r\n"); } } if (nextRecord.getTransgenicType() != null && nextRecord.getTransgenicType().equalsIgnoreCase( "knock-in")) { table.append("<dt><b><span class='lbl'>Knocked-in to:</span></b></dt>\r\n"); table.append(formatGene(nextRecord.getTargetGeneSymbol(), nextRecord.getTargetGeneName(), nextRecord.getTargetGeneID())); } else if (nextRecord.getTransgenicType() != null && nextRecord.getTransgenicType().equalsIgnoreCase( "random insertion")) { table.append("<dt><b><span class='lbl'>Regulatory element:</span></b> " + nextRecord.getRegulatoryElement() + "</dt>\r\n"); } } else if (nextRecord.isMA()) { table.append("</dt>\r\n"); table.append(formatGene(nextRecord.getGeneSymbol(), nextRecord.getGeneName(), nextRecord.getGeneID())); table.append("<dt><b><span class='lbl'>Modification Type:</span></b> " + nextRecord.getModificationType() + "</dt>\r\n"); if (!(nextRecord.getModificationType() == null || nextRecord .getModificationType().isEmpty())) { if (nextRecord.getModificationType().equalsIgnoreCase( "targeted knock-in")) { if (nextRecord.getExpressedSequence() != null) { if (nextRecord.getExpressedSequence() .equalsIgnoreCase("mouse gene") || nextRecord.getExpressedSequence() .equalsIgnoreCase( "Mouse Gene (unmodified)")) { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b></dt>\r\n"); table.append(formatGene( nextRecord.getTargetGeneSymbol(), nextRecord.getTargetGeneName(), nextRecord.getTargetGeneID())); } else if (nextRecord.getExpressedSequence() .equalsIgnoreCase("reporter")) { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b>\r\n"); table.append(nextRecord.getReporter() + "</dt>\r\n"); } else if (nextRecord.getExpressedSequence() .equalsIgnoreCase("other") || nextRecord .getExpressedSequence() .equalsIgnoreCase( "Modified mouse gene or Other")) { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b>\r\n"); table.append(nextRecord.getOtherComment() + "</dt>\r\n"); } else { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b> " + nextRecord.getExpressedSequence() + "</dt>\r\n"); } } else { table.append("<dt><b><span class='lbl'>Expressed Sequence:</span></b> " + nextRecord.getExpressedSequence() + "</dt>\r\n"); } } } } else if (nextRecord.getMouseType().equalsIgnoreCase( "inbred strain")) { table.append("</dt>\r\n"); table.append("<dt><span class='lbl'>Supplier and link to on-line catalog page (if available):</span> " + formatInbredStrainURL(nextRecord.getSource()) + "</dt>\r\n"); } table.append("</dl></td>\r\n"); // COLUMN - details (transgenic and mutant allele) table.append("<td class='mouselistcolumn-details'>\r\n"); table.append("<dl>\r\n"); if (nextRecord.isTG() || nextRecord.isMA()) { String source = ""; if (nextRecord.getSource() == null || nextRecord.getSource().equals("")) { source = "none"; } else { source = "<b>" + replaceBrackets(nextRecord.getSource()) + "</b>"; } String repositoryCatalogNumber = nextRecord .getRepositoryCatalogNumber(); if (repositoryCatalogNumber == null || repositoryCatalogNumber.equals("") || repositoryCatalogNumber.equals("null")) { repositoryCatalogNumber = "none"; } else { repositoryCatalogNumber = formatMGI(repositoryCatalogNumber); } table.append("<dt><span class='lbl'>Official Symbol:</span> " + source + "</dt>\r\n"); String officialName = nextRecord.getOfficialMouseName(); if (officialName != null && !officialName.isEmpty()) { table.append("<dt>("); table.append(officialName); table.append(")</dt>\r\n"); } table.append("<dt><span class='lbl'>MGI:</span> " + repositoryCatalogNumber + "</dt>\r\n"); if (nextRecord.getPubmedIDs() == null || nextRecord.getPubmedIDs().isEmpty()) { // unpublished mice table.append("<dt>Unpublished</dt>\r\n"); } else { String allIDs = ""; boolean first = true; boolean hasValidPmIds = false; for (String pmid : nextRecord.getPubmedIDs()) { if (!first) allIDs += ", "; if (pmid != null && !pmid.isEmpty()) hasValidPmIds = true; first = false; allIDs += formatPubMedID(pmid); } if (hasValidPmIds) table.append("<dt><span class='lbl'>PubMed:</span> " + allIDs + "</dt>\r\n"); } if (nextRecord.getBackgroundStrain() != null && !nextRecord.getBackgroundStrain().isEmpty()) { table.append("<dt><span class='lbl'>Background Strain:</span> " + nextRecord.getBackgroundStrain() + "</dt>\r\n"); } if (nextRecord.getMtaRequired() != null) { if (nextRecord.getMtaRequired().equalsIgnoreCase("Y")) { // table.append("<dt>MTA is required.</dt>\r\n"); } else if (nextRecord.getMtaRequired() .equalsIgnoreCase("D")) { // table.append("<dt>Unknown if MTA required.</dt>\r\n"); } else if (nextRecord.getMtaRequired() .equalsIgnoreCase("N")) { // table.append("<dt>MTA is not required</dt>\r\n"); } } if (nextRecord.getGensat() != null && !nextRecord.getGensat().isEmpty()) { table.append("<dt><span class='lbl'>Gensat founder line:</span> " + formatGensat(nextRecord.getGensat()) + "</dt>\r\n"); } } if (nextRecord.isCryoOnly()) { table.append("<dt><b>Cryopreserved <span class='lbl'>only</span></b></dt>\r\n"); } if (nextRecord.getCryopreserved() != null && nextRecord.getCryopreserved().equalsIgnoreCase("Y")) { table.append("<dt><i><b>Cryopreserved only</b></i></dt>\r\n"); } if (edit && nextRecord.isEndangered()) { table.append("<dt><span class='endangered'>Endangered</span></dt>\r\n"); } table.append("</dl>\r\n"); table.append("</td>\r\n"); // THIRD column - comment table.append("<td class='mouselistcolumn-comment'>\r\n"); table.append("<span class=\"mouseComment\">" + emptyIfNull(HTMLUtilities.getCommentForDisplay(nextRecord.getGeneralComment())) + "</span>"); table.append("</td>\r\n"); // FOURTH column - holders table.append("<td class='mouselistcolumn-holders'>\r\n"); int holderCount = 0; int maxHolders = 3; StringBuffer holderBuf = new StringBuffer("<dl class='mouselist-holderlist'>"); if (nextRecord.getHolders() != null) { boolean overMax = false; for (MouseHolder holder : nextRecord.getHolders()) { if (holder.isCovert() && !edit) { continue; } if (holder.getFirstname() == null && holder.getLastname() == null) { continue; } if (holderCount == maxHolders && !showAllHolders) { overMax = true; } String cryoLiveStatus = ""; if (holder.getCryoLiveStatus() != null) { // NULL = ignore // Live = live only // LiveCryo = live and cryo // Cryo = cryo only if (holder.getCryoLiveStatus().equalsIgnoreCase( "Live only")) { cryoLiveStatus = ""; } else if (holder.getCryoLiveStatus().equalsIgnoreCase( "Live and cryo")) { cryoLiveStatus = "(Cryo,Live)"; } else if (holder.getCryoLiveStatus().equalsIgnoreCase( "Cryo only")) { cryoLiveStatus = "(Cryo)"; } } String facilityName = holder.getFacilityID() == 1 ? " " : "(" + holder.getFacilityName() + ")"; String firstInitial = ""; if (holder.getFirstname() != null) { firstInitial = holder.getFirstname().substring(0, 1) + ". "; } EmailRecipient rec = EmailRecipientManager.recipientsForHolder(holder); String mailLink = edit ? getAdminMailLink(rec.recipients,rec.ccs, EmailTemplate.MOUSERECORD, firstInitial + holder.getLastname(), holder.getFirstname() + " " + holder.getLastname() + " (" + holder.getDept() + ")", -1,-1,nextRecord.getMouseID(),holder.getHolderID()) : getMailToLink(rec.recipients, rec.ccs, "Regarding " + nextRecord.getMouseName() + "-Record# " + nextRecord.getMouseID(), null, firstInitial + holder.getLastname(), holder.getFirstname() + " " + holder.getLastname() + " (" + holder.getDept() + ")"); holderBuf.append("<dt" + (overMax ? " style='display:none'" : "") + ">" + (holder.isCovert() ? "<b>CVT</b>-" : "") + mailLink + facilityName + "<span class='lbl'>" + cryoLiveStatus + "</span>" + "</dt>"); holderCount++; } if (overMax) { holderBuf.append("<dt><a class=\"mouselist-holderlist-showall btn btn-mini\" style='text-decoration:none' href='#'><span class='lbl'>show all</span></a></dt>"); } } holderBuf.append("</dl>"); table.append(holderBuf.toString()); table.append("</td>\r\n"); table.append("</tr>\r\n"); numMice++; nextRecord.prepareForSerialization(); } table.append("</table>\r\n"); table.append("</div>\r\n"); if (includeJson) { table.append("<script type='text/javascript'>\r\n"); table.append("MouseConf.addMice(" + new Gson().toJson(mice) + ")"); table.append("</script>"); } if (numMice <= 0) { return "No results found"; } return table.toString(); } private static String getChangeRequestTableHeaders() { StringBuffer table = new StringBuffer(); table.append("<tr class='changerequestlistH'>\r\n"); table.append("<td style='min-width:200px'\">\r\n"); table.append("Status"); table.append("</td>\r\n"); table.append("<td style='min-width:200px'\">\r\n"); table.append("Requestor Info"); table.append("</td>\r\n"); table.append("<td style='min-width:200px'>\r\n"); table.append("Changes Requested"); table.append("</td>\r\n"); table.append("<td style='min-width:200px'>\r\n"); table.append("Administration"); table.append("</td>\r\n"); table.append("<td style='min-width:200px'>\r\n"); table.append("Admin Comment"); table.append("</td>\r\n"); return table.toString(); } public static String getChangeRequestsTable(ArrayList<ChangeRequest> requests, String currentPageStatus) { StringBuffer table = new StringBuffer(); table.append("<div class=\"mouseTable\">\r\n"); table.append("<table style='width:100%'>\r\n"); int numRequests = 0; for (ChangeRequest nextRequest : requests) { if (numRequests % 20 == 0) table.append(getChangeRequestTableHeaders()); String rowStyle = getRowStyle(numRequests, "changerequestlist", "changerequestlistAlt"); table.append("<tr class='" + rowStyle + "'>\r\n"); // COLUMN - Status table.append("<td valign='top'>\r\n"); table.append("<dl>\r\n"); table.append("<dt>"); table.append("Request# " + nextRequest.getRequestID()); table.append("</dt>"); table.append("<dt>"); table.append("Request date: " + nextRequest.getRequestDate()); table.append("</dt>"); table.append("<dt>\r\n"); table.append("Status: <b>" + nextRequest.getStatus() + "</b>"); table.append("</dt>\r\n"); table.append("<dt>\r\n"); table.append("<a href='DeleteChangeRequest.jsp?id=" + nextRequest.getRequestID() + "'>Delete</a>"); table.append("</dt>\r\n"); table.append("</dl>\r\n"); table.append("</td>\r\n"); // COLUMN - Requestor Info table.append("<td valign='top'>\r\n"); table.append("<dl>\r\n"); table.append("<dt>\r\n"); table.append(nextRequest.getFirstname() + " " + nextRequest.getLastname()); table.append("</dt>\r\n"); table.append("<dt>\r\n"); String emailRecipient = nextRequest.getEmail(); String emailCc = null; if (nextRequest.Properties() != null) { String holderName = (String)nextRequest.Properties().get("Add Holder"); if (holderName == null){ holderName = (String)nextRequest.Properties().get("Add Holder Name"); } if (holderName == null){ holderName = (String)nextRequest.Properties().get("Delete Holder Name"); } if (holderName != null){ IHolder holder = DBConnect.findHolder(holderName); if (holder != null){ EmailRecipient rec = EmailRecipientManager.recipientsForRequestorAndHolder(nextRequest.getEmail(), holder); emailRecipient = rec.recipients; emailCc = rec.ccs; } } } table.append(getAdminMailLink(emailRecipient, emailCc, EmailTemplate.CHANGREQUEST, -1,nextRequest.getRequestID(), null,-1)); table.append("</dt>\r\n"); table.append("</dl>\r\n"); table.append("</td>\r\n"); // COLUMN - Requested changes table.append("<td valign='top'>\r\n"); table.append("<span class=\"mouseComment\">" + emptyIfNull(nextRequest.getUserComment()) + "</span>"); if (nextRequest.Properties() != null) { table.append("<dl>"); for (Object key : nextRequest.Properties().keySet()) { String propertyName = (String) key; String propertyValue = (String) nextRequest.Properties() .get(key); if (propertyName.equals("Add Holder") || propertyName.equals("Add Facility")) { int splitterIndex = propertyValue.indexOf('|'); if (splitterIndex > 0) { propertyValue = propertyValue .substring(splitterIndex + 1); } propertyValue = "<b>" + propertyValue + "</b>"; } table.append("<dt>"); table.append(propertyName + " = " + propertyValue); table.append("</dt>\r\n"); } table.append("</dl>"); } table.append("</td>\r\n"); // COLUMN - Administration table.append("<td valign='top'><dl>\r\n"); table.append("<dt>"); table.append("<dt><a href=\"CompleteChangeRequest.jsp?id=" + nextRequest.getRequestID() + "\">Edit record + nextRequest.getMouseID() + "</a></dt>\r\n"); table.append("<dt><b>" + nextRequest.getMouseName() + "</b></dt>"); table.append("</dt>"); // status updates? - ignore, delete, etc table.append("<dt>"); table.append("Last administered: " + emptyIfNull(nextRequest.getLastAdminDate())); table.append("</dt>"); table.append("</dl></td>\r\n"); // COLUMN - Admin comment table.append("<td valign='top'>\r\n"); table.append("<span class=\"mouseComment\">" + emptyIfNull(nextRequest.getAdminComment()) + "</span>"); table.append("</td>"); table.append("</tr>\r\n"); numRequests++; } table.append("</table>\r\n"); table.append("</div>\r\n"); table.append("<script type='text/javascript'>\r\n"); table.append("MouseConf.addChangeRequests(" + new Gson().toJson(requests) + ")"); table.append("</script>"); if (numRequests <= 0) { return "No results found"; } return table.toString(); } private static String getFacilityTableHeaders(boolean edit) { StringBuilder table = new StringBuilder(); table.append("<tr class='facilitylistH'>\r\n"); if (edit) { table.append("<td>ID</td>"); } table.append("<td style='min-width:400px'>\r\n"); table.append("Facility"); table.append("</td>\r\n"); table.append("<td style='min-width:100px'>\r\n"); table.append("Records"); table.append("</td>\r\n"); if (edit) { table.append("<td style='min-width:60px'\">\r\n"); table.append("Code (for data uploads)"); table.append("</td>\r\n"); table.append("<td style='min-width:60px'\">\r\n"); table.append("Edit"); table.append("</td>\r\n"); } table.append("</tr>\r\n"); return table.toString(); } public static String getFacilityTable(ArrayList<Facility> facilities, boolean edit) { StringBuilder table = new StringBuilder(); table.append("<div class=\"facilityTable\">\r\n"); table.append("<table><thead>\r\n"); table.append(getFacilityTableHeaders(edit)); table.append("</thead><tbody>"); int numFacilities = 0; for (Facility facility : facilities) { String rowStyle = getRowStyle(numFacilities, "facilitylist", "facilitylistAlt"); table.append("<tr class='" + rowStyle + "'>\r\n"); if (edit) { table.append("<td>" + facility.getFacilityID() + "</td>"); } table.append("<td style='min-width:400px'>\r\n"); table.append("<span class=\"mouseName\">" + facility.getFacilityName() + "</span> &nbsp;-&nbsp;" + facility.getFacilityDescription()); table.append("</td><td style='min-width:100px'>"); table.append("<span style=\"position:relative;left:5px\"><a href=\"" + siteRoot + "MouseReport.jsp?facility_id=" + facility.getFacilityID() + "\">" + facility.getRecordCount() + " records</a></span>\r\n"); table.append("</td>\r\n"); if (edit) { table.append("<td style='min-width:60px'>" + HTMLGeneration.emptyIfNull(facility.getFacilityCode()) + "</td>"); table.append("<td style='min-width:60px'><a href=\"EditFacilityForm.jsp?facilityID=" + facility.getFacilityID() + "\">Edit</a></td>\r\n"); } table.append("</tr>"); numFacilities++; } table.append("</tbody></table>\r\n"); if (numFacilities <= 0) return "No results found"; return table.toString(); } private static String getGeneTableHeaders(boolean edit) { StringBuilder table = new StringBuilder(); table.append("<tr class='facilitylistH'>\r\n"); table.append("<td style='width:500px'\">\r\n"); table.append("Gene Details"); table.append("</td>\r\n"); table.append("<td style='width:220px'\">\r\n"); table.append("Records"); table.append("</td>\r\n"); if (edit) { table.append("<td style='width:50px'\">\r\n"); table.append("Edit"); table.append("</td>\r\n"); } table.append("</tr>\r\n"); return table.toString(); } public static String getGeneTable(ArrayList<Gene> genes, boolean edit) { StringBuilder table = new StringBuilder(); table.append("<div class=\"facilityTable\">\r\n"); table.append("<table>\r\n"); table.append(getGeneTableHeaders(edit)); int numFacilities = 0; for (Gene gene : genes) { String rowStyle = getRowStyle(numFacilities, "facilitylist", "facilitylistAlt"); table.append("<tr class='" + rowStyle + "'>\r\n"); table.append("<td>\r\n"); table.append(formatGene(gene.getSymbol(), gene.getFullname(), gene.getMgiID())); table.append("</td>\r\n<td>\r\n"); table.append("<span style=\"position:relative;left:5px\">" + "<a href=\"" + siteRoot + "MouseReport.jsp?&geneID=" + gene.getGeneRecordID() + "&orderby=mouse.id&mousetype_id=-1\">" + gene.getRecordCount() + " record" + (gene.getRecordCount() != 1 ? "s" : "") + "</a></span>\r\n"); table.append("</td>\r\n"); if (edit) { table.append("<td><a href=\"EditGeneForm.jsp?geneRecordID=" + gene.getGeneRecordID() + "\">Edit</a></td>\r\n"); } table.append("</tr>"); numFacilities++; } table.append("</table>\r\n"); if (numFacilities <= 0) return "No results found"; return table.toString(); } private static String getHolderTableHeaders(boolean edit) { StringBuilder table = new StringBuilder(); table.append("<tr class='facilitylistH'>\r\n"); if (edit) { table.append("<td>ID</td>"); } table.append("<td style='min-width:350px'\">\r\n"); table.append("Holder Information"); table.append("</td>\r\n"); table.append("<td style='min-width:300px'\">\r\n"); table.append("Contact Information"); table.append("</td>\r\n"); table.append("<td style='min-width:150px'\">\r\n"); table.append("Primary Contact"); table.append("</td>\r\n"); table.append("<td >\r\n"); table.append("Last Review Date"); table.append("</td>\r\n"); table.append("<td style='min-width:100px'\">\r\n"); table.append("Mice Held"); table.append("</td>\r\n"); if (edit) { table.append("<td style='width:100px'\">\r\n"); table.append("Edit"); table.append("</td>\r\n"); } table.append("</tr>\r\n"); return table.toString(); } public static String getHolderTable(ArrayList<Holder> holders, boolean edit) { StringBuilder table = new StringBuilder(); table.append("<div class=\"facilityTable\">\r\n"); table.append("<table >\r\n"); table.append(getHolderTableHeaders(edit)); int numFacilities = 0; for (IHolder holder : holders) { String rowStyle = getRowStyle(numFacilities, "holderlist", "holderlistAlt"); table.append("<tr class='" + rowStyle + "'>\r\n"); if (edit) { table.append("<td>" + holder.getHolderID() + "</td>"); } table.append("<td>\r\n"); table.append("<div style=\"position:relative; left:2px; float:left;\"><b>" + holder.getFullname() + "</b></div>"); table.append(" <div style=\"position: relative; right: 10px; float:right;\">(" + holder.getDept() + ")</div>"); table.append("</td>\r\n"); table.append("<td>\r\n"); String emailLink = edit ? getAdminMailLink(holder.getEmail(), null, EmailTemplate.HOLDER, -1, -1, null, holder.getHolderID()) : formatEmail(holder.getEmail(), holder.getEmail(),""); table.append("<div style=\"position:relative; left:2px; float:left;\">" + emailLink + "</div>"); table.append(" <div style=\"position: relative; right: 10px; float:right;\">Tel: " + holder.getTel() + "</div>"); table.append("</td>\r\n"); table.append("<td>\r\n"); table.append(HTMLGeneration.emptyIfNull(holder.getAlternateName())); if (holder.getAlternateEmail() != null && !holder.getAlternateEmail().equals("")){ emailLink = edit ? getAdminMailLink(holder.getAlternateEmail(), null, EmailTemplate.HOLDER, -1, -1, null, holder.getHolderID()) : formatEmail(holder.getAlternateEmail(), holder.getAlternateEmail(),""); table.append(", " + emailLink); } table.append("</td>\r\n"); table.append("<td>\r\n"); if (holder.getDateValidated() != null) { table.append(holder.getDateValidated()); } table.append("</td>\r\n"); table.append("<td >\r\n"); String href = ""; if (edit) { href = adminRoot + "EditMouseSelection.jsp"; } else { href = siteRoot + "MouseReport.jsp"; } String covertList = ""; int count = holder.getVisibleMouseCount(); if (edit && holder.getCovertMouseCount() > 0) { covertList = "<br>(" + holder.getCovertMouseCount() + " covert)"; count += holder.getCovertMouseCount(); } table.append("<a href=\"" + href + "?holder_id=" + holder.getHolderID() + "&mousetype_id=-1\">" + (edit ? "edit " : "") + count + " records</a>" + covertList + ""); table.append("</td>\r\n"); if (edit) { table.append("<td><a href=\"EditHolderForm.jsp?holderID=" + holder.getHolderID() + "\">Edit holder #" + holder.getHolderID() + "</a></td>\r\n"); } table.append("</tr>"); numFacilities++; } table.append("</table>\r\n"); if (edit) { table.append("<script type='text/javascript'>\r\n"); table.append("MouseConf.addHolders(" + new Gson().toJson(holders) + ")"); table.append("</script>"); } if (numFacilities <= 0) return "No results found"; return table.toString(); } private static String getImportReportTableHeaders(boolean edit) { StringBuilder table = new StringBuilder(); table.append("<tr class='facilitylistH'>\r\n"); table.append("<td style='width:150px'\">\r\n"); table.append("Details"); table.append("</td>\r\n"); table.append("<td style='min-width:500px'\">\r\n"); table.append("Data Upload Results"); table.append("</td>\r\n"); // if (edit) // table.append("<td style='width:50px'\">\r\n"); // table.append("Edit"); // table.append("</td>\r\n"); table.append("</tr>\r\n"); return table.toString(); } public static String getImportReportTable(ArrayList<ImportReport> reports, boolean edit) { StringBuilder table = new StringBuilder(); table.append("<div class=\"facilityTable\">\r\n"); table.append("<table>\r\n"); table.append(getImportReportTableHeaders(edit)); int numFacilities = 0; for (ImportReport report : reports) { String rowStyle = getRowStyle(numFacilities, "facilitylist", "facilitylistAlt"); table.append("<tr class='" + rowStyle + "'>\r\n"); table.append("<td valign=\"top\">\r\n"); //table.append("<dl><dt>Report ID: " + report.getImportReportID() // + "</dt>\r\n"); table.append("<dt>Name: " + report.getName() + "</dt>\r\n"); table.append("<dt>Created: " + report.getCreationDate() + "</dt>\r\n"); table.append("<dt><a href='DeleteImportReport.jsp?id=" + report.getImportReportID() + "'>Delete...</a></dt></dl>"); table.append("</td>\r\n<td>\r\n"); table.append(report.getReportText()); table.append("</td>\r\n"); // if (edit) // table.append("<td><a href=\"EditGeneForm.jsp?geneRecordID=" // + gene.getGeneRecordID() // + "\">Edit</a></td>\r\n"); table.append("</tr>"); numFacilities++; } table.append("</table>\r\n"); if (numFacilities <= 0) return "No results found"; return table.toString(); } /* Small utility methods */ public static String emptyIfNull(Object input) { if (input != null) { return input.toString(); } else { return ""; } } public static String chooseOneIfNull(String input) { if (input != null) { return input; } else { return "Choose One"; } } public static String isChecked(boolean checked) { if (checked) { return "checked=\"checked\""; } return ""; } public static String elementVisibility(boolean show) { if (show) { return "display: block"; } return "display: none"; } public static String rowVisibility(boolean show) { if (show) { return ""; } return "display: none"; } // Superscript public static String replaceBrackets(String s) { String newStr = null; if (s != null) { newStr = s.replace("<", "<sup"); newStr = newStr.replace(">", "</sup>"); newStr = newStr.replace("<sup", "<sup>"); if (newStr.contains("<sup>") && !newStr.contains("</sup>")) { newStr += "</sup>"; } } return newStr; } private static String formatGene(String symbol, String name, String mgi) { return "<dd class=\"mouseSubDetail\"><span class='geneSymbol'>" + symbol + "</span> - <span class='geneName'>" + name + "</span></dd>\r\n" + "<dd class=\"mouseSubDetail\"><span class='mgiGeneLink'><span class='lbl'>MGI:</span> " + formatMGI(mgi) + "</span></dd>\r\n"; } public static String formatMGI(String id) { if (id == null) return "&lt;not available&gt;"; try { Integer.parseInt(id.trim()); } catch (Exception e) { return id; } String url = "http: + id.trim(); StringBuffer link = new StringBuffer(); link.append("<a href=\"" + url + "\" target=\"_blank\">"); link.append(id); link.append("</a>"); return link.toString(); } public static String formatPubMedID(String value) { if (value == null) return "&lt;not available&gt;"; if (value.equalsIgnoreCase("null")) return ""; return "<a href=\"http: + value + "&amp;dopt=Abstract\" target=\"_blank\">" + value + "</a>"; } public static String formatInbredStrainURL(String supplier) { if (supplier == null) { return ""; } String jaxUrl = "http://jaxmice.jax.org/strain/"; String jaxUrlTail = ".html"; // non jax urls are stored as <label>||<url> if (supplier.contains("||")) { String[] tokens = supplier.split("\\|\\|"); if (tokens.length == 2) { return formatInbredStrainURL(tokens[0], tokens[1]); } } else if (supplier.toUpperCase().startsWith("JAX")) { Matcher match = jaxPattern.matcher(supplier); String catalogUrl = ""; if (match.find()) { catalogUrl = jaxUrl + match.group(1) + jaxUrlTail; } return formatInbredStrainURL(supplier, catalogUrl); } return formatInbredStrainURL(supplier, null); } public static String formatInbredStrainURL(String label, String url) { if (label == null || label.isEmpty()) return "&lt;not available&gt;"; if (url == null || url.trim().isEmpty()) return label; String fixedUrl = url; if (!(fixedUrl.toLowerCase().startsWith("http://") || fixedUrl .toLowerCase().startsWith("https: fixedUrl = "http://" + fixedUrl; } return "<a target=\"_blank\" href='" + fixedUrl + "'>" + label + "</a>"; } public static String formatGensat(String value) { if (value == null) return ""; String gensatUrl = "http: String gensatUrlTail = ""; return "<a href='" + gensatUrl + value + gensatUrlTail + "'>" + value + "</a>"; } // To be retired @SuppressWarnings("rawtypes") public static void formatSearchTerms(StringBuffer buf, String title, Vector terms, int fontSize) { if (terms.size() > 0) { buf.append("<tr><td valign=top><font size=" + fontSize + ">" + title + "</font></td>"); buf.append("<td valign=top>"); for (Enumeration e = terms.elements(); e.hasMoreElements();) { buf.append("<font size=" + fontSize + ">" + (String) e.nextElement() + "<br></font>"); } buf.append("</td></tr>"); } } public static String getMultiSelectWidget(String name, ArrayList<String> allOptions, ArrayList<String> allOptionsNiceNames, ArrayList<String> selectedOptions, ArrayList<String> selectedOptionsNiceNames) { StringBuffer sb = new StringBuffer(); sb.append("<table cellspacing=\"0\" cellpadding=\"10\" border=\"1\" bgcolor=\"white\">"); sb.append("<tbody>"); sb.append("<tr>"); sb.append("<td align=\"center\">"); sb.append("<select multiple=\"\" size=\"10\" name=\"" + name + "All\" id=\"" + name + "All\">"); for (int i = 0; i < allOptions.size(); i++) { sb.append("<option value=\"" + allOptions.get(i) + "\">" + allOptionsNiceNames.get(i) + "</option>\r\n"); } sb.append("</select>"); sb.append("<br/>"); sb.append("<p align=\"center\">"); sb.append("<input type=\"button\" value=\"Select\" onclick=\"one2two('" + name + "')\"/>"); sb.append("</p>"); sb.append("</td>"); sb.append("<td align=\"center\">"); sb.append("<select multiple=\"\" size=\"10\" name=\"" + name + "\" id=\"" + name + "\">"); for (int i = 0; i < selectedOptions.size(); i++) { sb.append("<option value=\"" + selectedOptions.get(i) + "\">" + selectedOptionsNiceNames.get(i) + "</option>"); } sb.append("</select>"); sb.append("<br/>"); sb.append("<p align=\"center\">"); sb.append("<input type=\"button\" value=\" Deselect \" onclick=\"two2one('" + name + "')\"/>"); sb.append("</p>"); sb.append("</td>"); sb.append("</tr>"); sb.append("</tbody>"); sb.append("</table>"); return sb.toString(); } // Copied from fieldGenerators.jspf public static String genSelect(String name, String[] values, String current) { return genSelect(name, values, current, ""); } public static String genSelect(String name, String[] values, String current, String selectParams) { return genSelect(name, values, values, current, selectParams); } public static String genSelect(String name, String[] values, String[] niceNames, String current, String selectParams) { return genSelect(name,values,niceNames,current,selectParams,true,true); } public static String genSelect(String name, String[] values, String[] niceNames, String current, String selectParams,boolean includeId) { return genSelect(name, values, niceNames, current, selectParams, includeId, true); } public static String genSelect(String name, String[] values, String[] niceNames, String current, String selectParams,boolean includeId,boolean chosenIfLarge) { if (selectParams == null) selectParams = ""; StringBuffer b = new StringBuffer(); String cssClass = values.length > 20 && chosenIfLarge ? "class='chzn-select'" : ""; b.append("<select " + cssClass); if(includeId){ b.append("id='" + name + "' "); } b.append("name=\"" + name + "\" " + selectParams + ">"); for (int i = 0; i < values.length; i++) { String value = values[i]; String niceName = niceNames[i]; b.append("<option value=\"" + value + "\""); if (current != null && value != null && value.equalsIgnoreCase(current)) { b.append(" selected=selected"); } b.append(">" + niceName + "\n"); } b.append("</select>"); return b.toString(); } public static String getModificationTypeSelect(String current) { String name = "modificationType"; String[] values = { "Select one", "targeted disruption", "conditional allele (loxP/frt)", "gene trap insertion", "Chemically induced (ENU)", "spontaneous mutation", "other (info in comment)" }; return genSelect(name, values, current, ""); } public static String getModificationTypeSelect() { return getModificationTypeSelect(null); } public static String getMouseTypeSelect() { return getMouseTypeSelect(null); } public static String getMouseTypeSelect(String current) { return getMouseTypeSelectWithParams(current, ""); } public static String getMouseTypeSelectWithParams(String current, String selectParams) { String name = "MouseType"; String[] values = { "Select one", "Mutant Allele", "Transgene", "Inbred Strain" }; return genSelect(name, values, current, selectParams); } public static String getExpressedSequenceSelect(String current) { String name = "ExpressedSequence"; String[] values = { "Select one", "mouse gene", "Cre", "Reporter", "Other" }; return genSelect(name, values, current); } public static String getExpressedSequenceSelect() { return getExpressedSequenceSelect(null); } public static String getTransgenicTypeSelect(String current) { String name = "TransgenicType"; String[] values = { "Select one", "knock-in", "random insertion" }; return genSelect(name, values, current); } public static String getTransgenicTypeSelect() { return getTransgenicTypeSelect(null); } public static String genRadio(String name, String[] values, String current) { return genRadio(name, values, current, ""); } public static String genYesNoRadio(String name, String current) { String[] values = { "Yes", "No" }; return genRadio(name, values, current); } public static String genRadio(String name, String[] values, String current, String selectParams) { StringBuffer b = new StringBuffer(); for (int i = 0; i < values.length; i++) { String value = values[i]; b.append("<input type=\"radio\" name=\"" + name + "\" value=\"" + value + "\" " + selectParams); if (current != null && value.equalsIgnoreCase(current)) { b.append(" checked=checked"); } b.append(">" + value + "\n<br>\n"); } return b.toString(); } public static String genFlatRadio(String name, String[] values, String[] niceNames, String current, String selectParams) { StringBuffer b = new StringBuffer(); for (int i = 0; i < values.length; i++) { String value = values[i]; String niceName = niceNames[i]; b.append("<input type=\"radio\" name=\"" + name + "\" value=\"" + value + "\" " + selectParams); if (current != null && value.equalsIgnoreCase(current)) { b.append(" checked=checked"); } b.append(">" + niceName + "\n"); } return b.toString(); } public static String genRadio(String name, String[] values, String[] niceNames, String current, String selectParams) { StringBuffer b = new StringBuffer(); for (int i = 0; i < values.length; i++) { String value = values[i]; String niceName = niceNames[i]; b.append("<input type=\"radio\" name=\"" + name + "\" value=\"" + value + "\" " + selectParams); if (current != null && value.equalsIgnoreCase(current)) { b.append(" checked=checked"); } b.append(">" + niceName + "<br>\n"); } return b.toString(); } public static String getModificationTypeRadio(String current) { return getModificationTypeRadioWithParams(current, ""); } public static String getModificationTypeRadioWithParams(String current, String selectParams) { String name = "MAModificationType"; String[] values = { "targeted disruption", "conditional allele (loxP/frt)", "targeted knock-in", "gene trap insertion", "Chemically induced (ENU)", "spontaneous mutation", "other (info in comment)" }; return genRadio(name, values, current, selectParams); } public static String getModificationTypeRadio() { return getModificationTypeRadio(null); } public static String getMouseTypeRadio() { return getMouseTypeRadio(null); } public static String getMouseTypeRadio(String current) { return getMouseTypeRadioWithParams(current, ""); } public static String getMouseTypeRadioWithParams(String current, String selectParams) { String name = "mouseType"; String[] values = { "Mutant Allele", "Transgene", "Inbred Strain" }; return genRadio(name, values, current, selectParams); } public static String getExpressedSequenceRadio(String current) { return getExpressedSequenceRadioWithParams(current, ""); } public static String getExpressedSequenceRadioWithParams(String current, String selectParams) { String name = "TGExpressedSequence"; String[] values = { "Reporter", "Cre", "Mouse Gene (unmodified)", "Modified mouse gene or Other" }; return genRadio(name, values, current, selectParams); } public static String getExpressedSequenceRadio() { return getExpressedSequenceRadio(null); } public static String getTransgenicTypeRadio(String current) { return getTransgenicTypeRadioWithParams(current, ""); } public static String getTransgenicTypeRadioWithParams(String current, String selectParams) { String name = "transgenicType"; String[] values = { "knock-in", "random insertion" }; return genRadio(name, values, current, selectParams); } public static String getTransgenicTypeRadio() { return getTransgenicTypeRadio(null); } public static String genCheckbox(String name, String[] values, String current) { return genCheckbox(name, values, current, ""); } public static String genCheckbox(String name, String[] values, String current, String selectParams) { StringBuffer b = new StringBuffer(); for (int i = 0; i < values.length; i++) { String value = values[i]; b.append("<input type=\"checkbox\" name=\"" + name + "\" value=\"" + value + "\" " + selectParams); if (current != null && value.equals(current)) { b.append(" checked=checked"); } b.append(">" + value + "\n<br>\n"); } return b.toString(); } public static boolean isInArray(String value, String[] array) { if (value == null) return false; if (array == null || array.length <= 0) return false; for (String arrVal : array) { if (arrVal.equalsIgnoreCase(value)) return true; } return false; } public static String getMouseTypeSelectionLinks(int checkedMouseTypeID, String checkedOrderBy, int holderID, int geneRecordID, ArrayList<MouseType> mouseTypes, String status, String searchTerms, int creOnly, int facilityID) { StringBuffer buf = new StringBuffer(); buf.append("<div class='mousetype_selection_links'>"); buf.append("<ul>"); buf.append("<li>Sort by: "); buf.append(genSelect("orderby",new String[]{"mouse.name","mouse.id","mouse.id desc"}, new String[]{"Mouse Name", "Record #", "Record #(reverse)"},checkedOrderBy,null)); buf.append("</li>\n"); buf.append("<li>Category: "); String[] mouseTypeIds = new String[mouseTypes.size() + 1]; String[] mouseTypeNames = new String[mouseTypes.size() + 1]; int i = 1; mouseTypeIds[0] = "-1"; mouseTypeNames[0] = "All"; for (MouseType type : mouseTypes) { mouseTypeIds[i] = Integer.toString(type.getMouseTypeID()); mouseTypeNames[i] = type.getTypeName(); i++; } buf.append(genSelect("mousetype_id", mouseTypeIds, mouseTypeNames, Integer.toString(checkedMouseTypeID), null) ); buf.append("</li>"); if (status != null) { buf.append("<li>Status: "); buf.append(genSelect("status",new String[]{"live","deleted","all"},new String[]{"Live","Deleted","All"},status,null)); buf.append("</li>\n"); } if (creOnly >= 0) { buf.append("<li>Cre-expressing mice only: <input type='checkbox' name='creonly' value='1' " + (creOnly == 1 ? "checked='checked'" : "") + "></li>"); } if (status != null) { buf.append("<li class='cf'><input type='text' size='20' id='mousetypeselection_searchterms' name='searchterms'" + (searchTerms != null ? "value='" + searchTerms + "'" : "") + ">&nbsp;"); buf.append("<input class='btn btn-small' type='submit' value='Search'></input></li>"); } if (holderID != -1) { buf.append("<input type='hidden' name='holder_id' value='" + holderID + "'>"); } if (geneRecordID != -1) { buf.append("<input type='hidden' name='geneID' value='" + geneRecordID + "'>"); } if (facilityID != -1) { buf.append("<input type='hidden' name='facility_id' value='" + facilityID + "'>"); } buf.append("</div>"); return buf.toString(); } public static String getPageSelectionLinks(int limit, int pageNum, int total, boolean includeLimitSelector) { StringBuffer buf = new StringBuffer(); String[] values = new String[] { "10", "25", "50", "100", "500", "-2" }; String[] labels = new String[] { "10", "25", "50", "100", "500", "All" }; String perPageDropDown = genSelect("limit", values, labels, Integer.toString(limit), "style='width:60px'"); buf.append("<table>"); if (includeLimitSelector) { buf.append("<tr>" + "<td>" + "Records per page: &nbsp;" + perPageDropDown + "</td></tr>"); } if (limit > 0) { buf.append("<tr><td>Page "); int pageCount = (total + limit - 1) / limit; // int buttonCount = 0; // int maxButtons = 10; boolean skipping = false; for (int i = 1; i <= pageCount; i++) { String cssClass = "linkButton"; if (i == pageNum) { cssClass = "linkButtonCurrent"; } if (i != 1 && i != pageCount && i != (pageCount - 1) && (Math.abs(pageNum - i) > 4)) { if (!skipping) { buf.append("..."); } skipping = true; continue; } skipping = false; buf.append("<input class=\"" + cssClass + "\" type=\"submit\" name=\"pagenum\" value=\"" + i + "\">\r\n"); } buf.append("</td>" + "</tr>"); } buf.append("</table>"); return buf.toString(); } public static String getNewPageSelectionLinks(int limit, int pageNum, int total, boolean includeLimitSelector) { StringBuffer buf = new StringBuffer(); if (limit == -1) { return ""; } buf.append("<div class='pagination-container clearfix'>"); int pageCount = (total + limit - 1) / limit; if (limit == -2){ pageCount = 1; } String[] pageNums = new String[pageCount]; for (int i = 0; i < pageCount; i++) { pageNums[i] = Integer.toString(i + 1); } String pageSelect = genSelect("pagenum_select", pageNums, pageNums, Integer.toString(pageNum),"style='vertical-align: 0%;'",false,false); buf.append("<a class='btn" + ((pageNum <= 1) ? " disabled":"" ) + "'href='#' data-pagenum='" + (pageNum - 1) +"'><i class='icon-chevron-left'></i> Previous</a>\r\n"); buf.append("<span class='well' style='padding:6px;vertical-align:middle'>Page " + pageSelect + " of " + pageCount + "</span>\r\n"); buf.append("<a class='btn" + ((pageNum >= pageCount) ? " disabled":"" ) + "' href='#' data-pagenum='" + (pageNum + 1) +"'>Next <i class='icon-chevron-right'></i></a>\r\n"); if (includeLimitSelector) { String[] values = new String[] { "10", "25", "50", "100", "500", "-2" }; String[] labels = new String[] { "10", "25", "50", "100", "500", "All" }; String perPageDropDown = genSelect("limit", values, labels, Integer.toString(limit), "style='width:60px'",false,false); buf.append("<span style='vertical-align:middle'>&nbsp;&nbsp;" + perPageDropDown + " <span>per page</span></span>"); } buf.append("</div>"); return buf.toString(); } private static String gimmeSortRadio(String param, String niceName, String current) { return gimmeRadio(param, niceName, current, "orderby"); } private static String gimmeRadio(String param, String niceName, String current, String inputName) { String checked = ""; if (param != null && param.equalsIgnoreCase(current)) { checked = "checked"; } String s = "<td>"; if (niceName.length() > 10) { s = "<td colspan=2>"; } s += "<input type=\"radio\" name=\"" + inputName + "\" value=\"" + param + "\" " + checked + ">" + niceName + "</td>"; return s; } public static int stringToInt(String str) { try { return Integer.parseInt(str); } catch (Exception e) { return -1; } } public static String getTextInput(String name, String current, int size, int maxLength, String params) { return "<input type=\"text\" name=\"" + name + "\"" + (current != null ? " value=\"" + current + "\"" : "") + "size=\"" + size + "\" " + (maxLength > 0 ? "maxlength=\"" + maxLength + "\" " : "") + (params != null ? params : "") + ">\r\n"; } public static String tInput(String name, String current){ return "<input type='text' name='" + name + (current != null ? "' value='" + current + "'" : "'") + " />"; } public static String tArea(String name, String current){ return "<textarea name='" + name + "'>" + (current != null ? current : "") + "</textarea>"; } public static String formatEmail(String emailAddress, String linkText, String subject) { return formatEmail(emailAddress, null, linkText, subject); } public static String formatEmail(String emailAddress, String ccAddress, String linkText, String subject) { return getMailToLink(emailAddress, ccAddress, subject, null, linkText); } public static String getMailToLink(String address, String cc, String subject, String body, String linkText) { return getMailToLink(address, cc, subject, body, linkText, null, false, null); } public static String getMailToLink(String address, String cc, String subject, String body, String linkText, String linkTitle) { return getMailToLink(address, cc, subject, body, linkText, linkTitle, false, null); } public static String getAdminMailLink(String address, String cc, String templateCategory, int subId, int requestId, String mouseId, int holderId){ return getAdminMailLink(address, cc, templateCategory, null,null, subId, requestId, mouseId, holderId); } public static String getAdminMailLink(String address, String cc, String templateCategory, String linkText, String linkTitle, int subId, int requestId, String mouseId, int holderId){ Properties props = new Properties(); if (subId > 0) { props.setProperty("submission_id", Integer.toString(subId)); } if (requestId > 0) { props.setProperty("request_id", Integer.toString(requestId)); } if (mouseId != null) { props.setProperty("mouse_id", mouseId); } if (holderId > 0) { props.setProperty("holder_id", Integer.toString(holderId)); } props.setProperty("category", templateCategory); return getMailToLink(address, cc, null, null, linkText == null ? address : linkText, linkTitle, true, props); } private static String getMailToLink(String address, String cc, String subject, String body, String linkText, String linkTitle, boolean admin, Properties props) { if (address == null || address.isEmpty()) { address = cc; cc = null; } String recipient = address; String ccRecipient = null; String ccAddr = "?"; if (cc != null && !cc.isEmpty() && !cc.equals(address)) { ccRecipient = cc; ccAddr = "?cc=" + cc + "&"; } if (cc != null && !cc.isEmpty() && address == null){ address = cc; ccAddr = "?"; recipient = cc; } if (admin) { String link = "<a class='adminEmailButton' href=' link += " data-recipient='" + recipient + "'"; if (ccRecipient != null){ link += " data-cc='" + ccRecipient + "'"; } if (props != null) { for (String key : props.stringPropertyNames()) { link += " data-" + key + "='" + props.getProperty(key) + "'"; } } if (linkTitle != null) { link += " title='" + linkTitle + "'"; } link += ">" + linkText + "</a>"; return link; } else { return "<a" + (linkTitle != null ? " title='" + linkTitle + "'":"") + " href=\"mailto:" + address + ccAddr + "subject=" + urlEncode(subject) + (body != null ? "&body=" + urlEncode(body) : "") + "\">" + linkText + "</a>"; } } public static String dataEncode(String text){ if (text == null || text.isEmpty()){ return text; } return text.replace("'", "&quot;"); } public static String urlEncode(String text){ try { return URLEncoder.encode(text,"ISO-8859-1").replace("+", "%20"); } catch (UnsupportedEncodingException e) { Log.Error("Failed to encode text with ISO-8859-1 encoding",e); return "failed to encode"; } } public static boolean isAdminUser(HttpServletRequest request){ return request.isUserInRole("administrator"); } }
package fi.hsl.parkandride.dev; import com.mysema.query.sql.RelationalPath; import com.mysema.query.sql.postgres.PostgresQueryFactory; import fi.hsl.parkandride.FeatureProfile; import fi.hsl.parkandride.back.sql.*; import fi.hsl.parkandride.core.back.UserRepository; import fi.hsl.parkandride.core.domain.*; import fi.hsl.parkandride.core.service.AuthenticationService; import fi.hsl.parkandride.core.service.TransactionalRead; import fi.hsl.parkandride.core.service.TransactionalWrite; import fi.hsl.parkandride.core.service.UserService; import org.springframework.context.annotation.Profile; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.inject.Inject; import java.util.Objects; import static fi.hsl.parkandride.back.ContactDao.CONTACT_ID_SEQ; import static fi.hsl.parkandride.back.FacilityDao.FACILITY_ID_SEQ; import static fi.hsl.parkandride.back.HubDao.HUB_ID_SEQ; import static fi.hsl.parkandride.back.OperatorDao.OPERATOR_ID_SEQ; import static fi.hsl.parkandride.back.PredictorDao.PREDICTOR_ID_SEQ; import static fi.hsl.parkandride.back.UserDao.USER_ID_SEQ; import static java.lang.String.format; @Component @Profile({FeatureProfile.DEV_API}) public class DevHelper { private final PostgresQueryFactory queryFactory; private final JdbcTemplate jdbcTemplate; @Resource UserRepository userRepository; @Resource UserService userService; @Resource AuthenticationService authenticationService; @Inject public DevHelper(PostgresQueryFactory queryFactory, JdbcTemplate jdbcTemplate) { this.queryFactory = queryFactory; this.jdbcTemplate = jdbcTemplate; } @TransactionalWrite public void deleteAll() { deletePredictors(); deleteHubs(); deleteFacilities(); deleteContacts(); deleteUsers(); deleteOperators(); } @TransactionalWrite public void deleteContacts() { delete(QContact.contact); resetContactSequence(); } @TransactionalWrite public void deleteUsers() { delete(QAppUser.appUser); resetUserSequence(); } @TransactionalWrite public User createOrUpdateUser(NewUser newUser) { UserSecret userSecret; try { userSecret = userRepository.getUser(newUser.username); if (newUser.operatorId != null && !Objects.equals(newUser.operatorId, userSecret.user.operatorId)) { throw new IllegalArgumentException("Tried to create user '" + newUser.username + "' with operatorId " + newUser.operatorId + ", but there already was a user with same name and operatorId " + userSecret.user.operatorId + " and we can't change the operatorId afterwards"); } if (newUser.role != userSecret.user.role) { userRepository.updateUser(userSecret.user.id, newUser); } if (newUser.password != null) { userRepository.updatePassword(userSecret.user.id, authenticationService.encryptPassword(newUser.password)); } } catch (NotFoundException e) { userSecret = new UserSecret(); userSecret.user = userService.createUserNoValidate(newUser); } return userSecret.user; } @TransactionalRead public Login login(String username) { UserSecret userSecret = userRepository.getUser(username); Login login = new Login(); login.token = authenticationService.token(userSecret.user); login.username = userSecret.user.username; login.role = userSecret.user.role; login.operatorId = userSecret.user.operatorId; login.permissions = login.role.permissions; return login; } @TransactionalWrite public void deleteOperators() { delete(QOperator.operator); resetOperatorSequence(); } @TransactionalWrite public void deleteFacilities() { delete( QFacilityPrediction.facilityPrediction, QFacilityUtilization.facilityUtilization, QFacilityService.facilityService, QFacilityPaymentMethod.facilityPaymentMethod, QFacilityAlias.facilityAlias, QPricing.pricing, QPort.port, QUnavailableCapacity.unavailableCapacity, QFacility.facility); resetFacilitySequence(); } @TransactionalWrite public void deleteHubs() { delete(QHubFacility.hubFacility, QHub.hub); resetHubSequence(); } @TransactionalWrite public void deletePredictors() { delete(QPredictor.predictor); resetPredictorSequence(); } @TransactionalWrite public void resetHubSequence() { resetSequence(HUB_ID_SEQ, queryFactory.from(QHub.hub).singleResult(QHub.hub.id.max())); } @TransactionalWrite public void resetFacilitySequence() { resetSequence(FACILITY_ID_SEQ, queryFactory.from(QFacility.facility).singleResult(QFacility.facility.id.max())); } @TransactionalWrite public void resetPredictorSequence() { resetSequence(PREDICTOR_ID_SEQ, queryFactory.from(QPredictor.predictor).singleResult(QPredictor.predictor.id.max())); } @TransactionalWrite public void resetContactSequence() { resetSequence(CONTACT_ID_SEQ, queryFactory.from(QContact.contact).singleResult(QContact.contact.id.max())); } @TransactionalWrite public void resetUserSequence() { resetSequence(USER_ID_SEQ, queryFactory.from(QAppUser.appUser).singleResult(QAppUser.appUser.id.max())); } @TransactionalWrite public void resetOperatorSequence() { resetSequence(OPERATOR_ID_SEQ, queryFactory.from(QOperator.operator).singleResult(QOperator.operator.id.max())); } private void delete(RelationalPath... tables) { for (RelationalPath table : tables) { queryFactory.delete(table).execute(); } } private void resetSequence(String sequence, Long currentMax) { if (currentMax == null) { currentMax = 0L; } jdbcTemplate.execute(format("drop sequence %s", sequence)); jdbcTemplate.execute(format("create sequence %s increment by 1 start with %s", sequence, currentMax + 1)); } }
package edu.uib.info310.model.mock; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import edu.uib.info310.model.Artist; import edu.uib.info310.model.Record; import edu.uib.info310.model.Track; public class MockRecord implements Record { public String getName() { return "Music of the Sun"; } public String getImage() { return "http://images.uulyrics.com/cover/r/rihanna/album-music-of-the-sun.jpg"; } public String getYear() { return "2005"; } public String getLabel() { return "Def Jam Recordings"; } public List<Track> getTracks(){ List<Track> tracks = new LinkedList<Track>(); tracks.add(new MockTrack()); tracks.add(new MockTrack()); tracks.add(new MockTrack()); tracks.add(new MockTrack()); return tracks; } public String getId() { return "http://dbpedia.org/resource/Music_of_the_Sun"; } public String getDescription() { return "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; } public List<Artist> getArtist(){ List<Artist> artists = new LinkedList<Artist>(); artists.add(new MockArtist()); return artists; } public List<Record> getRelatedRecord(){ List<Record> records = new LinkedList<Record>(); records.add(new MockRecord()); records.add(new MockRecord()); records.add(new MockRecord()); records.add(new MockRecord()); records.add(new MockRecord()); records.add(new MockRecord()); records.add(new MockRecord()); records.add(new MockRecord()); return records; } }
package eu.thog92.generator.api.irc; import eu.thog92.generator.api.BotGenerator; import eu.thog92.generator.api.events.EventBus; import eu.thog92.generator.api.events.irc.IRCChannelMessage; import eu.thog92.generator.api.events.irc.IRCPrivateMessage; import eu.thog92.generator.api.events.irc.IRCReady; import java.io.*; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class IRCClient { private final EventBus eventBus; private String host, username; private Socket socket; private BufferedReader in; private BufferedWriter out; private PrintStream printStream; private List<String> channels; private int port; private String serverPassword; private IRCClient(String host, int port, String username) { this.host = host; this.username = username; this.port = port; this.printStream = System.out; this.eventBus = BotGenerator.getInstance().getEventBus(); this.channels = new ArrayList<>(); } public IRCClient connect() throws IOException { this.socket = new Socket(host, port); this.socket.setKeepAlive(true); this.socket.setSoTimeout(200000); this.in = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); this.login(); this.startLoop(); return this; } public IRCClient setPrintStream(PrintStream printStream) { this.printStream = printStream; return this; } private void startLoop() { final IRCClient instance = this; new Thread() { public void run() { String line; while ((line = getLastLine()) != null) { printStream.println("STARTUP: " + line); if (line.indexOf("004") >= 0) { // We are now logged in. printStream.println("Logged in!"); eventBus.post(new IRCReady(instance)); for(String channel : channels) { joinChannel(channel); } break; } else if (line.startsWith("PING")) { pong(line.substring(5), true); } else if (line.indexOf("433") >= 0) { printStream.println("Nickname is already in use."); return; } } // Keep reading lines from the server. while ((line = getLastLine()) != null) { if (line.startsWith("PING")) { // We must respond to PINGs to avoid being disconnected. pong(line, false); } else if (line.contains("PRIVMSG { String sender = line.substring(1, line.indexOf("!")); String channel = line.substring(line.indexOf("#"), line.indexOf(":", line.indexOf("#"))); String str = "PRIVMSG " + channel + ":"; str = line.substring(line.indexOf(str) + str.length()); printStream.println("[" + channel + "] <" + sender + "> " + str); eventBus.post(new IRCChannelMessage(instance, channel, sender, str)); } else if (line.contains("PRIVMSG " + username)) { String sender = line.substring(1, line.indexOf("!")); String str = "PRIVMSG " + sender + ":"; str = line.substring(line.indexOf(str) + str.length()); printStream.println("<" + sender + "> " + str); eventBus.post(new IRCPrivateMessage(instance, sender, str)); } else { // Print the raw line received by the bot. printStream.println(line); } } } }.start(); } public void login() throws IOException { if (this.serverPassword != null) { this.writeToBuffer("PASS " + this.serverPassword + "\r\n"); } this.writeToBuffer("NICK " + username + "\r\n"); this.writeToBuffer("USER " + username + " 0 * :" + username + "\r\n"); } public IRCClient joinChannel(final String channel) { writeToBuffer("JOIN " + channel + "\r\n"); return this; } public IRCClient addChannels(String... channels) { for(String channel : channels) { this.channels.add(channel); } return this; } public IRCClient quit(String reason) { new Thread() { public void run() { try { out.write("QUIT Bye!\r\n"); out.flush(); } catch (IOException e) { System.exit(1); } } }.start(); return this; } public void sendToChat(String channel, String message) { try { out.write("PRIVMSG " + channel + " :" + message + "\r\n"); out.flush(); } catch (IOException e) { System.err.println("Error while send Chat Message " + message); } } public void writeToBuffer(final String buffer) { try { out.write(buffer); out.flush(); } catch (IOException e) { System.err.println("Error while send " + buffer); } } public String getLastLine() { try { return in.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } public void pong(final String id, final boolean space) { printStream.println(id); try { if (space) out.write("PONG " + id + "\r\n"); else out.write(id.replace("PING", "PONG")); out.flush(); } catch (IOException e) { System.err.println("Error while pong " + id + " (" + e +")"); } } public List<String> getChannelList() { return channels; } public IRCClient setServerPassword(String pass) { this.serverPassword = pass; return this; } public static IRCClient createIRCClient(String host, int port, String username) { return new IRCClient(host, port, username); } }
package ge.edu.freeuni.sdp.xo.rooms.data; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Room { @XmlElement private int id; @XmlElement(nillable=true) private Integer x_user; @XmlElement(nillable=true) private Integer o_user; /** * @param id * @param x_user * @param o_user */ public Room(int id, Integer x_user, Integer o_user) { this.id = id; this.x_user = x_user; this.o_user = o_user; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the x_user */ public int getx_user() { return x_user; } /** * @param x_user the x_user to set */ public void setx_user(Integer x_user) { this.x_user = x_user; } /** * @return the o_user */ public int geto_user() { return o_user; } /** * @param o_user the o_user to set */ public void seto_user(Integer o_user) { this.o_user = o_user; } }
package gui.sub_controllers; import graph.SequenceGraph; import gui.GraphDrawer; import gui.MenuController; import javafx.concurrent.Task; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import java.util.Observable; public final class PanningController extends Observable { /** * The amount of nodes to render. */ public static final int RENDER_RANGE = 4000; /** * The speed at which to pan. */ private static final double PANN_FACTOR = 0.03; /** * The the threshold to update the subGraph. */ private static final int RENDER_THRESHOLD = 1000; /** * The amount of nodes to shift. */ private static final int RENDER_SHIFT = 2000; private static final PanningController PANNING_CONTROLLER = new PanningController(); private MenuController menuController; private Button rightPannButton; private Button leftPannButton; private boolean updating; /** * Constructor for the panning controller. */ private PanningController() { } /** * Return the singleton instance of panning controller. * * @return The panning controller */ public static PanningController getInstance() { return PANNING_CONTROLLER; } /** * Initialize the panningcontroller. * * @param leftPannButton the pan left button. * @param rightPannButton the pan right button, */ public void initialize(Button leftPannButton, Button rightPannButton) { this.leftPannButton = leftPannButton; this.rightPannButton = rightPannButton; initializeButtons(); } /** * initialize function for the pan buttons. */ private void initializeButtons() { rightPannButton.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> panRight()); leftPannButton.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> panLeft()); } /** * listener for key presses. * * @param canvasPanel - the canvas which to apply the listener to, */ public void initializeKeys(Node canvasPanel) { canvasPanel.requestFocus(); canvasPanel.addEventHandler(KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.RIGHT) { panRight(); } else if (event.getCode() == KeyCode.LEFT) { panLeft(); } else if (event.getCode() == KeyCode.UP) { menuController.zoomInClicked(); } else if (event.getCode() == KeyCode.DOWN) { menuController.zoomOutClicked(); } event.consume(); }); } /** * Pan right method. */ private void panRight() { if (!updating) { if (GraphDrawer.getInstance().getGraph().getRightBoundIndex() < GraphDrawer.getInstance().getGraph().getFullGraphRightBoundIndex()) { if (GraphDrawer.getInstance().getMostRightNode().getId() + RENDER_THRESHOLD > GraphDrawer.getInstance().getGraph().getRightBoundID()) { updateGraph(Direction.RIGHT); } } } if (GraphDrawer.getInstance().getGraph().getNodes() .containsKey(GraphDrawer.getInstance().getGraph().getFullGraphRightBoundID())) { if (GraphDrawer.getInstance().getxDifference() + GraphDrawer.getInstance().getZoomLevel() > GraphDrawer.getInstance().getColumnWidth(GraphDrawer.getInstance().getGraph().getColumns().size())) { return; } } GraphDrawer.getInstance().moveShapes(GraphDrawer.getInstance().getxDifference() + GraphDrawer.getInstance().getZoomLevel() * PANN_FACTOR); } /** * Pan left method. */ private void panLeft() { if (!updating) { if (GraphDrawer.getInstance().getGraph().getLeftBoundIndex() > GraphDrawer.getInstance().getGraph().getFullGraphLeftBoundIndex()) { if (GraphDrawer.getInstance().getxDifference() - RENDER_THRESHOLD < 0) { updateGraph(Direction.LEFT); } } } if (GraphDrawer.getInstance().getGraph().getNodes() .containsKey(GraphDrawer.getInstance().getGraph().getFullGraphLeftBoundID())) { if (GraphDrawer.getInstance().getxDifference() < 0) { return; } } GraphDrawer.getInstance().moveShapes(GraphDrawer.getInstance().getxDifference() - GraphDrawer.getInstance().getZoomLevel() * PANN_FACTOR); } /** * Run a separate thread to update the graph when the screen nears the left or right bound. * * @param dir The direction in which is being panned. */ private void updateGraph(Direction dir) { updating = true; new Thread(new Task<Integer>() { @Override protected Integer call() throws Exception { SequenceGraph newGraph = GraphDrawer.getInstance().getGraph().copy(); int centerNodeID = GraphDrawer.getInstance().getGraph().getCenterNodeID(); if (dir == Direction.RIGHT) { newGraph.createSubGraph(centerNodeID + RENDER_SHIFT, RENDER_RANGE); } else { newGraph.createSubGraph(centerNodeID - RENDER_SHIFT, RENDER_RANGE); } int leftMostID = GraphDrawer.getInstance().getMostLeftNode().getId(); GraphDrawer.getInstance().setGraph(newGraph); GraphDrawer.getInstance().setxDifference(GraphDrawer.getInstance() .getColumnWidth(GraphDrawer.getInstance().getGraph().getNode(leftMostID).getColumn())); updating = false; return null; } }).start(); } /** * Enum to define the direction of panning. */ private enum Direction { LEFT, RIGHT } public void setMenuController(MenuController menuController) { this.menuController = menuController; } }
package com.intellij.util.xml; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Condition; import com.intellij.util.SmartList; import com.intellij.util.ReflectionCache; import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.Nullable; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * @author peter */ public class JavaMethodSignature { private static final Map<Method, JavaMethodSignature> ourSignatures = new THashMap<Method, JavaMethodSignature>(); private static final Map<Pair<String, Class[]>, JavaMethodSignature> ourSignatures2 = new THashMap<Pair<String, Class[]>, JavaMethodSignature>(); private final String myMethodName; private final Class[] myMethodParameters; private final Set<Class> myKnownClasses = new THashSet<Class>(); private final List<Method> myAllMethods = new SmartList<Method>(); private final Map<Class,Method> myMethods = new THashMap<Class, Method>(); private JavaMethodSignature(final String methodName, final Class[] methodParameters) { myMethodName = methodName; myMethodParameters = methodParameters; } public String getMethodName() { return myMethodName; } public Class[] getParameterTypes() { return myMethodParameters; } public final Object invoke(final Object instance, final Object... args) throws IllegalAccessException, InvocationTargetException { final Class<?> aClass = instance.getClass(); final Method method = findMethod(aClass); assert method != null : "No method " + this + " in " + aClass; return method.invoke(instance, args); } @Nullable public final synchronized Method findMethod(final Class aClass) { if (myMethods.containsKey(aClass)) { return myMethods.get(aClass); } Method method = getDeclaredMethod(aClass); if (method == null && ReflectionCache.isInterface(aClass)) { method = getDeclaredMethod(Object.class); } myMethods.put(aClass, method); return method; } private void addMethodsIfNeeded(final Class aClass) { if (!myKnownClasses.contains(aClass)) { addMethodWithSupers(aClass, findMethod(aClass)); } } @Nullable private Method getDeclaredMethod(final Class aClass) { final Method method = ReflectionUtil.getMethod(aClass, myMethodName, myMethodParameters); return method == null ? ReflectionUtil.getDeclaredMethod(aClass, myMethodName, myMethodParameters) : method; } private void addMethodWithSupers(final Class aClass, final Method method) { myKnownClasses.add(aClass); if (method != null) { myAllMethods.add(method); } final Class superClass = aClass.getSuperclass(); if (superClass != null) { addMethodsIfNeeded(superClass); } else { if (aClass.isInterface()) { addMethodsIfNeeded(Object.class); } } for (final Class anInterface : aClass.getInterfaces()) { addMethodsIfNeeded(anInterface); } } @Nullable public final synchronized <T extends Annotation> T findAnnotation(final Class<T> annotationClass, final Class startFrom) { addMethodsIfNeeded(startFrom); //noinspection ForLoopReplaceableByForEach T result = null; Class bestClass = null; final int size = myAllMethods.size(); for (int i = 0; i < size; i++) { Method method = myAllMethods.get(i); final T annotation = method.getAnnotation(annotationClass); if (annotation != null) { final Class<?> declaringClass = method.getDeclaringClass(); if (ReflectionCache.isAssignable(declaringClass, startFrom) && (result == null || ReflectionCache.isAssignable(bestClass, declaringClass))) { result = annotation; bestClass = declaringClass; } } } return result; } public final synchronized List<Method> getAllMethods(final Class startFrom) { addMethodsIfNeeded(startFrom); final List<Method> list = ContainerUtil.findAll(myAllMethods, new Condition<Method>() { public boolean value(final Method method) { return method.getDeclaringClass().isAssignableFrom(startFrom); } }); return list; } @Nullable public final synchronized <T extends Annotation> Method findAnnotatedMethod(final Class<T> annotationClass, final Class startFrom) { addMethodsIfNeeded(startFrom); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < myAllMethods.size(); i++) { Method method = myAllMethods.get(i); final T annotation = method.getAnnotation(annotationClass); if (annotation != null && ReflectionCache.isAssignable(method.getDeclaringClass(), startFrom)) { return method; } } return null; } public String toString() { return myMethodName + Arrays.asList(myMethodParameters); } public static JavaMethodSignature getSignature(Method method) { JavaMethodSignature methodSignature; synchronized (ourSignatures) { methodSignature = ourSignatures.get(method); if (methodSignature == null) { ourSignatures.put(method, methodSignature = _getSignature(method.getName(), method.getParameterTypes())); } //methodSignature.addKnownMethod(method); } return methodSignature; } public static JavaMethodSignature getSignature(final String name, final Class<?>... parameterTypes) { synchronized (ourSignatures) { return _getSignature(name, parameterTypes); } } private static JavaMethodSignature _getSignature(final String name, final Class<?>... parameterTypes) { final JavaMethodSignature methodSignature; final Pair<String, Class[]> key = new Pair<String, Class[]>(name, parameterTypes); JavaMethodSignature oldSignature = ourSignatures2.get(key); if (oldSignature == null) { oldSignature = new JavaMethodSignature(name, parameterTypes); ourSignatures2.put(key, oldSignature); } methodSignature = oldSignature; return methodSignature; } }
package io.github.flibio.utils.sql; import org.slf4j.Logger; import org.spongepowered.api.Sponge; import org.spongepowered.api.service.sql.SqlService; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.sql.DataSource; public class SqlManager { private Logger logger; private String datasource; private SqlService sql; private Connection con; protected SqlManager(Logger logger, String datasource) { this.logger = logger; this.datasource = datasource; this.sql = Sponge.getServiceManager().provide(SqlService.class).get(); } public boolean initialTestConnection() { try { sql.getDataSource(datasource); return true; } catch (Exception e) { return false; } } /** * Tests if the connection to the database if functional. * * @return If the connection to the database if functional. */ public boolean testConnection() { try { PreparedStatement ps = con.prepareStatement("SELECT 1"); ps.executeQuery(); return true; } catch (Exception e) { return false; } } private void openConnection() { try { DataSource source = sql.getDataSource(datasource); con = source.getConnection(); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } } private void reconnect() { try { if (con == null || !testConnection()) { if (con != null && !con.isClosed()) { con.close(); } openConnection(); } } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } } /** * Executes an update to the database. Recommended to run in an async * thread. * * @param sql The sql to execute. * @param vars The variables to replace in the sql. Replaced in * chronological order. * @return If the update was successful or not. */ public boolean executeUpdate(String sql, Object... vars) { try { reconnect(); PreparedStatement ps = con.prepareStatement(sql); ps.closeOnCompletion(); for (int i = 0; i < vars.length; i++) { ps.setObject(i + 1, vars[i]); } return (ps.executeUpdate() > 0); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); return false; } } /** * Runs a query on the database. Recommended to run in an async thread. * * @param sql The sql to run. * @param vars The variables to replace in the sql. Replaced in * chronological order. * @return The ResultSet retrieved from the query. */ public Optional<ResultSet> executeQuery(String sql, Object... vars) { try { reconnect(); PreparedStatement ps = con.prepareStatement(sql); ps.closeOnCompletion(); for (int i = 0; i < vars.length; i++) { ps.setObject(i + 1, vars[i]); } return Optional.of(ps.executeQuery()); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); return Optional.empty(); } } /** * Queries the database and retrieves a column's data. * * @param columnName The column to retrieve that data of. * @param type The type of data to retrieve. * @param sql The sql to run. * @param vars The variables to replace in sql. Replaced in chronological * order. * @return The column's data, if it was found. */ @SuppressWarnings("unchecked") public <T> Optional<T> queryType(String columnName, Class<T> type, String sql, Object... vars) { try { Optional<ResultSet> rOpt = executeQuery(sql, vars); if (rOpt.isPresent()) { ResultSet rs = rOpt.get(); rs.next(); Object raw = rs.getObject(columnName); rs.close(); if (raw.getClass().equals(type)) { return Optional.of((T) raw); } } return Optional.empty(); } catch (Exception e) { logger.error(e.getMessage()); return Optional.empty(); } } /** * Queries the database and retrieves a list of data. * * @param columnName The column whose data will be added to the list. * @param type The type of data to retrieve. * @param sql The sql to run. * @param vars The variables to replace in sql. Replaced in chronological * order. * @return The list of data. */ @SuppressWarnings("unchecked") public <T> List<T> queryTypeList(String columnName, Class<T> type, String sql, Object... vars) { ArrayList<T> list = new ArrayList<>(); try { Optional<ResultSet> rOpt = executeQuery(sql, vars); if (rOpt.isPresent()) { ResultSet rs = rOpt.get(); while (rs.next()) { Object raw = rs.getObject(columnName); list.add((T) raw); } rs.close(); } } catch (Exception e) { logger.error(e.getMessage()); } return list; } /** * Queries the database and checks if a row exists. * * @param sql The sql to run. * @param vars The variables to replace in the sql. Replaced in * chronological order. * @return If the row was found or not. */ public boolean queryExists(String sql, Object... vars) { try { Optional<ResultSet> rOpt = executeQuery(sql, vars); if (rOpt.isPresent()) { ResultSet rs = rOpt.get(); boolean exists = rs.next(); rs.close(); return exists; } return false; } catch (Exception e) { logger.error(e.getMessage()); return false; } } }
package com.futureplatforms.kirin.android.db; import java.util.Map; import com.google.common.collect.Maps; import android.database.Cursor; public class AndroidDbDropbox { private AndroidDbDropbox() {} private final Map<Integer, Cursor> _Map = Maps.newHashMap(); private int _NextToken = Integer.MIN_VALUE; protected String putCursor(Cursor c) { int next = _NextToken; _NextToken++; _Map.put(next, c); return ""+next; } public Cursor getCursor(String token) { return _Map.remove(Integer.parseInt(token, 10)); } private static AndroidDbDropbox instance; public static AndroidDbDropbox getInstance() { if (instance == null) { instance = new AndroidDbDropbox(); } return instance; } }
package io.pivotal.labsboot; import android.content.Context; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import dagger.Module; import dagger.Provides; import io.pivotal.labsboot.alkyhol.AlkyholModule; import retrofit.RestAdapter; import retrofit.converter.JacksonConverter; @Module( includes = { AlkyholModule.class }, library = true, complete = false ) public class ApplicationModule { private AndroidBootApplication mAndroidBootApplication; public ApplicationModule(final AndroidBootApplication application) { mAndroidBootApplication = application; } @Provides Context providesApplicationContext() { return mAndroidBootApplication; } @Provides RestAdapter providesRestAdapter(final ObjectMapper objectMapper) { return new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setConverter(new JacksonConverter(objectMapper)) .setEndpoint("http://192.168.1.141:8080") .build(); } @Provides ObjectMapper providesObjectMapper() { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); return objectMapper; } @Provides Injector providesInjector() { return mAndroidBootApplication; } }
package joshie.harvest.npcs.gift; import joshie.harvest.animals.HFAnimals; import joshie.harvest.animals.item.ItemAnimalProduct.Sizeable; import joshie.harvest.api.core.Ore; import joshie.harvest.api.core.Size; import joshie.harvest.cooking.item.ItemMeal.Meal; import joshie.harvest.gathering.HFGathering; import joshie.harvest.gathering.block.BlockNature.NaturalBlock; import net.minecraft.init.Items; import static joshie.harvest.api.npc.gift.GiftCategory.*; import static joshie.harvest.cooking.HFCooking.MEAL; @SuppressWarnings("unused") public class GiftsCandice extends Gifts { public GiftsCandice() { stackRegistry.register(HFAnimals.ANIMAL_PRODUCT.getStack(Sizeable.MILK, Size.SMALL), Quality.AWESOME); stackRegistry.register(HFAnimals.ANIMAL_PRODUCT.getStack(Sizeable.MILK, Size.MEDIUM), Quality.AWESOME); stackRegistry.register(HFAnimals.ANIMAL_PRODUCT.getStack(Sizeable.MILK, Size.LARGE), Quality.AWESOME); categoryRegistry.put(MILK, Quality.GOOD); stackRegistry.register(Ore.of("cropStrawberry"), Quality.DECENT); stackRegistry.register(Ore.of("cropTomato"), Quality.DECENT); categoryRegistry.put(FLOWER, Quality.DECENT); stackRegistry.register(MEAL.getStackFromEnum(Meal.BUN_JAM), Quality.DECENT); stackRegistry.register(HFGathering.NATURE.getStackFromEnum(NaturalBlock.LAVENDER), Quality.DISLIKE); stackRegistry.register(MEAL.getStackFromEnum(Meal.JAM_APPLE), Quality.BAD); stackRegistry.register(MEAL.getStackFromEnum(Meal.PIE_APPLE), Quality.BAD); stackRegistry.register(MEAL.getStackFromEnum(Meal.SOUFFLE_APPLE), Quality.BAD); categoryRegistry.put(FRUIT, Quality.BAD); stackRegistry.register(Items.GOLDEN_APPLE, Quality.TERRIBLE); stackRegistry.register(Ore.of("cropApple"), Quality.TERRIBLE); stackRegistry.register(Ore.of("cropWatermelon"), Quality.TERRIBLE); } }
package mcjty.immcraft.blocks.bundle; import mcjty.immcraft.api.block.IOrientedBlock; import mcjty.immcraft.api.cable.*; import mcjty.immcraft.api.util.Vector; import mcjty.immcraft.blocks.generic.GenericTE; import mcjty.immcraft.cables.CableSection; import mcjty.immcraft.multiblock.MultiBlockCableHelper; import mcjty.immcraft.multiblock.MultiBlockData; import mcjty.immcraft.multiblock.MultiBlockNetwork; import mcjty.immcraft.varia.BlockTools; import mcjty.immcraft.varia.IntersectionTools; import mcjty.immcraft.varia.NBTHelper; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; public class BundleTE extends GenericTE implements ITickable, IBundle { private final List<CableSection> cableSections = new ArrayList<>(); @Override public TileEntity getTileEntity() { return this; } @Override public void update() { if (!worldObj.isRemote) { MultiBlockData.get(worldObj); // Make sure the multiblock data is loaded cableSections.stream().forEach(p -> p.getType().getCableHandler().tick(this, p)); } } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) { super.onDataPacket(net, packet); worldObj.markBlockRangeForRenderUpdate(getPos(), getPos()); } public List<CableSection> getCableSections() { return cableSections; } @Override public ICableSection findSection(ICableType type, ICableSubType subType, int id) { for (CableSection section : cableSections) { if (section.getType() == type && section.getSubType() == subType && section.getId() == id) { return section; } } return null; } /** * Find a good section to connect too. It must have the same type and subtype. * If there is a section with no connections then that will be taken first. * Otherwise a section with one connection is taken (if any). * Sections with an id that is present in the given 'excluded' set are never considered. */ public CableSection findConnectableSection(ICableType type, ICableSubType subType, Set<Integer> excluded) { // First try to find a cable that has no connections. Optional<CableSection> section = cableSections.stream().filter(p -> cableWithNoConnections(p, type, subType, excluded)).findFirst(); if (section.isPresent()) { return section.get(); } // If that fails find one that has only one connection. return cableSections.stream().filter(p -> cableWithOneConnection(p, type, subType, excluded)).findFirst().orElse(null); } private boolean cableWithNoConnections(CableSection p, ICableType type, ICableSubType subType, Set<Integer> excluded) { return (!excluded.contains(p.getId())) && p.getType() == type && p.getSubType() == subType && p.getConnection(0) == null && p.getConnection(1) == null; } private boolean cableWithOneConnection(CableSection p, ICableType type, ICableSubType subType, Set<Integer> excluded) { return (!excluded.contains(p.getId())) && p.getType() == type && p.getSubType() == subType && (p.getConnection(0) == null || p.getConnection(1) == null); } /* * Disconnect the given section from connected connectors so that they * can be freshly reconnected. */ private void disconnectFromConnector(ICableType type, ICableSubType subType, int id, BlockPos current) { BundleTE bundle = BlockTools.getTE(BundleTE.class, worldObj, current).get(); ICableSection isection = bundle.findSection(type, subType, id); CableSection section = (CableSection) isection; if (section.getConnectorID(0) != -1 && section.getConnector(worldObj, 0) != null) { section.getConnector(worldObj, 0).disconnect(section.getConnectorID(0)); section.setConnection(0, null, null, -1); } if (section.getConnectorID(1) != -1 && section.getConnector(worldObj, 1) != null) { section.getConnector(worldObj, 1).disconnect(section.getConnectorID(1)); section.setConnection(1, null, null, -1); } } private Vector getVectorFromCable(BlockPos c, ICableType type, ICableSubType subType, int id) { BundleTE bundle = BlockTools.getTE(BundleTE.class, worldObj, c).get(); CableSection section = (CableSection) bundle.findSection(type, subType, id); return section.getVector(); } /* * Add a cable with type and subtype to this bundle. First the cable is merged * with possible adjacent multiblock networks of the same type and subtype. After that * the entire resulting cable multiblock is reconnected. */ public void addCableToNetwork(ICableType type, ICableSubType subType, Vector vector) { ICableHandler cableHandler = type.getCableHandler(); String networkName = cableHandler.getNetworkName(subType); MultiBlockNetwork network = MultiBlockData.getNetwork(networkName); int id = MultiBlockCableHelper.addBlockToNetwork(network, type, subType, -1, worldObj, getPos()); MultiBlockData.save(worldObj); CableSection section = new CableSection(type, subType, id, vector); cableSections.add(section); reconnectCable(cableHandler.getCable(worldObj, subType, id), type, subType, id); } /* * Fix all connections of this cable. This has to be called after adding a block to a * cable or merging two cables. */ private void reconnectCable(ICable cable, ICableType type, ICableSubType subType, int id) { List<BlockPos> path = cable.getPath(); List<Vector> vectors = path.stream().map(p -> getVectorFromCable(p, type, subType, id)).collect(Collectors.toList()); disconnectFromConnector(type, subType, id, path.get(0)); disconnectFromConnector(type, subType, id, path.get(path.size()-1)); for (int i = 0 ; i < path.size() ; i++) { BlockPos current = path.get(i); BundleTE bundle = BlockTools.getTE(BundleTE.class, worldObj, current).get(); CableSection section = (CableSection) bundle.findSection(type, subType, id); ICableConnector connector = null; if (i <= 0) { connector = tryConnectToConnector(section, id, 0, bundle.getPos(), null); } else { section.setConnection(0, path.get(i-1), IntersectionTools.intersectAtGrid(current, path.get(i - 1), vectors.get(i), vectors.get(i - 1)), -1); } if (i >= path.size() - 1) { tryConnectToConnector(section, id, 1, bundle.getPos(), connector); } else { section.setConnection(1, path.get(i+1), IntersectionTools.intersectAtGrid(current, path.get(i + 1), vectors.get(i), vectors.get(i + 1)), -1); } bundle.markDirtyClient(); } } /* * Try to connect this section to compatible connectors. If alreadyConnected is given then this * connector will not be considered for connecting too. */ private ICableConnector tryConnectToConnector(CableSection section, int networkId, int directionId, BlockPos pos, ICableConnector alreadyConnected) { for (EnumFacing direction : EnumFacing.VALUES) { BlockPos adj = pos.offset(direction); TileEntity te = worldObj.getTileEntity(adj); if (te instanceof ICableConnector && te != alreadyConnected) { IOrientedBlock orientedBlock = (IOrientedBlock) worldObj.getBlockState(adj).getBlock(); EnumFacing blockSide = orientedBlock.worldToBlockSpace(worldObj, adj, direction.getOpposite()); ICableConnector connector = (ICableConnector) te; if (connector.getType() == section.getType() && connector.canConnect(blockSide)) { int connectorId = connector.connect(blockSide, networkId, section.getSubType()); EnumFacing frontDirection = orientedBlock.getFrontDirection(worldObj.getBlockState(adj)); section.setConnection(directionId, adj, connector.getConnectorLocation(connectorId, frontDirection), connectorId); return connector; } } } return null; } /** * Count how many cables of the given type are end points in this bundle. * In other words, this is the amount of cables that a new adjacent cable of this type * and subtype can connect too. */ public int countCableEndPoints(ICableType type, ICableSubType subType) { return (int) cableSections.stream().filter(s -> s.getType() == type && s.getSubType() == subType && (s.getConnection(0) == null || s.getConnection(1) == null)).count(); } /** * Remove all cables from the multiblock network (used when the entire bundle is broken) */ public void removeAllCables() { // Make a copy of the list to avoid a concurrent modification exception (new ArrayList<CableSection>(cableSections)).stream().forEach(this::removeCableFromNetwork); } /* * Remove a cable that is part of this bundle from its network. * It will first disconnect the segment out of the cable and * then remove the cable from the multiblock (possibly creating * new cables). It will also spawn the corresponding cable block * in the world. */ public void removeCableFromNetwork(CableSection section) { disconnectCable(section); ICableHandler cableHandler = section.getType().getCableHandler(); String networkName = cableHandler.getNetworkName(section.getSubType()); MultiBlockNetwork network = MultiBlockData.getNetwork(networkName); MultiBlockCableHelper.removeBlockFromNetwork(network, section.getType(), section.getSubType(), section.getId(), worldObj, getPos()); MultiBlockData.save(worldObj); cableSections.remove(section); markDirtyClient(); section.getSubType().getBlock() .ifPresent(block -> BlockTools.spawnItemStack(worldObj, getPos(), new ItemStack(block))); } /* * Disconnect this section from its cable. It will also clear this section from * the possible adjacent sections and it will release the connectors. */ public void disconnectCable(CableSection section) { for (int i = 0 ; i < 2 ; i++) { BlockPos connection = section.getConnection(i); if (connection != null) { BlockTools.getTE(BundleTE.class, worldObj, connection).ifPresent(p -> disconnectOther(p, section)); } section.releaseConnector(worldObj, i); section.setConnection(i, null, null, -1); } markDirtyClient(); } private void disconnectOther(BundleTE other, CableSection thisSection) { CableSection otherSection = (CableSection) other.findSection(thisSection.getType(), thisSection.getSubType(), thisSection.getId()); other.disconnectFrom(otherSection, getPos()); other.markDirtyClient(); } public void disconnectFrom(CableSection section, BlockPos other) { if (section == null) { return; } if (other.equals(section.getConnection(0))) { section.releaseConnector(worldObj, 0); section.setConnection(0, null, null, -1); } else if (other.equals(section.getConnection(1))) { section.releaseConnector(worldObj, 1); section.setConnection(1, null, null, -1); } } /* * Check all connectors for this bundle and see if the blocks that are being * connected too are still present. If not clear the connector. * This is for checking with connectors (ICableConnector). Not for checking with * other bundles. */ public void checkConnections() { for (CableSection section : cableSections) { for (int i = 0 ; i < 2 ; i++) { int id = section.getConnectorID(i); if (id != -1) { BlockPos connection = section.getConnection(i); if (connection != null) { TileEntity te = worldObj.getTileEntity(connection); if (!(te instanceof ICableConnector)) { System.out.println("Connector removed"); // This is no longer a connector. section.setConnection(i, null, null, -1); markDirtyClient(); } } } } } } @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); int size = tagCompound.getInteger("size"); cableSections.clear(); for (int i = 0 ; i < size ; i++) { NBTTagCompound tc = (NBTTagCompound) tagCompound.getTag("c"+i); if (tc != null) { cableSections.add(new CableSection(tc)); } } } @Override protected void writeToNBT(NBTHelper helper) { super.writeToNBT(helper); helper.set("size", cableSections.size()); int i = 0; for (CableSection section : cableSections) { helper.set("c"+i, section.writeToNBT(NBTHelper.create()).get()); i++; } } }
package me.joshuamarquez.sails.io; import io.socket.client.Ack; import io.socket.client.IO; import io.socket.client.Socket; import io.socket.emitter.Emitter; import org.json.JSONObject; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import static me.joshuamarquez.sails.io.SailsSocketRequest.*; public class SailsSocket { private static final Logger logger = Logger.getLogger(SailsSocket.class.getName()); private Socket socket; private IO.Options options; private boolean isConnecting; // Global headers private Map<String, String> headers = Collections.emptyMap(); private Set<SailsSocketRequest> requestQueue; public SailsSocket(String url, IO.Options options) throws URISyntaxException { this.options = options; socket = IO.socket(url, this.options); requestQueue = new HashSet<SailsSocketRequest>(); Emitter.Listener clearRequestQueue = new Emitter.Listener() { @Override public void call(Object... args) { drainRequestQueue(); } }; socket.once(Socket.EVENT_CONNECT, clearRequestQueue); socket.on(Socket.EVENT_RECONNECT, clearRequestQueue); } /** * Set HTTP headers to be sent in every request. * * @param headers */ public void setHeaders(Map<String, String> headers) { if (headers != null && !headers.isEmpty()) { this.headers = headers; } } /** * Drains request queue sending each * request to {@link #emitFrom(SailsSocketRequest)} */ private void drainRequestQueue() { synchronized (requestQueue) { if (!requestQueue.isEmpty()) { for (SailsSocketRequest request : requestQueue) { emitFrom(request); } requestQueue.clear(); } } } /** * Begin connecting private socket to the server. * * @return {@link SailsSocket} */ public SailsSocket connect() { isConnecting = true; socket.connect(); socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() { @Override public void call(Object... args) { isConnecting = false; logger.fine("Now connected to Sails."); } }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() { @Override public void call(Object... args) { logger.warning("Socket was disconnected from Sails."); } }).on(Socket.EVENT_RECONNECTING, new Emitter.Listener() { @Override public void call(Object... args) { logger.fine("Socket is trying to reconnect to Sails..."); } }).on(Socket.EVENT_RECONNECT, new Emitter.Listener() { @Override public void call(Object... args) { logger.fine("Socket reconnected successfully"); } }).on(Socket.EVENT_ERROR, new Emitter.Listener() { @Override public void call(Object... args) { isConnecting = false; logger.severe("Failed to connect socket (possibly due to failed `beforeConnect` on server)"); } }); return this; } /** * Reconnect the socket. * * @return {@link SailsSocket} */ public SailsSocket reconnect() { if (this.isConnecting) { throw new Error("Cannot connect- socket is already connecting"); } if (socket.connected()) { throw new Error("Cannot connect- socket is already connected"); } socket.connect(); return this; } /** * Disconnect the socket. * * @return {@link SailsSocket} */ public SailsSocket disconnect() { this.isConnecting = false; if (!socket.connected()) { throw new Error("Cannot disconnect- socket is already disconnected"); } socket.disconnect(); return this; } /** * * Chainable method to unbind an event to the socket. * * @param event event name * @param fn {@link Emitter.Listener event handler listener * @return {@link SailsSocket} */ public SailsSocket on(String event, Emitter.Listener fn) { socket.on(event, fn); return this; } /** * * Chainable method to bind an event to the socket. * * @param event event name * @param fn {@link Emitter.Listener event handler listener * @return {@link SailsSocket} */ public SailsSocket off(String event, Emitter.Listener fn) { socket.off(event, fn); return this; } /** * Simulate a GET request to sails * * @param tag Set a tag on this request. Can be used to cancel all requests with this * tag by {@link SailsSocket#removeRequestsByTag(String)}. * @param url {@link String} destination URL * @param params {@link JSONObject} parameters to send with the request, can be null. * @param listener {@link SailsSocketResponse.Listener} listener to call when finished */ public SailsSocket get(String tag, String url, JSONObject params, SailsSocketResponse.Listener listener) { request(tag, METHOD_GET, url, params, null, listener); return this; } /** * Simulate a POST request to sails * * @param tag Set a tag on this request. Can be used to cancel all requests with this * tag by {@link SailsSocket#removeRequestsByTag(String)}. * @param url {@link String} destination URL * @param params {@link JSONObject} parameters to send with the request, can be null. * @param listener {@link SailsSocketResponse.Listener} listener to call when finished */ public SailsSocket post(String tag, String url, JSONObject params, SailsSocketResponse.Listener listener) { request(tag, METHOD_POST, url, params, null, listener); return this; } /** * Simulate a PUT request to sails * * @param tag Set a tag on this request. Can be used to cancel all requests with this * tag by {@link SailsSocket#removeRequestsByTag(String)}. * @param url {@link String} destination URL * @param params {@link JSONObject} parameters to send with the request, can be null. * @param listener {@link SailsSocketResponse.Listener} listener to call when finished */ public SailsSocket put(String tag, String url, JSONObject params, SailsSocketResponse.Listener listener) { request(tag, METHOD_PUT, url, params, null, listener); return this; } /** * Simulate a DELETE request to sails * * @param tag Set a tag on this request. Can be used to cancel all requests with this * tag by {@link SailsSocket#removeRequestsByTag(String)}. * @param url {@link String} destination URL * @param params {@link JSONObject} parameters to send with the request, can be null. * @param listener {@link SailsSocketResponse.Listener} listener to call when finished */ public SailsSocket delete(String tag, String url, JSONObject params, SailsSocketResponse.Listener listener) { request(tag, METHOD_DELETE, url, params, null, listener); return this; } /** * Simulate an HTTP request to sails * * @param tag Set a tag on this request. Can be used to cancel all requests with this * tag by {@link SailsSocket#removeRequestsByTag(String)}. * @param method {@link String} HTTP request method * @param url {@link String} destination URL * @param params {@link JSONObject} parameters to send with the request, can be null. * @param headers {@link Map} headers to be sent with the request, can be null. * @param listener {@link SailsSocketResponse.Listener} listener to call when finished */ public SailsSocket request(String tag, String method, String url, JSONObject params, Map<String, String> headers, SailsSocketResponse.Listener listener) { Map<String, String> requestHeaders = new HashMap<String, String>(); // Merge global headers in if (headers != null && !headers.isEmpty()) { // Merge global headers into requestHeaders requestHeaders.putAll(this.headers); // Merge request headers headers into requestHeaders requestHeaders.putAll(headers); } // Build request SailsSocketRequest request = new SailsSocketRequest(tag, method, url, params, new JSONObject(requestHeaders), listener); // If this socket is not connected yet, queue up this request // instead of sending it (so it can be replayed when the socket comes online.) if (!socket.connected()) { synchronized (requestQueue) { requestQueue.add(request); } } else { emitFrom(request); } return this; } /** * Private method used by {@link SailsSocket#request} * * @param request {@link SailsSocketRequest} */ private void emitFrom(SailsSocketRequest request) { // Name of the appropriate socket.io listener on the server String sailsEndpoint = request.getMethod(); // Since Listener is embedded in request, retrieve it. SailsSocketResponse.Listener listener = request.getListener(); socket.emit(sailsEndpoint, request.toJSONObject(), new Ack() { @Override public void call(Object... args) { // Send back jsonWebSocketResponse if (listener != null) { listener.onResponse(new JWR((JSONObject) args[0])); } } }); } /** * Removes all requests in this queue with the given tag. */ protected void removeRequestsByTag(final String tag) { if (tag == null) { throw new IllegalArgumentException("tag cannot be null"); } synchronized (requestQueue) { for (SailsSocketRequest request : requestQueue) { if (request.getTag().equals(tag)) { requestQueue.remove(request); } } } } /** * Removes all pending request in queue. */ protected void removeAllRequests() { synchronized (requestQueue) { requestQueue.clear(); } } }
package me.nallar.javapatcher.patcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.io.Files; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException; import me.nallar.javapatcher.PatcherLog; import me.nallar.javapatcher.mappings.ClassDescription; import me.nallar.javapatcher.mappings.DefaultMappings; import me.nallar.javapatcher.mappings.FieldDescription; import me.nallar.javapatcher.mappings.Mappings; import me.nallar.javapatcher.mappings.MethodDescription; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import java.io.*; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; /** * Patcher which uses javassist, a config file and a patcher class to patch arbitrary classes. */ public class Patcher { private static final String debugPatchedOutput = System.getProperty("patcher.debug", ""); private static final Splitter idSplitter = Splitter.on(" ").trimResults().omitEmptyStrings(); private final ClassPool classPool; private final Mappings mappings; private final Map<String, PatchMethodDescriptor> patchMethods = new HashMap<String, PatchMethodDescriptor>(); private final Map<String, PatchGroup> classToPatchGroup = new HashMap<String, PatchGroup>(); private Object patchClassInstance; /** * Creates a patcher instance * * @param classPool Javassist classpool set up with correct classpath containing needed classes */ public Patcher(ClassPool classPool) { this(classPool, Patches.class); } /** * Creates a patcher instance * * @param classPool Javassist classpool set up with correct classpath containing needed classes * @param patchesClass Class to instantiate containing @Patch annotated methods */ public Patcher(ClassPool classPool, Class<?> patchesClass) { this(classPool, patchesClass, new DefaultMappings()); } /** * Creates a patcher instance * * @param classPool Javassist classpool set up with correct classpath containing needed classes * @param patchesClass Class to instantiate containing @Patch annotated methods * @param mappings Mappings instance */ public Patcher(ClassPool classPool, Class<?> patchesClass, Mappings mappings) { for (Method method : patchesClass.getDeclaredMethods()) { for (Annotation annotation : method.getDeclaredAnnotations()) { if (annotation instanceof Patch) { PatchMethodDescriptor patchMethodDescriptor = new PatchMethodDescriptor(method, (Patch) annotation); if (patchMethods.put(patchMethodDescriptor.name, patchMethodDescriptor) != null) { PatcherLog.warn("Duplicate @Patch method with name " + patchMethodDescriptor.name); } } } } this.classPool = classPool; this.mappings = mappings; try { patchClassInstance = patchesClass.getDeclaredConstructors()[0].newInstance(classPool, mappings); } catch (Exception e) { PatcherLog.error("Failed to instantiate patch class", e); } } /** * Convenience method which reads an XML document from the input stream and passes it to readPatchesFromXMLDocument * * @param inputStream input stream to read from */ public void readPatchesFromXmlInputStream(InputStream inputStream) { readPatchesFromXmlString(DomUtil.readInputStreamToString(inputStream)); } /** * Convenience method which reads an XML document from the input stream and passes it to readPatchesFromXMLDocument * * @param inputStream input stream to read from */ public void readPatchesFromJsonInputStream(InputStream inputStream) { readPatchesFromJsonString(DomUtil.readInputStreamToString(inputStream)); } public void readPatchesFromJsonString(String json) { readPatchesFromXmlString(DomUtil.makePatchXmlFromJson(json)); } /** * Reads patches from the given XML Document * * @param document XML document */ public void readPatchesFromXmlString(String document) { try { readPatchesFromXmlDocument(DomUtil.readDocumentFromString(document)); } catch (IOException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } } public void readPatchesFromXmlDocument(Document document) { List<Element> patchGroupElements = DomUtil.elementList(document.getDocumentElement().getChildNodes()); for (Element patchGroupElement : patchGroupElements) { // TODO - rework this. Side-effect of object creation makes this look redundant when it isn't new PatchGroup(patchGroupElement); } } /** * @return The Mappings */ public Mappings getMappings() { return mappings; } /** * @return The ClassPool */ public ClassPool getClassPool() { return classPool; } /** * Returns whether the given class will be patched * * @param className Name of the class to check * @return Whether a patch exists for that class */ public boolean willPatch(String className) { return getPatchGroup(className) != null; } /** * Patch the class with the given name, if it has a patch associated with it. * * @param className Name of the class * @return Returns patched class if needed, else returns null */ public byte[] patch(String className) { return patch(className, null); } /** * Patch the class with the given name, if it has a patch associated with it. * * @param className Name of the class * @param originalBytes original class bytes * @return Returns patched class if needed, else returns original class */ public synchronized byte[] patch(String className, byte[] originalBytes) { PatchGroup patchGroup = getPatchGroup(className); if (patchGroup != null) { return patchGroup.getClassBytes(className, originalBytes); } return originalBytes; } /** * Writes debug info about this patcher to the debug logger */ public void logDebugInfo() { PatcherLog.info("Logging Patcher debug info of " + classToPatchGroup.size() + " patch groups"); for (PatchGroup patchGroup : classToPatchGroup.values()) { PatcherLog.info(patchGroup.toString()); } } private PatchGroup getPatchGroup(String name) { return classToPatchGroup.get(name); } private static class PatchDescriptor { private final Map<String, String> attributes; private final String patch; private String methods; PatchDescriptor(Element element) { attributes = DomUtil.getAttributes(element); methods = element.getTextContent().trim(); patch = element.getTagName(); } public String set(String name, String value) { return attributes.put(name, value); } public String get(String name) { return attributes.get(name); } public Map<String, String> getAttributes() { return attributes; } public String getMethods() { return methods; } public void setMethods(String methods) { this.methods = methods; } public String getPatch() { return patch; } } private static class PatchMethodDescriptor { public final String name; public final List<String> requiredAttributes; public final Method patchMethod; public final boolean isClassPatch; public final boolean emptyConstructor; private PatchMethodDescriptor(Method method, Patch patch) { String name = patch.name(); if (Arrays.asList(method.getParameterTypes()).contains(Map.class)) { this.requiredAttributes = Lists.newArrayList(Splitter.on(",").trimResults().omitEmptyStrings().split(patch.requiredAttributes())); } else { this.requiredAttributes = null; } if (name == null || name.isEmpty()) { name = method.getName(); } this.name = name; emptyConstructor = patch.emptyConstructor(); isClassPatch = method.getParameterTypes()[0].equals(CtClass.class); patchMethod = method; } public Object run(PatchDescriptor patchDescriptor, CtClass ctClass, Object patchClassInstance) { String methods = patchDescriptor.getMethods(); Map<String, String> attributes = patchDescriptor.getAttributes(); Map<String, String> attributesClean = new HashMap<String, String>(attributes); attributesClean.remove("code"); PatcherLog.trace("Patching " + ctClass.getName() + " with " + this.name + '(' + CollectionsUtil.mapToString(attributesClean) + ')' + (methods.isEmpty() ? "" : " {" + methods + '}')); if (requiredAttributes != null && !requiredAttributes.isEmpty() && !attributes.keySet().containsAll(requiredAttributes)) { PatcherLog.error("Missing required attributes " + requiredAttributes.toString() + " when patching " + ctClass.getName()); return null; } if ("^all^".equals(methods)) { patchDescriptor.set("silent", "true"); List<CtBehavior> ctBehaviors = new ArrayList<CtBehavior>(); Collections.addAll(ctBehaviors, ctClass.getDeclaredMethods()); Collections.addAll(ctBehaviors, ctClass.getDeclaredConstructors()); CtBehavior initializer = ctClass.getClassInitializer(); if (initializer != null) { ctBehaviors.add(initializer); } for (CtBehavior ctBehavior : ctBehaviors) { run(ctBehavior, attributes, patchClassInstance); } } else if (isClassPatch || (!emptyConstructor && methods.isEmpty())) { return run(ctClass, attributes, patchClassInstance); } else if (methods.isEmpty()) { for (CtConstructor ctConstructor : ctClass.getDeclaredConstructors()) { run(ctConstructor, attributes, patchClassInstance); } } else if ("^static^".equals(methods)) { CtConstructor ctBehavior = ctClass.getClassInitializer(); if (ctBehavior == null) { PatcherLog.error("No static initializer found patching " + ctClass.getName() + " with " + toString()); } else { run(ctBehavior, attributes, patchClassInstance); } } else { List<MethodDescription> methodDescriptions = MethodDescription.fromListString(ctClass.getName(), methods); for (MethodDescription methodDescription : methodDescriptions) { CtMethod ctMethod; try { ctMethod = methodDescription.inClass(ctClass); } catch (Throwable t) { if (!attributes.containsKey("allowMissing")) { PatcherLog.warn("", t); } continue; } run(ctMethod, attributes, patchClassInstance); } } return null; } private Object run(CtClass ctClass, Map<String, String> attributes, Object patchClassInstance) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchClassInstance, ctClass); } else { return patchMethod.invoke(patchClassInstance, ctClass, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { PatcherLog.error("Code: " + attributes.get("code")); } PatcherLog.error("Error patching " + ctClass.getName() + " with " + toString(), t); return null; } } private Object run(CtBehavior ctBehavior, Map<String, String> attributes, Object patchClassInstance) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchClassInstance, ctBehavior); } else { return patchMethod.invoke(patchClassInstance, ctBehavior, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { PatcherLog.error("Code: " + attributes.get("code")); } PatcherLog.error("Error patching " + ctBehavior.getName() + " in " + ctBehavior.getDeclaringClass().getName() + " with " + toString(), t); return null; } } @Override public String toString() { return name; } } private class PatchGroup { public final String name; public final boolean onDemand; public final ClassPool classPool; public final Mappings mappings; private final Map<String, ClassPatchDescriptor> patches; private final Map<String, byte[]> patchedBytes = new HashMap<String, byte[]>(); private final List<ClassPatchDescriptor> classPatchDescriptors = new ArrayList<ClassPatchDescriptor>(); private boolean ranPatches = false; private PatchGroup(Element element) { Map<String, String> attributes = DomUtil.getAttributes(element); name = element.getTagName(); classPool = Patcher.this.classPool; mappings = Patcher.this.mappings; obfuscateAttributesAndTextContent(element); onDemand = !attributes.containsKey("onDemand") || attributes.get("onDemand").toLowerCase().equals("true"); patches = onDemand ? new HashMap<String, ClassPatchDescriptor>() : null; for (Element classElement : DomUtil.elementList(element.getChildNodes())) { ClassPatchDescriptor classPatchDescriptor; try { classPatchDescriptor = new ClassPatchDescriptor(classElement); } catch (Throwable t) { throw new RuntimeException("Failed to create class patch for " + classElement.getAttribute("id"), t); } PatchGroup other = classToPatchGroup.get(classPatchDescriptor.name); if (other != null) { PatcherLog.error("Adding class " + classPatchDescriptor.name + " in patch group " + name + " to patch group with different preSrg setting " + other.name); } (other == null ? this : other).addClassPatchDescriptor(classPatchDescriptor); } } @Override public String toString() { StringBuilder sb = new StringBuilder("name: " + name + "\tnumber of patches: " + patches.size() + " patches:\n"); for (ClassPatchDescriptor classPatchDescriptor : patches.values()) { sb.append(classPatchDescriptor.name).append('\n'); } return sb.toString(); } private void addClassPatchDescriptor(ClassPatchDescriptor classPatchDescriptor) { classToPatchGroup.put(classPatchDescriptor.name, this); classPatchDescriptors.add(classPatchDescriptor); if (onDemand && patches.put(classPatchDescriptor.name, classPatchDescriptor) != null) { throw new Error("Duplicate class patch for " + classPatchDescriptor.name + ", but onDemand is set."); } } private void obfuscateAttributesAndTextContent(Element root) { // TODO - reimplement environments? /* for (Element classElement : DomUtil.elementList(root.getChildNodes())) { String env = classElement.getAttribute("env"); if (env != null && !env.isEmpty()) { if (!env.equals(getEnv())) { root.removeChild(classElement); } } } */ for (Element element : DomUtil.elementList(root.getChildNodes())) { if (!DomUtil.elementList(element.getChildNodes()).isEmpty()) { obfuscateAttributesAndTextContent(element); } else if (element.getTextContent() != null && !element.getTextContent().isEmpty()) { element.setTextContent(mappings.obfuscate(element.getTextContent())); } Map<String, String> attributes = DomUtil.getAttributes(element); for (Map.Entry<String, String> attributeEntry : attributes.entrySet()) { element.setAttribute(attributeEntry.getKey(), mappings.obfuscate(attributeEntry.getValue())); } } for (Element classElement : DomUtil.elementList(root.getChildNodes())) { String id = classElement.getAttribute("id"); ArrayList<String> list = Lists.newArrayList(idSplitter.split(id)); if (list.size() > 1) { for (String className : list) { Element newClassElement = (Element) classElement.cloneNode(true); newClassElement.setAttribute("id", className.trim()); classElement.getParentNode().insertBefore(newClassElement, classElement); } classElement.getParentNode().removeChild(classElement); } } } private void saveByteCode(byte[] bytes, String name) { if (!debugPatchedOutput.isEmpty()) { name = name.replace('.', '/') + ".class"; File file = new File(debugPatchedOutput + '/' + name); //noinspection ResultOfMethodCallIgnored file.getParentFile().mkdirs(); try { Files.write(bytes, file); } catch (IOException e) { PatcherLog.error("Failed to save patched bytes for " + name, e); } } } public byte[] getClassBytes(String name, byte[] originalBytes) { byte[] bytes = patchedBytes.get(name); if (bytes != null) { return bytes; } if (onDemand) { try { bytes = patches.get(name).runPatches().toBytecode(); patchedBytes.put(name, bytes); saveByteCode(bytes, name); return bytes; } catch (Throwable t) { PatcherLog.error("Failed to patch " + name + " in patch group " + name + '.', t); return originalBytes; } } runPatchesIfNeeded(); bytes = patchedBytes.get(name); if (bytes == null) { PatcherLog.error("Got no patched bytes for " + name); return originalBytes; } return bytes; } private void runPatchesIfNeeded() { if (ranPatches) { return; } ranPatches = true; Set<CtClass> patchedClasses = new HashSet<CtClass>(); for (ClassPatchDescriptor classPatchDescriptor : classPatchDescriptors) { try { try { patchedClasses.add(classPatchDescriptor.runPatches()); } catch (NotFoundException e) { if (e.getMessage().contains(classPatchDescriptor.name)) { PatcherLog.warn("Skipping patch for " + classPatchDescriptor.name + ", not found."); } else { throw e; } } } catch (Throwable t) { PatcherLog.error("Failed to patch " + classPatchDescriptor.name + " in patch group " + name + '.', t); } } for (CtClass ctClass : patchedClasses) { String className = ctClass.getName(); if (!ctClass.isModified()) { PatcherLog.error("Failed to get patched bytes for " + className + " as it was never modified in patch group " + name + '.'); continue; } try { byte[] byteCode = ctClass.toBytecode(); patchedBytes.put(className, byteCode); saveByteCode(byteCode, className); } catch (Throwable t) { PatcherLog.error("Failed to get patched bytes for " + className + " in patch group " + name + '.', t); } } } private class ClassPatchDescriptor { public final String name; public final List<PatchDescriptor> patches = new ArrayList<PatchDescriptor>(); private final Map<String, String> attributes; private ClassPatchDescriptor(Element element) { attributes = DomUtil.getAttributes(element); ClassDescription deobfuscatedClass = new ClassDescription(attributes.get("id")); ClassDescription obfuscatedClass = mappings.map(deobfuscatedClass); name = obfuscatedClass == null ? deobfuscatedClass.name : obfuscatedClass.name; for (Element patchElement : DomUtil.elementList(element.getChildNodes())) { PatchDescriptor patchDescriptor = new PatchDescriptor(patchElement); patches.add(patchDescriptor); List<MethodDescription> methodDescriptionList = MethodDescription.fromListString(deobfuscatedClass.name, patchDescriptor.getMethods()); if (!patchDescriptor.getMethods().isEmpty()) { patchDescriptor.set("deobf", methodDescriptionList.get(0).getShortName()); patchDescriptor.setMethods(MethodDescription.toListString(mappings.map(methodDescriptionList))); } String field = patchDescriptor.get("field"), prefix = ""; if (field != null && !field.isEmpty()) { if (field.startsWith("this.")) { field = field.substring("this.".length()); prefix = "this."; } String after = "", type = name; if (field.indexOf('.') != -1) { after = field.substring(field.indexOf('.')); field = field.substring(0, field.indexOf('.')); if (!field.isEmpty() && (field.charAt(0) == '$') && prefix.isEmpty()) { ArrayList<String> parameterList = new ArrayList<String>(); for (MethodDescription methodDescriptionOriginal : methodDescriptionList) { MethodDescription methodDescription = mappings.unmap(mappings.map(methodDescriptionOriginal)); methodDescription = methodDescription == null ? methodDescriptionOriginal : methodDescription; int i = 0; for (String parameter : methodDescription.getParameterList()) { if (parameterList.size() <= i) { parameterList.add(parameter); } else if (!parameterList.get(i).equals(parameter)) { parameterList.set(i, null); } i++; } } int parameterIndex = Integer.valueOf(field.substring(1)) - 1; if (parameterIndex >= parameterList.size()) { if (!parameterList.isEmpty()) { PatcherLog.error("Can not obfuscate parameter field " + patchDescriptor.get("field") + ", index: " + parameterIndex + " but parameter list is: " + Joiner.on(',').join(parameterList)); } break; } type = parameterList.get(parameterIndex); if (type == null) { PatcherLog.error("Can not obfuscate parameter field " + patchDescriptor.get("field") + " automatically as this parameter does not have a single type across the methods used in this patch."); break; } prefix = field + '.'; field = after.substring(1); after = ""; } } FieldDescription obfuscatedField = mappings.map(new FieldDescription(type, field)); if (obfuscatedField != null) { patchDescriptor.set("field", prefix + obfuscatedField.name + after); } } } } public CtClass runPatches() throws NotFoundException { CtClass ctClass = classPool.get(name); for (PatchDescriptor patchDescriptor : patches) { PatchMethodDescriptor patchMethodDescriptor = patchMethods.get(patchDescriptor.getPatch()); Object result = patchMethodDescriptor.run(patchDescriptor, ctClass, patchClassInstance); if (result instanceof CtClass) { ctClass = (CtClass) result; } } return ctClass; } } } }
package mezz.jei.ingredients; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.collect.ImmutableList; import gnu.trove.iterator.TIntIterator; import gnu.trove.map.TCharObjectMap; import gnu.trove.map.hash.TCharObjectHashMap; import gnu.trove.set.TIntSet; import mezz.jei.Internal; import mezz.jei.api.IIngredientFilter; import mezz.jei.api.ingredients.IIngredientHelper; import mezz.jei.config.Config; import mezz.jei.config.EditModeToggleEvent; import mezz.jei.gui.ingredients.IIngredientListElement; import mezz.jei.gui.overlay.IngredientListOverlay; import mezz.jei.runtime.JeiHelpers; import mezz.jei.runtime.JeiRuntime; import mezz.jei.suffixtree.CombinedSearchTrees; import mezz.jei.suffixtree.GeneralizedSuffixTree; import mezz.jei.suffixtree.ISearchTree; import mezz.jei.util.ErrorUtil; import mezz.jei.util.Translator; import net.minecraftforge.fml.common.ProgressManager; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class IngredientFilter implements IIngredientFilter { private static final Pattern QUOTE_PATTERN = Pattern.compile("\""); private static final Pattern FILTER_SPLIT_PATTERN = Pattern.compile("(\".*?(?:\"|$)|\\S+)"); private final JeiHelpers helpers; /** * indexed list of ingredients for use with the suffix trees * includes all elements (even hidden ones) for use when rebuilding */ private final List<IIngredientListElement> elementList; private final GeneralizedSuffixTree searchTree; private final TCharObjectMap<PrefixedSearchTree> prefixedSearchTrees = new TCharObjectHashMap<>(); private final List<PrefixedSearchTree> earlyLoadSearchTrees = new ArrayList<>(); private CombinedSearchTrees combinedSearchTrees; @Nullable private String filterCached; private List<IIngredientListElement> ingredientListCached = Collections.emptyList(); public IngredientFilter(JeiHelpers helpers) { this.helpers = helpers; this.elementList = new ArrayList<>(); this.searchTree = new GeneralizedSuffixTree(); PrefixedSearchTree modNameSearchTree = createPrefixedSearchTree('@', Config::getModNameSearchMode, IIngredientListElement::getModNameStrings); PrefixedSearchTree tooltipSearchTree = createPrefixedSearchTree('#', Config::getTooltipSearchMode, IIngredientListElement::getTooltipStrings); PrefixedSearchTree oreDictSearchTree = createPrefixedSearchTree('$', Config::getOreDictSearchMode, IIngredientListElement::getOreDictStrings); PrefixedSearchTree creativeTabSearchTree = createPrefixedSearchTree('%', Config::getCreativeTabSearchMode, IIngredientListElement::getCreativeTabsStrings); PrefixedSearchTree colorSearchTree = createPrefixedSearchTree('^', Config::getColorSearchMode, IIngredientListElement::getColorStrings); PrefixedSearchTree resourceIdSearchTree = createPrefixedSearchTree('&', Config::getResourceIdSearchMode, element -> Collections.singleton(element.getResourceId())); this.earlyLoadSearchTrees.add(tooltipSearchTree); this.earlyLoadSearchTrees.add(modNameSearchTree); this.earlyLoadSearchTrees.add(oreDictSearchTree); this.earlyLoadSearchTrees.add(creativeTabSearchTree); this.earlyLoadSearchTrees.add(resourceIdSearchTree); // color search tree gets loaded in onTick this.combinedSearchTrees = buildCombinedSearchTrees(this.searchTree, this.prefixedSearchTrees.valueCollection()); } private static CombinedSearchTrees buildCombinedSearchTrees(ISearchTree searchTree, Collection<PrefixedSearchTree> prefixedSearchTrees) { CombinedSearchTrees combinedSearchTrees = new CombinedSearchTrees(); combinedSearchTrees.addSearchTree(searchTree); for (PrefixedSearchTree prefixedTree : prefixedSearchTrees) { if (prefixedTree.getMode() == Config.SearchMode.ENABLED) { combinedSearchTrees.addSearchTree(prefixedTree.getTree()); } } return combinedSearchTrees; } private PrefixedSearchTree createPrefixedSearchTree(char prefix, PrefixedSearchTree.IModeGetter modeGetter, PrefixedSearchTree.IStringsGetter stringsGetter) { GeneralizedSuffixTree tree = new GeneralizedSuffixTree(); PrefixedSearchTree prefixedTree = new PrefixedSearchTree(tree, stringsGetter, modeGetter); this.prefixedSearchTrees.put(prefix, prefixedTree); return prefixedTree; } public void addIngredients(Collection<IIngredientListElement> ingredients) { ProgressManager.ProgressBar progressBar = ProgressManager.push("Indexing ingredients", ingredients.size()); for (IIngredientListElement<?> element : ingredients) { progressBar.step(element.getDisplayName()); addIngredient(element); } filterCached = null; ProgressManager.pop(progressBar); } private <V> void addIngredient(@Nullable IIngredientListElement<V> element) { if (element == null) { return; } V ingredient = element.getIngredient(); IngredientBlacklist ingredientBlacklist = helpers.getIngredientBlacklist(); if (ingredientBlacklist.isIngredientBlacklistedByApi(ingredient)) { return; } boolean hidden = Config.isIngredientOnConfigBlacklist(ingredient, element.getIngredientHelper()); element.setHidden(hidden); final int index = elementList.size(); elementList.add(element); searchTree.put(Translator.toLowercaseWithLocale(element.getDisplayName()), index); for (PrefixedSearchTree prefixedSearchTree : this.earlyLoadSearchTrees) { Config.SearchMode searchMode = prefixedSearchTree.getMode(); if (searchMode != Config.SearchMode.DISABLED) { Collection<String> strings = prefixedSearchTree.getStringsGetter().getStrings(element); for (String string : strings) { prefixedSearchTree.getTree().put(string, index); } } } } public void removeIngredients(Collection<IIngredientListElement> ingredients) { for (IIngredientListElement<?> element : ingredients) { removeIngredient(element); } filterCached = null; } private <V> void removeIngredient(IIngredientListElement<V> element) { final IIngredientHelper<V> ingredientHelper = element.getIngredientHelper(); final V ingredient = element.getIngredient(); final String ingredientUid = ingredientHelper.getUniqueId(ingredient); //noinspection unchecked final Class<? extends V> ingredientClass = (Class<? extends V>) ingredient.getClass(); final TIntSet matchingIndexes = searchTree.search(Translator.toLowercaseWithLocale(element.getDisplayName())); final TIntIterator iterator = matchingIndexes.iterator(); while (iterator.hasNext()) { int index = iterator.next(); IIngredientListElement matchingElement = this.elementList.get(index); if (matchingElement != null) { Object matchingIngredient = matchingElement.getIngredient(); if (ingredientClass.isInstance(matchingIngredient)) { V castMatchingIngredient = ingredientClass.cast(matchingIngredient); String matchingUid = ingredientHelper.getUniqueId(castMatchingIngredient); if (ingredientUid.equals(matchingUid)) { this.elementList.set(index, null); } } } } } public void modesChanged() { this.combinedSearchTrees = buildCombinedSearchTrees(this.searchTree, this.prefixedSearchTrees.valueCollection()); onClientTick(10000); this.filterCached = null; } public void onClientTick(final int timeoutMs) { final long startTime = System.currentTimeMillis(); for (PrefixedSearchTree prefixedTree : this.prefixedSearchTrees.valueCollection()) { Config.SearchMode mode = prefixedTree.getMode(); if (mode != Config.SearchMode.DISABLED) { PrefixedSearchTree.IStringsGetter stringsGetter = prefixedTree.getStringsGetter(); GeneralizedSuffixTree tree = prefixedTree.getTree(); for (int i = tree.getHighestIndex() + 1; i < this.elementList.size(); i++) { IIngredientListElement element = elementList.get(i); if (element != null) { Collection<String> strings = stringsGetter.getStrings(element); if (strings.isEmpty()) { tree.put("", i); } else { for (String string : strings) { tree.put(string, i); } } } if (System.currentTimeMillis() - startTime >= timeoutMs) { return; } } } } } @SubscribeEvent public void onEditModeToggleEvent(EditModeToggleEvent event) { this.filterCached = null; updateHidden(); } public void updateHidden() { for (IIngredientListElement<?> element : elementList) { if (element != null) { updateHiddenState(element); } } } private <V> void updateHiddenState(IIngredientListElement<V> element) { V ingredient = element.getIngredient(); boolean hidden = Config.isIngredientOnConfigBlacklist(ingredient, element.getIngredientHelper()); element.setHidden(hidden); } public List<IIngredientListElement> getIngredientList() { String filterText = Translator.toLowercaseWithLocale(Config.getFilterText()); if (!filterText.equals(filterCached)) { List<IIngredientListElement> ingredientList = getIngredientListUncached(filterText); ingredientList.sort(IngredientListElementComparator.INSTANCE); ingredientListCached = Collections.unmodifiableList(ingredientList); filterCached = filterText; } return ingredientListCached; } @Override public ImmutableList<Object> getFilteredIngredients() { List<IIngredientListElement> elements = getIngredientList(); ImmutableList.Builder<Object> builder = ImmutableList.builder(); for (IIngredientListElement element : elements) { Object ingredient = element.getIngredient(); builder.add(ingredient); } return builder.build(); } @Override public String getFilterText() { return Config.getFilterText(); } @Override public void setFilterText(String filterText) { ErrorUtil.checkNotNull(filterText, "filterText"); if (Config.setFilterText(filterText)) { JeiRuntime runtime = Internal.getRuntime(); if (runtime != null) { IngredientListOverlay ingredientListOverlay = runtime.getIngredientListOverlay(); ingredientListOverlay.onSetFilterText(filterText); } } } private List<IIngredientListElement> getIngredientListUncached(String filterText) { String[] filters = filterText.split("\\|"); if (filters.length == 1) { String filter = filters[0]; return getElements(filter); } else { List<IIngredientListElement> ingredientList = new ArrayList<>(); for (String filter : filters) { List<IIngredientListElement> ingredients = getElements(filter); ingredientList.addAll(ingredients); } return ingredientList; } } private List<IIngredientListElement> getElements(String filterText) { Matcher filterMatcher = FILTER_SPLIT_PATTERN.matcher(filterText); TIntSet matches = null; while (filterMatcher.find()) { String token = filterMatcher.group(1); token = QUOTE_PATTERN.matcher(token).replaceAll(""); TIntSet searchResults = getSearchResults(token); if (searchResults != null) { if (matches == null) { matches = searchResults; } else { matches = intersection(matches, searchResults); } if (matches.isEmpty()) { break; } } } List<IIngredientListElement> matchingIngredients = new ArrayList<>(); if (matches == null) { for (IIngredientListElement element : elementList) { if (element != null && (!element.isHidden() || Config.isEditModeEnabled())) { matchingIngredients.add(element); } } } else { int[] matchesList = matches.toArray(); Arrays.sort(matchesList); for (Integer match : matchesList) { IIngredientListElement<?> element = elementList.get(match); if (element != null && (!element.isHidden() || Config.isEditModeEnabled())) { matchingIngredients.add(element); } } } return matchingIngredients; } /** * Gets the appropriate search tree for the given token, based on if the token has a prefix. */ @Nullable private TIntSet getSearchResults(String token) { if (token.isEmpty()) { return null; } final char firstChar = token.charAt(0); final PrefixedSearchTree prefixedSearchTree = this.prefixedSearchTrees.get(firstChar); if (prefixedSearchTree != null && prefixedSearchTree.getMode() != Config.SearchMode.DISABLED) { token = token.substring(1); if (token.isEmpty()) { return null; } GeneralizedSuffixTree tree = prefixedSearchTree.getTree(); return tree.search(token); } else { return combinedSearchTrees.search(token); } } /** * Efficiently get the elements contained in both sets. * Note that this implementation will alter the original sets. */ private static TIntSet intersection(TIntSet set1, TIntSet set2) { if (set1.size() > set2.size()) { set2.retainAll(set1); return set2; } else { set1.retainAll(set2); return set1; } } public int size() { return getIngredientList().size(); } }
package mingzuozhibi.service; import mingzuozhibi.persist.disc.Disc; import mingzuozhibi.persist.disc.Disc.DiscType; import mingzuozhibi.persist.disc.Sakura; import mingzuozhibi.support.Dao; import org.json.JSONArray; import org.json.JSONObject; import org.jsoup.Connection.Method; import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.HashSet; import java.util.Objects; import java.util.Set; @Service public class AmazonDiscSpider { private static Logger LOGGER = LoggerFactory.getLogger(AmazonDiscSpider.class); @Value("${BCLOUD_IP}") private String bcloudIp; @Autowired private Dao dao; public JSONObject fetchDiscInfo(String asin) { LOGGER.info(", ASIN={}", asin); return new JSONObject(discInfosAsinGet(asin)); } @Transactional public void fetchFromBCloud() { LOGGER.info(""); Set<String> asins = new HashSet<>(); dao.findBy(Sakura.class, "enabled", true) .forEach(sakura -> { sakura.getDiscs().forEach(disc -> { asins.add(disc.getAsin()); }); }); discRanksActivePut(asins); JSONObject root = new JSONObject(discRanksActiveGet()); LocalDateTime updateOn = Instant.ofEpochMilli(root.getLong("updateOn")) .atZone(ZoneId.systemDefault()).toLocalDateTime(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); JSONArray discInfos = root.getJSONArray("data"); for (int i = 0; i < discInfos.length(); i++) { JSONObject discInfo = discInfos.getJSONObject(i); String asin = discInfo.getString("asin"); Disc disc = dao.lookup(Disc.class, "asin", asin); if (disc != null) { disc.setTitle(discInfo.getString("title")); if (disc.getDiscType() == DiscType.Auto || disc.getDiscType() == DiscType.Other) { disc.setDiscType(DiscType.valueOf(discInfo.getString("type"))); } LocalDate date = LocalDate.parse(discInfo.getString("date"), formatter); if (date.isAfter(disc.getReleaseDate())) { disc.setReleaseDate(date); } if (discInfo.has("rank")) { if (disc.getModifyTime() == null || updateOn.isAfter(disc.getModifyTime())) { disc.setPrevRank(disc.getThisRank()); disc.setThisRank(discInfo.getInt("rank")); if (!Objects.equals(disc.getThisRank(), disc.getPrevRank())) { disc.setModifyTime(updateOn); } disc.setUpdateTime(updateOn); } } } } if (discInfos.length() > 0) { LOGGER.info("{}", discInfos.length()); for (Sakura sakura : dao.findBy(Sakura.class, "enabled", true)) { sakura.setModifyTime(updateOn); } } else { LOGGER.warn(""); } } private String discRanksActivePut(Set<String> asins) { JSONArray array = new JSONArray(); asins.forEach(array::put); System.out.println(array.toString().length()); String url = "http://" + bcloudIp + ":8762/discRanks/active"; Exception lastThrown = null; for (int retry = 0; retry < 3; retry++) { try { return Jsoup.connect(url) .header("Content-Type", "application/json;charset=utf-8") .requestBody(array.toString()) .ignoreContentType(true) .method(Method.PUT) .timeout(10000) .execute() .body(); } catch (Exception e) { lastThrown = e; } } String format = "Jsoup: [url=%s][message=%s]"; String message = String.format(format, url, lastThrown.getMessage()); throw new RuntimeException(message, lastThrown); } private String discRanksActiveGet() { String url = "http://" + bcloudIp + ":8762/discRanks/active"; Exception lastThrown = null; for (int retry = 0; retry < 3; retry++) { try { return Jsoup.connect(url) .ignoreContentType(true) .method(Method.GET) .timeout(30000) .execute() .body(); } catch (Exception e) { lastThrown = e; } } String format = "Jsoup: [url=%s][message=%s]"; String message = String.format(format, url, lastThrown.getMessage()); throw new RuntimeException(message, lastThrown); } private String discInfosAsinGet(String asin) { String url = "http://" + bcloudIp + ":8762/discInfos/" + asin; Exception lastThrown = null; for (int retry = 0; retry < 3; retry++) { try { return Jsoup.connect(url) .ignoreContentType(true) .method(Method.GET) .timeout(30000) .execute() .body(); } catch (Exception e) { lastThrown = e; } } String format = "Jsoup: [url=%s][message=%s]"; String message = String.format(format, url, lastThrown.getMessage()); throw new RuntimeException(message, lastThrown); } }
package com.afollestad.silk.fragments; import android.os.Bundle; import android.view.View; import com.afollestad.silk.Silk; import com.afollestad.silk.caching.SilkComparable; import com.afollestad.silk.views.list.SilkListView; import java.util.List; /** * @author Aidan Follestad (afollestad) */ public abstract class SilkFeedFragment<ItemType extends SilkComparable<ItemType>> extends SilkListFragment<ItemType> { private boolean mBlockPaginate = false; public static class OfflineException extends Exception { public OfflineException() { super("You are currently offline."); } } protected int getAddIndex() { return -1; } protected void onPostLoad(List<ItemType> results, boolean paginated) { if (results != null) { if (paginated || getAddIndex() < 0) { getAdapter().add(results); } else { getAdapter().add(getAddIndex(), results); } } setLoadComplete(false); } protected abstract List<ItemType> refresh() throws Exception; protected abstract List<ItemType> paginate() throws Exception; protected abstract void onError(Exception e); public void performRefresh(boolean showProgress) { if (isLoading()) return; setLoading(showProgress); Thread t = new Thread(new Runnable() { @Override public void run() { try { if (!Silk.isOnline(getActivity())) throw new OfflineException(); final List<ItemType> items = refresh(); runOnUiThread(new Runnable() { @Override public void run() { onPostLoad(items, false); } }); } catch (final Exception e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { onError(e); setLoadComplete(true); } }); } } }); t.setPriority(Thread.MAX_PRIORITY); t.start(); } public void performPaginate(boolean showProgress) { if (isLoading()) return; else if (mBlockPaginate) return; setLoading(showProgress); Thread t = new Thread(new Runnable() { @Override public void run() { try { if (!Silk.isOnline(getActivity())) throw new OfflineException(); final List<ItemType> items = paginate(); if (items == null) mBlockPaginate = true; runOnUiThread(new Runnable() { @Override public void run() { int beforeCount = getAdapter().getCount(); onPostLoad(items, true); if (items != null) getListView().smoothScrollToPosition(beforeCount); } }); } catch (final Exception e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { onError(e); setLoadComplete(true); } }); } } }); t.setPriority(Thread.MAX_PRIORITY); t.start(); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); performRefresh(true); getListView().setOnSilkScrollListener(new SilkListView.OnSilkScrollListener() { @Override public void onScrollToTop() { } @Override public void onScrollToBottom() { performPaginate(false); } }); } }
package mtsar.processors.answer; import com.google.common.collect.*; import mtsar.api.Answer; import mtsar.api.AnswerAggregation; import mtsar.api.Process; import mtsar.api.Task; import mtsar.api.sql.AnswerDAO; import mtsar.api.sql.TaskDAO; import mtsar.processors.AnswerAggregator; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import javax.inject.Inject; import javax.inject.Provider; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; public class KOSAggregator implements AnswerAggregator { private final Provider<Process> process; private final TaskDAO taskDAO; private final AnswerDAO answerDAO; @Inject public KOSAggregator(Provider<Process> process, TaskDAO taskDAO, AnswerDAO answerDAO) { this.process = process; this.taskDAO = taskDAO; this.answerDAO = answerDAO; } @Override public Map<Task, AnswerAggregation> aggregate(Collection<Task> tasks) { if (tasks.isEmpty()) return Collections.emptyMap(); checkArgument(tasks.stream().allMatch( task -> task.getAnswers().size() == 2 && task.getType() == TaskDAO.TASK_TYPE_SINGLE ), "tasks should be of the type single and have only two possible answers"); final List<Answer> answers = answerDAO.listForProcess(process.get().getId()); if (answers.isEmpty()) return Collections.emptyMap(); final Map<Integer, Task> taskMap = taskDAO.listForProcess(process.get().getId()).stream(). filter(task -> task.getType() == TaskDAO.TASK_TYPE_SINGLE && task.getAnswers().size() == 2). collect(Collectors.toMap(Task::getId, Function.identity())); final Map<Integer, BiMap<String, Short>> answerIndex = taskMap.values().stream().collect(Collectors.toMap(Task::getId, task -> { final BiMap<String, Short> map = HashBiMap.create(2); map.put(task.getAnswers().get(0), (short) -1); map.put(task.getAnswers().get(1), (short) +1); return map; } )); /* rows are tasks IDs, columns are answer IDs, values are answers */ final Table<Integer, Integer, Short> graph = HashBasedTable.create(); for (final Answer answer : answers) { if (answer.getType() != AnswerDAO.ANSWER_TYPE_ANSWER) continue; graph.put(answer.getTaskId(), answer.getWorkerId(), answerIndex.get(answer.getTaskId()).get(answer.getAnswers().get(0))); } final Map<Integer, Double> estimations = converge(graph, 10); return estimations.entrySet().stream().collect(Collectors.toMap( estimation -> taskMap.get(estimation.getKey()), estimation -> { final String answer = answerIndex.get(estimation.getKey()).inverse().get(estimation.getValue() < 0 ? (short) -1 : (short) +1); return new AnswerAggregation(taskMap.get(estimation.getKey()), Lists.newArrayList(answer)); } )); } protected Map<Integer, Double> converge(Table<Integer, Integer, Short> graph, int kMax) { final RealDistribution distribution = new NormalDistribution(1, 1); Table<Integer, Integer, Double> ys = HashBasedTable.create(graph.rowKeySet().size(), graph.columnKeySet().size()); for (final Table.Cell<Integer, Integer, Short> cell : graph.cellSet()) { ys.put(cell.getRowKey(), cell.getColumnKey(), distribution.sample()); } for (int k = 1; k <= kMax; k++) { final Table<Integer, Integer, Double> xs = tasksUpdate(graph, ys); if (k < kMax) ys = workersUpdate(graph, xs); } final Map<Integer, Double> estimations = new HashMap<>(); for (final Integer taskId : graph.rowKeySet()) { double sumProduct = 0.0; final Map<Integer, Double> workers = ys.row(taskId); for (final Map.Entry<Integer, Double> worker : workers.entrySet()) { sumProduct += graph.get(taskId, worker.getKey()) * worker.getValue(); } estimations.put(taskId, sumProduct); } return estimations; } protected Table<Integer, Integer, Double> tasksUpdate(Table<Integer, Integer, Short> graph, Table<Integer, Integer, Double> ys) { final Table<Integer, Integer, Double> xs = HashBasedTable.create(graph.rowKeySet().size(), graph.columnKeySet().size()); for (final Table.Cell<Integer, Integer, Short> cell : graph.cellSet()) { double sumProduct = 0.0; final int taskId = cell.getRowKey(), workerId = cell.getColumnKey(); final Map<Integer, Short> workers = graph.row(taskId); for (final Map.Entry<Integer, Short> worker : workers.entrySet()) { if (worker.getKey() == workerId) continue; sumProduct += worker.getValue() * ys.get(taskId, worker.getKey()); } xs.put(taskId, workerId, sumProduct); } return xs; } protected Table<Integer, Integer, Double> workersUpdate(Table<Integer, Integer, Short> graph, Table<Integer, Integer, Double> xs) { final Table<Integer, Integer, Double> ys = HashBasedTable.create(graph.rowKeySet().size(), graph.columnKeySet().size()); for (final Table.Cell<Integer, Integer, Short> cell : graph.cellSet()) { double sumProduct = 0.0; final int taskId = cell.getRowKey(), workerId = cell.getColumnKey(); final Map<Integer, Short> tasks = graph.column(workerId); for (final Map.Entry<Integer, Short> task : tasks.entrySet()) { if (task.getKey() == taskId) continue; sumProduct += task.getValue() * xs.get(task.getKey(), workerId); } ys.put(taskId, workerId, sumProduct); } return ys; } }
package com.digi.xbee.api; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.digi.xbee.api.connection.IConnectionInterface; import com.digi.xbee.api.connection.DataReader; import com.digi.xbee.api.connection.serial.SerialPortParameters; import com.digi.xbee.api.exceptions.ATCommandException; import com.digi.xbee.api.exceptions.InterfaceNotOpenException; import com.digi.xbee.api.exceptions.InvalidOperatingModeException; import com.digi.xbee.api.exceptions.OperationNotSupportedException; import com.digi.xbee.api.exceptions.TimeoutException; import com.digi.xbee.api.exceptions.TransmitException; import com.digi.xbee.api.exceptions.XBeeException; import com.digi.xbee.api.io.IOLine; import com.digi.xbee.api.io.IOMode; import com.digi.xbee.api.io.IOSample; import com.digi.xbee.api.io.IOValue; import com.digi.xbee.api.listeners.IIOSampleReceiveListener; import com.digi.xbee.api.listeners.IPacketReceiveListener; import com.digi.xbee.api.listeners.IDataReceiveListener; import com.digi.xbee.api.models.ATCommand; import com.digi.xbee.api.models.ATCommandResponse; import com.digi.xbee.api.models.ATCommandStatus; import com.digi.xbee.api.models.AssociationIndicationStatus; import com.digi.xbee.api.models.HardwareVersion; import com.digi.xbee.api.models.HardwareVersionEnum; import com.digi.xbee.api.models.PowerLevel; import com.digi.xbee.api.models.RemoteATCommandOptions; import com.digi.xbee.api.models.XBee16BitAddress; import com.digi.xbee.api.models.XBee64BitAddress; import com.digi.xbee.api.models.OperatingMode; import com.digi.xbee.api.models.XBeeProtocol; import com.digi.xbee.api.models.XBeeTransmitStatus; import com.digi.xbee.api.packet.XBeeAPIPacket; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.XBeePacket; import com.digi.xbee.api.packet.common.ATCommandPacket; import com.digi.xbee.api.packet.common.ATCommandResponsePacket; import com.digi.xbee.api.packet.common.IODataSampleRxIndicatorPacket; import com.digi.xbee.api.packet.common.RemoteATCommandPacket; import com.digi.xbee.api.packet.common.RemoteATCommandResponsePacket; import com.digi.xbee.api.packet.common.TransmitStatusPacket; import com.digi.xbee.api.packet.raw.RX16IOPacket; import com.digi.xbee.api.packet.raw.RX64IOPacket; import com.digi.xbee.api.packet.raw.TXStatusPacket; import com.digi.xbee.api.utils.ByteUtils; import com.digi.xbee.api.utils.HexUtils; public abstract class AbstractXBeeDevice { // Constants. protected static int DEFAULT_RECEIVE_TIMETOUT = 2000; // 2.0 seconds of timeout to receive packet and command responses. protected static int TIMEOUT_BEFORE_COMMAND_MODE = 1200; protected static int TIMEOUT_ENTER_COMMAND_MODE = 1500; // Variables. protected IConnectionInterface connectionInterface; protected DataReader dataReader = null; protected XBeeProtocol xbeeProtocol = XBeeProtocol.UNKNOWN; protected OperatingMode operatingMode = OperatingMode.UNKNOWN; protected XBee16BitAddress xbee16BitAddress = XBee16BitAddress.UNKNOWN_ADDRESS; protected XBee64BitAddress xbee64BitAddress = XBee64BitAddress.UNKNOWN_ADDRESS; protected int currentFrameID = 0xFF; protected int receiveTimeout = DEFAULT_RECEIVE_TIMETOUT; protected Logger logger; private String nodeID; private String firmwareVersion; private HardwareVersion hardwareVersion; protected AbstractXBeeDevice localXBeeDevice; private Object ioLock = new Object(); private boolean ioPacketReceived = false; private boolean applyConfigurationChanges = true; private byte[] ioPacketPayload; public AbstractXBeeDevice(String port, int baudRate) { this(XBee.createConnectiontionInterface(port, baudRate)); } public AbstractXBeeDevice(String port, int baudRate, int dataBits, int stopBits, int parity, int flowControl) { this(port, new SerialPortParameters(baudRate, dataBits, stopBits, parity, flowControl)); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object in the * given serial port name and parameters. * * @param port Serial port name where XBee device is attached to. * @param serialPortParameters Object containing the serial port parameters. * * @throws NullPointerException if {@code port == null} or * if {@code serialPortParameters == null}. * * @see SerialPortParameters */ public AbstractXBeeDevice(String port, SerialPortParameters serialPortParameters) { this(XBee.createConnectiontionInterface(port, serialPortParameters)); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object with the * given connection interface. * * @param connectionInterface The connection interface with the physical * XBee device. * * @throws NullPointerException if {@code connectionInterface == null}. * * @see IConnectionInterface */ public AbstractXBeeDevice(IConnectionInterface connectionInterface) { if (connectionInterface == null) throw new NullPointerException("ConnectionInterface cannot be null."); this.connectionInterface = connectionInterface; this.logger = LoggerFactory.getLogger(this.getClass()); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName()); } public AbstractXBeeDevice(XBeeDevice localXBeeDevice, XBee64BitAddress addr64) { this(localXBeeDevice, addr64, null, null); } public AbstractXBeeDevice(XBeeDevice localXBeeDevice, XBee64BitAddress addr64, XBee16BitAddress addr16, String id) { if (localXBeeDevice == null) throw new NullPointerException("Local XBee device cannot be null."); if (addr64 == null) throw new NullPointerException("XBee 64-bit address of the device cannot be null."); if (localXBeeDevice.isRemote()) throw new IllegalArgumentException("The given local XBee device is remote."); this.localXBeeDevice = localXBeeDevice; this.connectionInterface = localXBeeDevice.getConnectionInterface(); this.xbee64BitAddress = addr64; this.xbee16BitAddress = addr16; if (addr16 == null) xbee16BitAddress = XBee16BitAddress.UNKNOWN_ADDRESS; this.nodeID = id; this.logger = LoggerFactory.getLogger(this.getClass()); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName()); } /** * Retrieves the connection interface associated to this XBee device. * * @return XBee device's connection interface. * * @see IConnectionInterface */ public IConnectionInterface getConnectionInterface() { return connectionInterface; } /** * Retrieves whether or not the XBee device is a remote device. * * @return {@code true} if the XBee device is a remote device, * {@code false} otherwise. */ abstract public boolean isRemote(); /** * Reads some parameters from the device and obtains its protocol. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout reading the parameters. * @throws XBeeException if there is any other XBee related exception. * * @see #get64BitAddress() * @see #get16BitAddress() * @see #getNodeID() * @see #setNodeID(String) * @see #getHardwareVersion() * @see #getFirmwareVersion() * @see #getXBeeProtocol() */ public void readDeviceInfo() throws TimeoutException, XBeeException { byte[] response = null; // Get the 64-bit address. if (xbee64BitAddress == null || xbee64BitAddress == XBee64BitAddress.UNKNOWN_ADDRESS) { String addressHigh; String addressLow; response = getParameter("SH"); addressHigh = HexUtils.byteArrayToHexString(response); response = getParameter("SL"); addressLow = HexUtils.byteArrayToHexString(response); while(addressLow.length() < 8) addressLow = "0" + addressLow; xbee64BitAddress = new XBee64BitAddress(addressHigh + addressLow); } // Get the Node ID. response = getParameter("NI"); nodeID = new String(response); // Get the hardware version. if (hardwareVersion == null) { response = getParameter("HV"); hardwareVersion = HardwareVersion.get(response[0]); } // Get the firmware version. response = getParameter("VR"); firmwareVersion = HexUtils.byteArrayToHexString(response); // Obtain the device protocol. xbeeProtocol = XBeeProtocol.determineProtocol(hardwareVersion, firmwareVersion); // Get the 16-bit address. This must be done after obtaining the protocol because // DigiMesh protocol does not have 16-bit addresses. if (getXBeeProtocol() != XBeeProtocol.DIGI_MESH) { response = getParameter("MY"); xbee16BitAddress = new XBee16BitAddress(response); } } /** * Retrieves the 16-bit address of the XBee device. * * @return The 16-bit address of the XBee device. * * @see XBee16BitAddress */ public XBee16BitAddress get16BitAddress() { return xbee16BitAddress; } /** * Retrieves the 64-bit address of the XBee device. * * @return The 64-bit address of the XBee device. * * @see XBee64BitAddress */ public XBee64BitAddress get64BitAddress() { return xbee64BitAddress; } /** * Retrieves the Operating mode (AT, API or API escaped) of the XBee device. * * @return The operating mode of the XBee device. * * @see OperatingMode */ protected OperatingMode getOperatingMode() { if (isRemote()) return localXBeeDevice.getOperatingMode(); return operatingMode; } /** * Retrieves the XBee Protocol of the XBee device. * * @return The XBee device protocol. * * @see XBeeProtocol * @see #setXBeeProtocol(XBeeProtocol) */ public XBeeProtocol getXBeeProtocol() { return xbeeProtocol; } /** * Retrieves the node identifier of the XBee device. * * @return The node identifier of the device. * * @see #setNodeID(String) */ public String getNodeID() { return nodeID; } public void setNodeID(String nodeID) throws TimeoutException, XBeeException { if (nodeID == null) throw new NullPointerException("Node ID cannot be null."); if (nodeID.length() > 20) throw new IllegalArgumentException("Node ID length must be less than 21."); setParameter("NI", nodeID.getBytes()); this.nodeID = nodeID; } /** * Retrieves the firmware version (hexadecimal string value) of the XBee device. * * @return The firmware version of the XBee device. */ public String getFirmwareVersion() { return firmwareVersion; } /** * Retrieves the hardware version of the XBee device. * * @return The hardware version of the XBee device. * * @see HardwareVersion * @see HardwareVersionEnum */ public HardwareVersion getHardwareVersion() { return hardwareVersion; } /** * Updates the current device reference with the data provided for the given * device. * * <p><b>This is only for internal use.</b></p> * * @param device The XBee Device to get the data from. */ public void updateDeviceDataFrom(AbstractXBeeDevice device) { // TODO Should the devices have the same protocol?? // TODO Should be allow to update a local from a remote or viceversa?? Maybe // this must be in the Local/Remote device class(es) and not here... this.nodeID = device.getNodeID(); // Only update the 64-bit address if the original is null or unknown. XBee64BitAddress addr64 = device.get64BitAddress(); if (addr64 != null && addr64 != XBee64BitAddress.UNKNOWN_ADDRESS && !addr64.equals(xbee64BitAddress) && (xbee64BitAddress == null || xbee64BitAddress.equals(XBee64BitAddress.UNKNOWN_ADDRESS))) { xbee64BitAddress = addr64; } // TODO Change here the 16-bit address or maybe in ZigBee and 802.15.4? // TODO Should the 16-bit address be always updated? Or following the same rule as the 64-bit address. XBee16BitAddress addr16 = device.get16BitAddress(); if (addr16 != null && !addr16.equals(xbee16BitAddress)) { xbee16BitAddress = addr16; } //this.deviceType = device.deviceType; // This is not yet done. // The operating mode: only API/API2. Do we need this for a remote device? // The protocol of the device should be the same. // The hardware version should be the same. // The firmware version can change... } /** * Adds the provided listener to the list of listeners to be notified * when new packets are received. * * <p>If the listener has been already included, this method does nothing. * </p> * * @param listener Listener to be notified when new packets are received. * * @see IPacketReceiveListener * @see #removePacketListener(IPacketReceiveListener) */ protected void addPacketListener(IPacketReceiveListener listener) { if (dataReader == null) return; dataReader.addPacketReceiveListener(listener); } /** * Removes the provided listener from the list of packets listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @see IPacketReceiveListener * @see #addPacketListener(IPacketReceiveListener) */ protected void removePacketListener(IPacketReceiveListener listener) { if (dataReader == null) return; dataReader.removePacketReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new data is received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new data is received. * * @see IDataReceiveListener * @see #removeDataListener(IDataReceiveListener) */ protected void addDataListener(IDataReceiveListener listener) { if (dataReader == null) return; dataReader.addDataReceiveListener(listener); } /** * Removes the provided listener from the list of data listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @see IDataReceiveListener * @see #addDataListener(IDataReceiveListener) */ protected void removeDataListener(IDataReceiveListener listener) { if (dataReader == null) return; dataReader.removeDataReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new IO samples are received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new IO samples are received. * * @throws NullPointerException if {@code listener == null} * * @see IIOSampleReceiveListener * @see #removeIOSampleListener(IIOSampleReceiveListener) */ protected void addIOSampleListener(IIOSampleReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addIOSampleReceiveListener(listener); } /** * Removes the provided listener from the list of IO samples listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see IIOSampleReceiveListener * @see #addIOSampleListener(IIOSampleReceiveListener) */ protected void removeIOSampleListener(IIOSampleReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removeIOSampleReceiveListener(listener); } /** * Sends the given AT command and waits for answer or until the configured * receive timeout expires. * * <p>The receive timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * @param command AT command to be sent. * @return An {@code ATCommandResponse} object containing the response of * the command or {@code null} if there is no response. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws TimeoutException if the configured time expires while waiting * for the command reply. * @throws IOException if an I/O error occurs while sending the AT command. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code command == null}. * * @see ATCommand * @see ATCommandResponse * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ protected ATCommandResponse sendATCommand(ATCommand command) throws InvalidOperatingModeException, TimeoutException, IOException { // Check if command is null. if (command == null) throw new NullPointerException("AT command cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Create the corresponding AT command packet depending on if the device is local or remote. XBeePacket packet; if (isRemote()) { XBee16BitAddress remote16BitAddress = get16BitAddress(); if (remote16BitAddress == null) remote16BitAddress = XBee16BitAddress.UNKNOWN_ADDRESS; int remoteATCommandOptions = RemoteATCommandOptions.OPTION_NONE; if (isApplyConfigurationChangesEnabled()) remoteATCommandOptions |= RemoteATCommandOptions.OPTION_APPLY_CHANGES; packet = new RemoteATCommandPacket(getNextFrameID(), get64BitAddress(), remote16BitAddress, remoteATCommandOptions, command.getCommand(), command.getParameter()); } else { // TODO: If the apply configuration changes option is enabled, send an AT command frame. // If the apply configuration changes option is disabled, send a queue AT command frame. packet = new ATCommandPacket(getNextFrameID(), command.getCommand(), command.getParameter()); } if (command.getParameter() == null) logger.debug(toString() + "Sending AT command '{}'.", command.getCommand()); else logger.debug(toString() + "Sending AT command '{} {}'.", command.getCommand(), HexUtils.prettyHexString(command.getParameter())); try { // Send the packet and build the corresponding response depending on if the device is local or remote. XBeePacket answerPacket; if (isRemote()) answerPacket = localXBeeDevice.sendXBeePacket(packet); else answerPacket = sendXBeePacket(packet); if (answerPacket instanceof ATCommandResponsePacket) response = new ATCommandResponse(command, ((ATCommandResponsePacket)answerPacket).getCommandValue(), ((ATCommandResponsePacket)answerPacket).getStatus()); else if (answerPacket instanceof RemoteATCommandResponsePacket) response = new ATCommandResponse(command, ((RemoteATCommandResponsePacket)answerPacket).getCommandValue(), ((RemoteATCommandResponsePacket)answerPacket).getStatus()); if (response.getResponse() != null) logger.debug(toString() + "AT command response: {}.", HexUtils.prettyHexString(response.getResponse())); else logger.debug(toString() + "AT command response: null."); } catch (ClassCastException e) { logger.error("Received an invalid packet type after sending an AT command packet." + e); } } return response; } /** * Sends the given XBee packet asynchronously. * * <p>To be notified when the answer is received, use * {@link #sendXBeePacket(XBeePacket, IPacketReceiveListener)}.</p> * * @param packet XBee packet to be sent asynchronously. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, boolean) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener, boolean) */ protected void sendXBeePacketAsync(XBeePacket packet) throws InvalidOperatingModeException, IOException { sendXBeePacket(packet, null); } /** * Sends the given XBee packet asynchronously and registers the given packet * listener (if not {@code null}) to wait for an answer. * * @param packet XBee packet to be sent. * @param packetReceiveListener Listener for the operation, {@code null} * not to be notified when the answer arrives. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see IPacketReceiveListener * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, boolean) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket, boolean) */ protected void sendXBeePacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener) throws InvalidOperatingModeException, IOException { // Check if the packet to send is null. if (packet == null) throw new NullPointerException("XBee packet cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Add the required frame ID and subscribe listener if given. if (packet instanceof XBeeAPIPacket) { if (((XBeeAPIPacket)packet).needsAPIFrameID()) { if (((XBeeAPIPacket)packet).getFrameID() == XBeeAPIPacket.NO_FRAME_ID) ((XBeeAPIPacket)packet).setFrameID(getNextFrameID()); if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener, ((XBeeAPIPacket)packet).getFrameID()); } else if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener); } // Write packet data. writePacket(packet); break; } } /** * Sends the given XBee packet synchronously and blocks until response is * received or receive timeout is reached. * * <p>The receive timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>Use {@link #sendXBeePacketAsync(XBeePacket, boolean)} for non-blocking * operations.</p> * * @param packet XBee packet to be sent. * @return An {@code XBeePacket} containing the response of the sent packet * or {@code null} if there is no response. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws TimeoutException if the configured time expires while waiting for the packet reply. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener, boolean) * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket, boolean) * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ protected XBeePacket sendXBeePacket(final XBeePacket packet) throws InvalidOperatingModeException, TimeoutException, IOException { // Check if the packet to send is null. if (packet == null) throw new NullPointerException("XBee packet cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Build response container. ArrayList<XBeePacket> responseList = new ArrayList<XBeePacket>(); // If the packet does not need frame ID, send it async. and return null. if (packet instanceof XBeeAPIPacket) { if (!((XBeeAPIPacket)packet).needsAPIFrameID()) { sendXBeePacketAsync(packet); return null; } } else { sendXBeePacketAsync(packet); return null; } // Add the required frame ID to the packet if necessary. insertFrameID(packet); // Generate a packet received listener for the packet to be sent. IPacketReceiveListener packetReceiveListener = createPacketReceivedListener(packet, responseList); // Add the packet listener to the data reader. addPacketListener(packetReceiveListener); // Write the packet data. writePacket(packet); try { // Wait for response or timeout. synchronized (responseList) { try { responseList.wait(receiveTimeout); } catch (InterruptedException e) {} } // After the wait check if we received any response, if not throw timeout exception. if (responseList.size() < 1) throw new TimeoutException(); // Return the received packet. return responseList.get(0); } finally { // Always remove the packet listener from the list. removePacketListener(packetReceiveListener); } } } /** * Insert (if possible) the next frame ID stored in the device to the * provided packet. * * @param xbeePacket The packet to add the frame ID. * * @see XBeePacket */ private void insertFrameID(XBeePacket xbeePacket) { if (xbeePacket instanceof XBeeAPIPacket) return; if (((XBeeAPIPacket)xbeePacket).needsAPIFrameID() && ((XBeeAPIPacket)xbeePacket).getFrameID() == XBeeAPIPacket.NO_FRAME_ID) ((XBeeAPIPacket)xbeePacket).setFrameID(getNextFrameID()); } /** * Retrieves the packet listener corresponding to the provided sent packet. * * <p>The listener will filter those packets matching with the Frame ID of * the sent packet storing them in the provided responseList array.</p> * * @param sentPacket The packet sent. * @param responseList List of packets received that correspond to the * frame ID of the packet sent. * * @return A packet receive listener that will filter the packets received * corresponding to the sent one. * * @see IPacketReceiveListener * @see XBeePacket */ private IPacketReceiveListener createPacketReceivedListener(final XBeePacket sentPacket, final ArrayList<XBeePacket> responseList) { IPacketReceiveListener packetReceiveListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ @Override public void packetReceived(XBeePacket receivedPacket) { // Check if it is the packet we are waiting for. if (((XBeeAPIPacket)receivedPacket).checkFrameID((((XBeeAPIPacket)sentPacket).getFrameID()))) { // Security check to avoid class cast exceptions. It has been observed that parallel processes // using the same connection but with different frame index may collide and cause this exception at some point. if (sentPacket instanceof XBeeAPIPacket && receivedPacket instanceof XBeeAPIPacket) { XBeeAPIPacket sentAPIPacket = (XBeeAPIPacket)sentPacket; XBeeAPIPacket receivedAPIPacket = (XBeeAPIPacket)receivedPacket; // If the packet sent is an AT command, verify that the received one is an AT command response and // the command matches in both packets. if (sentAPIPacket.getFrameType() == APIFrameType.AT_COMMAND) { if (receivedAPIPacket.getFrameType() != APIFrameType.AT_COMMAND_RESPONSE) return; if (!((ATCommandPacket)sentAPIPacket).getCommand().equalsIgnoreCase(((ATCommandResponsePacket)receivedPacket).getCommand())) return; } // If the packet sent is a remote AT command, verify that the received one is a remote AT command response and // the command matches in both packets. if (sentAPIPacket.getFrameType() == APIFrameType.REMOTE_AT_COMMAND_REQUEST) { if (receivedAPIPacket.getFrameType() != APIFrameType.REMOTE_AT_COMMAND_RESPONSE) return; if (!((RemoteATCommandPacket)sentAPIPacket).getCommand().equalsIgnoreCase(((RemoteATCommandResponsePacket)receivedPacket).getCommand())) return; } } // Verify that the sent packet is not the received one! This can happen when the echo mode is enabled in the // serial port. if (!isSamePacket(sentPacket, receivedPacket)) { responseList.add(receivedPacket); synchronized (responseList) { responseList.notify(); } } } } }; return packetReceiveListener; } /** * Retrieves whether or not the sent packet is the same than the received one. * * @param sentPacket The packet sent. * @param receivedPacket The packet received. * * @return {@code true} if the sent packet is the same than the received * one, {@code false} otherwise. * * @see XBeePacket */ private boolean isSamePacket(XBeePacket sentPacket, XBeePacket receivedPacket) { // TODO Should not we implement the {@code equals} method in the XBeePacket?? if (HexUtils.byteArrayToHexString(sentPacket.generateByteArray()).equals(HexUtils.byteArrayToHexString(receivedPacket.generateByteArray()))) return true; return false; } /** * Writes the given XBee packet in the connection interface. * * @param packet XBee packet to be written. * * @throws IOException if an I/O error occurs while writing the XBee packet * in the connection interface. */ private void writePacket(XBeePacket packet) throws IOException { logger.debug(toString() + "Sending XBee packet: \n{}", packet.toPrettyString()); // Write bytes with the required escaping mode. switch (operatingMode) { case API: default: connectionInterface.writeData(packet.generateByteArray()); break; case API_ESCAPE: connectionInterface.writeData(packet.generateByteArrayEscaped()); break; } } /** * Retrieves the next Frame ID of the XBee protocol. * * @return The next Frame ID. */ protected int getNextFrameID() { if (isRemote()) return localXBeeDevice.getNextFrameID(); if (currentFrameID == 0xff) { // Reset counter. currentFrameID = 1; } else currentFrameID ++; return currentFrameID; } /** * Sends the provided {@code XBeePacket} and determines if the transmission * status is success for synchronous transmissions. If the status is not * success, an {@code TransmitException} is thrown. * * @param packet The {@code XBeePacket} to be sent. * @param asyncTransmission Determines whether or not the transmission * should be made asynchronously. * * @throws TransmitException if {@code packet} is not an instance of {@code TransmitStatusPacket} or * if {@code packet} is not an instance of {@code TXStatusPacket} or * if its transmit status is different than {@code XBeeTransmitStatus.SUCCESS}. * @throws XBeeException if there is any other XBee related error. * * @see XBeePacket */ protected void sendAndCheckXBeePacket(XBeePacket packet, boolean asyncTransmission) throws TransmitException, XBeeException { XBeePacket receivedPacket = null; // Send the XBee packet. try { if (asyncTransmission) sendXBeePacketAsync(packet); else receivedPacket = sendXBeePacket(packet); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // If the transmission is async. we are done. if (asyncTransmission) return; // Check if the packet received is a valid transmit status packet. if (receivedPacket == null) throw new TransmitException(null); if (receivedPacket instanceof TransmitStatusPacket) { if (((TransmitStatusPacket)receivedPacket).getTransmitStatus() == null) throw new TransmitException(null); else if (((TransmitStatusPacket)receivedPacket).getTransmitStatus() != XBeeTransmitStatus.SUCCESS) throw new TransmitException(((TransmitStatusPacket)receivedPacket).getTransmitStatus()); } else if (receivedPacket instanceof TXStatusPacket) { if (((TXStatusPacket)receivedPacket).getTransmitStatus() == null) throw new TransmitException(null); else if (((TXStatusPacket)receivedPacket).getTransmitStatus() != XBeeTransmitStatus.SUCCESS) throw new TransmitException(((TXStatusPacket)receivedPacket).getTransmitStatus()); } else throw new TransmitException(null); } /** * Sets the configuration of the given IO line. * * @param ioLine The IO line to configure. * @param mode The IO mode to set to the IO line. * * @throws TimeoutException if there is a timeout sending the set * configuration command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null} or * if {@code ioMode == null}. * * @see IOLine * @see IOMode * @see #getIOConfiguration(IOLine) */ public void setIOConfiguration(IOLine ioLine, IOMode ioMode) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); if (ioMode == null) throw new NullPointerException("IO mode cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); setParameter(ioLine.getConfigurationATCommand(), new byte[]{(byte)ioMode.getID()}); } /** * Retrieves the configuration mode of the provided IO line. * * @param ioLine The IO line to get its configuration. * * @return The IO mode (configuration) of the provided IO line. * * @throws TimeoutException if there is a timeout sending the get * configuration command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode * @see #setIOConfiguration(IOLine, IOMode) */ public IOMode getIOConfiguration(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("DIO pin cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if the received configuration mode is valid. int ioModeValue = getParameter(ioLine.getConfigurationATCommand())[0]; IOMode dioMode = IOMode.getIOMode(ioModeValue, ioLine); if (dioMode == null) throw new OperationNotSupportedException("Received configuration mode '" + HexUtils.integerToHexString(ioModeValue, 1) + "' is not valid."); // Return the configuration mode. return dioMode; } /** * Sets the digital value (high or low) to the provided IO line. * * @param ioLine The IO line to set its value. * @param value The IOValue to set to the IO line ({@code HIGH} or * {@code LOW}). * * @throws TimeoutException if there is a timeout sending the set DIO * command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null} or * if {@code ioValue == null}. * * @see IOLine * @see IOValue * @see IOMode#DIGITAL_OUT_HIGH * @see IOMode#DIGITAL_OUT_LOW * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public void setDIOValue(IOLine ioLine, IOValue ioValue) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check IO value. if (ioValue == null) throw new NullPointerException("IO value cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); setParameter(ioLine.getConfigurationATCommand(), new byte[]{(byte)ioValue.getID()}); } /** * Retrieves the digital value of the provided IO line (must be configured * as digital I/O). * * @param ioLine The IO line to get its digital value. * * @return The digital value corresponding to the provided IO line. * * @throws NullPointerException if {@code ioLine == null}. * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout sending the get IO values * command. * @throws XBeeException if there is any other XBee related exception. * * @see IOLine * @see IOMode#DIGITAL_IN * @see IOMode#DIGITAL_OUT_HIGH * @see IOMode#DIGITAL_OUT_LOW * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public IOValue getDIOValue(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Obtain an IO Sample from the XBee device. IOSample ioSample = readIOSample(); // Check if the IO sample contains the expected IO line and value. if (!ioSample.hasDigitalValues() || !ioSample.getDigitalValues().containsKey(ioLine)) throw new OperationNotSupportedException("Answer does not contain digital data for " + ioLine.getName() + "."); // Return the digital value. return ioSample.getDigitalValues().get(ioLine); } public void setPWMDutyCycle(IOLine ioLine, double dutyCycle) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check if the IO line has PWM capability. if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); // Check duty cycle limits. if (dutyCycle < 0 || dutyCycle > 100) throw new IllegalArgumentException("Duty Cycle must be between 0% and 100%."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Convert the value. int finaldutyCycle = (int)(dutyCycle * 1023.0/100.0); setParameter(ioLine.getPWMDutyCycleATCommand(), ByteUtils.intToByteArray(finaldutyCycle)); } public double getPWMDutyCycle(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check if the IO line has PWM capability. if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); byte[] value = getParameter(ioLine.getPWMDutyCycleATCommand()); // Return the PWM duty cycle value. int readValue = ByteUtils.byteArrayToInt(value); return Math.round((readValue * 100.0/1023.0) * 100.0) / 100.0; } /** * Retrieves the analog value of the provided IO line (must be configured * as ADC). * * @param ioLine The IO line to get its analog value. * * @return The analog value corresponding to the provided IO line. * * @throws TimeoutException if there is a timeout sending the get IO values * command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#ADC * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public int getADCValue(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Obtain an IO Sample from the XBee device. IOSample ioSample = readIOSample(); // Check if the IO sample contains the expected IO line and value. if (!ioSample.hasAnalogValues() || !ioSample.getAnalogValues().containsKey(ioLine)) throw new OperationNotSupportedException("Answer does not contain analog data for " + ioLine.getName() + "."); // Return the analog value. return ioSample.getAnalogValues().get(ioLine); } /** * Sets the 64 bit destination extended address. * * <p>{@link XBee64BitAddress#BROADCAST_ADDRESS} is the broadcast address * for the PAN. {@link XBee64BitAddress#COORDINATOR_ADDRESS} can be used to * address the Pan Coordinator.</p> * * @param xbee64BitAddress Destination address. * * @throws NullPointerException if {@code xbee64BitAddress == null}. * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout sending the set * destination address command. * @throws XBeeException if there is any other XBee related exception. * * @see XBee64BitAddress */ public void setDestinationAddress(XBee64BitAddress xbee64BitAddress) throws TimeoutException, XBeeException { if (xbee64BitAddress == null) throw new NullPointerException("Address cannot be null."); // This method needs to apply changes after modifying the destination // address, but only if the destination address could be set successfully. boolean applyChanges = isApplyConfigurationChangesEnabled(); if (applyChanges) enableApplyConfigurationChanges(false); byte[] address = xbee64BitAddress.getValue(); try { setParameter("DH", Arrays.copyOfRange(address, 0, 4)); setParameter("DL", Arrays.copyOfRange(address, 4, 8)); applyChanges(); } finally { // Always restore the old value of the AC. enableApplyConfigurationChanges(applyChanges); } } /** * Retrieves the 64 bit destination extended address. * * @return 64 bit destination address. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout sending the get * destination address command. * @throws XBeeException if there is any other XBee related exception. * * @see XBee64BitAddress */ public XBee64BitAddress getDestinationAddress() throws TimeoutException, XBeeException { byte[] dh = getParameter("DH"); byte[] dl = getParameter("DL"); byte[] address = new byte[dh.length + dl.length]; System.arraycopy(dh, 0, address, 0, dh.length); System.arraycopy(dl, 0, address, dh.length, dl.length); return new XBee64BitAddress(address); } public void setIOSamplingRate(int rate) throws TimeoutException, XBeeException { // Check range. if (rate < 0 || rate > 0xFFFF) throw new IllegalArgumentException("Rate must be between 0 and 0xFFFF."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); setParameter("IR", ByteUtils.intToByteArray(rate)); } /** * Retrieves the IO sampling rate. * * <p>A sample rate of {@code 0} means the IO sampling feature is disabled. * </p> * * @return IO sampling rate in milliseconds. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout sending the get IO * sampling rate command. * @throws XBeeException if there is any other XBee related exception. * * @see #setIOSamplingRate(int) */ public int getIOSamplingRate() throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); byte[] rate = getParameter("IR"); return ByteUtils.byteArrayToInt(rate); } /** * Sets the digital IO lines to be monitored and sampled when their status * changes. * * <p>If a change is detected on an enabled digital IO pin, a digital IO * sample is immediately transmitted to the configured destination address. * </p> * * <p>A {@code null} set disables this feature.</p> * * @param lines Set of IO lines to be monitored, {@code null} to disable * this feature. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout sending the set DIO * change detection command. * @throws XBeeException if there is any other XBee related exception. * * @see #getDIOChangeDetection() * @see #setDestinationAddress(XBee64BitAddress) * @see #getDestinationAddress() */ public void setDIOChangeDetection(Set<IOLine> lines) throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); byte[] bitfield = new byte[2]; if (lines != null) { for (IOLine line : lines) { int i = line.getIndex(); if (i < 8) bitfield[1] = (byte) (bitfield[1] | (1 << i)); else bitfield[0] = (byte) (bitfield[0] | (1 << i - 8)); } } setParameter("IC", bitfield); } /** * Retrieves the set of IO lines that are monitored for change detection. * * <p>A {@code null} set means the DIO change detection feature is disabled. * </p> * * @return Set of digital IO lines that are monitored for change detection, * {@code null} if there are no monitored lines. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout sending the get DIO * change detection command. * @throws XBeeException if there is any other XBee related exception. * * @see #setDIOChangeDetection(Set) */ public Set<IOLine> getDIOChangeDetection() throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); byte[] bitfield = getParameter("IC"); TreeSet<IOLine> lines = new TreeSet<IOLine>(); int mask = (bitfield[0] << 8) + bitfield[1]; for (int i = 0; i < 16; i++) { if (ByteUtils.isBitEnabled(mask, i)) lines.add(IOLine.getDIO(i)); } if (lines.size() > 0) return lines; return null; } /** * Applies changes to all command registers causing queued command register * values to be applied. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout sending the get Apply * Changes command. * @throws XBeeException if there is any other XBee related exception. */ public void applyChanges() throws TimeoutException, XBeeException { executeParameter("AC"); } /** * Checks if the provided {@code ATCommandResponse} is valid throwing an * {@code ATCommandException} in case it is not. * * @param response The {@code ATCommandResponse} to check. * * @throws ATCommandException if {@code response == null} or * if {@code response.getResponseStatus() != ATCommandStatus.OK}. */ protected void checkATCommandResponseIsValid(ATCommandResponse response) throws ATCommandException { if (response == null || response.getResponseStatus() == null) throw new ATCommandException(null); else if (response.getResponseStatus() != ATCommandStatus.OK) throw new ATCommandException(response.getResponseStatus()); } /** * Retrieves an IO sample from the XBee device containing the value of all * enabled digital IO and analog input channels. * * @return An IO sample containing the value of all enabled digital IO and * analog input channels. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout getting the IO sample. * @throws XBeeException if there is any other XBee related exception. * * @see IOSample */ public IOSample readIOSample() throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Try to build an IO Sample from the sample payload. byte[] samplePayload = getParameter("IS"); IOSample ioSample; // If it is a local 802.15.4 device, the response does not contain the // IO sample, so we have to create a packet listener to receive the // sample. if (!isRemote() && getXBeeProtocol() == XBeeProtocol.RAW_802_15_4) { samplePayload = receiveRaw802IOPacket(); if (samplePayload == null) throw new TimeoutException("Timeout waiting for the IO response packet."); } try { ioSample = new IOSample(samplePayload); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } return ioSample; } /** * Retrieves the latest 802.15.4 IO packet and returns its value. * * @return The value of the latest received 802.15.4 IO packet. */ private byte[] receiveRaw802IOPacket() { ioPacketReceived = false; ioPacketPayload = null; addPacketListener(IOPacketReceiveListener); synchronized (ioLock) { try { ioLock.wait(receiveTimeout); } catch (InterruptedException e) { } } removePacketListener(IOPacketReceiveListener); if (ioPacketReceived) return ioPacketPayload; return null; } /** * Custom listener for 802.15.4 IO packets. It will try to receive an 802.15.4 IO * sample packet. * * <p>When an IO sample packet is received, it saves its payload and notifies * the object that was waiting for the reception.</p> */ private IPacketReceiveListener IOPacketReceiveListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ @Override public void packetReceived(XBeePacket receivedPacket) { // Discard non API packets. if (!(receivedPacket instanceof XBeeAPIPacket)) return; // If we already have received an IO packet, ignore this packet. if (ioPacketReceived) return; // Save the packet value (IO sample payload) switch (((XBeeAPIPacket)receivedPacket).getFrameType()) { case IO_DATA_SAMPLE_RX_INDICATOR: ioPacketPayload = ((IODataSampleRxIndicatorPacket)receivedPacket).getRFData(); break; case RX_IO_16: ioPacketPayload = ((RX16IOPacket)receivedPacket).getRFData(); break; case RX_IO_64: ioPacketPayload = ((RX64IOPacket)receivedPacket).getRFData(); break; default: return; } // Set the IO packet received flag. ioPacketReceived = true; // Continue execution by notifying the lock object. synchronized (ioLock) { ioLock.notify(); } } }; /** * Performs a software reset on the module and blocks until the process * is completed. * * @throws TimeoutException if the configured time expires while waiting * for the command reply. * @throws XBeeException if there is any other XBee related exception. */ abstract public void reset() throws TimeoutException, XBeeException; public void setParameter(String parameter, byte[] parameterValue) throws TimeoutException, XBeeException { if (parameterValue == null) throw new NullPointerException("Value of the parameter cannot be null."); sendParameter(parameter, parameterValue); } public byte[] getParameter(String parameter) throws TimeoutException, XBeeException { byte[] parameterValue = sendParameter(parameter, null); // Check if the response is null, if so throw an exception (maybe it was a write-only parameter). if (parameterValue == null) throw new OperationNotSupportedException("Couldn't get the '" + parameter + "' value."); return parameterValue; } public void executeParameter(String parameter) throws TimeoutException, XBeeException { sendParameter(parameter, null); } private byte[] sendParameter(String parameter, byte[] parameterValue) throws TimeoutException, XBeeException { if (parameter == null) throw new NullPointerException("Parameter cannot be null."); if (parameter.length() != 2) throw new IllegalArgumentException("Parameter must contain exactly 2 characters."); ATCommand atCommand = new ATCommand(parameter, parameterValue); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(atCommand); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); // Return the response value. return response.getResponse(); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return connectionInterface.toString(); } /** * Enables or disables the apply configuration changes option. * * <p>Enabling this option means that when any parameter of the XBee device is set, it will * be also applied. If this option is disabled you will need to issue the {@code #applyChanges()} * method in order to apply the changes in all the parameters that were previously set.</p> * * @see #isApplyConfigurationChangesEnabled() */ public void enableApplyConfigurationChanges(boolean enabled) { applyConfigurationChanges = enabled; } /** * Retrieves whether or not the apply configuration changes option is enabled. * * @return True if the option is enabled, false otherwise. * * @see #enableApplyConfigurationChanges(boolean) */ public boolean isApplyConfigurationChangesEnabled() { return applyConfigurationChanges; } /** * Configures the 16-bit address (network address) of the XBee device with the provided one. * * @param xbee16BitAddress The new 16-bit address. * * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code xbee16BitAddress == null}. * @throws TimeoutException if there is a timeout setting the address. * @throws XBeeException if there is any other XBee related exception. * * @see XBee16BitAddress * @see #get16BitAddress() */ protected void set16BitAddress(XBee16BitAddress xbee16BitAddress) throws TimeoutException, XBeeException { if (xbee16BitAddress == null) throw new NullPointerException("16-bit address canot be null."); setParameter("MY", xbee16BitAddress.getValue()); this.xbee16BitAddress = xbee16BitAddress; } /** * Retrieves the operating PAN ID of the XBee device. * * @return The operating PAN ID of the XBee device. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout getting the PAN ID. * @throws XBeeException if there is any other XBee related exception. */ public byte[] getPANID() throws TimeoutException, XBeeException { switch (getXBeeProtocol()) { case ZIGBEE: return getParameter("OP"); default: return getParameter("ID"); } } public void setPANID(byte[] panID) throws TimeoutException, XBeeException { if (panID == null) throw new NullPointerException("PAN ID cannot be null."); if (panID.length == 0) throw new IllegalArgumentException("Length of the PAN ID cannot be 0."); if (panID.length > 8) throw new IllegalArgumentException("Length of the PAN ID cannot be longer than 8 bytes."); setParameter("ID", panID); } /** * Retrieves the output power level of the XBee device. * * @return The output power level of the XBee device. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout getting the power level. * @throws XBeeException if there is any other XBee related exception. * * @see PowerLevel */ public PowerLevel getPowerLevel() throws TimeoutException, XBeeException { byte[] powerLevelValue = getParameter("PL"); return PowerLevel.get(ByteUtils.byteArrayToInt(powerLevelValue)); } /** * Sets the output power level of the XBee device. * * @param powerLevel The new output power level to be set in the XBee device. * * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code powerLevel == null}. * @throws TimeoutException if there is a timeout setting the power level. * @throws XBeeException if there is any other XBee related exception. * * @see PowerLevel */ public void setPowerLevel(PowerLevel powerLevel) throws TimeoutException, XBeeException { if (powerLevel == null) throw new NullPointerException("Power level cannot be null."); setParameter("PL", ByteUtils.intToByteArray(powerLevel.getValue())); } /** * Retrieves the current association indication status of the XBee device. * * @return The association indication status of the XBee device. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout getting the association indication status. * @throws XBeeException if there is any other XBee related exception. * * @see AssociationIndicationStatus */ protected AssociationIndicationStatus getAssociationIndicationStatus() throws TimeoutException, XBeeException { byte[] associationIndicationValue = getParameter("AI"); return AssociationIndicationStatus.get(ByteUtils.byteArrayToInt(associationIndicationValue)); } /** * Forces the XBee device to disassociate from the network and reattempt to associate. * * <p>Only valid for End Devices.</p> * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout executing the disassociation command. * @throws XBeeException if there is any other XBee related exception. */ protected void forceDisassociate() throws TimeoutException, XBeeException { executeParameter("DA"); } /** * Writes parameter values to non-volatile memory of the XBee device so that parameter * modifications persist through subsequent resets. * * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout executing the write changes command. * @throws XBeeException if there is any other XBee related exception. */ public void writeChanges() throws TimeoutException, XBeeException { executeParameter("WR"); } }
package net.darkhax.bookshelf.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import javax.annotation.Nullable; import net.darkhax.bookshelf.lib.Constants; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntitySpawnPlacementRegistry; import net.minecraft.entity.EnumCreatureType; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.DimensionType; import net.minecraft.world.World; import net.minecraft.world.WorldEntitySpawner; import net.minecraft.world.WorldServer; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.Biome.SpawnListEntry; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.fml.common.eventhandler.Event.Result; public final class WorldUtils { /** * Utility classes, such as this one, are not meant to be instantiated. Java adds an * implicit public constructor to every class which does not define at lease one * explicitly. Hence why this constructor was added. */ private WorldUtils () { throw new IllegalAccessError("Utility class"); } /** * Gets the display name of a world. * * @param world The world to get the name of. * @return The name of the world. */ public static String getWorldName (World world) { String result = "Unknown"; // TODO add more fallback options if (world.provider != null) { result = world.provider.getDimensionType().getName(); } return result; } /** * Gets the amount of loaded chunks. * * @param world The world to get the chunk count of. * @return The amount of chunks. -1 means it was unable to get the amount. */ public static int getLoadedChunks (WorldServer world) { return world.getChunkProvider() != null ? world.getChunkProvider().getLoadedChunkCount() : -1; } /** * Gets the dimension id of a world. * * @param world The world to get the id of. * @return The id of the world. 0 (surface) is used if none is found. */ public static int getDimId (WorldServer world) { return world.provider != null ? world.provider.getDimension() : 0; } /** * Checks if two block positions are in the same chunk in a given world. * * @param first The first position. * @param second The second position. * @return Whether or not the two positions are in the same chunk. */ public static boolean areSameChunk (BlockPos first, BlockPos second) { return new ChunkPos(first).equals(new ChunkPos(second)); } /** * Checks if two block positions are in the same chunk in a given world. * * @param world The world to check within. * @param first The first position. * @param second The second position. * @return Whether or not the two positions are in the same chunk. */ @Deprecated public static boolean areSameChunk (World world, BlockPos first, BlockPos second) { return areSameChunk(first, second); } /** * Checks if the dimension id of a world matches the provided dimension id. * * @param world The world to check. * @param id The dimension id you are looking for. * @return Whether or not they are the same. */ public static boolean isDimension (World world, int id) { return getDimensionId(world) == id; } /** * Checks if the dimension type of a world matches the provided dimension type. * * @param world The world to check. * @param type The dimension type you are looking for. * @return Whether or not they are the same. */ public static boolean isDimension (World world, DimensionType type) { return getDimensionType(world) == type; } /** * Gets the dimension id of a world. * * @param world The world you are looking into. * @return The id of the world. */ public static int getDimensionId (World world) { return getDimensionType(world).getId(); } /** * Gets the dimension type of a world. * * @param world The world you are looking into. * @return The type of the world. */ public static DimensionType getDimensionType (World world) { return world.provider.getDimensionType(); } /** * Attempts to set the biome of an entire chunk. Please note that this will also cause * conecting chunks to do an update, and will cause the targeted chunk to recieve a render * update. * * @param world The world to set the biome in. * @param pos The block position to target. This will target the chunk the psotion is in. * @param biome The biome to set the chunk to. */ public static void setBiomes (World world, BlockPos pos, Biome biome) { try { final Chunk chunk = world.getChunkFromBlockCoords(pos); final byte[] biomes = chunk.getBiomeArray(); Arrays.fill(biomes, (byte) Biome.getIdForBiome(biome)); chunk.markDirty(); updateNearbyChunks(world, chunk, true, true); } catch (final Exception e) { Constants.LOG.warn(e, "Unable to set biome for Pos: {}, Biome: {}", pos.toString(), biome.getRegistryName()); } } /** * Marks a chunk for an update. This will set it dirty, and potentially do a render update. * * @param world The world to update chunks in. * @param chunk The chunk to update. * @param render Whether or not you want a render update. */ public static void markChunkForUpdate (World world, Chunk chunk, boolean render) { chunk.markDirty(); if (render) { final BlockPos initial = chunk.getPos().getBlock(1, 1, 1); world.markBlockRangeForRenderUpdate(initial, initial); } } /** * Updates all chunks near the provided chunk. This is a 3x3 area centered on the chunk. * * @param world The world to update chunks in. * @param chunk The chunk to update. * @param includeSelf Whether or not the base chunk should be updated. * @param render Whether or not you want a render update. */ public static void updateNearbyChunks (World world, Chunk chunk, boolean includeSelf, boolean render) { for (final Chunk other : getNearbyChunks(world, chunk)) { if (other != chunk || includeSelf) { markChunkForUpdate(world, other, render); } } } /** * Gets a list of 9 chunks in a 3x3 area, centered around the passed chunk. * * @param world The world to get chunks from. * @param chunk The initial chunk. * @return A list of 9 chunks that are near the passed chunk, as well as the initial chunk. */ public static List<Chunk> getNearbyChunks (World world, Chunk chunk) { return getNearbyChunks(world, chunk.getPos()); } /** * Gets a list of 9 chunks in a 3x3 area, centered around the passed chunk position. * * @param world The world to get chunks from. * @param chunk The chunk position. * @return A list of 9 chunks that are near the passed chunk pos, as well as the chunk at * the passed position. */ public static List<Chunk> getNearbyChunks (World world, ChunkPos chunk) { final List<Chunk> chunks = new ArrayList<>(); for (int offX = -1; offX < 2; offX++) { for (int offY = -1; offY < 2; offY++) { chunks.add(world.getChunkFromChunkCoords(chunk.x + offX, chunk.z + offY)); } } return chunks; } /** * Gets a random position within a chunk. This will load the chunk if it is not already * loaded. * * @param world The world to get a position within. * @param x The chunk X position. * @param z The chunk Y position. * @return A random position within the chunk. */ public static BlockPos getRandomChunkPosition (World world, int x, int z) { final Chunk chunk = world.getChunkFromChunkCoords(x, z); final int posX = x * 16 + world.rand.nextInt(16); final int posZ = z * 16 + world.rand.nextInt(16); final int height = MathHelper.roundUp(chunk.getHeight(new BlockPos(posX, 0, posZ)) + 1, 16); final int posY = world.rand.nextInt(height > 0 ? height : chunk.getTopFilledSegment() + 16 - 1); return new BlockPos(posX, posY, posZ); } /** * Attempts to spawn mobs in a chunk. * * @param world The world to spawn the mobs in. * @param pos The position of the chunk to spawn in. * @param mobType The type of mob to try and spawn. * @param spawnHook A hook for running additional code on mob spawn. */ public static void attemptChunkSpawn (WorldServer world, BlockPos pos, EnumCreatureType mobType, @Nullable Consumer<EntityLiving> spawnHook) { final ChunkPos chunkPos = new ChunkPos(pos); final BlockPos blockpos = getRandomChunkPosition(world, chunkPos.x, chunkPos.z); final int randX = blockpos.getX(); final int randY = blockpos.getY(); final int randZ = blockpos.getZ(); // Checks if block is not a solid cube. if (!world.getBlockState(blockpos).isNormalCube()) { final int offsetX = randX + MathsUtils.nextIntInclusive(-6, 6); final int spawnY = randY + MathsUtils.nextIntInclusive(-1, 1); final int offsetY = randZ + MathsUtils.nextIntInclusive(-6, 6); final BlockPos currentPos = new BlockPos(offsetX, spawnY, offsetY); final float spawnX = offsetX + 0.5F; final float spawnZ = offsetY + 0.5F; // Get a random spawn list entry for the current chunk. final SpawnListEntry spawnListEntry = world.getSpawnListEntryForTypeAt(mobType, currentPos); if (spawnListEntry == null) { return; } // Checks if the mob entry is valid for the current position. if (world.canCreatureTypeSpawnHere(mobType, spawnListEntry, currentPos) && WorldEntitySpawner.canCreatureTypeSpawnAtLocation(EntitySpawnPlacementRegistry.getPlacementForEntity(spawnListEntry.entityClass), world, currentPos)) { // Get a random amount of mobs to spawn by using the pack size numbers. final int amountToSpawn = MathsUtils.nextIntInclusive(spawnListEntry.minGroupCount, spawnListEntry.maxGroupCount); for (int attempt = 0; attempt < amountToSpawn; attempt++) { EntityLiving spawnedMob; try { spawnedMob = spawnListEntry.newInstance(world); } catch (final Exception exception) { Constants.LOG.catching(exception); return; } if (spawnedMob != null) { spawnedMob.setLocationAndAngles(spawnX, spawnY, spawnZ, world.rand.nextFloat() * 360.0F, 0.0F); // Run forge's entity spawn check event final Result canSpawn = ForgeEventFactory.canEntitySpawn(spawnedMob, world, spawnX, spawnY, spawnZ, false); if (canSpawn == Result.ALLOW || canSpawn == Result.DEFAULT && spawnedMob.getCanSpawnHere() && spawnedMob.isNotColliding()) { if (!ForgeEventFactory.doSpecialSpawn(spawnedMob, world, spawnX, spawnY, spawnZ)) { spawnedMob.onInitialSpawn(world.getDifficultyForLocation(new BlockPos(spawnedMob)), null); } if (spawnedMob.isNotColliding()) { world.spawnEntity(spawnedMob); if (spawnHook != null) { spawnHook.accept(spawnedMob); } } else { spawnedMob.setDead(); } } } } } } } }
package net.dean.jraw.managers; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; import net.dean.jraw.AccountPreferencesEditor; import net.dean.jraw.ApiException; import net.dean.jraw.EndpointImplementation; import net.dean.jraw.Endpoints; import net.dean.jraw.RedditClient; import net.dean.jraw.http.MediaTypes; import net.dean.jraw.http.NetworkException; import net.dean.jraw.http.RequestBody; import net.dean.jraw.http.RestResponse; import net.dean.jraw.models.AccountPreferences; import net.dean.jraw.models.Captcha; import net.dean.jraw.models.Contribution; import net.dean.jraw.models.FlairTemplate; import net.dean.jraw.models.KarmaBreakdown; import net.dean.jraw.models.PublicContribution; import net.dean.jraw.models.Submission; import net.dean.jraw.models.Subreddit; import net.dean.jraw.models.Thing; import net.dean.jraw.models.UserRecord; import net.dean.jraw.models.VoteDirection; import net.dean.jraw.models.attr.Votable; import net.dean.jraw.util.JrawUtils; import java.net.URL; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class manages common user actions, such as voting, commenting, saving, etc. */ public class AccountManager extends AbstractManager { /** * Instantiates a new AccountManager * * @param client The RedditClient to use */ public AccountManager(RedditClient client) { super(client); } /** * Submits a new link * * @param b The SubmissionBuilder to gather data from * @return A representation of the newly submitted Submission * @throws NetworkException If the request was not successful * @throws net.dean.jraw.ApiException If the Reddit API returned an error */ public Submission submit(SubmissionBuilder b) throws NetworkException, ApiException { return submit(b, null, null); } /** * Submits a new link with a given captcha. Only really needed if the user has less than 10 link karma. * * @param b The SubmissionBuilder to gather data from * @param captcha The Captcha the user is attempting * @param captchaAttempt The user's guess at the captcha * @return A representation of the newly submitted Submission * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.SUBMIT) public Submission submit(SubmissionBuilder b, Captcha captcha, String captchaAttempt) throws NetworkException, ApiException { Map<String, String> args = JrawUtils.mapOf( "api_type", "json", "extension", "json", "kind", b.selfPost ? "self" : "link", "resubmit", b.resubmit, "save", b.saveAfter, "sendreplies", b.sendRepliesToInbox, "sr", b.subreddit, "then", "comments", "title", b.title ); if (b.selfPost) { args.put("text", b.selfText); } else { args.put("url", b.url.toExternalForm()); } if (captcha != null) { if (captchaAttempt == null) { throw new IllegalArgumentException("Captcha present but the attempt is not"); } args.put("iden", captcha.getId()); args.put("captcha", captchaAttempt); } RestResponse response = genericPost(reddit.request() .endpoint(Endpoints.SUBMIT) .post(args) .build()); return reddit.getSubmission(response.getJson().get("json").get("data").get("id").asText()); } /** * Votes on a comment or submission. Please note that "API clients proxying a human's action one-for-one are OK, but * bots deciding how to vote on content or amplifying a human's vote are not". * * @param s The submission to vote on * @param voteDirection How to vote * @param <T> The Votable Thing to vote on * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.VOTE) public <T extends Thing & Votable> void vote(T s, VoteDirection voteDirection) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.VOTE) .post(JrawUtils.mapOf( "api_type", "json", "dir", voteDirection.getValue(), "id", s.getFullName()) ).build()); } /** * Reports a comment or submission. * * @param s The submission to vote on * @param voteDirection How to vote * @param <T> The Votable Thing to vote on * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.REPORT) public <T extends Thing> void report(T s, String reason) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.REPORT) .post(JrawUtils.mapOf( "api_type", "json", "reason", reason, "thing_id", s.getFullName()) ).build()); } /** * Stores visited links (Reddit Gold feature) * * @param fullnames The submission fullnames to store visits for * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.STORE_VISITS) public void storeVisits(String... fullnames) throws NetworkException, ApiException { StringBuilder b = new StringBuilder(); for (String s : fullnames) { b.append(s); b.append(","); } String listFullnames = b.toString().substring(0, b.length() - 1); genericPost(reddit.request() .endpoint(Endpoints.STORE_VISITS) .post(JrawUtils.mapOf( "links", listFullnames) ).build()); } /** * Saves a given submission * * @param s The submission to save * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ public void save(PublicContribution s) throws NetworkException, ApiException { setSaved(s, true); } /** * Unsaves a given submission * * @param s The submission to unsave * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ public void unsave(PublicContribution s) throws NetworkException, ApiException { setSaved(s, false); } /** * Saves or unsaves a submission. * * @param s The submission to save or unsave * @param save Whether or not to save the submission * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation({Endpoints.SAVE, Endpoints.UNSAVE}) private void setSaved(PublicContribution s, boolean save) throws NetworkException, ApiException { // Send it to "/api/save" if save == true, "/api/unsave" if save == false genericPost(reddit.request() .endpoint(save ? Endpoints.SAVE : Endpoints.UNSAVE) .post(JrawUtils.mapOf( "id", s.getFullName() )).build()); } /** * Sets whether or not replies to this submission should be sent to your inbox. You must own this Submission. * * @param s The submission to modify * @param send Whether or not to send replies to your inbox * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.SENDREPLIES) public void sendRepliesToInbox(Submission s, boolean send) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.SENDREPLIES) .post(JrawUtils.mapOf( "id", s.getFullName(), "state", send )).build()); } /** * Sets whether or not a submission is hidden * * @param s The submission to hide or unhide * @param hide If the submission is to be hidden * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation({Endpoints.HIDE, Endpoints.UNHIDE}) public void hide(boolean hide, Submission s, Submission... more) throws NetworkException, ApiException { String ids = s.getFullName(); if (more != null) { String[] idList = new String[more.length]; for (int i = 0; i < more.length; i++) { idList[i] = more[i].getFullName(); } ids = ids + "," + JrawUtils.join(idList); } genericPost(reddit.request() .endpoint(hide ? Endpoints.HIDE : Endpoints.UNHIDE) .post(JrawUtils.mapOf( "id", ids )).build()); } /** * Updates the body of a self-text Submission or Comment * * @param contribution The self-post or comment that to edit the text for * @param text The new body * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.EDITUSERTEXT) public <T extends PublicContribution> void updateContribution(T contribution, String text) throws NetworkException, ApiException { genericPost(reddit.request().endpoint(Endpoints.EDITUSERTEXT) .post(JrawUtils.mapOf( "api_type", "json", "text", text, "thing_id", contribution.getFullName() )).build()); } /** * Sends a reply to a Comment, Submission, or Message. * * @param contribution The contribution to reply to * @param text The body of the message, formatted in Markdown * @return The ID of the newly created reply * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ @EndpointImplementation(Endpoints.COMMENT) public <T extends Contribution> String reply(T contribution, String text) throws NetworkException, ApiException { RestResponse response = genericPost(reddit.request() .endpoint(Endpoints.COMMENT) .post(JrawUtils.mapOf( "api_type", "json", "text", text, "thing_id", contribution.getFullName() )).build()); return response.getJson().get("json").get("data").get("things").get(0).get("data").get("id").asText(); } /** * Subscribes to a subreddit * * @param subreddit The subreddit to subscribe to * @throws NetworkException If the request was not successful * @see #unsubscribe(Subreddit) */ @EndpointImplementation(Endpoints.SUBSCRIBE) public void subscribe(Subreddit subreddit) throws NetworkException { setSubscribed(subreddit, true); } /** * Unsubscribes from a subreddit * * @param subreddit The subreddit to unsubscribe to * @throws NetworkException If the request was not successful * @see #subscribe(Subreddit) */ public void unsubscribe(Subreddit subreddit) throws NetworkException { setSubscribed(subreddit, false); } /** * Subscribe or unsubscribe to a subreddit * * @param subreddit The subreddit to (un)subscribe to * @param sub Whether to subscribe (true) or unsubscribe (false) * @throws NetworkException If the request was not successful */ private void setSubscribed(Subreddit subreddit, boolean sub) throws NetworkException { reddit.execute(reddit.request() .endpoint(Endpoints.SUBSCRIBE) .post(JrawUtils.mapOf( "sr", subreddit.getFullName(), "action", sub ? "sub" : "unsub" // JSON is returned on subscribe, HTML is returned on unsubscribe )).build()); } /** * Gets a list of possible flair templates for this subreddit. See also: {@link #getFlairChoices(Submission)}, * {@link #getCurrentFlair(String)}, {@link #getCurrentFlair(Submission)} * * @param subreddit The subreddit to look up * @return A list of flair templates * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ @EndpointImplementation(Endpoints.FLAIRSELECTOR) public List<FlairTemplate> getFlairChoices(String subreddit) throws NetworkException, ApiException { ImmutableList.Builder<FlairTemplate> templates = ImmutableList.builder(); for (JsonNode choiceNode : getFlairChoicesRootNode(subreddit, null).get("choices")) { templates.add(new FlairTemplate(choiceNode)); } return templates.build(); } /** * Gets a list of possible flair templates for this submission * * @param link The submission to look up * @return A list of flair templates * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ public List<FlairTemplate> getFlairChoices(Submission link) throws NetworkException, ApiException { ImmutableList.Builder<FlairTemplate> templates = ImmutableList.builder(); for (JsonNode choiceNode : getFlairChoicesRootNode(link.getSubredditName(), link).get("choices")) { templates.add(new FlairTemplate(choiceNode)); } return templates.build(); } /** * Gets the current user flair for this subreddit * * @param subreddit The subreddit to look up * @return The flair template that is being used by the authenticated user * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ public FlairTemplate getCurrentFlair(String subreddit) throws NetworkException, ApiException { return new FlairTemplate(getFlairChoicesRootNode(subreddit, null).get("current")); } /** * Gets the current user flair for this subreddit * * @param link The submission to look up * @return The given submission's current flair * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ public FlairTemplate getCurrentFlair(Submission link) throws NetworkException, ApiException { return new FlairTemplate(getFlairChoicesRootNode(link.getSubredditName(), link).get("current")); } /** * Enables or disables user flair on a subreddit * * @param subreddit The subreddit to enable or disable flair on * @param enabled If user flair is enabled * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.SETFLAIRENABLED) public void setFlairEnabled(String subreddit, boolean enabled) throws NetworkException, ApiException { RestResponse response = reddit.execute(reddit.request() .path("/r/" + subreddit + Endpoints.SETFLAIRENABLED.getEndpoint().getUri()) .post(JrawUtils.mapOf( "api_type", "json", "enabled", enabled )) .build()); if (response.hasErrors()) { throw response.getError(); } } /** * Gives gold to a comment or submission */ @EndpointImplementation(Endpoints.OAUTH_GOLD_GILD_FULLNAME) public void giveGold(PublicContribution target) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.OAUTH_GOLD_GILD_FULLNAME, target.getFullName()) .post() .build()); } /** * Gives creddits to a user */ @EndpointImplementation(Endpoints.OAUTH_GOLD_GIVE_USERNAME) public void giveGold(String username, int months) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.OAUTH_GOLD_GIVE_USERNAME, username) .post(JrawUtils.mapOf("months", months)) .build()); } public AccountPreferences getPreferences(String... prefs) { return getPreferences(Arrays.asList(prefs)); } @EndpointImplementation(Endpoints.OAUTH_ME_PREFS_GET) public AccountPreferences getPreferences(List<String> prefs) { RestResponse response = reddit.execute(reddit.request() .endpoint(Endpoints.OAUTH_ME_PREFS_GET) .query(JrawUtils.mapOf("fields", JrawUtils.join(prefs))) .build()); return new AccountPreferences(response.getJson()); } /** * Updates the preferences for this account * * @param prefs The preferences * @return The preferences after they were updated * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_PREFS_PATCH) public AccountPreferences updatePreferences(AccountPreferencesEditor prefs) throws NetworkException { RestResponse response = reddit.execute(reddit.request() .endpoint(Endpoints.OAUTH_ME_PREFS_PATCH) .patch(RequestBody.create(MediaTypes.JSON.type(), JrawUtils.toJson(prefs.getArgs()))) .build()); return new AccountPreferences(response.getJson()); } /** * Gets a breakdown of link and comment karma by subreddit * * @return A KarmaBreakdown for this account * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_KARMA) public KarmaBreakdown getKarmaBreakdown() throws NetworkException { RestResponse response = reddit.execute(reddit.request() .endpoint(Endpoints.OAUTH_ME_KARMA) .build()); return new KarmaBreakdown(response.getJson().get("data")); } /** * Removes a friend * * @param friend The username of the friend * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_FRIENDS_USERNAME_DELETE) public void deleteFriend(String friend) throws NetworkException { reddit.execute(reddit.request() .delete() .endpoint(Endpoints.OAUTH_ME_FRIENDS_USERNAME_DELETE, friend) .build()); } /** * Gets a user record pertaining to a particular relationship * * @param name The name of the user * @return A UserRecord representing the relationship * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_FRIENDS_USERNAME_GET) public UserRecord getFriend(String name) throws NetworkException { RestResponse response = reddit.execute(reddit.request() .endpoint(Endpoints.OAUTH_ME_FRIENDS_USERNAME_GET, name) .build()); return new UserRecord(response.getJson()); } /** * Adds of updates a friend * * @param name The name of the user * @return A UserRecord representing the new or updated relationship * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_FRIENDS_USERNAME_PUT) public UserRecord updateFriend(String name) throws NetworkException { RestResponse response = reddit.execute(reddit.request() .put(RequestBody.create(MediaTypes.JSON.type(), JrawUtils.toJson(new FriendModel(name)))) .endpoint(Endpoints.OAUTH_ME_FRIENDS_USERNAME_PUT, name) .build()); return new UserRecord(response.getJson()); } private static final class FriendModel { private final String name; private FriendModel(String name) { this.name = name == null ? "" : name; } public String getName() { return name; } } private JsonNode getFlairChoicesRootNode(String subreddit, Submission link) throws NetworkException, ApiException { String linkFullname = link != null ? link.getFullName() : null; Map<String, String> formArgs = new HashMap<>(); if (linkFullname != null) { formArgs.put("link", linkFullname); } RestResponse response = genericPost(reddit.request() .path("/r/" + subreddit + Endpoints.FLAIRSELECTOR.getEndpoint().getUri()) .post(formArgs.isEmpty() ? null : formArgs) .build()); return response.getJson(); } /** * This class provides a way to configure posting parameters of a new submission */ public static class SubmissionBuilder { private final boolean selfPost; private final String selfText; private final URL url; private final String subreddit; private final String title; private boolean saveAfter; // = false; private boolean sendRepliesToInbox; // = false; private boolean resubmit = true; /** * Instantiates a new SubmissionBuilder that will result in a self post. * * @param selfText The body text of the submission, formatted in Markdown * @param subreddit The subreddit to submit the link to (e.g. "funny", "pics", etc.) * @param title The title of the submission */ public SubmissionBuilder(String selfText, String subreddit, String title) { this.selfPost = true; this.selfText = selfText; this.url = null; this.subreddit = subreddit; this.title = title; } /** * Instantiates a new SubmissionBuilder that will result in a link post. * * @param url The URL that this submission will link to * @param subreddit The subreddit to submit the link to (e.g. "funny", "pics", etc.) * @param title The title of the submission */ public SubmissionBuilder(URL url, String subreddit, String title) { this.selfPost = false; this.url = url; this.selfText = null; this.subreddit = subreddit; this.title = title; } /** * Whether to save after right after posting * * @param flag To save or not to save, that is the question * @return This builder */ public SubmissionBuilder saveAfter(boolean flag) { this.saveAfter = flag; return this; } /** * Whether to send top-level replies to your inbox * * @param flag Send replies to your inbox? * @return This builder */ public SubmissionBuilder sendRepliesToInbox(boolean flag) { this.sendRepliesToInbox = flag; return this; } /** * Set whether or not the Reddit API will return an error if the link's URL has already been posted * * @param flag If there should be an exception if there is already a post like this * @return This builder */ public SubmissionBuilder resubmit(boolean flag) { this.resubmit = flag; return this; } } }
package net.gtaun.shoebill.streamer; import net.gtaun.shoebill.Shoebill; import net.gtaun.shoebill.amx.AmxCallable; import net.gtaun.shoebill.amx.AmxInstance; import net.gtaun.shoebill.amx.types.ReferenceFloat; import net.gtaun.shoebill.amx.types.ReferenceInt; import net.gtaun.shoebill.amx.types.ReferenceString; import net.gtaun.shoebill.constant.ObjectMaterialSize; import net.gtaun.shoebill.data.Color; import net.gtaun.shoebill.data.Location; import net.gtaun.shoebill.data.Vector3D; import net.gtaun.shoebill.event.amx.AmxLoadEvent; import net.gtaun.shoebill.object.Player; import net.gtaun.shoebill.streamer.data.*; import net.gtaun.util.event.EventManager; import net.gtaun.util.event.EventManagerNode; public class Functions { private static EventManagerNode eventManagerNode; //Objects: private static AmxCallable createDynamicObject; private static AmxCallable destroyDynamicObject; private static AmxCallable isValidDynamicObject; private static AmxCallable setDynamicObjectPos; private static AmxCallable getDynamicObjectPos; private static AmxCallable setDynamicObjectRot; private static AmxCallable getDynamicObjectRot; private static AmxCallable moveDynamicObject; private static AmxCallable stopDynamicObject; private static AmxCallable isDynamicObjectMoving; private static AmxCallable attachCameraToDynamicObject; private static AmxCallable attachDynamicObjectToObject; private static AmxCallable attachDynamicObjectToPlayer; private static AmxCallable attachDynamicObjectToVehicle; private static AmxCallable editDynamicObject; private static AmxCallable isDynamicObjectMaterialUsed; private static AmxCallable getDynamicObjectMaterial; private static AmxCallable setDynamicObjectMaterial; private static AmxCallable isDynamicObjectMaterialTextUsed; private static AmxCallable getDynamicObjectMaterialText; private static AmxCallable setDynamicObjectMaterialText; //Pickups: private static AmxCallable createDynamicPickup; private static AmxCallable destroyDynamicPickup; private static AmxCallable isValidDynamicPickup; //3DTextLabels: private static AmxCallable createDynamic3DTextLabel; private static AmxCallable destroyDynamic3DTextLabel; private static AmxCallable isValidDynamic3DTextLabel; private static AmxCallable getDynamic3DTextLabelText; private static AmxCallable updateDynamic3DTextLabelText; //Streamer: private static AmxCallable update; private static AmxCallable updateEx; public static void registerHandlers(EventManager eventManager) { eventManagerNode = eventManager.createChildNode(); AmxInstance amxInstance = AmxInstance.getDefault(); findObjectFunctions(amxInstance); findPickupFunctions(amxInstance); find3DTextLabelFunctions(amxInstance); findStreamerFunctions(amxInstance); } public static void unregisterHandlers() { eventManagerNode.cancelAll(); eventManagerNode.destroy(); eventManagerNode = null; } private static void findObjectFunctions(AmxInstance instance) { AmxCallable tickFunc = instance.getNative("Streamer_GetTickRate"); if(tickFunc != null && createDynamicObject == null) { createDynamicObject = instance.getNative("CreateDynamicObject"); destroyDynamicObject = instance.getNative("DestroyDynamicObject"); isValidDynamicObject = instance.getNative("IsValidDynamicObject"); setDynamicObjectPos = instance.getNative("SetDynamicObjectPos"); getDynamicObjectPos = instance.getNative("GetDynamicObjectPos"); setDynamicObjectRot = instance.getNative("SetDynamicObjectRot"); getDynamicObjectRot = instance.getNative("GetDynamicObjectRot"); moveDynamicObject = instance.getNative("MoveDynamicObject"); stopDynamicObject = instance.getNative("StopDynamicObject"); isDynamicObjectMoving = instance.getNative("IsDynamicObjectMoving"); attachCameraToDynamicObject = instance.getNative("AttachCameraToDynamicObject"); attachDynamicObjectToObject = instance.getNative("AttachDynamicObjectToObject"); attachDynamicObjectToPlayer = instance.getNative("AttachDynamicObjectToPlayer"); attachDynamicObjectToVehicle = instance.getNative("AttachDynamicObjectToVehicle"); editDynamicObject = instance.getNative("EditDynamicObject"); isDynamicObjectMaterialUsed = instance.getNative("IsDynamicObjectMaterialUsed"); getDynamicObjectMaterial = instance.getNative("GetDynamicObjectMaterial"); setDynamicObjectMaterial = instance.getNative("SetDynamicObjectMaterial"); isDynamicObjectMaterialTextUsed = instance.getNative("IsDynamicObjectMaterialTextUsed"); getDynamicObjectMaterialText = instance.getNative("GetDynamicObjectMaterialText"); setDynamicObjectMaterialText = instance.getNative("SetDynamicObjectMaterialText"); } } private static void findPickupFunctions(AmxInstance instance) { if (createDynamicPickup == null) { createDynamicPickup = instance.getNative("CreateDynamicPickup"); destroyDynamicPickup = instance.getNative("DestroyDynamicPickup"); isValidDynamicPickup = instance.getNative("IsValidDynamicPickup"); } } private static void find3DTextLabelFunctions(AmxInstance instance) { if (createDynamic3DTextLabel == null) { createDynamic3DTextLabel = instance.getNative("CreateDynamic3DTextLabel"); destroyDynamic3DTextLabel = instance.getNative("DestroyDynamic3DTextLabel"); isValidDynamic3DTextLabel = instance.getNative("IsValidDynamic3DTextLabel"); getDynamic3DTextLabelText = instance.getNative("GetDynamic3DTextLabelText"); updateDynamic3DTextLabelText = instance.getNative("UpdateDynamic3DTextLabelText"); } } private static void findStreamerFunctions(AmxInstance instance) { update = instance.getNative("Streamer_Update"); updateEx = instance.getNative("Streamer_UpdateEx"); } public static DynamicObject createDynamicObject(int modelid, Location location, Vector3D rotation) { return createDynamicObject(modelid, location, rotation, 200f, 0f); } public static DynamicObject createDynamicObject(int modelid, Location location, Vector3D rotation, float streamDistance, float drawDistance) { return createDynamicObject(modelid, location, rotation, -1, streamDistance, drawDistance); } public static DynamicObject createDynamicObject(int modelid, Location location, Vector3D rotation, int playerid, float streamDistance, float drawDistance) { return createDynamicObject(modelid, location.x, location.y, location.z, rotation.x, rotation.y, rotation.z, location.worldId, location.interiorId, playerid, streamDistance, drawDistance); } public static DynamicObject createDynamicObject(int modelid, float x, float y, float z, float rX, float rY, float rZ, int worldId, int interiorId, int playerId, float streamDistance, float drawDistance) { createDynamicObject = Shoebill.get().getAmxInstanceManager().getAmxInstances().iterator().next().getNative("CreateDynamicObject"); int id = (int)createDynamicObject.call(modelid, x, y, z, rX, rY, rZ, worldId, interiorId, playerId, streamDistance, drawDistance); return new DynamicObject(id, modelid, playerId, streamDistance, drawDistance); } public static void destroyDynamicObject(DynamicObject object) { destroyDynamicObject(object.getId()); } public static void destroyDynamicObject(int id) { destroyDynamicObject.call(id); } public static boolean isValidDynamicObject(DynamicObject object) { return isValidDynamicObject(object.getId()); } public static boolean isValidDynamicObject(int id) { return (int) isValidDynamicObject.call(id) > 0; } public static void setDynamicObjectPos(DynamicObject object, Vector3D pos) { setDynamicObjectPos(object.getId(), pos); } public static void setDynamicObjectPos(int id, Vector3D pos) { setDynamicObjectPos(id, pos.x, pos.y, pos.z); } public static void setDynamicObjectPos(int id, float x, float y, float z) { setDynamicObjectPos.call(id, x, y, z); } public static Vector3D getDynamicObjectPos(DynamicObject object) { return getDynamicObjectPos(object.getId()); } public static Vector3D getDynamicObjectPos(int id) { ReferenceFloat refX = new ReferenceFloat(0.0f); ReferenceFloat refY = new ReferenceFloat(0.0f); ReferenceFloat refZ = new ReferenceFloat(0.0f); getDynamicObjectPos.call(id, refX, refY, refZ); return new Vector3D(refX.getValue(), refY.getValue(), refZ.getValue()); } public static void setDynamicObjectRot(DynamicObject object, Vector3D rot) { setDynamicObjectRot(object.getId(), rot); } public static void setDynamicObjectRot(int id, Vector3D rot) { setDynamicObjectRot(id, rot.x, rot.y, rot.z); } public static void setDynamicObjectRot(int id, float x, float y, float z) { setDynamicObjectRot.call(id, x, y, z); } public static Vector3D getDynamicObjectRot(DynamicObject object) { return getDynamicObjectRot(object.getId()); } public static Vector3D getDynamicObjectRot(int id) { ReferenceFloat refX = new ReferenceFloat(0.0f); ReferenceFloat refY = new ReferenceFloat(0.0f); ReferenceFloat refZ = new ReferenceFloat(0.0f); getDynamicObjectRot.call(id, refX, refY, refZ); return new Vector3D(refX.getValue(), refY.getValue(), refZ.getValue()); } public static void moveDynamicObject(int id, Vector3D newPos, float speed, Vector3D newRot) { moveDynamicObject.call(id, newPos.x, newPos.y, newPos.z, speed, newRot.x, newRot.y, newRot.z); } public static void stopDynamicObject(int id) { stopDynamicObject.call(id); } public static boolean isDynamicObjectMoving(int id) { return (int)isDynamicObjectMoving.call(id) > 0; } public static void attachCameraToDynamicObject(int playerid, int objectId) { attachCameraToDynamicObject.call(playerid, objectId); } public static void attachDynamicObjectToObject(int object, int toObject, float offsetX, float offsetY, float offsetZ, float rotX, float rotY, float rotZ, boolean syncRotation) { attachDynamicObjectToObject.call(object, toObject, offsetX, offsetY, offsetZ, rotX, rotY, rotZ, syncRotation ? 1 : 0); } public static void attachDynamicObjectToPlayer(int object, int playerid, float offsetX, float offsetY, float offsetZ, float rotX, float rotY, float rotZ) { attachDynamicObjectToPlayer.call(object, playerid, offsetX, offsetY, offsetZ, rotX, rotY, rotZ); } public static void attachDynamicObjectToVehicle(int object, int vehicle, float offsetX, float offsetY, float offsetZ, float rotX, float rotY, float rotZ) { attachDynamicObjectToVehicle.call(object, vehicle, offsetX, offsetY, offsetZ, rotX, rotY, rotZ); } public static void editDynamicObject(int playerid, int objectId) { editDynamicObject.call(playerid, objectId); } public static boolean isDynamicObjectMaterialUsed(int objectid, int materialindex) { return (int) isDynamicObjectMaterialUsed.call(objectid, materialindex) > 0; } public static DynamicObjectMaterial getDynamicObjectMaterial(int objectid, int materialindex) { ReferenceInt refModel = new ReferenceInt(0); ReferenceInt refMaterialColor = new ReferenceInt(0); ReferenceString refTxdName = new ReferenceString("", 128); ReferenceString refTextureName = new ReferenceString("", 128); getDynamicObjectMaterial.call(objectid, materialindex, refModel, refTxdName, refTextureName, refMaterialColor, refTxdName.getLength(), refTextureName.getLength()); return new DynamicObjectMaterial(refModel.getValue(), refMaterialColor.getValue(), refTxdName.getValue(), refTextureName.getValue()); } public static void setDynamicObjectMaterial(int objectid, int materialindex, int modelid, String txdname, String texturename, int materialcolor) { setDynamicObjectMaterial.call(objectid, materialindex, modelid, txdname, texturename, materialcolor); } public static boolean isDynamicobjectMaterialTextUsed(int objectid, int materialindex) { return (int) isDynamicObjectMaterialTextUsed.call(objectid, materialindex) > 0; } public static DynamicObjectMaterialText getDynamicObjectMaterialText(int objectid, int materialindex) { ReferenceString refText = new ReferenceString("", 256); ReferenceInt refMaterialSize = new ReferenceInt(0); ReferenceString refFontFace = new ReferenceString("", 64); ReferenceInt refFontSize = new ReferenceInt(0); ReferenceInt refBold = new ReferenceInt(0); ReferenceInt refFontColor = new ReferenceInt(0); ReferenceInt refBackColor = new ReferenceInt(0); ReferenceInt refTextAlignment = new ReferenceInt(0); getDynamicObjectMaterialText.call(objectid, materialindex, refText, refMaterialSize, refFontFace, refFontSize, refBold, refFontColor, refBackColor, refTextAlignment, refText.getLength(), refFontFace.getLength()); return new DynamicObjectMaterialText(refText.getValue(), refFontFace.getValue(), refMaterialSize.getValue(), refFontSize.getValue(), refBold.getValue() > 0, refFontColor.getValue(), refBackColor.getValue(), refTextAlignment.getValue()); } public static void setDynamicObjectMaterialText(int objectid, int materialindex, String text, ObjectMaterialSize materialsize, String fontFace, int fontSize, boolean bold, int fontColor, int backColor, int textAlignment) { setDynamicObjectMaterialText.call(objectid, materialindex, text, materialsize.getValue(), fontFace, fontSize, bold ? 1 : 0, fontColor, backColor, textAlignment); } //Pickups: public static DynamicPickup createDynamicPickup(int modelid, int type, Location location, int playerid, float streamDistance) { return createDynamicPickup(modelid, type, location.x, location.y, location.z, location.worldId, location.interiorId, playerid, streamDistance); } public static DynamicPickup createDynamicPickup(int modelid, int type, float x, float y, float z, int worldid, int interiorid, int playerid, float streamDistance) { int id = (int) createDynamicPickup.call(modelid, type, x,y,z, worldid, interiorid, playerid, streamDistance); return new DynamicPickup(id, modelid, type, playerid, streamDistance); } public static void destroyDynamicPickup(int id) { destroyDynamicPickup.call(id); } public static boolean isValidDynamicPickup(int id) { return (int)isValidDynamicPickup.call(id) > 0; } //3DTextLabels: public static Dynamic3DTextLabel createDynamic3DTextLabel(String text, Color color, Location location) { return createDynamic3DTextLabel(text, color, location, 200f, 0, 200f); } public static Dynamic3DTextLabel createDynamic3DTextLabel(String text, Color color, Location location, float drawDistance, int testLOS, float streamDistance) { return createDynamic3DTextLabel(text, color, location, drawDistance, testLOS, -1, streamDistance); } public static Dynamic3DTextLabel createDynamic3DTextLabel(String text, Color color, Location location, float drawDistance, int testLOS, int playerid, float streamDistance) { return createDynamic3DTextLabel(text, color, location, drawDistance, 0xFFFF, 0xFFFF, testLOS, playerid, streamDistance); } public static Dynamic3DTextLabel createDynamic3DTextLabel(String text, Color color, Location location, float drawDistance, int attachedPlayer, int attachedVehicle, int testLOS, int playerid, float streamDistance) { return createDynamic3DTextLabel(text, color, location.x, location.y, location.z, drawDistance, attachedPlayer, attachedVehicle, testLOS, location.worldId, location.interiorId, playerid, streamDistance); } public static Dynamic3DTextLabel createDynamic3DTextLabel(String text, Color color, float x, float y, float z, float drawDistance, int attachedPlayer, int attachedVehicle, int testLOS, int worldid, int interiorid, int playerid, float streamDistance) { int id = (int) createDynamic3DTextLabel.call(text, color.getValue(), x,y,z, drawDistance, attachedPlayer, attachedVehicle, testLOS, worldid, interiorid, playerid, streamDistance); return new Dynamic3DTextLabel(id, playerid, streamDistance, drawDistance); } public static void destroyDynamic3DTextLabel(int id) { destroyDynamic3DTextLabel.call(id); } public static boolean isValidDynamic3DTextLabel(int id) { return (int)isValidDynamic3DTextLabel.call(id) > 0; } public static String getDynamic3DTextLabelText(int id) { String text = ""; getDynamic3DTextLabelText.call(id, text, 1024); // Hope no-one will have length of a label text greater then 1024 :) return text; } public static void updateDynamic3DTextLabelText(int id, Color color, String text) { updateDynamic3DTextLabelText.call(id, color.getValue(), text); } public static void update(Player player) { update(player, StreamerType.ALL); } public static void update(Player player, StreamerType streamerType) { update.call(player.getId(), streamerType.getValue()); } public static void updateEx(Player player, float x, float y, float z, int worldid, int interiorid) { updateEx(player, x, y, z, worldid, interiorid, StreamerType.ALL); } public static void updateEx(Player player, float x, float y, float z, int worldid, int interiorid, StreamerType streamerType) { updateEx.call(player.getId(), x, y, z, worldid, interiorid, streamerType.getValue()); } }
package net.imagej.ops.create; import net.imagej.ImgPlus; import net.imagej.ImgPlusMetadata; import net.imagej.ops.AbstractNamespace; import net.imagej.ops.Namespace; import net.imagej.ops.OpMethod; import net.imagej.ops.Ops; import net.imglib2.Dimensions; import net.imglib2.FinalDimensions; import net.imglib2.Interval; import net.imglib2.IterableInterval; import net.imglib2.RandomAccessibleInterval; import net.imglib2.img.Img; import net.imglib2.img.ImgFactory; import net.imglib2.roi.labeling.ImgLabeling; import net.imglib2.roi.labeling.LabelingMapping; import net.imglib2.type.NativeType; import net.imglib2.type.Type; import net.imglib2.type.numeric.ComplexType; import net.imglib2.type.numeric.IntegerType; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.real.DoubleType; import org.scijava.plugin.Plugin; /** * The create namespace contains ops that create objects. * * @author Curtis Rueden */ @Plugin(type = Namespace.class) public class CreateNamespace extends AbstractNamespace { @Override public String getName() { return "create"; } // -- img -- /** * Creates an {@link Img} of type {@link DoubleType} with the given * dimensions. */ public Img<DoubleType> img(final Integer[] dims) { int[] ints = new int[dims.length]; for (int i=0; i<ints.length; i++) ints[i] = dims[i]; return img(ints); } /** * Creates an {@link Img} of type {@link DoubleType} with the given * dimensions. */ public Img<DoubleType> img(final Long[] dims) { long[] longs = new long[dims.length]; for (int i=0; i<longs.length; i++) longs[i] = dims[i]; return img(longs); } /** * Creates an {@link Img} of type {@link DoubleType} with the given * dimensions. */ public Img<DoubleType> img(final int[] dims) { return img(new FinalDimensions(dims), new DoubleType()); } /** * Creates an {@link Img} of type {@link DoubleType} with the given * dimensions. */ public Img<DoubleType> img(final long[] dims) { return img(new FinalDimensions(dims), new DoubleType()); } @OpMethod(op = net.imagej.ops.create.img.CreateImgFromDimsAndType.class) public <T extends NativeType<T>> Img<T> img(final Dimensions in1, final T in2) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( net.imagej.ops.Ops.Create.Img.class, in1, in2); return result; } @OpMethod(op = net.imagej.ops.create.img.CreateImgFromDimsAndType.class) public <T extends NativeType<T>> Img<T> img(final Dimensions in1, final T in2, final ImgFactory<T> factory) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( net.imagej.ops.Ops.Create.Img.class, in1, in2, factory); return result; } @OpMethod(op = net.imagej.ops.create.img.CreateImgFromII.class) public <T extends NativeType<T>> Img<T> img(final IterableInterval<T> in) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( net.imagej.ops.Ops.Create.Img.class, in); return result; } // NB: Should be "T extends Type<T>" but then the Java compiler considers // it ambiguous with img(IterableInterval) and img(RandomAccessibleInterval). @OpMethod(op = net.imagej.ops.create.img.CreateImgFromImg.class) public <T extends NativeType<T>> Img<T> img(final Img<T> in) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( net.imagej.ops.Ops.Create.Img.class, in); return result; } @OpMethod(op = net.imagej.ops.create.img.CreateImgFromInterval.class) public Img<DoubleType> img(final Interval interval) { @SuppressWarnings("unchecked") final Img<DoubleType> result = (Img<DoubleType>) ops().run( net.imagej.ops.Ops.Create.Img.class, interval); return result; } @OpMethod(op = net.imagej.ops.create.img.CreateImgFromRAI.class) public <T extends NativeType<T>> Img<T> img( final RandomAccessibleInterval<T> in) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( net.imagej.ops.Ops.Create.Img.class, in); return result; } // -- imgFactory -- @OpMethod(op = net.imagej.ops.Ops.Create.ImgFactory.class) public Object imgFactory(final Object... args) { return ops().run(net.imagej.ops.Ops.Create.ImgFactory.class, args); } @OpMethod(op = net.imagej.ops.create.imgFactory.DefaultCreateImgFactory.class) public <T extends NativeType<T>> ImgFactory<T> imgFactory() { // NB: The generic typing of ImgFactory is broken; see: @SuppressWarnings("unchecked") final ImgFactory<T> result = (ImgFactory<T>) ops().run( net.imagej.ops.Ops.Create.ImgFactory.class); return result; } @OpMethod( ops = net.imagej.ops.create.imgFactory.DefaultCreateImgFactory.class) public <T extends NativeType<T>> ImgFactory<T> imgFactory( final Dimensions dims) { // NB: The generic typing of ImgFactory is broken; see: @SuppressWarnings("unchecked") final ImgFactory<T> result = (ImgFactory<T>) ops().run( net.imagej.ops.Ops.Create.ImgFactory.class, dims); return result; } @OpMethod( ops = net.imagej.ops.create.imgFactory.CreateImgFactoryFromImg.class) public <T extends NativeType<T>> ImgFactory<T> imgFactory(final Img<T> in) { @SuppressWarnings("unchecked") final ImgFactory<T> result = (ImgFactory<T>) ops().run( net.imagej.ops.Ops.Create.ImgFactory.class, in); return result; } // -- imgLabeling -- @OpMethod(op = net.imagej.ops.Ops.Create.ImgLabeling.class) public Object imgLabeling(final Object... args) { return ops().run(net.imagej.ops.Ops.Create.ImgLabeling.class, args); } @OpMethod( op = net.imagej.ops.create.imgLabeling.DefaultCreateImgLabeling.class) public <L, T extends IntegerType<T>> ImgLabeling<L, T> imgLabeling( final Dimensions dims) { @SuppressWarnings("unchecked") final ImgLabeling<L, T> result = (ImgLabeling<L, T>) ops().run( Ops.Create.ImgLabeling.class, dims); return result; } @OpMethod( op = net.imagej.ops.create.imgLabeling.DefaultCreateImgLabeling.class) public <L, T extends IntegerType<T>> ImgLabeling<L, T> imgLabeling( final Dimensions dims, final T outType) { @SuppressWarnings("unchecked") final ImgLabeling<L, T> result = (ImgLabeling<L, T>) ops().run( Ops.Create.ImgLabeling.class, dims, outType); return result; } @OpMethod( op = net.imagej.ops.create.imgLabeling.DefaultCreateImgLabeling.class) public <L, T extends IntegerType<T>> ImgLabeling<L, T> imgLabeling( final Dimensions dims, final T outType, final ImgFactory<T> fac) { @SuppressWarnings("unchecked") final ImgLabeling<L, T> result = (ImgLabeling<L, T>) ops().run( Ops.Create.ImgLabeling.class, dims, outType, fac); return result; } @OpMethod( op = net.imagej.ops.create.imgLabeling.DefaultCreateImgLabeling.class) public <L, T extends IntegerType<T>> ImgLabeling<L, T> imgLabeling( final Dimensions dims, final T outType, final ImgFactory<T> fac, final int maxNumLabelSets) { @SuppressWarnings("unchecked") final ImgLabeling<L, T> result = (ImgLabeling<L, T>) ops().run( Ops.Create.ImgLabeling.class, dims, outType, fac, maxNumLabelSets); return result; } @OpMethod( op = net.imagej.ops.create.imgLabeling.CreateImgLabelingFromInterval.class) public <L, T extends IntegerType<T>> ImgLabeling<L, T> imgLabeling( final Interval interval) { @SuppressWarnings("unchecked") final ImgLabeling<L, T> result = (ImgLabeling<L, T>) ops().run( Ops.Create.ImgLabeling.class, interval); return result; } @OpMethod( op = net.imagej.ops.create.imgLabeling.CreateImgLabelingFromInterval.class) public <L, T extends IntegerType<T>> ImgLabeling<L, T> imgLabeling( final Interval interval, final T outType) { @SuppressWarnings("unchecked") final ImgLabeling<L, T> result = (ImgLabeling<L, T>) ops().run( Ops.Create.ImgLabeling.class, interval, outType); return result; } @OpMethod( op = net.imagej.ops.create.imgLabeling.CreateImgLabelingFromInterval.class) public <L, T extends IntegerType<T>> ImgLabeling<L, T> imgLabeling( final Interval interval, final T outType, final ImgFactory<T> fac) { @SuppressWarnings("unchecked") final ImgLabeling<L, T> result = (ImgLabeling<L, T>) ops().run( Ops.Create.ImgLabeling.class, interval, outType, fac); return result; } @OpMethod( op = net.imagej.ops.create.imgLabeling.CreateImgLabelingFromInterval.class) public <L, T extends IntegerType<T>> ImgLabeling<L, T> imgLabeling( final Interval interval, final T outType, final ImgFactory<T> fac, final int maxNumLabelSets) { @SuppressWarnings("unchecked") final ImgLabeling<L, T> result = (ImgLabeling<L, T>) ops().run( Ops.Create.ImgLabeling.class, interval, outType, fac, maxNumLabelSets); return result; } // -- imgPlus -- @OpMethod(op = net.imagej.ops.Ops.Create.ImgPlus.class) public Object imgPlus(final Object... args) { return ops().run(net.imagej.ops.Ops.Create.ImgPlus.class, args); } @OpMethod(op = net.imagej.ops.create.imgPlus.DefaultCreateImgPlus.class) public <T> ImgPlus<T> imgPlus(final Img<T> img) { @SuppressWarnings("unchecked") final ImgPlus<T> result = (ImgPlus<T>) ops().run( Ops.Create.ImgPlus.class, img); return result; } @OpMethod(op = net.imagej.ops.create.imgPlus.DefaultCreateImgPlus.class) public <T> ImgPlus<T> imgPlus(final Img<T> img, final ImgPlusMetadata metadata) { @SuppressWarnings("unchecked") final ImgPlus<T> result = (ImgPlus<T>) ops() .run(Ops.Create.ImgPlus.class, img, metadata); return result; } // -- integerType -- @OpMethod(op = net.imagej.ops.Ops.Create.IntegerType.class) public Object integerType(final Object... args) { return ops().run(net.imagej.ops.Ops.Create.IntegerType.class, args); } @OpMethod( op = net.imagej.ops.create.integerType.DefaultCreateIntegerType.class) public IntegerType integerType() { final IntegerType result = (IntegerType) ops().run( Ops.Create.IntegerType.class); return result; } @OpMethod( op = net.imagej.ops.create.integerType.DefaultCreateIntegerType.class) public IntegerType integerType(final long maxValue) { final IntegerType result = (IntegerType) ops().run( Ops.Create.IntegerType.class, maxValue); return result; } // -- integralImg -- @SuppressWarnings({ "unchecked", "rawtypes" }) @OpMethod(ops = { net.imagej.ops.create.integralImg.DefaultCreateIntegralImg.class, net.imagej.ops.create.integralImg.WrappedCreateIntegralImg.class }) public <T extends RealType<T>> RandomAccessibleInterval<DoubleType> integralImg(final RandomAccessibleInterval<T> in) { final RandomAccessibleInterval<DoubleType> result = (RandomAccessibleInterval) ops().run(Ops.Create.IntegralImg.class, in); return result; } @SuppressWarnings({ "unchecked", "rawtypes" }) @OpMethod(ops = { net.imagej.ops.create.integralImg.DefaultCreateIntegralImg.class, net.imagej.ops.create.integralImg.WrappedCreateIntegralImg.class }) public <T extends RealType<T>> RandomAccessibleInterval<DoubleType> integralImg(final RandomAccessibleInterval<T> in, final int order) { final RandomAccessibleInterval<DoubleType> result = (RandomAccessibleInterval) ops().run(Ops.Create.IntegralImg.class, in, order); return result; } // -- kernel -- /** Executes the "kernel" operation on the given arguments. */ @OpMethod(op = Ops.Create.Kernel.class) public Object kernel(final Object... args) { return ops().run(Ops.Create.Kernel.NAME, args); } /** Executes the "kernel" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernel.CreateKernel.class) public <T extends ComplexType<T>> Img<T> kernel(final double[]... values) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run(net.imagej.ops.Ops.Create.Kernel.class, new Object[] { values }); return result; } /** Executes the "kernel" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernel.CreateKernel.class) public <T extends ComplexType<T>> Img<T> kernel(final T outType, final double[]... values) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run(net.imagej.ops.Ops.Create.Kernel.class, outType, values); return result; } /** Executes the "kernel" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernel.CreateKernel.class) public <T extends ComplexType<T>> Img<T> kernel(final T outType, final ImgFactory<T> fac, final double[]... values) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run(net.imagej.ops.Ops.Create.Kernel.class, outType, fac, values); return result; } // -- kernelGauss -- /** Executes the "kernelGauss" operation on the given arguments. */ @OpMethod(op = Ops.Create.KernelGauss.class) public Object kernelGauss(final Object... args) { return ops().run(Ops.Create.KernelGauss.NAME, args); } /** Executes the "kernelGauss" operation on the given arguments. */ @OpMethod( op = net.imagej.ops.create.kernelGauss.CreateKernelGaussSymmetric.class) public <T extends ComplexType<T>> Img<T> kernelGauss(final int numDimensions, final double sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelGauss.class, numDimensions, sigma); return result; } /** Executes the "kernelGauss" operation on the given arguments. */ @OpMethod( op = net.imagej.ops.create.kernelGauss.CreateKernelGaussSymmetric.class) public <T extends ComplexType<T>> Img<T> kernelGauss(final T outType, final int numDimensions, final double sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelGauss.class, outType, numDimensions, sigma); return result; } /** Executes the "kernelGauss" operation on the given arguments. */ @OpMethod( op = net.imagej.ops.create.kernelGauss.CreateKernelGaussSymmetric.class) public <T extends ComplexType<T>> Img<T> kernelGauss(final T outType, final ImgFactory<T> fac, final int numDimensions, final double sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelGauss.class, outType, fac, numDimensions, sigma); return result; } /** Executes the "kernelGauss" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelGauss.CreateKernelGauss.class) public <T extends ComplexType<T> & NativeType<T>> Img<T> kernelGauss( final double... sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelGauss.class, sigma); return result; } /** Executes the "kernelGauss" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelGauss.CreateKernelGauss.class) public <T extends ComplexType<T> & NativeType<T>> Img<T> kernelGauss( final T outType, final double... sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelGauss.class, outType, sigma); return result; } /** Executes the "kernelGauss" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelGauss.CreateKernelGauss.class) public <T extends ComplexType<T> & NativeType<T>> Img<T> kernelGauss( final T outType, final ImgFactory<T> fac, final double... sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelGauss.class, outType, fac, sigma); return result; } // -- kernelLog -- /** Executes the "kernelLog" operation on the given arguments. */ @OpMethod(op = Ops.Create.KernelLog.class) public Object kernelLog(final Object... args) { return ops().run(Ops.Create.KernelLog.NAME, args); } /** Executes the "kernelLog" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelLog.CreateKernelLogSymmetric.class) public <T extends ComplexType<T>> Img<T> kernelLog(final int numDimensions, final double sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelLog.class, numDimensions, sigma); return result; } /** Executes the "kernelLog" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelLog.CreateKernelLogSymmetric.class) public <T extends ComplexType<T>> Img<T> kernelLog(final T outType, final int numDimensions, final double sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelLog.class, outType, numDimensions, sigma); return result; } /** Executes the "kernelLog" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelLog.CreateKernelLogSymmetric.class) public <T extends ComplexType<T>> Img<T> kernelLog(final T outType, final ImgFactory<T> fac, final int numDimensions, final double sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run( Ops.Create.KernelLog.class, outType, fac, numDimensions, sigma); return result; } /** Executes the "kernelLog" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelLog.CreateKernelLog.class) public <T extends ComplexType<T> & NativeType<T>> Img<T> kernelLog( final double... sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run(Ops.Create.KernelLog.class, sigma); return result; } /** Executes the "kernelLog" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelLog.CreateKernelLog.class) public <T extends ComplexType<T> & NativeType<T>> Img<T> kernelLog( final T outType, final double... sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run(Ops.Create.KernelLog.class, outType, sigma); return result; } /** Executes the "kernelLog" operation on the given arguments. */ @OpMethod(op = net.imagej.ops.create.kernelLog.CreateKernelLog.class) public <T extends ComplexType<T> & NativeType<T>> Img<T> kernelLog( final T outType, final ImgFactory<T> fac, final double... sigma) { @SuppressWarnings("unchecked") final Img<T> result = (Img<T>) ops().run(Ops.Create.KernelLog.class, outType, fac, sigma); return result; } // -- labelingMapping -- @OpMethod(op = net.imagej.ops.Ops.Create.LabelingMapping.class) public Object labelingMapping(final Object... args) { return ops().run(net.imagej.ops.Ops.Create.LabelingMapping.class, args); } @OpMethod( op = net.imagej.ops.create.labelingMapping.DefaultCreateLabelingMapping.class) public <L> LabelingMapping<L> labelingMapping() { @SuppressWarnings("unchecked") final LabelingMapping<L> result = (LabelingMapping<L>) ops() .run( Ops.Create.LabelingMapping.class); return result; } @OpMethod( op = net.imagej.ops.create.labelingMapping.DefaultCreateLabelingMapping.class) public <L> LabelingMapping<L> labelingMapping(final int maxNumSets) { @SuppressWarnings("unchecked") final LabelingMapping<L> result = (LabelingMapping<L>) ops() .run( Ops.Create.LabelingMapping.class, maxNumSets); return result; } // -- nativeType -- @OpMethod(op = net.imagej.ops.create.nativeType.DefaultCreateNativeType.class) public DoubleType nativeType() { final DoubleType result = (DoubleType) ops().run( net.imagej.ops.Ops.Create.NativeType.class); return result; } @OpMethod( op = net.imagej.ops.create.nativeType.CreateNativeTypeFromClass.class) public <T extends NativeType<T>> T nativeType(final Class<T> type) { @SuppressWarnings("unchecked") final T result = (T) ops().run( net.imagej.ops.Ops.Create.NativeType.class, type); return result; } // -- object -- @OpMethod(op = net.imagej.ops.create.object.CreateObjectFromClass.class) public <T> T object(final Class<T> in) { @SuppressWarnings("unchecked") final T result = (T) ops().run( net.imagej.ops.Ops.Create.Object.class, in); return result; } }
package edu.umich.eac; import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import android.content.Context; import android.net.ConnectivityManager; import android.util.Log; import edu.umich.eac.WifiTracker.ConditionChange; import edu.umich.eac.WifiTracker.Prediction; import edu.umich.libpowertutor.EnergyEstimates; public class AdaptivePrefetchStrategy extends PrefetchStrategy { private static final String LOG_FILENAME = "/sdcard/intnw/adaptive_prefetch_decisions.log"; static final String TAG = AdaptivePrefetchStrategy.class.getName(); private PrintWriter logFileWriter; private void logPrint(String msg) { if (logFileWriter != null) { final long now = System.currentTimeMillis(); logFileWriter.println(String.format("%d %s", now, msg)); } } // TODO: determine this from Android APIs private static final String CELLULAR_IFNAME = "rmnet0"; private static int nextOrder = 0; static class PrefetchTask implements Comparable<PrefetchTask> { private Date scheduledTime; private FetchFuture<?> prefetch; private int order; /** * Schedule the prefetch for this many milliseconds in the future. */ PrefetchTask(FetchFuture<?> pf) { prefetch = pf; scheduledTime = new Date(); synchronized(PrefetchTask.class) { order = ++nextOrder; } } public int compareTo(PrefetchTask another) { if (prefetch.equals(another.prefetch)) { return 0; } return order - another.order; } } private PriorityBlockingQueue<PrefetchTask> deferredPrefetches = new PriorityBlockingQueue<PrefetchTask>(); private static final int NUM_CONCURRENT_PREFETCHES = 1; private BlockingQueue<FetchFuture<?> > prefetchesInProgress = new ArrayBlockingQueue<FetchFuture<?> >(NUM_CONCURRENT_PREFETCHES); private Date mStartTime; private Date mGoalTime; private int mEnergyBudget; private int mDataBudget; private static boolean fixedAdaptiveParamsEnabled = false; private static double fixedEnergyWeight; private static double fixedDataWeight; private int mEnergySpent; private ProcNetworkStats mDataSpent; // These map TYPE_WIFI or TYPE_MOBILE to the network stats. private Map<Integer, NetworkStats> currentNetworkStats; private AverageNetworkStats averageNetworkStats; private MonitorThread monitorThread; @Override public void setup(Context context, Date goalTime, int energyBudget, int dataBudget) { this.context = context; try { logFileWriter = new PrintWriter(new FileWriter(LOG_FILENAME, true), true); } catch (IOException e) { Log.e(TAG, "Failed to create log file: " + e.getMessage()); } mStartTime = new Date(); mGoalTime = goalTime; mEnergyBudget = energyBudget; mDataBudget = dataBudget; mEnergySpent = 0; mDataSpent = new ProcNetworkStats(CELLULAR_IFNAME); wifiTracker = new WifiTracker(context); currentNetworkStats = NetworkStats.getAllNetworkStats(context); averageNetworkStats = new AverageNetworkStats(); averageNetworkStats.initialize(NetworkStats.getAllNetworkStats(context)); monitorThread = new MonitorThread(); monitorThread.start(); } @Override public void updateGoalTime(Date newGoalTime) { mGoalTime = newGoalTime; } public static void setStaticParams(double energyWeight, double dataWeight) { fixedAdaptiveParamsEnabled = true; fixedEnergyWeight = energyWeight; fixedDataWeight = dataWeight; } private Date lastStatsUpdate = new Date(); private Context context; private synchronized void updateStats() { updateEnergyStats(); mDataSpent.updateStats(); if (System.currentTimeMillis() - lastStatsUpdate.getTime() > 1000) { updateNetworkStats(); } lastStatsUpdate = new Date(); } private synchronized void updateEnergyStats() { // TODO: implement. } private synchronized void updateNetworkStats() { currentNetworkStats = NetworkStats.getAllNetworkStats(context); for (Integer type : currentNetworkStats.keySet()) { NetworkStats newStats = currentNetworkStats.get(type); averageNetworkStats.add(type, newStats); } } class MonitorThread extends Thread { BlockingQueue<PrefetchTask> tasksToEvaluate = new LinkedBlockingQueue<PrefetchTask>(); @Override public void run() { final int SAMPLE_PERIOD_MS = 200; updateStats(); while (true) { try { reevaluateAllDeferredPrefetches(); updateStats(); Thread.sleep(SAMPLE_PERIOD_MS); } catch (InterruptedException e) { break; } } } private void reevaluateAllDeferredPrefetches() throws InterruptedException { if (prefetchesInProgress.remainingCapacity() == 0) { // too many prefetches in progress; defer logPrint(String.format("%d prefetches outstanding (first is 0x%08x); deferring", prefetchesInProgress.size(), prefetchesInProgress.peek().hashCode())); return; } deferredPrefetches.drainTo(tasksToEvaluate); logPrint(String.format("Reevaluating %d deferred prefetches", tasksToEvaluate.size())); while (!tasksToEvaluate.isEmpty()) { PrefetchTask task = tasksToEvaluate.remove(); logPrint(String.format("Evaluating prefetch 0x%08x", task.prefetch.hashCode())); if (shouldIssuePrefetch(task.prefetch)) { // restart evaluation at beginning, so as to avoid // the situation where network conditions change // in the middle of reevaluating the list. // I know I'm only issuing one prefetch at a time, // so don't bother checking the rest of the list. PrefetchTask firstTask = deferredPrefetches.poll(); if (firstTask != null && shouldIssuePrefetch(firstTask.prefetch)) { issuePrefetch(firstTask.prefetch); deferDecision(task); } else { issuePrefetch(task.prefetch); if (firstTask != null) { deferDecision(firstTask); } } break; } else { deferDecision(task); } } // add back any tasks that I didn't evaluate; they'll go to // their original place in the queue. tasksToEvaluate.drainTo(deferredPrefetches); } void removeTask(FetchFuture<?> prefetch) { PrefetchTask dummy = new PrefetchTask(prefetch); tasksToEvaluate.remove(dummy); deferredPrefetches.remove(dummy); } } @Override public void onDemandFetch(FetchFuture<?> prefetch) { prefetchesInProgress.remove(prefetch); monitorThread.removeTask(prefetch); } @Override public void onPrefetchDone(FetchFuture<?> prefetch, boolean cancelled) { if (cancelled) { monitorThread.removeTask(prefetch); } prefetchesInProgress.remove(prefetch); } @Override public void onPrefetchEnqueued(FetchFuture<?> prefetch) { // The prefetch will get evaluated the next time around the loop. // Queue instead of calling issuePrefetch so that // issuePrefetch never hangs on prefetchesInProgress.offer(); // otherwise there's a race with // prefetchesInProgress.remainingCapacity() deferDecision(new PrefetchTask(prefetch)); } private boolean shouldIssuePrefetch(FetchFuture<?> prefetch) { updateNetworkStats(); Double cost = calculateCost(prefetch); Double benefit = calculateBenefit(prefetch); final boolean shouldIssuePrefetch = cost < benefit; logPrint(String.format("Cost = %s; benefit = %s; %s prefetch 0x%08x", cost.toString(), benefit.toString(), shouldIssuePrefetch ? "issuing" : "deferring", prefetch.hashCode())); return shouldIssuePrefetch; } private double calculateCost(FetchFuture<?> prefetch) { double energyWeight = calculateEnergyWeight(); double dataWeight = calculateDataWeight(); double energyCostNow = currentEnergyCost(prefetch); double dataCostNow = currentDataCost(prefetch); double energyCostFuture = averageEnergyCost(prefetch); double dataCostFuture = averageDataCost(prefetch); double hintAccuracy = prefetch.getCache().stats.getPrefetchAccuracy(); double energyCostDelta = energyCostNow - (hintAccuracy * energyCostFuture); double dataCostDelta = dataCostNow - (hintAccuracy * dataCostFuture); return (energyWeight * energyCostDelta) + (dataWeight * dataCostDelta); } private static final String ADAPTATION_NOT_IMPL_MSG = "Fixed adaptive params not set and auto-adaptation not yet implemented"; private double calculateEnergyWeight() { if (fixedAdaptiveParamsEnabled) { return fixedEnergyWeight; } // TODO: tune adaptively based on resource usage history & projection. throw new Error(ADAPTATION_NOT_IMPL_MSG); } private double calculateDataWeight() { if (fixedAdaptiveParamsEnabled) { return fixedDataWeight; } // TODO: tune adaptively based on resource usage history & projection. throw new Error(ADAPTATION_NOT_IMPL_MSG); } private double currentEnergyCost(FetchFuture<?> prefetch) { int datalen = prefetch.bytesToTransfer(); NetworkStats wifiStats = currentNetworkStats.get(ConnectivityManager.TYPE_WIFI); NetworkStats mobileStats = currentNetworkStats.get(ConnectivityManager.TYPE_MOBILE); double energyCost = 0.0; if (wifiTracker.isWifiAvailable() && wifiStats != null) { // TODO: should try sending on wifi even if I don't have the stats yet. // But: in my experiments, I should have the stats. energyCost = EnergyEstimates.estimateWifiEnergyCost(datalen, wifiStats.bandwidthDown, wifiStats.rttMillis); } else { energyCost = EnergyEstimates.estimateMobileEnergyCost(datalen, mobileStats.bandwidthDown, mobileStats.rttMillis); } return energyCost / 1000.0; // mJ to J } private double averageEnergyCost(FetchFuture<?> prefetch) { int datalen = prefetch.bytesToTransfer(); NetworkStats wifiStats = averageNetworkStats.get(ConnectivityManager.TYPE_WIFI); NetworkStats mobileStats = averageNetworkStats.get(ConnectivityManager.TYPE_MOBILE); double wifiEnergyCost = EnergyEstimates.estimateWifiEnergyCost(datalen, wifiStats.bandwidthDown, wifiStats.rttMillis); double mobileEnergyCost = EnergyEstimates.estimateMobileEnergyCostFromIdle(datalen, mobileStats.bandwidthDown, mobileStats.rttMillis); double wifiAvailability = wifiTracker.availability(); return expectedValue(wifiEnergyCost, mobileEnergyCost, wifiAvailability) / 1000.0; } private double currentDataCost(FetchFuture<?> prefetch) { if (!wifiTracker.isWifiAvailable()) { return prefetch.bytesToTransfer(); } else { return 0; } } private double averageDataCost(FetchFuture<?> prefetch) { return expectedValue(0, prefetch.bytesToTransfer(), wifiTracker.availability()); } private double calculateBenefit(FetchFuture<?> prefetch) { // Application implements this computation. // averageNetworkStats contains an estimate of the average network conditions // that the fetch might encounter, so estimateFetchTime represents the // average benefit of prefetching (taking size into account). NetworkStats expectedNetworkStats = calculateExpectedNetworkStats(); double benefit = prefetch.estimateFetchTime(expectedNetworkStats.bandwidthDown, expectedNetworkStats.bandwidthUp, expectedNetworkStats.rttMillis); double accuracy = prefetch.getCache().stats.getPrefetchAccuracy(); //Log.d(TAG, String.format("Computed prefetch accuracy: %f", accuracy)); return (accuracy * benefit); } private NetworkStats calculateExpectedNetworkStats() { NetworkStats wifiStats = averageNetworkStats.get(ConnectivityManager.TYPE_WIFI); NetworkStats mobileStats = averageNetworkStats.get(ConnectivityManager.TYPE_MOBILE); if (wifiStats == null) { return mobileStats; } double wifiAvailability = wifiTracker.availability(); NetworkStats expectedStats = new NetworkStats(); expectedStats.bandwidthDown = (int) expectedValue(wifiStats.bandwidthDown, mobileStats.bandwidthDown, wifiAvailability); expectedStats.bandwidthUp = (int) expectedValue(wifiStats.bandwidthUp, mobileStats.bandwidthUp, wifiAvailability); expectedStats.rttMillis = (int) expectedValue(wifiStats.rttMillis, mobileStats.rttMillis, wifiAvailability); return expectedStats; } private double expectedValue(double valueIfTrue, double valueIfFalse, double probability) { return probability * valueIfTrue + (1 - probability) * valueIfFalse; } private WifiTracker wifiTracker; private double timeUntilGoal() { Date now = new Date(); return (mGoalTime.getTime() - now.getTime()) / 1000.0; } private double timeSinceStart() { Date now = new Date(); return (now.getTime() - mStartTime.getTime()) / 1000.0; } private synchronized double energyUsageRate() { return mEnergySpent / timeSinceStart(); } private synchronized double dataUsageRate() { return mDataSpent.getTotalBytes() / timeSinceStart(); } private void issuePrefetch(FetchFuture<?> prefetch) { if (alreadyIssued(prefetch)) { return; } if (!prefetchesInProgress.offer(prefetch)) { // shouldn't happen, because only one thread calls this, // and it always checks prefetchesInProgress.remainingCapacity() > 0 // before doing so. Log.e(TAG, "WARNING: pending queue refused prefetch. Shouldn't happen."); } prefetch.addLabels(IntNWLabels.MIN_ENERGY); prefetch.addLabels(IntNWLabels.MIN_COST); try { prefetch.startAsync(false); } catch (CancellationException e) { Log.e(TAG, "Prefetch cancelled; discarding"); } } private boolean alreadyIssued(FetchFuture<?> prefetch) { // don't issue a prefetch if some fetch for this data // was already issued; it'll only hang up future prefetches boolean issued = prefetch.wasIssued() || prefetch.isCancelled(); if (issued) { logPrint(String.format("Ignoring already-issued prefetch 0x%08x", prefetch.hashCode())); } return issued; } private void deferDecision(PrefetchTask task) { if (!alreadyIssued(task.prefetch)) { deferredPrefetches.add(task); } } }
package net.imagej.ui.swing.script; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import java.util.concurrent.ExecutionException; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.zip.ZipException; import javax.script.ScriptEngine; import javax.script.ScriptException; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.BadLocationException; import javax.swing.text.Position; import net.imagej.ui.swing.script.commands.ChooseFontSize; import net.imagej.ui.swing.script.commands.ChooseTabSize; import net.imagej.ui.swing.script.commands.GitGrep; import net.imagej.ui.swing.script.commands.KillScript; import org.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.TokenMakerFactory; import org.fife.ui.rsyntaxtextarea.modes.JavaScriptTokenMaker; import org.fife.ui.rsyntaxtextarea.modes.JavaTokenMaker; import org.scijava.Context; import org.scijava.command.CommandService; import org.scijava.event.ContextDisposingEvent; import org.scijava.event.EventHandler; import org.scijava.io.IOService; import org.scijava.log.LogService; import org.scijava.module.ModuleException; import org.scijava.module.ModuleService; import org.scijava.platform.PlatformService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.PluginService; import org.scijava.plugins.scripting.java.JavaEngine; import org.scijava.prefs.PrefService; import org.scijava.script.ScriptHeaderService; import org.scijava.script.ScriptInfo; import org.scijava.script.ScriptLanguage; import org.scijava.script.ScriptModule; import org.scijava.script.ScriptService; import org.scijava.ui.CloseConfirmable; import org.scijava.ui.UIService; import org.scijava.util.AppUtils; import org.scijava.util.FileUtils; import org.scijava.util.MiscUtils; import org.scijava.widget.FileWidget; @SuppressWarnings("serial") public class TextEditor extends JFrame implements ActionListener, ChangeListener, CloseConfirmable { private static final Set<String> TEMPLATE_PATHS = new HashSet<String>(); public static final String AUTO_IMPORT_PREFS = "script.editor.AutoImport"; public static final String TAB_SIZE_PREFS = "script.editor.TabSize"; public static final String FONT_SIZE_PREFS = "script.editor.FontSize"; public static final String LINE_WRAP_PREFS = "script.editor.WrapLines"; public static final String TABS_EMULATED_PREFS = "script.editor.TabsEmulated"; public static final String WINDOW_HEIGHT = "script.editor.height"; public static final String WINDOW_WIDTH = "script.editor.width"; public static final int DEFAULT_TAB_SIZE = 4; public static final int DEFAULT_WINDOW_WIDTH = 800; public static final int DEFAULT_WINDOW_HEIGHT = 600; static { // Add known script template paths. addTemplatePath("script_templates"); // This path interferes with javadoc generation but is preserved for // backwards compatibility addTemplatePath("script-templates"); } private static AbstractTokenMakerFactory tokenMakerFactory = null; protected JTabbedPane tabbed; protected JMenuItem newFile, open, save, saveas, compileAndRun, compile, close, undo, redo, cut, copy, paste, find, replace, selectAll, kill, gotoLine, makeJar, makeJarWithSource, removeUnusedImports, sortImports, removeTrailingWhitespace, findNext, findPrevious, openHelp, addImport, clearScreen, nextError, previousError, openHelpWithoutFrames, nextTab, previousTab, runSelection, extractSourceJar, toggleBookmark, listBookmarks, openSourceForClass, openSourceForMenuItem, openMacroFunctions, decreaseFontSize, increaseFontSize, chooseFontSize, chooseTabSize, gitGrep, openInGitweb, replaceTabsWithSpaces, replaceSpacesWithTabs, toggleWhiteSpaceLabeling, zapGremlins, savePreferences; protected RecentFilesMenuItem openRecent; protected JMenu gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, toolsMenu, runMenu, whiteSpaceMenu; protected int tabsMenuTabsStart; protected Set<JMenuItem> tabsMenuItems; protected FindAndReplaceDialog findDialog; protected JCheckBoxMenuItem autoSave, wrapLines, tabsEmulated, autoImport; protected JTextArea errorScreen = new JTextArea(); protected final String templateFolder = "templates/"; protected int compileStartOffset; protected Position compileStartPosition; protected ErrorHandler errorHandler; protected boolean respectAutoImports; @Parameter protected Context context; @Parameter protected LogService log; @Parameter protected ModuleService moduleService; @Parameter protected PlatformService platformService; @Parameter protected IOService ioService; @Parameter protected CommandService commandService; @Parameter protected ScriptService scriptService; @Parameter protected PluginService pluginService; @Parameter protected ScriptHeaderService scriptHeaderService; @Parameter private UIService uiService; @Parameter protected PrefService prefService; protected Map<ScriptLanguage, JRadioButtonMenuItem> languageMenuItems; protected JRadioButtonMenuItem noneLanguageItem; public TextEditor(final Context context) { super("Script Editor"); context.inject(this); initializeTokenMakers(pluginService, log); loadPreferences(); // Initialize menu int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); int shift = ActionEvent.SHIFT_MASK; JMenuBar mbar = new JMenuBar(); setJMenuBar(mbar); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); newFile = addToMenu(file, "New", KeyEvent.VK_N, ctrl); newFile.setMnemonic(KeyEvent.VK_N); open = addToMenu(file, "Open...", KeyEvent.VK_O, ctrl); open.setMnemonic(KeyEvent.VK_O); openRecent = new RecentFilesMenuItem(prefService, this); openRecent.setMnemonic(KeyEvent.VK_R); file.add(openRecent); save = addToMenu(file, "Save", KeyEvent.VK_S, ctrl); save.setMnemonic(KeyEvent.VK_S); saveas = addToMenu(file, "Save as...", 0, 0); saveas.setMnemonic(KeyEvent.VK_A); file.addSeparator(); makeJar = addToMenu(file, "Export as .jar", 0, 0); makeJar.setMnemonic(KeyEvent.VK_E); makeJarWithSource = addToMenu(file, "Export as .jar (with source)", 0, 0); makeJarWithSource.setMnemonic(KeyEvent.VK_X); file.addSeparator(); close = addToMenu(file, "Close", KeyEvent.VK_W, ctrl); mbar.add(file); JMenu edit = new JMenu("Edit"); edit.setMnemonic(KeyEvent.VK_E); undo = addToMenu(edit, "Undo", KeyEvent.VK_Z, ctrl); redo = addToMenu(edit, "Redo", KeyEvent.VK_Y, ctrl); edit.addSeparator(); selectAll = addToMenu(edit, "Select All", KeyEvent.VK_A, ctrl); cut = addToMenu(edit, "Cut", KeyEvent.VK_X, ctrl); copy = addToMenu(edit, "Copy", KeyEvent.VK_C, ctrl); paste = addToMenu(edit, "Paste", KeyEvent.VK_V, ctrl); edit.addSeparator(); find = addToMenu(edit, "Find...", KeyEvent.VK_F, ctrl); find.setMnemonic(KeyEvent.VK_F); findNext = addToMenu(edit, "Find Next", KeyEvent.VK_F3, 0); findNext.setMnemonic(KeyEvent.VK_N); findPrevious = addToMenu(edit, "Find Previous", KeyEvent.VK_F3, shift); findPrevious.setMnemonic(KeyEvent.VK_P); replace = addToMenu(edit, "Find and Replace...", KeyEvent.VK_H, ctrl); gotoLine = addToMenu(edit, "Goto line...", KeyEvent.VK_G, ctrl); gotoLine.setMnemonic(KeyEvent.VK_G); toggleBookmark = addToMenu(edit, "Toggle Bookmark", KeyEvent.VK_B, ctrl); toggleBookmark.setMnemonic(KeyEvent.VK_B); listBookmarks = addToMenu(edit, "List Bookmarks", 0, 0); listBookmarks.setMnemonic(KeyEvent.VK_O); edit.addSeparator(); // Font adjustments decreaseFontSize = addToMenu(edit, "Decrease font size", KeyEvent.VK_MINUS, ctrl); decreaseFontSize.setMnemonic(KeyEvent.VK_D); increaseFontSize = addToMenu(edit, "Increase font size", KeyEvent.VK_PLUS, ctrl); increaseFontSize.setMnemonic(KeyEvent.VK_C); fontSizeMenu = new JMenu("Font sizes"); fontSizeMenu.setMnemonic(KeyEvent.VK_Z); boolean[] fontSizeShortcutUsed = new boolean[10]; ButtonGroup buttonGroup = new ButtonGroup(); for (final int size : new int[] { 8, 10, 12, 16, 20, 28, 42 }) { JRadioButtonMenuItem item = new JRadioButtonMenuItem("" + size + " pt"); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { getEditorPane().setFontSize(size); updateTabAndFontSize(false); } }); for (char c : ("" + size).toCharArray()) { int digit = c - '0'; if (!fontSizeShortcutUsed[digit]) { item.setMnemonic(KeyEvent.VK_0 + digit); fontSizeShortcutUsed[digit] = true; break; } } buttonGroup.add(item); fontSizeMenu.add(item); } chooseFontSize = new JRadioButtonMenuItem("Other...", false); chooseFontSize.setMnemonic(KeyEvent.VK_O); chooseFontSize.addActionListener(this); buttonGroup.add(chooseFontSize); fontSizeMenu.add(chooseFontSize); edit.add(fontSizeMenu); // Add tab size adjusting menu tabSizeMenu = new JMenu("Tab sizes"); tabSizeMenu.setMnemonic(KeyEvent.VK_T); ButtonGroup bg = new ButtonGroup(); for (final int size : new int[] { 2, 4, 8 }) { JRadioButtonMenuItem item = new JRadioButtonMenuItem("" + size); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { getEditorPane().setTabSize(size); updateTabAndFontSize(false); } }); item.setMnemonic(KeyEvent.VK_0 + (size % 10)); bg.add(item); tabSizeMenu.add(item); } chooseTabSize = new JRadioButtonMenuItem("Other...", false); chooseTabSize.setMnemonic(KeyEvent.VK_O); chooseTabSize.addActionListener(this); bg.add(chooseTabSize); tabSizeMenu.add(chooseTabSize); edit.add(tabSizeMenu); wrapLines = new JCheckBoxMenuItem("Wrap lines"); wrapLines.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { getEditorPane().setLineWrap(wrapLines.getState()); } }); edit.add(wrapLines); // Add Tab inserts as spaces tabsEmulated = new JCheckBoxMenuItem("Tab key inserts spaces"); tabsEmulated.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { getEditorPane().setTabsEmulated(tabsEmulated.getState()); } }); edit.add(tabsEmulated); savePreferences = addToMenu(edit, "Save Preferences", 0, 0); edit.addSeparator(); clearScreen = addToMenu(edit, "Clear output panel", 0, 0); clearScreen.setMnemonic(KeyEvent.VK_L); zapGremlins = addToMenu(edit, "Zap Gremlins", 0, 0); edit.addSeparator(); addImport = addToMenu(edit, "Add import...", 0, 0); addImport.setMnemonic(KeyEvent.VK_I); removeUnusedImports = addToMenu(edit, "Remove unused imports", 0, 0); removeUnusedImports.setMnemonic(KeyEvent.VK_U); sortImports = addToMenu(edit, "Sort imports", 0, 0); sortImports.setMnemonic(KeyEvent.VK_S); respectAutoImports = prefService.getBoolean(AUTO_IMPORT_PREFS, false); autoImport = new JCheckBoxMenuItem("Auto-import (deprecated)", respectAutoImports); autoImport.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { respectAutoImports = e.getStateChange() == ItemEvent.SELECTED; prefService.put(AUTO_IMPORT_PREFS, respectAutoImports); } }); edit.add(autoImport); mbar.add(edit); whiteSpaceMenu = new JMenu("Whitespace"); whiteSpaceMenu.setMnemonic(KeyEvent.VK_W); removeTrailingWhitespace = addToMenu(whiteSpaceMenu, "Remove trailing whitespace", 0, 0); removeTrailingWhitespace.setMnemonic(KeyEvent.VK_W); replaceTabsWithSpaces = addToMenu(whiteSpaceMenu, "Replace tabs with spaces", 0, 0); replaceTabsWithSpaces.setMnemonic(KeyEvent.VK_S); replaceSpacesWithTabs = addToMenu(whiteSpaceMenu, "Replace spaces with tabs", 0, 0); replaceSpacesWithTabs.setMnemonic(KeyEvent.VK_T); toggleWhiteSpaceLabeling = new JRadioButtonMenuItem("Label whitespace"); toggleWhiteSpaceLabeling.setMnemonic(KeyEvent.VK_L); toggleWhiteSpaceLabeling.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getTextArea().setWhitespaceVisible( toggleWhiteSpaceLabeling.isSelected()); } }); whiteSpaceMenu.add(toggleWhiteSpaceLabeling); edit.add(whiteSpaceMenu); languageMenuItems = new LinkedHashMap<ScriptLanguage, JRadioButtonMenuItem>(); Set<Integer> usedShortcuts = new HashSet<Integer>(); JMenu languages = new JMenu("Language"); languages.setMnemonic(KeyEvent.VK_L); ButtonGroup group = new ButtonGroup(); // get list of languages, and sort them by name final ArrayList<ScriptLanguage> list = new ArrayList<ScriptLanguage>(scriptService.getLanguages()); Collections.sort(list, new Comparator<ScriptLanguage>() { @Override public int compare(final ScriptLanguage l1, final ScriptLanguage l2) { final String name1 = l1.getLanguageName(); final String name2 = l2.getLanguageName(); return MiscUtils.compare(name1, name2); } }); list.add(null); Map<String, ScriptLanguage> languageMap = new HashMap<String, ScriptLanguage>(); for (final ScriptLanguage language : list) { String name = language == null ? "None" : language.getLanguageName(); languageMap.put(name, language); JRadioButtonMenuItem item = new JRadioButtonMenuItem(name); if (language == null) { noneLanguageItem = item; } else { languageMenuItems.put(language, item); } int shortcut = -1; for (char ch : name.toCharArray()) { int keyCode = KeyStroke.getKeyStroke(ch, 0).getKeyCode(); if (usedShortcuts.contains(keyCode)) continue; shortcut = keyCode; usedShortcuts.add(shortcut); break; } if (shortcut > 0) item.setMnemonic(shortcut); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setLanguage(language, true); } }); group.add(item); languages.add(item); } noneLanguageItem.setSelected(true); mbar.add(languages); JMenu templates = new JMenu("Templates"); templates.setMnemonic(KeyEvent.VK_T); addTemplates(templates, languageMap); mbar.add(templates); runMenu = new JMenu("Run"); runMenu.setMnemonic(KeyEvent.VK_R); compileAndRun = addToMenu(runMenu, "Compile and Run", KeyEvent.VK_R, ctrl); compileAndRun.setMnemonic(KeyEvent.VK_R); runSelection = addToMenu(runMenu, "Run selected code", KeyEvent.VK_R, ctrl | shift); runSelection.setMnemonic(KeyEvent.VK_S); compile = addToMenu(runMenu, "Compile", KeyEvent.VK_C, ctrl | shift); compile.setMnemonic(KeyEvent.VK_C); autoSave = new JCheckBoxMenuItem("Auto-save before compiling"); runMenu.add(autoSave); runMenu.addSeparator(); nextError = addToMenu(runMenu, "Next Error", KeyEvent.VK_F4, 0); nextError.setMnemonic(KeyEvent.VK_N); previousError = addToMenu(runMenu, "Previous Error", KeyEvent.VK_F4, shift); previousError.setMnemonic(KeyEvent.VK_P); runMenu.addSeparator(); kill = addToMenu(runMenu, "Kill running script...", 0, 0); kill.setMnemonic(KeyEvent.VK_K); kill.setEnabled(false); mbar.add(runMenu); toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic(KeyEvent.VK_O); openHelpWithoutFrames = addToMenu(toolsMenu, "Open Help for Class...", 0, 0); openHelpWithoutFrames.setMnemonic(KeyEvent.VK_O); openHelp = addToMenu(toolsMenu, "Open Help for Class (with frames)...", 0, 0); openHelp.setMnemonic(KeyEvent.VK_P); openMacroFunctions = addToMenu(toolsMenu, "Open Help on Macro Functions...", 0, 0); openMacroFunctions.setMnemonic(KeyEvent.VK_H); extractSourceJar = addToMenu(toolsMenu, "Extract source .jar...", 0, 0); extractSourceJar.setMnemonic(KeyEvent.VK_E); openSourceForClass = addToMenu(toolsMenu, "Open .java file for class...", 0, 0); openSourceForClass.setMnemonic(KeyEvent.VK_J); openSourceForMenuItem = addToMenu(toolsMenu, "Open .java file for menu item...", 0, 0); openSourceForMenuItem.setMnemonic(KeyEvent.VK_M); mbar.add(toolsMenu); gitMenu = new JMenu("Git"); gitMenu.setMnemonic(KeyEvent.VK_G); /* showDiff = addToMenu(gitMenu, "Show diff...", 0, 0); showDiff.setMnemonic(KeyEvent.VK_D); commit = addToMenu(gitMenu, "Commit...", 0, 0); commit.setMnemonic(KeyEvent.VK_C); */ gitGrep = addToMenu(gitMenu, "Grep...", 0, 0); gitGrep.setMnemonic(KeyEvent.VK_G); openInGitweb = addToMenu(gitMenu, "Open in gitweb", 0, 0); openInGitweb.setMnemonic(KeyEvent.VK_W); mbar.add(gitMenu); tabsMenu = new JMenu("Tabs"); tabsMenu.setMnemonic(KeyEvent.VK_A); nextTab = addToMenu(tabsMenu, "Next Tab", KeyEvent.VK_PAGE_DOWN, ctrl); nextTab.setMnemonic(KeyEvent.VK_N); previousTab = addToMenu(tabsMenu, "Previous Tab", KeyEvent.VK_PAGE_UP, ctrl); previousTab.setMnemonic(KeyEvent.VK_P); tabsMenu.addSeparator(); tabsMenuTabsStart = tabsMenu.getItemCount(); tabsMenuItems = new HashSet<JMenuItem>(); mbar.add(tabsMenu); // Add the editor and output area tabbed = new JTabbedPane(); tabbed.addChangeListener(this); open(null); // make sure the editor pane is added tabbed.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); getContentPane().setLayout( new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); getContentPane().add(tabbed); // for Eclipse and MS Visual Studio lovers addAccelerator(compileAndRun, KeyEvent.VK_F11, 0, true); addAccelerator(compileAndRun, KeyEvent.VK_F5, 0, true); addAccelerator(nextTab, KeyEvent.VK_PAGE_DOWN, ctrl, true); addAccelerator(previousTab, KeyEvent.VK_PAGE_UP, ctrl, true); addAccelerator(increaseFontSize, KeyEvent.VK_EQUALS, ctrl | shift, true); // make sure that the window is not closed by accident addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (!confirmClose()) return; dispose(); } }); addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(WindowEvent e) { final EditorPane editorPane = getEditorPane(); editorPane.checkForOutsideChanges(); } }); Font font = new Font("Courier", Font.PLAIN, 12); errorScreen.setFont(font); errorScreen.setEditable(false); errorScreen.setLineWrap(true); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); try { if (SwingUtilities.isEventDispatchThread()) { pack(); } else { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { pack(); } }); } } catch (Exception ie) {} findDialog = new FindAndReplaceDialog(this); // Save the size of the window in the preferences addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { saveWindowSizeToPrefs(); } }); setLocationRelativeTo(null); // center on screen open(null); final EditorPane editorPane = getEditorPane(); editorPane.requestFocus(); } private synchronized static void initializeTokenMakers( final PluginService pluginService, final LogService log) { if (tokenMakerFactory != null) return; tokenMakerFactory = (AbstractTokenMakerFactory) TokenMakerFactory.getDefaultInstance(); for (final PluginInfo<SyntaxHighlighter> info : pluginService .getPluginsOfType(SyntaxHighlighter.class)) try { tokenMakerFactory.putMapping("text/" + info.getLabel(), info .getClassName()); } catch (Throwable t) { log.warn("Could not register " + info.getLabel(), t); } } /** * Adds a script template path that will be scanned by future TextEditor * instances. * * @param path Resource path to scan for scripts. */ public static void addTemplatePath(final String path) { TEMPLATE_PATHS.add(path); } @Plugin(type = SyntaxHighlighter.class, label = "ecmascript") public static class ECMAScriptHighlighter extends JavaScriptTokenMaker implements SyntaxHighlighter {} @Plugin(type = SyntaxHighlighter.class, label = "matlab") public static class MatlabHighlighter extends MatlabTokenMaker implements SyntaxHighlighter {} @Plugin(type = SyntaxHighlighter.class, label = "ij1-macro") public static class IJ1MacroHighlighter extends ImageJMacroTokenMaker implements SyntaxHighlighter {} @Plugin(type = SyntaxHighlighter.class, label = "beanshell") public static class BeanshellHighlighter extends JavaTokenMaker implements SyntaxHighlighter {} @EventHandler private void onEvent(final ContextDisposingEvent e) { if (isDisplayable()) dispose(); } /** * Loads the preferences for the JFrame from file */ public void loadPreferences() { Dimension dim = getSize(); // If a dimension is 0 then use the default dimension size if (0 == dim.width) { dim.width = DEFAULT_WINDOW_WIDTH; } if (0 == dim.height) { dim.height = DEFAULT_WINDOW_HEIGHT; } setPreferredSize(new Dimension(prefService.getInt(WINDOW_WIDTH, dim.width), prefService.getInt(WINDOW_HEIGHT, dim.height))); } /** * Retrieves and saves the preferences to the persistent store */ public void savePreferences() { EditorPane pane = getEditorPane(); prefService.put(TAB_SIZE_PREFS, pane.getTabSize()); prefService.put(FONT_SIZE_PREFS, pane.getFontSize()); prefService.put(LINE_WRAP_PREFS, pane.getLineWrap()); prefService.put(TABS_EMULATED_PREFS, pane.getTabsEmulated()); } /** * Saves the window size to preferences. * <p> * Separated from savePreferences because we always want to save the window * size when it's resized, however, we don't want to automatically save the * font, tab size, etc. without the user pressing "Save Preferences" * </p> */ public void saveWindowSizeToPrefs() { Dimension dim = getSize(); prefService.put(WINDOW_HEIGHT, dim.height); prefService.put(WINDOW_WIDTH, dim.width); } final public RSyntaxTextArea getTextArea() { return getEditorPane(); } /** * Get the currently selected tab. * * @return The currently selected tab. Never null. */ public Tab getTab() { int index = tabbed.getSelectedIndex(); if (index < 0) { // should not happen, but safety first. if (tabbed.getTabCount() == 0) { // should not happen either, but, again, safety first. createNewDocument(); } tabbed.setSelectedIndex(0); } return (Tab) tabbed.getComponentAt(index); } /** * Get tab at provided index. * * @param index the index of the tab. * @return the {@link Tab} at given index or <code>null</code>. */ public Tab getTab(int index) { return (Tab) tabbed.getComponentAt(index); } /** * Return the {@link EditorPane} of the currently selected {@link Tab}. * * @return the current {@link EditorPane}. Never <code>null</code>. */ public EditorPane getEditorPane() { return getTab().editorPane; } public ScriptLanguage getCurrentLanguage() { return getEditorPane().currentLanguage; } public JMenuItem addToMenu(JMenu menu, String menuEntry, int key, int modifiers) { JMenuItem item = new JMenuItem(menuEntry); menu.add(item); if (key != 0) item.setAccelerator(KeyStroke.getKeyStroke(key, modifiers)); item.addActionListener(this); return item; } protected static class AcceleratorTriplet { JMenuItem component; int key, modifiers; } protected List<AcceleratorTriplet> defaultAccelerators = new ArrayList<AcceleratorTriplet>(); public void addAccelerator(final JMenuItem component, int key, int modifiers) { addAccelerator(component, key, modifiers, false); } public void addAccelerator(final JMenuItem component, int key, int modifiers, boolean record) { if (record) { AcceleratorTriplet triplet = new AcceleratorTriplet(); triplet.component = component; triplet.key = key; triplet.modifiers = modifiers; defaultAccelerators.add(triplet); } RSyntaxTextArea textArea = getTextArea(); if (textArea != null) addAccelerator(textArea, component, key, modifiers); } public void addAccelerator(RSyntaxTextArea textArea, final JMenuItem component, int key, int modifiers) { textArea.getInputMap().put(KeyStroke.getKeyStroke(key, modifiers), component); textArea.getActionMap().put(component, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (!component.isEnabled()) return; ActionEvent event = new ActionEvent(component, 0, "Accelerator"); TextEditor.this.actionPerformed(event); } }); } public void addDefaultAccelerators(RSyntaxTextArea textArea) { for (AcceleratorTriplet triplet : defaultAccelerators) addAccelerator(textArea, triplet.component, triplet.key, triplet.modifiers); } protected JMenu getMenu(JMenu root, String menuItemPath, boolean createIfNecessary) { int gt = menuItemPath.indexOf('>'); if (gt < 0) return root; String menuLabel = menuItemPath.substring(0, gt); String rest = menuItemPath.substring(gt + 1); for (int i = 0; i < root.getItemCount(); i++) { JMenuItem item = root.getItem(i); if ((item instanceof JMenu) && menuLabel.equals(item.getText())) return getMenu( (JMenu) item, rest, createIfNecessary); } if (!createIfNecessary) return null; JMenu subMenu = new JMenu(menuLabel); root.add(subMenu); return getMenu(subMenu, rest, createIfNecessary); } /** * Initializes the template menu. * <p> * Third-party components can add templates simply by providing * language-specific files in their resources, identified by a path of the * form {@code /script-templates/<language>/menu label}. * </p> * <p> * The sub menus of the template menu correspond to language names; Entries * for languages unknown to the script service will be discarded quietly. * </p> * * @param templatesMenu the top-level menu to populate * @param languageMap the known languages */ protected void addTemplates(JMenu templatesMenu, Map<String, ScriptLanguage> languageMap) { for (final String templatePath : TEMPLATE_PATHS) { for (final Map.Entry<String, URL> entry : new TreeMap<String, URL>( FileFunctions.findResources(null, templatePath)).entrySet()) { final String path = entry.getKey().replace('/', '>').replace('_', ' '); int gt = path.indexOf('>'); if (gt < 1) { log.warn("Ignoring invalid editor template: " + entry.getValue()); continue; } final String language = path.substring(0, gt); if (!languageMap.containsKey(language)) { log.debug("Ignoring editor template for language " + language + ": " + entry.getValue()); continue; } final ScriptLanguage engine = languageMap.get(language); final JMenu menu = getMenu(templatesMenu, path, true); String label = path.substring(path.lastIndexOf('>') + 1); final int dot = label.lastIndexOf('.'); if (dot > 0) label = label.substring(0, dot); final JMenuItem item = new JMenuItem(label); menu.add(item); final URL url = entry.getValue(); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadTemplate(url, engine); } }); } } } /** * Loads a template file from the given resource * * @param url The resource to load. */ public void loadTemplate(final String url) { try { loadTemplate(new URL(url)); } catch (Exception e) { log.error(e); error("The template '" + url + "' was not found."); } } public void loadTemplate(final URL url) { final String path = url.getPath(); int dot = path.lastIndexOf('.'); ScriptLanguage language = null; if (dot > 0) { language = scriptService.getLanguageByExtension(path.substring(dot + 1)); } loadTemplate(url, language); } public void loadTemplate(final URL url, final ScriptLanguage language) { createNewDocument(); try { // Load the template InputStream in = url.openStream(); getTextArea().read(new BufferedReader(new InputStreamReader(in)), null); if (language != null) { setLanguage(language); } final String path = url.getPath(); setFileName(path.substring(path.lastIndexOf('/') + 1)); } catch (Exception e) { e.printStackTrace(); error("The template '" + url + "' was not found."); } } public void createNewDocument() { open(null); } public void createNewDocument(String title, String text) { open(null); final EditorPane editorPane = getEditorPane(); editorPane.setText(text); editorPane.setLanguageByFileName(title); setFileName(title); setTitle(); } /** * Open a new editor to edit the given file, with a templateFile if the file * does not exist yet */ public void createNewFromTemplate(File file, File templateFile) { open(file.exists() ? file : templateFile); if (!file.exists()) { final EditorPane editorPane = getEditorPane(); try { editorPane.open(file); } catch (IOException e) { handleException(e); } editorPane.setLanguageByFileName(file.getName()); setTitle(); } } public boolean fileChanged() { return getEditorPane().fileChanged(); } public boolean handleUnsavedChanges() { return handleUnsavedChanges(false); } public boolean handleUnsavedChanges(boolean beforeCompiling) { if (!fileChanged()) return true; if (beforeCompiling && autoSave.getState()) { save(); return true; } switch (JOptionPane.showConfirmDialog(this, "Do you want to save changes?")) { case JOptionPane.NO_OPTION: return true; case JOptionPane.YES_OPTION: if (save()) return true; } return false; } protected void grabFocus() { toFront(); } protected void grabFocus(final int laterCount) { if (laterCount == 0) { grabFocus(); return; } SwingUtilities.invokeLater(new Thread() { @Override public void run() { grabFocus(laterCount - 1); } }); } @Override public void actionPerformed(ActionEvent ae) { final Object source = ae.getSource(); if (source == newFile) createNewDocument(); else if (source == open) { final EditorPane editorPane = getEditorPane(); final File defaultDir = editorPane.file != null ? editorPane.file .getParentFile() : AppUtils.getBaseDirectory("imagej.dir", TextEditor.class, null); final File file = openWithDialog(defaultDir); if (file != null) new Thread() { @Override public void run() { open(file); } }.start(); return; } else if (source == save) save(); else if (source == saveas) saveAs(); else if (source == makeJar) makeJar(false); else if (source == makeJarWithSource) makeJar(true); else if (source == compileAndRun) runText(); else if (source == compile) compile(); else if (source == runSelection) runText(true); else if (source == nextError) new Thread() { @Override public void run() { nextError(true); } }.start(); else if (source == previousError) new Thread() { @Override public void run() { nextError(false); } }.start(); else if (source == kill) chooseTaskToKill(); else if (source == close) if (tabbed.getTabCount() < 2) processWindowEvent(new WindowEvent( this, WindowEvent.WINDOW_CLOSING)); else { if (!handleUnsavedChanges()) return; int index = tabbed.getSelectedIndex(); removeTab(index); if (index > 0) index switchTo(index); } else if (source == cut) getTextArea().cut(); else if (source == copy) getTextArea().copy(); else if (source == paste) getTextArea().paste(); else if (source == undo) getTextArea().undoLastAction(); else if (source == redo) getTextArea().redoLastAction(); else if (source == find) findOrReplace(false); else if (source == findNext) findDialog.searchOrReplace(false); else if (source == findPrevious) findDialog.searchOrReplace(false, false); else if (source == replace) findOrReplace(true); else if (source == gotoLine) gotoLine(); else if (source == toggleBookmark) toggleBookmark(); else if (source == listBookmarks) listBookmarks(); else if (source == selectAll) { getTextArea().setCaretPosition(0); getTextArea().moveCaretPosition(getTextArea().getDocument().getLength()); } else if (source == chooseFontSize) { commandService.run(ChooseFontSize.class, true, "editor", this); } else if (source == chooseTabSize) { commandService.run(ChooseTabSize.class, true, "editor", this); } else if (source == addImport) addImport(null); else if (source == removeUnusedImports) new TokenFunctions(getTextArea()) .removeUnusedImports(); else if (source == sortImports) new TokenFunctions(getTextArea()) .sortImports(); else if (source == removeTrailingWhitespace) new TokenFunctions( getTextArea()).removeTrailingWhitespace(); else if (source == replaceTabsWithSpaces) getTextArea() .convertTabsToSpaces(); else if (source == replaceSpacesWithTabs) getTextArea() .convertSpacesToTabs(); else if (source == clearScreen) { getTab().getScreen().setText(""); } else if (source == zapGremlins) zapGremlins(); else if (source == savePreferences) savePreferences(); else if (source == openHelp) openHelp(null); else if (source == openHelpWithoutFrames) openHelp(null, false); else if (source == openMacroFunctions) try { new MacroFunctions(this).openHelp(getTextArea().getSelectedText()); } catch (IOException e) { handleException(e); } else if (source == extractSourceJar) extractSourceJar(); else if (source == openSourceForClass) { String className = getSelectedClassNameOrAsk(); if (className != null) try { String path = new FileFunctions(this).getSourcePath(className); if (path != null) open(new File(path)); else { String url = new FileFunctions(this).getSourceURL(className); try { platformService.open(new URL(url)); } catch (Throwable e) { handleException(e); } } } catch (ClassNotFoundException e) { error("Could not open source for class " + className); } } /* TODO else if (source == showDiff) { new Thread() { public void run() { EditorPane pane = getEditorPane(); new FileFunctions(TextEditor.this).showDiff(pane.file, pane.getGitDirectory()); } }.start(); } else if (source == commit) { new Thread() { public void run() { EditorPane pane = getEditorPane(); new FileFunctions(TextEditor.this).commit(pane.file, pane.getGitDirectory()); } }.start(); } */ else if (source == gitGrep) { String searchTerm = getTextArea().getSelectedText(); File searchRoot = getEditorPane().file; if (searchRoot == null) { error("File was not yet saved; no location known!"); return; } searchRoot = searchRoot.getParentFile(); commandService.run(GitGrep.class, true, "editor", this, "searchTerm", searchTerm, "searchRoot", searchRoot); } else if (source == openInGitweb) { EditorPane editorPane = getEditorPane(); new FileFunctions(this).openInGitweb(editorPane.file, editorPane.gitDirectory, editorPane.getCaretLineNumber() + 1); } else if (source == increaseFontSize || source == decreaseFontSize) { getEditorPane().increaseFontSize( (float) (source == increaseFontSize ? 1.2 : 1 / 1.2)); updateTabAndFontSize(false); } else if (source == nextTab) switchTabRelative(1); else if (source == previousTab) switchTabRelative(-1); else if (handleTabsMenu(source)) return; } protected boolean handleTabsMenu(Object source) { if (!(source instanceof JMenuItem)) return false; JMenuItem item = (JMenuItem) source; if (!tabsMenuItems.contains(item)) return false; for (int i = tabsMenuTabsStart; i < tabsMenu.getItemCount(); i++) if (tabsMenu.getItem(i) == item) { switchTo(i - tabsMenuTabsStart); return true; } return false; } @Override public void stateChanged(ChangeEvent e) { int index = tabbed.getSelectedIndex(); if (index < 0) { setTitle(""); return; } final EditorPane editorPane = getEditorPane(index); editorPane.requestFocus(); setTitle(); editorPane.checkForOutsideChanges(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { editorPane.setLanguageByFileName(editorPane.getFileName()); toggleWhiteSpaceLabeling.setSelected(((RSyntaxTextArea) editorPane) .isWhitespaceVisible()); } }); } public EditorPane getEditorPane(int index) { return getTab(index).editorPane; } public void findOrReplace(boolean replace) { findDialog.setLocationRelativeTo(this); // override search pattern only if // there is sth. selected String selection = getTextArea().getSelectedText(); if (selection != null) findDialog.setSearchPattern(selection); findDialog.show(replace); } public void gotoLine() { String line = JOptionPane.showInputDialog(this, "Line:", "Goto line...", JOptionPane.QUESTION_MESSAGE); if (line == null) return; try { gotoLine(Integer.parseInt(line)); } catch (BadLocationException e) { error("Line number out of range: " + line); } catch (NumberFormatException e) { error("Invalid line number: " + line); } } public void gotoLine(int line) throws BadLocationException { getTextArea().setCaretPosition(getTextArea().getLineStartOffset(line - 1)); } public void toggleBookmark() { getEditorPane().toggleBookmark(); } public void listBookmarks() { Vector<EditorPane.Bookmark> bookmarks = new Vector<EditorPane.Bookmark>(); for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).getBookmarks(i, bookmarks); BookmarkDialog dialog = new BookmarkDialog(this, bookmarks); dialog.setVisible(true); } public boolean reload() { return reload("Reload the file?"); } public boolean reload(String message) { File file = getEditorPane().file; if (file == null || !file.exists()) return true; boolean modified = getEditorPane().fileChanged(); String[] options = { "Reload", "Do not reload" }; if (modified) options[0] = "Reload (discarding changes)"; switch (JOptionPane.showOptionDialog(this, message, "Reload", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0])) { case 0: try { getEditorPane().open(file); return true; } catch (IOException e) { error("Could not reload " + file.getPath()); } break; } return false; } public class Tab extends JSplitPane { protected final EditorPane editorPane = new EditorPane(TextEditor.this); protected final JTextArea screen = new JTextArea(); protected final JScrollPane scroll; protected boolean showingErrors; private Executer executer; private final JButton runit, killit, toggleErrors; public Tab() { super(JSplitPane.VERTICAL_SPLIT); super.setResizeWeight(350.0 / 430.0); screen.setEditable(false); screen.setLineWrap(true); screen.setFont(new Font("Courier", Font.PLAIN, 12)); JPanel bottom = new JPanel(); bottom.setLayout(new GridBagLayout()); GridBagConstraints bc = new GridBagConstraints(); bc.gridx = 0; bc.gridy = 0; bc.weightx = 0; bc.weighty = 0; bc.anchor = GridBagConstraints.NORTHWEST; bc.fill = GridBagConstraints.NONE; runit = new JButton("Run"); runit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { runText(); } }); bottom.add(runit, bc); bc.gridx = 1; killit = new JButton("Kill"); killit.setEnabled(false); killit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { kill(); } }); bottom.add(killit, bc); bc.gridx = 2; bc.fill = GridBagConstraints.HORIZONTAL; bc.weightx = 1; bottom.add(new JPanel(), bc); bc.gridx = 3; bc.fill = GridBagConstraints.NONE; bc.weightx = 0; bc.anchor = GridBagConstraints.NORTHEAST; toggleErrors = new JButton("Show Errors"); toggleErrors.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggleErrors(); } }); bottom.add(toggleErrors, bc); bc.gridx = 4; bc.fill = GridBagConstraints.NONE; bc.weightx = 0; bc.anchor = GridBagConstraints.NORTHEAST; JButton clear = new JButton("Clear"); clear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (showingErrors) errorScreen.setText(""); else screen.setText(""); } }); bottom.add(clear, bc); bc.gridx = 0; bc.gridy = 1; bc.anchor = GridBagConstraints.NORTHWEST; bc.fill = GridBagConstraints.BOTH; bc.weightx = 1; bc.weighty = 1; bc.gridwidth = 5; screen.setEditable(false); screen.setLineWrap(true); Font font = new Font("Courier", Font.PLAIN, 12); screen.setFont(font); scroll = new JScrollPane(screen); scroll.setPreferredSize(new Dimension(600, 80)); bottom.add(scroll, bc); super.setTopComponent(editorPane.embedWithScrollbars()); super.setBottomComponent(bottom); loadPreferences(); } /** * Loads the preferences for the Tab and apply them. */ public void loadPreferences() { editorPane.setTabSize(getTabSizeSetting()); editorPane.setFontSize(prefService.getFloat(FONT_SIZE_PREFS, editorPane .getFontSize())); editorPane.setLineWrap(prefService.getBoolean(LINE_WRAP_PREFS, editorPane .getLineWrap())); editorPane.setTabsEmulated(prefService.getBoolean(TABS_EMULATED_PREFS, editorPane.getTabsEmulated())); } /** Invoke in the context of the event dispatch thread. */ private void prepare() { editorPane.setEditable(false); runit.setEnabled(false); killit.setEnabled(true); } private void restore() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { editorPane.setEditable(true); runit.setEnabled(true); killit.setEnabled(false); executer = null; } }); } public void toggleErrors() { showingErrors = !showingErrors; if (showingErrors) { toggleErrors.setText("Show Output"); scroll.setViewportView(errorScreen); } else { toggleErrors.setText("Show Errors"); scroll.setViewportView(screen); } } public void showErrors() { if (!showingErrors) toggleErrors(); else if (scroll.getViewport().getView() == null) scroll .setViewportView(errorScreen); } public void showOutput() { if (showingErrors) toggleErrors(); } public JTextArea getScreen() { return showingErrors ? errorScreen : screen; } boolean isExecuting() { return null != executer; } String getTitle() { return (editorPane.fileChanged() ? "*" : "") + editorPane.getFileName() + (isExecuting() ? " (Running)" : ""); } /** Invoke in the context of the event dispatch thread. */ private void execute(final boolean selectionOnly) throws IOException { prepare(); final JTextAreaWriter output = new JTextAreaWriter(this.screen, TextEditor.this.log); final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log); final File file = getEditorPane().file; // Pipe current text into the runScript: final PipedInputStream pi = new PipedInputStream(); final PipedOutputStream po = new PipedOutputStream(pi); // The Executer creates a Thread that // does the reading from PipedInputStream this.executer = new TextEditor.Executer(output, errors) { @Override public void execute() { try { evalScript(file == null ? getEditorPane().getFileName() : file .getAbsolutePath(), new InputStreamReader(pi), output, errors); output.flush(); errors.flush(); markCompileEnd(); } catch (Throwable t) { output.flush(); errors.flush(); if (t instanceof ScriptException && t.getCause() != null && t.getCause().getClass().getName().endsWith("CompileError")) { errorScreen.append("Compilation failed"); showErrors(); } else { handleException(t); } } finally { restore(); } } }; // Write into PipedOutputStream // from another Thread try { final String text; if (selectionOnly) { String selected = editorPane.getSelectedText(); if (selected == null) { error("Selection required!"); text = null; } else text = selected + "\n"; // Ensure code blocks are terminated } else { text = editorPane.getText(); } new Thread() { { setPriority(Thread.NORM_PRIORITY); } @Override public void run() { PrintWriter pw = new PrintWriter(po); pw.write(text); pw.flush(); // will lock and wait in some cases try { po.close(); } catch (Throwable tt) { tt.printStackTrace(); } pw.close(); } }.start(); } catch (Throwable t) { t.printStackTrace(); } finally { // Re-enable when all text to send has been sent editorPane.setEditable(true); } } protected void kill() { if (null == executer) return; // Graceful attempt: executer.interrupt(); // Give it 3 seconds. Then, stop it. final long now = System.currentTimeMillis(); new Thread() { { setPriority(Thread.NORM_PRIORITY); } @Override public void run() { while (System.currentTimeMillis() - now < 3000) try { Thread.sleep(100); } catch (InterruptedException e) {} if (null != executer) executer.obliterate(); restore(); } }.start(); } } public static boolean isBinary(File file) { if (file == null) return false; // heuristic: read the first up to 8000 bytes, and say that it is binary if // it contains a NUL try { FileInputStream in = new FileInputStream(file); int left = 8000; byte[] buffer = new byte[left]; while (left > 0) { int count = in.read(buffer, 0, left); if (count < 0) break; for (int i = 0; i < count; i++) if (buffer[i] == 0) { in.close(); return true; } left -= count; } in.close(); return false; } catch (IOException e) { return false; } } /** * Open a new tab with some content; the languageExtension is like ".java", * ".py", etc. */ public Tab newTab(String content, String language) { Tab tab = open(null); if (null != language && language.length() > 0) { language = language.trim().toLowerCase(); if ('.' != language.charAt(0)) language = "." + language; tab.editorPane.setLanguage(scriptService.getLanguageByName(language)); } if (null != content) tab.editorPane.setText(content); return tab; } public Tab open(File file) { if (isBinary(file)) { // TODO! throw new RuntimeException("TODO: open image using IJ2"); // return null; } try { Tab tab = (tabbed.getTabCount() == 0) ? null : getTab(); boolean wasNew = tab != null && tab.editorPane.isNew(); if (!wasNew) { tab = new Tab(); context.inject(tab.editorPane); addDefaultAccelerators(tab.editorPane); } synchronized (tab.editorPane) { tab.editorPane.open(file); if (wasNew) { int index = tabbed.getSelectedIndex() + tabsMenuTabsStart; tabsMenu.getItem(index).setText(tab.editorPane.getFileName()); } else { tabbed.addTab("", tab); switchTo(tabbed.getTabCount() - 1); tabsMenuItems.add(addToMenu(tabsMenu, tab.editorPane.getFileName(), 0, 0)); } setFileName(tab.editorPane.file); try { updateTabAndFontSize(true); } catch (NullPointerException e) { /* ignore */ } } if (file != null) openRecent.add(file.getAbsolutePath()); return tab; } catch (FileNotFoundException e) { e.printStackTrace(); error("The file '" + file + "' was not found."); } catch (Exception e) { e.printStackTrace(); error("There was an error while opening '" + file + "': " + e); } return null; } public boolean saveAs() { EditorPane editorPane = getEditorPane(); File file = editorPane.file; if (file == null) { final File ijDir = AppUtils.getBaseDirectory("imagej.dir", TextEditor.class, null); file = new File(ijDir, editorPane.getFileName()); } final File fileToSave = uiService.chooseFile(file, FileWidget.SAVE_STYLE); if (fileToSave == null) return false; return saveAs(fileToSave.getAbsolutePath(), true); } public void saveAs(String path) { saveAs(path, true); } public boolean saveAs(String path, boolean askBeforeReplacing) { File file = new File(path); if (file.exists() && askBeforeReplacing && JOptionPane.showConfirmDialog(this, "Do you want to replace " + path + "?", "Replace " + path + "?", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return false; if (!write(file)) return false; setFileName(file); openRecent.add(path); return true; } public boolean save() { File file = getEditorPane().file; if (file == null) return saveAs(); if (!write(file)) return false; setTitle(); return true; } public boolean write(File file) { try { getEditorPane().write(file); return true; } catch (IOException e) { error("Could not save " + file.getName()); e.printStackTrace(); return false; } } public boolean makeJar(boolean includeSources) { File file = getEditorPane().file; if ((file == null || isCompiled()) && !handleUnsavedChanges(true)) { return false; } String name = getEditorPane().getFileName(); String ext = FileUtils.getExtension(name); if (!"".equals(ext)) name = name.substring(0, name.length() - ext.length()); if (name.indexOf('_') < 0) name += "_"; name += ".jar"; final File selectedFile = uiService.chooseFile(file, FileWidget.SAVE_STYLE); if (selectedFile == null) return false; if (selectedFile.exists() && JOptionPane.showConfirmDialog(this, "Do you want to replace " + selectedFile + "?", "Replace " + selectedFile + "?", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return false; try { makeJar(selectedFile, includeSources); return true; } catch (IOException e) { e.printStackTrace(); error("Could not write " + selectedFile + ": " + e.getMessage()); return false; } } public void makeJar(final File file, final boolean includeSources) throws IOException { if (!handleUnsavedChanges(true)) return; final ScriptEngine interpreter = getCurrentLanguage().getScriptEngine(); if (interpreter instanceof JavaEngine) { final JavaEngine java = (JavaEngine) interpreter; final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log); markCompileStart(); getTab().showErrors(); new Thread() { @Override public void run() { java.makeJar(getEditorPane().file, includeSources, file, errors); errorScreen.insert("Compilation finished.\n", errorScreen .getDocument().getLength()); markCompileEnd(); } }.start(); } } static void getClasses(File directory, List<String> paths, List<String> names) { getClasses(directory, paths, names, ""); } static void getClasses(File directory, List<String> paths, List<String> names, String prefix) { if (!prefix.equals("")) prefix += "/"; for (File file : directory.listFiles()) if (file.isDirectory()) getClasses(file, paths, names, prefix + file.getName()); else { paths.add(file.getAbsolutePath()); names.add(prefix + file.getName()); } } static void writeJarEntry(JarOutputStream out, String name, byte[] buf) throws IOException { try { JarEntry entry = new JarEntry(name); out.putNextEntry(entry); out.write(buf, 0, buf.length); out.closeEntry(); } catch (ZipException e) { e.printStackTrace(); throw new IOException(e.getMessage()); } } static byte[] readFile(String fileName) throws IOException { File file = new File(fileName); InputStream in = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; in.read(buffer); in.close(); return buffer; } static void deleteRecursively(File directory) { for (File file : directory.listFiles()) if (file.isDirectory()) deleteRecursively(file); else file.delete(); directory.delete(); } void setLanguage(ScriptLanguage language) { setLanguage(language, false); } void setLanguage(ScriptLanguage language, boolean addHeader) { getEditorPane().setLanguage(language, addHeader); updateTabAndFontSize(true); } void updateLanguageMenu(ScriptLanguage language) { JMenuItem item = languageMenuItems.get(language); if (item == null) item = noneLanguageItem; if (!item.isSelected()) { item.setSelected(true); } final boolean isRunnable = item != noneLanguageItem; final boolean isCompileable = language != null && language.isCompiledLanguage(); runMenu.setVisible(isRunnable); compileAndRun.setText(isCompileable ? "Compile and Run" : "Run"); compileAndRun.setEnabled(isRunnable); runSelection.setVisible(isRunnable && !isCompileable); compile.setVisible(isCompileable); autoSave.setVisible(isCompileable); makeJar.setVisible(isCompileable); makeJarWithSource.setVisible(isCompileable); boolean isJava = language != null && language.getLanguageName().equals("Java"); addImport.setVisible(isJava); removeUnusedImports.setVisible(isJava); sortImports.setVisible(isJava); openSourceForMenuItem.setVisible(isJava); boolean isMacro = language != null && language.getLanguageName().equals("ImageJ Macro"); openMacroFunctions.setVisible(isMacro); openSourceForClass.setVisible(!isMacro); openHelp.setVisible(!isMacro && isRunnable); openHelpWithoutFrames.setVisible(!isMacro && isRunnable); nextError.setVisible(!isMacro && isRunnable); previousError.setVisible(!isMacro && isRunnable); boolean isInGit = getEditorPane().getGitDirectory() != null; gitMenu.setVisible(isInGit); updateTabAndFontSize(false); } public void updateTabAndFontSize(boolean setByLanguage) { EditorPane pane = getEditorPane(); if (pane.currentLanguage == null) return; if (setByLanguage) { final boolean isPython = pane.currentLanguage.getLanguageName().equals("Python"); pane.setTabSize(isPython ? 4 : getTabSizeSetting()); } int tabSize = pane.getTabSize(); boolean defaultSize = false; for (int i = 0; i < tabSizeMenu.getItemCount(); i++) { JMenuItem item = tabSizeMenu.getItem(i); if (item == chooseTabSize) { item.setSelected(!defaultSize); item.setText("Other" + (defaultSize ? "" : " (" + tabSize + ")") + "..."); } else if (tabSize == Integer.parseInt(item.getText())) { item.setSelected(true); defaultSize = true; } } int fontSize = (int) pane.getFontSize(); defaultSize = false; for (int i = 0; i < fontSizeMenu.getItemCount(); i++) { JMenuItem item = fontSizeMenu.getItem(i); if (item == chooseFontSize) { item.setSelected(!defaultSize); item.setText("Other" + (defaultSize ? "" : " (" + fontSize + ")") + "..."); continue; } String label = item.getText(); if (label.endsWith(" pt")) label = label.substring(0, label.length() - 3); if (fontSize == Integer.parseInt(label)) { item.setSelected(true); defaultSize = true; } } wrapLines.setState(pane.getLineWrap()); tabsEmulated.setState(pane.getTabsEmulated()); } public void setFileName(String baseName) { getEditorPane().setFileName(baseName); } public void setFileName(File file) { getEditorPane().setFileName(file); } synchronized void setTitle() { final Tab tab = getTab(); final boolean fileChanged = tab.editorPane.fileChanged(); final String fileName = tab.editorPane.getFileName(); final String title = (fileChanged ? "*" : "") + fileName + (executingTasks.isEmpty() ? "" : " (Running)"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { setTitle(title); // to the main window // Update all tabs: could have changed for (int i = 0; i < tabbed.getTabCount(); i++) tabbed.setTitleAt(i, ((Tab) tabbed.getComponentAt(i)).getTitle()); } }); } @Override public synchronized void setTitle(String title) { super.setTitle(title); int index = tabsMenuTabsStart + tabbed.getSelectedIndex(); if (index < tabsMenu.getItemCount()) { JMenuItem item = tabsMenu.getItem(index); if (item != null) item.setText(title); } } private ArrayList<Executer> executingTasks = new ArrayList<Executer>(); /** * Generic Thread that keeps a starting time stamp, sets the priority to * normal and starts itself. */ public abstract class Executer extends ThreadGroup { JTextAreaWriter output, errors; Executer(final JTextAreaWriter output, final JTextAreaWriter errors) { super("Script Editor Run :: " + new Date().toString()); this.output = output; this.errors = errors; // Store itself for later executingTasks.add(this); setTitle(); // Enable kill menu kill.setEnabled(true); // Fork a task, as a part of this ThreadGroup new Thread(this, getName()) { { setPriority(Thread.NORM_PRIORITY); start(); } @Override public void run() { try { execute(); // Wait until any children threads die: int activeCount = getThreadGroup().activeCount(); while (activeCount > 1) { if (isInterrupted()) break; try { Thread.sleep(500); List<Thread> ts = getAllThreads(); activeCount = ts.size(); if (activeCount <= 1) break; log.debug("Waiting for " + ts.size() + " threads to die"); int count_zSelector = 0; for (Thread t : ts) { if (t.getName().equals("zSelector")) { count_zSelector++; } log.debug("THREAD: " + t.getName()); } if (activeCount == count_zSelector + 1) { // Do not wait on the stack slice selector thread. break; } } catch (InterruptedException ie) {} } } catch (Throwable t) { handleException(t); } finally { executingTasks.remove(Executer.this); try { if (null != output) output.shutdown(); if (null != errors) errors.shutdown(); } catch (Exception e) { handleException(e); } // Leave kill menu item enabled if other tasks are running kill.setEnabled(executingTasks.size() > 0); setTitle(); } } }; } /** The method to extend, that will do the actual work. */ abstract void execute(); /** Fetch a list of all threads from all thread subgroups, recursively. */ List<Thread> getAllThreads() { ArrayList<Thread> threads = new ArrayList<Thread>(); // From all subgroups: ThreadGroup[] tgs = new ThreadGroup[activeGroupCount() * 2 + 100]; this.enumerate(tgs, true); for (ThreadGroup tg : tgs) { if (null == tg) continue; Thread[] ts = new Thread[tg.activeCount() * 2 + 100]; tg.enumerate(ts); for (Thread t : ts) { if (null == t) continue; threads.add(t); } } // And from this group: Thread[] ts = new Thread[activeCount() * 2 + 100]; this.enumerate(ts); for (Thread t : ts) { if (null == t) continue; threads.add(t); } return threads; } /** * Totally destroy/stop all threads in this and all recursive thread * subgroups. Will remove itself from the executingTasks list. */ @SuppressWarnings("deprecation") void obliterate() { try { // Stop printing to the screen if (null != output) output.shutdownNow(); if (null != errors) errors.shutdownNow(); } catch (Exception e) { e.printStackTrace(); } for (Thread thread : getAllThreads()) { try { thread.interrupt(); Thread.yield(); // give it a chance thread.stop(); } catch (Throwable t) { t.printStackTrace(); } } executingTasks.remove(this); setTitle(); } @Override public String toString() { return getName(); } } /** Returns a list of currently executing tasks */ public List<Executer> getExecutingTasks() { return executingTasks; } public void kill(Executer executer) { for (int i = 0; i < tabbed.getTabCount(); i++) { Tab tab = (Tab) tabbed.getComponentAt(i); if (executer == tab.executer) { tab.kill(); break; } } } /** * Query the list of running scripts and provide a dialog to choose one and * kill it. */ public void chooseTaskToKill() { if (executingTasks.size() == 0) { error("\nNo running scripts\n"); return; } commandService.run(KillScript.class, true, "editor", this); } /** Run the text in the textArea without compiling it, only if it's not java. */ public void runText() { runText(false); } public void runText(final boolean selectionOnly) { if (isCompiled()) { if (selectionOnly) { error("Cannot run selection of compiled language!"); return; } if (handleUnsavedChanges(true)) runScript(); return; } final ScriptLanguage currentLanguage = getCurrentLanguage(); if (currentLanguage == null) { error("Select a language first!"); // TODO guess the language, if possible. return; } markCompileStart(); try { Tab tab = getTab(); tab.showOutput(); tab.execute(selectionOnly); } catch (Throwable t) { t.printStackTrace(); } } public void runScript() { if (isCompiled()) getTab().showErrors(); else getTab().showOutput(); markCompileStart(); final JTextAreaWriter output = new JTextAreaWriter(getTab().screen, log); final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log); final File file = getEditorPane().file; new TextEditor.Executer(output, errors) { @Override public void execute() { Reader reader = null; try { reader = evalScript(getEditorPane().file.getPath(), new FileReader(file), output, errors); output.flush(); errors.flush(); markCompileEnd(); } catch (Throwable e) { handleException(e); } finally { if (reader != null) { try { reader.close(); } catch (final IOException exc) { handleException(exc); } } } } }; } public void compile() { if (!handleUnsavedChanges(true)) return; final ScriptEngine interpreter = getCurrentLanguage().getScriptEngine(); if (interpreter instanceof JavaEngine) { final JavaEngine java = (JavaEngine) interpreter; final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log); markCompileStart(); getTab().showErrors(); new Thread() { @Override public void run() { java.compile(getEditorPane().file, errors); errorScreen.insert("Compilation finished.\n", errorScreen .getDocument().getLength()); markCompileEnd(); } }.start(); } } public String getSelectedTextOrAsk(String label) { String selection = getTextArea().getSelectedText(); if (selection == null || selection.indexOf('\n') >= 0) { selection = JOptionPane.showInputDialog(this, label + ":", label + "...", JOptionPane.QUESTION_MESSAGE); if (selection == null) return null; } return selection; } public String getSelectedClassNameOrAsk() { String className = getSelectedTextOrAsk("Class name"); if (className != null) className = className.trim(); return className; } protected static void append(JTextArea textArea, String text) { int length = textArea.getDocument().getLength(); textArea.insert(text, length); textArea.setCaretPosition(length); } public void markCompileStart() { errorHandler = null; String started = "Started " + getEditorPane().getFileName() + " at " + new Date() + "\n"; int offset = errorScreen.getDocument().getLength(); append(errorScreen, started); append(getTab().screen, started); compileStartOffset = errorScreen.getDocument().getLength(); try { compileStartPosition = errorScreen.getDocument().createPosition(offset); } catch (BadLocationException e) { handleException(e); } ExceptionHandler.addThread(Thread.currentThread(), this); } public void markCompileEnd() { if (errorHandler == null) { errorHandler = new ErrorHandler(getCurrentLanguage(), errorScreen, compileStartPosition.getOffset()); if (errorHandler.getErrorCount() > 0) getTab().showErrors(); } if (compileStartOffset != errorScreen.getDocument().getLength()) getTab() .showErrors(); if (getTab().showingErrors) { errorHandler.scrollToVisible(compileStartOffset); } } public boolean nextError(boolean forward) { if (errorHandler != null && errorHandler.nextError(forward)) try { File file = new File(errorHandler.getPath()); if (!file.isAbsolute()) file = getFileForBasename(file.getName()); errorHandler.markLine(); switchTo(file, errorHandler.getLine()); getTab().showErrors(); errorScreen.invalidate(); return true; } catch (Exception e) { handleException(e); } return false; } public void switchTo(String path, int lineNumber) throws IOException { switchTo(new File(path).getCanonicalFile(), lineNumber); } public void switchTo(File file, final int lineNumber) { if (!editorPaneContainsFile(getEditorPane(), file)) switchTo(file); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { gotoLine(lineNumber); } catch (BadLocationException e) { // ignore } } }); } public void switchTo(File file) { for (int i = 0; i < tabbed.getTabCount(); i++) if (editorPaneContainsFile(getEditorPane(i), file)) { switchTo(i); return; } open(file); } public void switchTo(int index) { if (index == tabbed.getSelectedIndex()) return; tabbed.setSelectedIndex(index); } protected void switchTabRelative(int delta) { int index = tabbed.getSelectedIndex(); int count = tabbed.getTabCount(); index = ((index + delta) % count); if (index < 0) index += count; switchTo(index); } protected void removeTab(int index) { tabbed.remove(index); index += tabsMenuTabsStart; tabsMenuItems.remove(tabsMenu.getItem(index)); tabsMenu.remove(index); } boolean editorPaneContainsFile(EditorPane editorPane, File file) { try { return file != null && editorPane != null && editorPane.file != null && file.getCanonicalFile().equals(editorPane.file.getCanonicalFile()); } catch (IOException e) { return false; } } public File getFile() { return getEditorPane().file; } public File getFileForBasename(String baseName) { File file = getFile(); if (file != null && file.getName().equals(baseName)) return file; for (int i = 0; i < tabbed.getTabCount(); i++) { file = getEditorPane(i).file; if (file != null && file.getName().equals(baseName)) return file; } return null; } public void addImport(String className) { if (className == null) className = getSelectedClassNameOrAsk(); if (className != null) new TokenFunctions(getTextArea()) .addImport(className.trim()); } public void openHelp(String className) { openHelp(className, true); } public void openHelp(String className, boolean withFrames) { if (className == null) className = getSelectedClassNameOrAsk(); } public void extractSourceJar() { File file = openWithDialog(null); if (file != null) extractSourceJar(file); } public void extractSourceJar(File file) { try { FileFunctions functions = new FileFunctions(this); final File workspace = uiService.chooseFile(new File(System.getProperty("user.home")), FileWidget.DIRECTORY_STYLE); if (workspace == null) return; List<String> paths = functions.extractSourceJar(file.getAbsolutePath(), workspace); for (String path : paths) if (!functions.isBinaryFile(path)) { open(new File(path)); EditorPane pane = getEditorPane(); new TokenFunctions(pane).removeTrailingWhitespace(); if (pane.fileChanged()) save(); } } catch (IOException e) { error("There was a problem opening " + file + ": " + e.getMessage()); } } /* extensionMustMatch == false means extension must not match */ protected File openWithDialog(final File defaultDir) { return uiService.chooseFile(defaultDir, FileWidget.OPEN_STYLE); } /** * Write a message to the output screen * * @param message The text to write */ public void write(String message) { Tab tab = getTab(); if (!message.endsWith("\n")) message += "\n"; tab.screen.insert(message, tab.screen.getDocument().getLength()); } public void writeError(String message) { Tab tab = getTab(); tab.showErrors(); if (!message.endsWith("\n")) message += "\n"; errorScreen.insert(message, errorScreen.getDocument().getLength()); } protected void error(String message) { JOptionPane.showMessageDialog(this, message); } protected void handleException(Throwable e) { handleException(e, errorScreen); getTab().showErrors(); } public static void handleException(Throwable e, JTextArea textArea) { final CharArrayWriter writer = new CharArrayWriter(); PrintWriter out = new PrintWriter(writer); e.printStackTrace(out); for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { out.write("Caused by: "); cause.printStackTrace(out); } out.close(); textArea.append(writer.toString()); } /** * Removes invalid characters, shows a dialog. * * @return The amount of invalid characters found. */ public int zapGremlins() { int count = getEditorPane().zapGremlins(); String msg = count > 0 ? "Zap Gremlins converted " + count + " invalid characters to spaces" : "No invalid characters found!"; JOptionPane.showMessageDialog(this, msg); return count; } // -- Helper methods -- private boolean isCompiled() { final ScriptLanguage language = getCurrentLanguage(); if (language == null) return false; return language.isCompiledLanguage(); } private int getTabSizeSetting() { return prefService.getInt(TAB_SIZE_PREFS, DEFAULT_TAB_SIZE); } private Reader evalScript(final String filename, Reader reader, final Writer output, final Writer errors) throws FileNotFoundException, ModuleException { final ScriptLanguage language = getCurrentLanguage(); if (respectAutoImports) { reader = DefaultAutoImporters.prefixAutoImports(context, language, reader, errors); } // create script module for execution final ScriptInfo info = new ScriptInfo(context, filename, reader); final ScriptModule module = info.createModule(); context.inject(module); // use the currently selected language to execute the script module.setLanguage(language); // map stdout and stderr to the UI module.setOutputWriter(output); module.setErrorWriter(errors); // execute the script try { moduleService.run(module, true).get(); } catch (InterruptedException e) { error("Interrupted"); } catch (ExecutionException e) { log.error(e); } return reader; } @Override public boolean confirmClose() { while (tabbed.getTabCount() > 0) { if (!handleUnsavedChanges()) return false; int index = tabbed.getSelectedIndex(); removeTab(index); } return true; } }
package ch.jodersky.sbt.jni.javah; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; class Utils { public static final int MAX_SUPPORTED_VERSION = 13; public static final List<String> MULTI_RELEASE_VERSIONS = IntStream.rangeClosed(9, MAX_SUPPORTED_VERSION).mapToObj(Integer::toString).collect(Collectors.toList()); public static final Pattern SIMPLE_NAME_PATTERN = Pattern.compile("[^.;\\[/]+"); public static final Pattern FULL_NAME_PATTERN = Pattern.compile("[^.;\\[/]+(\\.[^.;\\[/]+)*"); public static final Pattern METHOD_NAME_PATTERN = Pattern.compile("(<init>)|(<cinit>)|([^.;\\[/<>]+)"); public static final Pattern METHOD_TYPE_PATTERN = Pattern.compile("\\((?<args>(\\[*([BCDFIJSZ]|L[^.;\\[/]+(/[^.;\\\\\\[/]+)*;))*)\\)(?<ret>\\[*([BCDFIJSZV]|L[^.;\\[/]+(/[^.;\\[/]+)*;))"); public static final PrintWriter NOOP_WRITER = new PrintWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); public static String mangleName(String name) { StringBuilder builder = new StringBuilder(name.length() * 2); int len = name.length(); for (int i = 0; i < len; i++) { char ch = name.charAt(i); if (ch == '.') { builder.append('_'); } else if (ch == '$') { builder.append("__"); } else if (ch == '_') { builder.append("_1"); } else if (ch == ';') { builder.append("_2"); } else if (ch == '[') { builder.append("_3"); } else if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && (ch <= 'Z'))) { builder.append(ch); } else { builder.append(String.format("_0%04x", (int) ch)); } } return builder.toString(); } public static String escape(String unicode) { Objects.requireNonNull(unicode); int len = unicode.length(); StringBuilder builder = new StringBuilder(len); for (int i = 0; i < len; i++) { char ch = unicode.charAt(i); if (ch >= ' ' && ch <= '~') { builder.append(ch); } else { builder.append(String.format("\\u%04x", (int) ch)); } } return builder.toString(); } public static Path classPathRoot(Path p) { Objects.requireNonNull(p); p = p.toAbsolutePath(); if (Files.notExists(p)) { return null; } if (Files.isDirectory(p)) { return p; } try { FileSystem fs = FileSystems.newFileSystem(p, (ClassLoader) null); String name = p.getFileName().toString().toLowerCase(); if (name.endsWith(".jar") || name.endsWith(".zip")) { return fs.getPath("/"); } if (name.endsWith(".jmod")) { return fs.getPath("/", "classes"); } fs.close(); } catch (IOException ignored) { return null; } return null; } public static ClassName superClassOf(ClassReader reader) { Objects.requireNonNull(reader); class V extends ClassVisitor { V() { super(Opcodes.ASM6); } ClassName superName = null; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if (superName != null) { this.superName = ClassName.of(superName.replace('/', '.')); } } } V v = new V(); reader.accept(v, ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); return v.superName; } }
package com.facebook.litho; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.util.SimpleArrayMap; import android.view.View; import com.facebook.litho.reference.Reference; import com.facebook.yoga.YogaAlign; import com.facebook.yoga.YogaConstants; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaEdge; import com.facebook.yoga.YogaFlexDirection; import com.facebook.yoga.YogaJustify; import com.facebook.yoga.YogaNode; import com.facebook.yoga.YogaPositionType; import com.facebook.yoga.YogaValue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; /** * A DebugComponent represents a node in Litho's component hierarchy. DebugComponent removes the * need to worry about implementation details of whether a node is represented by a * {@link Component} or a {@link ComponentLayout}. The purpose of this class is for tools such as * Stetho's UI inspector to be able to easily visualize a component hierarchy without worrying about * implementation details of Litho. */ public final class DebugComponent { public interface Overrider { void applyOverrides(DebugComponent node); } private static final SimpleArrayMap<String, DebugComponent> mDebugNodes = new SimpleArrayMap<>(); private String mKey; private WeakReference<InternalNode> mNode; private int mComponentIndex; private Overrider mOverrider; private int mGeneration; private DebugComponent() {} static synchronized DebugComponent getInstance(InternalNode node, int componentIndex) { final String globalKey = createKey(node, componentIndex); DebugComponent debugComponent = mDebugNodes.get(globalKey); if (debugComponent == null) { debugComponent = new DebugComponent(); mDebugNodes.put(globalKey, debugComponent); } debugComponent.mKey = globalKey; debugComponent.mNode = new WeakReference<>(node); debugComponent.mComponentIndex = componentIndex; debugComponent.mGeneration = node.getGeneration(); return debugComponent; } public boolean isValidInstance() { final InternalNode node = mNode.get(); return node != null && node.getGeneration() == mGeneration && mKey.equals(createKey(node, mComponentIndex)); } /** * @return The root {@link DebugComponent} of a LithoView. This should be the start of your * traversal. */ @Nullable public static DebugComponent getRootInstance(LithoView view) { return getRootInstance(view.getComponentTree()); } @Nullable public static DebugComponent getRootInstance(@Nullable ComponentTree componentTree) { final LayoutState layoutState = componentTree == null ? null : componentTree.getMainThreadLayoutState(); final InternalNode root = layoutState == null ? null : layoutState.getLayoutRoot(); if (root != null) { final int outerWrapperComponentIndex = Math.max(0, root.getComponents().size() - 1); return DebugComponent.getInstance(root, outerWrapperComponentIndex); } return null; } /** * @return A conanical name for this component. Suitable to present to the user. */ public String getName() { return getComponentClass().getName(); } /** * @return A simpler canonical name for this component. Suitable to present to the user. */ public String getSimpleName() { final Component component = getComponent(); if (component != null) { return component.getSimpleName(); } return getComponentClass().getSimpleName(); } /** * @return The class of the underlying Component. */ public Class getComponentClass() { final Component component = getComponent(); if (component == null) { final InternalNode node = mNode.get(); final YogaNode yogaNode = node == null ? null : node.mYogaNode; if (yogaNode == null) { // Should not happen :/ return InternalNode.class; } switch (yogaNode.getFlexDirection()) { case COLUMN: return Column.class; case COLUMN_REVERSE: return ColumnReverse.class; case ROW: return Row.class; case ROW_REVERSE: return RowReverse.class; } } return component.getClass(); } public void setOverrider(Overrider overrider) { mOverrider = overrider; } /** * Get the list of components composed by this component. This will not include any {@link View}s * that are mounted by this component as those are not components. * Use {@link this#getMountedView} for that. * * @return A list of child components. */ public List<DebugComponent> getChildComponents() { final InternalNode node = mNode.get(); if (node == null) { return Collections.EMPTY_LIST; } if (mComponentIndex > 0) { final int wrappedComponentIndex = mComponentIndex - 1; return Arrays.asList(getInstance(node, wrappedComponentIndex)); } final ArrayList<DebugComponent> children = new ArrayList<>(); for (int i = 0, count = node.getChildCount(); i < count; i++) { final InternalNode childNode = node.getChildAt(i); final int outerWrapperComponentIndex = Math.max(0, childNode.getComponents().size() - 1); children.add(getInstance(childNode, outerWrapperComponentIndex)); } if (node.hasNestedTree()) { final InternalNode nestedTree = node.getNestedTree(); for (int i = 0, count = nestedTree.getChildCount(); i < count; i++) { final InternalNode childNode = nestedTree.getChildAt(i); children.add(getInstance(childNode, Math.max(0, childNode.getComponents().size() - 1))); } } return children; } /** * @return A mounted view or null if this component does not mount a view. */ @Nullable public View getMountedView() { final InternalNode node = mNode.get(); final Component component = node == null ? null : node.getRootComponent(); if (component != null && Component.isMountViewSpec(component)) { return (View) getMountedContent(); } return null; } /** * @return A mounted drawable or null if this component does not mount a drawable. */ @Nullable public Drawable getMountedDrawable() { final InternalNode node = mNode.get(); final Component component = node == null ? null : node.getRootComponent(); if (component != null && Component.isMountDrawableSpec(component)) { return (Drawable) getMountedContent(); } return null; } /** * @return The litho view hosting this component. */ @Nullable public LithoView getLithoView() { final InternalNode node = mNode.get(); final ComponentContext c = node == null ? null : node.getContext(); final ComponentTree tree = c == null ? null : c.getComponentTree(); return tree == null ? null : tree.getLithoView(); } /** * @return The bounds of this component relative to its hosting {@link LithoView}. */ public Rect getBoundsInLithoView() { final InternalNode node = mNode.get(); if (node == null) { return new Rect(); } final int x = getXFromRoot(node); final int y = getYFromRoot(node); return new Rect(x, y, x + node.getWidth(), y + node.getHeight()); } /** * @return The bounds of this component relative to its parent. */ public Rect getBounds() { final InternalNode node = mNode.get(); if (node == null) { return new Rect(); } final int x = node.getX(); final int y = node.getY(); return new Rect(x, y, x + node.getWidth(), y + node.getHeight()); } /** * @return the {@link ComponentContext} for this component. */ public ComponentContext getContext() { return mNode.get().getContext(); } /** * @return True if this not has layout information attached to it (backed by a Yoga node) */ public boolean isLayoutNode() { final InternalNode node = mNode.get(); return node != null && (node.getComponents().isEmpty() || mComponentIndex == 0); } /** * @return This component's testKey or null if none is set. */ @Nullable public String getTestKey() { return isLayoutNode() ? mNode.get().getTestKey() : null; } /** * @return A concatenated string of all text content within the underlying LithoView. * Null if the node doesn't have an associated LithoView. */ @Nullable public String getTextContent() { final LithoView lithoView = getLithoView(); final Component component = getComponent(); if (lithoView == null || component == null) { return null; } final MountState mountState = lithoView.getMountState(); final StringBuilder sb = new StringBuilder(); for (int i = 0, size = mountState.getItemCount(); i < size; i++) { final MountItem mountItem = mountState.getItemAt(i); final Component<?> mountItemComponent = mountItem == null ? null : mountItem.getComponent(); if (mountItemComponent != null && mountItemComponent.isEquivalentTo(component)) { final Object content = mountItem.getContent(); if (content instanceof TextContent) { for (CharSequence charSequence : ((TextContent) content).getTextItems()) { sb.append(charSequence); } } } } return sb.toString(); } /** * @return The {@link ComponentHost} that wraps this component or null if one cannot be found. */ @Nullable public ComponentHost getComponentHost() { final LithoView lithoView = getLithoView(); final Component component = getComponent(); if (lithoView == null || component == null) { return null; } for (int i = 0, size = lithoView.getMountState().getItemCount(); i < size; i++) { final MountItem mountItem = lithoView.getMountState().getItemAt(i); final Component<?> mountItemComponent = mountItem == null ? null : mountItem.getComponent(); if (mountItemComponent != null && mountItemComponent.isEquivalentTo(component)) { return mountItem.getHost(); } } return null; } /** * @return This component's key or null if none is set. */ @Nullable public String getKey() { final InternalNode node = mNode.get(); if (node != null && !node.getComponents().isEmpty()) { final Component component = node.getComponents().get(mComponentIndex); return component == null ? null : component.getKey(); } return null; } /** * @return The Component instance this debug component wraps. */ @Nullable public Component getComponent() { final InternalNode node = mNode.get(); if (node == null || node.getComponents().isEmpty()) { return null; } return node.getComponents().get(mComponentIndex); } /** * @return The Yoga node asscociated with this debug component. May be null. */ @Nullable public YogaNode getYogaNode() { final InternalNode node = mNode.get(); if (node == null || !isLayoutNode()) { return null; } return node.mYogaNode; } /** * @return The foreground drawable asscociated with this debug component. May be null. */ @Nullable public Drawable getForeground() { final InternalNode node = mNode.get(); if (node == null || !isLayoutNode()) { return null; } return node.getForeground(); } /** * @return The background drawable asscociated with this debug component. May be null. */ @Nullable public Reference<? extends Drawable> getBackground() { final InternalNode node = mNode.get(); if (node == null || !isLayoutNode()) { return null; } return node.getBackground(); } /** * @return The int value of the importantForAccessibility property on this debug component. */ @Nullable public Integer getImportantForAccessibility() { final InternalNode node = mNode.get(); return node == null ? null : node.getImportantForAccessibility(); } /** * @return The boolean value of the focusable property on this debug component. */ public boolean getFocusable() { final NodeInfo nodeInfo = mNode.get().getNodeInfo(); if (nodeInfo != null) { return nodeInfo.getFocusState() == NodeInfo.FOCUS_SET_TRUE; } return false; } /** * @return The content description CharSequence on this debug component. May be null. */ @Nullable public CharSequence getContentDescription() { final NodeInfo nodeInfo = mNode.get().getNodeInfo(); if (nodeInfo != null) { return mNode.get().getNodeInfo().getContentDescription(); } return null; } public void rerender() { final LithoView lithoView = getLithoView(); if (lithoView != null) { lithoView.forceRelayout(); } } public void setBackgroundColor(int color) { mNode.get().backgroundColor(color); } public void setForegroundColor(int color) { mNode.get().foregroundColor(color); } public void setLayoutDirection(YogaDirection yogaDirection) { mNode.get().layoutDirection(yogaDirection); } public void setFlexDirection(YogaFlexDirection direction) { mNode.get().flexDirection(direction); } public void setJustifyContent(YogaJustify yogaJustify) { mNode.get().justifyContent(yogaJustify); } public void setAlignItems(YogaAlign yogaAlign) { mNode.get().alignItems(yogaAlign); } public void setAlignSelf(YogaAlign yogaAlign) { mNode.get().alignSelf(yogaAlign); } public void setAlignContent(YogaAlign yogaAlign) { mNode.get().alignContent(yogaAlign); } public void setPositionType(YogaPositionType yogaPositionType) { mNode.get().positionType(yogaPositionType); } public void setFlexGrow(float value) { mNode.get().flexGrow(value); } public void setFlexShrink(float value) { mNode.get().flexShrink(value); } public void setFlexBasis(YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().flexBasisAuto(); break; case PERCENT: mNode.get().flexBasisPercent(value.value); break; case POINT: mNode.get().flexBasisPx((int) value.value); break; } } public void setWidth(YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().widthAuto(); break; case PERCENT: mNode.get().widthPercent(value.value); break; case POINT: mNode.get().widthPx((int) value.value); break; } } public void setMinWidth(YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().minWidthPx(Integer.MIN_VALUE); break; case PERCENT: mNode.get().minWidthPercent(value.value); break; case POINT: mNode.get().minWidthPx((int) value.value); break; } } public void setMaxWidth(YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().maxWidthPx(Integer.MAX_VALUE); break; case PERCENT: mNode.get().maxWidthPercent(value.value); break; case POINT: mNode.get().maxWidthPx((int) value.value); break; } } public void setHeight(YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().heightAuto(); break; case PERCENT: mNode.get().heightPercent(value.value); break; case POINT: mNode.get().heightPx((int) value.value); break; } } public void setMinHeight(YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().minHeightPx(Integer.MIN_VALUE); break; case PERCENT: mNode.get().minHeightPercent(value.value); break; case POINT: mNode.get().minHeightPx((int) value.value); break; } } public void setMaxHeight(YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().maxHeightPx(Integer.MAX_VALUE); break; case PERCENT: mNode.get().maxHeightPercent(value.value); break; case POINT: mNode.get().maxHeightPx((int) value.value); break; } } public void setAspectRatio(float aspectRatio) { mNode.get().aspectRatio(aspectRatio); } public void setMargin(YogaEdge edge, YogaValue value) { switch (value.unit) { case UNDEFINED: mNode.get().marginPx(edge, 0); break; case AUTO: mNode.get().marginAuto(edge); break; case PERCENT: mNode.get().marginPercent(edge, value.value); break; case POINT: mNode.get().marginPx(edge, (int) value.value); break; } } public void setPadding(YogaEdge edge, YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().paddingPx(edge, 0); break; case PERCENT: mNode.get().paddingPercent(edge, value.value); break; case POINT: mNode.get().paddingPx(edge, (int) value.value); break; } } public void setPosition(YogaEdge edge, YogaValue value) { switch (value.unit) { case UNDEFINED: case AUTO: mNode.get().positionPercent(edge, YogaConstants.UNDEFINED); break; case PERCENT: mNode.get().positionPercent(edge, value.value); break; case POINT: mNode.get().positionPx(edge, (int) value.value); break; } } public void setBorderWidth(YogaEdge edge, float value) { mNode.get().setBorderWidth(edge, (int) value); } public void setContentDescription(CharSequence contentDescription) { mNode.get().contentDescription(contentDescription); } public void setImportantForAccessibility(int importantForAccessibility) { mNode.get().importantForAccessibility(importantForAccessibility); } public void setFocusable(boolean focusable) { mNode.get().focusable(focusable); } @Nullable public ComponentLifecycle.StateContainer getStateContainer() { final Component component = getComponent(); return component == null ? null : component.getStateContainer(); } void applyOverrides() { final InternalNode node = mNode.get(); if (node != null && mOverrider != null) { mOverrider.applyOverrides(this); } } private InternalNode parent(InternalNode node) { final InternalNode parent = node.getParent(); return parent != null ? parent : node.getNestedTreeHolder(); } private int getXFromRoot(InternalNode node) { if (node == null) { return 0; } return node.getX() + getXFromRoot(parent(node)); } private int getYFromRoot(InternalNode node) { if (node == null) { return 0; } return node.getY() + getYFromRoot(parent(node)); } private static String createKey(InternalNode node, int componentIndex) { final InternalNode parent = node.getParent(); final InternalNode nestedTreeHolder = node.getNestedTreeHolder(); String key; if (parent != null) { key = createKey(parent, 0) + "." + parent.getChildIndex(node); } else if (nestedTreeHolder != null) { key = createKey(nestedTreeHolder, 0) + ".nested"; } else { final ComponentContext c = node.getContext(); final ComponentTree tree = c == null ? null : c.getComponentTree(); key = Integer.toString(System.identityHashCode(tree)); } return key + "(" + componentIndex + ")"; } public String getId() { return mKey; } @Nullable public EventHandler getClickHandler() { if (mComponentIndex > 0) { return null; } final InternalNode node = mNode.get(); if (node == null) { return null; } return node.getClickHandler(); } @Nullable private Object getMountedContent() { if (mComponentIndex > 0) { return null; } final InternalNode node = mNode.get(); final ComponentContext context = node == null ? null : node.getContext(); final ComponentTree tree = context == null ? null : context.getComponentTree(); final LithoView view = tree == null ? null : tree.getLithoView(); final MountState mountState = view == null ? null : view.getMountState(); if (mountState != null) { for (int i = 0, count = mountState.getItemCount(); i < count; i++) { final MountItem mountItem = mountState.getItemAt(i); final Component component = mountItem == null ? null : mountItem.getComponent(); if (component != null && component == node.getRootComponent()) { return mountItem.getContent(); } } } return null; } }
package com.intellij.cvsSupport2; import com.intellij.cvsSupport2.application.CvsEntriesManager; import com.intellij.cvsSupport2.application.CvsInfo; import com.intellij.cvsSupport2.connections.CvsConnectionSettings; import com.intellij.cvsSupport2.connections.CvsRootParser; import com.intellij.cvsSupport2.cvsstatuses.CvsStatusProvider; import com.intellij.cvsSupport2.util.CvsFileUtil; import com.intellij.cvsSupport2.util.CvsVfsUtil; import com.intellij.cvsSupport2.config.CvsApplicationLevelConfiguration; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.CvsBundle; import org.netbeans.lib.cvsclient.admin.Entries; import org.netbeans.lib.cvsclient.admin.EntriesHandler; import org.netbeans.lib.cvsclient.admin.Entry; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.*; public class CvsUtil { private final static SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(Entry.getLastModifiedDateFormatter().toPattern(), Locale.US); static { //noinspection HardCodedStringLiteral DATE_FORMATTER.setTimeZone(TimeZone.getTimeZone("GMT+0000")); } @NonNls public static final String CVS_IGNORE_FILE = ".cvsignore"; @NonNls public static final String CVS_ROOT_FILE = "Root"; private static final Logger LOG = Logger.getInstance("#com.intellij.cvsSupport2.CvsUtil"); @NonNls private static final String REPOSITORY = "Repository"; @NonNls private static final String TAG = "Tag"; @NonNls public static final String CVS = "CVS"; @NonNls public static final String ENTRIES = "Entries"; @NonNls private static final String CONFLICTS = "Conflicts"; @NonNls private static final String STICKY_DATE_PREFIX = "D"; @NonNls private static final String TEMPLATE = "Template"; @NonNls private static final String STICKY_BRANCH_TAG_PREFIX = "T"; @NonNls private static final String STICKY_NON_BRANCH_TAG_PREFIX = "N"; @NonNls public static final String HEAD = "HEAD"; @NonNls public static final String BASE = "Base"; public static void skip(InputStream inputStream, int length) throws IOException { int skipped = 0; while (skipped < length) { skipped += inputStream.skip(length - skipped); } } public static String getModuleName(VirtualFile file) { if (file.isDirectory()) { return CvsEntriesManager.getInstance().getRepositoryFor(file); } else { return CvsEntriesManager.getInstance().getRepositoryFor(file.getParent()) + "/" + file.getName(); } } public static boolean fileIsUnderCvs(VirtualFile vFile) { return fileIsUnderCvs(CvsVfsUtil.getFileFor(vFile)); } public static boolean fileIsUnderCvs(File ioFile) { try { if (ioFile.isDirectory()) { return directoryIsUnderCVS(ioFile); } return fileIsUnderCvs(getEntryFor(ioFile)); } catch (Exception e1) { return false; } } private static boolean directoryIsUnderCVS(File directory) { if (!getAdminDir(directory).isDirectory()) return false; if (!getFileInTheAdminDir(directory, ENTRIES).isFile()) return false; if (!getFileInTheAdminDir(directory, CVS_ROOT_FILE).isFile()) return false; if (!getFileInTheAdminDir(directory, REPOSITORY).isFile()) return false; return true; } public static Entry getEntryFor(VirtualFile file) { return CvsEntriesManager.getInstance().getEntryFor(CvsVfsUtil.getParentFor(file), file.getName()); } public static Entry getEntryFor(File ioFile) { File parentFile = ioFile.getParentFile(); if (parentFile == null) return null; return CvsEntriesManager.getInstance().getEntryFor(CvsVfsUtil.findFileByIoFile(parentFile), ioFile.getName()); } private static boolean fileIsUnderCvs(Entry entry) { return entry != null; } public static boolean filesAreUnderCvs(File[] selectedFiles) { return allSatisfy(selectedFiles, fileIsUnderCvsCondition()); } public static boolean filesArentUnderCvs(File[] selectedFiles) { return !anySatisfy(selectedFiles, fileIsUnderCvsCondition()); } private static FileCondition fileIsUnderCvsCondition() { return new FileCondition() { public boolean verify(File file) { return fileIsUnderCvs(file); } }; } private static boolean allSatisfy(File[] files, FileCondition condition) { for (File file : files) { if (!condition.verify(file)) return false; } return true; } private static boolean anySatisfy(File[] files, FileCondition condition) { return !allSatisfy(files, new ReverseFileCondition(condition)); } public static boolean filesHaveParentUnderCvs(File[] files) { return allSatisfy(files, new FileCondition() { public boolean verify(File file) { return fileHasParentUnderCvs(file); } }); } private static boolean fileHasParentUnderCvs(File file) { return fileIsUnderCvs(file.getParentFile()); } public static boolean fileIsLocallyAdded(File file) { Entry entry = getEntryFor(file); return entry == null ? false : entry.isAddedFile(); } public static boolean fileIsLocallyDeleted(File file) { Entry entry = getEntryFor(file); return entry == null ? false : entry.isRemoved(); } public static boolean fileIsLocallyAdded(VirtualFile file) { return fileIsLocallyAdded(CvsVfsUtil.getFileFor(file)); } public static Entries getEntriesIn(File dir) { return getEntriesHandlerIn(dir).getEntries(); } private static EntriesHandler getEntriesHandlerIn(final File dir) { EntriesHandler entriesHandler = new EntriesHandler(dir); try { entriesHandler.read(CvsApplicationLevelConfiguration.getCharset()); return entriesHandler; } catch (Exception ex) { final String entries = loadFrom(dir, ENTRIES, true); if (entries != null) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { final String entriesFileRelativePath = CVS + File.separatorChar + ENTRIES; Messages.showErrorDialog(CvsBundle.message("message.error.invalid.entries", entriesFileRelativePath, dir.getAbsolutePath(), entries), CvsBundle.message("message.error.invalid.entries.title")); } }); } return entriesHandler; } } public static void removeEntryFor(File file) { File entriesFile = file.getParentFile(); EntriesHandler handler = new EntriesHandler(entriesFile); String charset = CvsApplicationLevelConfiguration.getCharset(); try { handler.read(charset); } catch (IOException e) { return; } Entries entries = handler.getEntries(); entries.removeEntry(file.getName()); try { handler.write(getLineSeparator(), charset); } catch (IOException e) { LOG.error(e); } CvsEntriesManager.getInstance().removeEntryForFile(file.getParentFile(), file.getName()); } private static String getLineSeparator() { return CodeStyleSettingsManager.getInstance().getCurrentSettings().getLineSeparator(); } public static boolean fileIsLocallyRemoved(File file) { Entry entry = getEntryFor(file); if (entry == null) return false; return entry.isRemoved(); } public static boolean fileIsLocallyRemoved(VirtualFile file) { return fileIsLocallyRemoved(CvsVfsUtil.getFileFor(file)); } public static String formatDate(Date date) { return DATE_FORMATTER.format(date); } public static void saveEntryForFile(File file, Entry entry) throws IOException { EntriesHandler entriesHandler = new EntriesHandler(file.getParentFile()); entriesHandler.read(CvsApplicationLevelConfiguration.getCharset()); entriesHandler.getEntries().addEntry(entry); entriesHandler.write(getLineSeparator(), CvsApplicationLevelConfiguration.getCharset()); } public static String loadRepositoryFrom(File file) { return loadFrom(file, REPOSITORY, true); } public static String loadRootFrom(File file) { return loadFrom(file, CVS_ROOT_FILE, true); } private static String loadFrom(File directory, String fileName, boolean trimContent) { if (directory == null) return null; File file = getFileInTheAdminDir(directory, fileName); if (!file.isFile()) return null; try { String result = new String(FileUtil.loadFileText(file)); if (trimContent) { return result.trim(); } else { return result; } } catch (IOException e) { return null; } } private static File getFileInTheAdminDir(File file, String fileName) { return new File(getAdminDir(file), fileName); } private static File getAdminDir(File file) { return new File(file, CVS); } public static String getStickyDateForDirectory(VirtualFile parentFile) { File file = CvsVfsUtil.getFileFor(parentFile); String tag = loadStickyTagFrom(file); if (tag == null) return null; if (tag.startsWith(STICKY_DATE_PREFIX)) { return tag.substring(STICKY_DATE_PREFIX.length()); } if (tag.startsWith(STICKY_BRANCH_TAG_PREFIX)) { return tag.substring(STICKY_BRANCH_TAG_PREFIX.length()); } return tag; } public static String loadStickyTagFrom(File file) { return loadFrom(file, TAG, true); } public static String getStickyTagForDirectory(VirtualFile parentFile) { String tag = loadFrom(CvsVfsUtil.getFileFor(parentFile), TAG, true); if (tag == null) return null; if (tag.length() == 0) return null; if (tag.startsWith(STICKY_DATE_PREFIX)) return null; if (tag.startsWith(STICKY_BRANCH_TAG_PREFIX)) return tag.substring(1); if (tag.startsWith(STICKY_NON_BRANCH_TAG_PREFIX)) return tag.substring(1); return null; } public static void ignoreFile(final VirtualFile file) throws IOException { VirtualFile directory = CvsVfsUtil.getParentFor(file); File cvsignoreFile = cvsignoreFileFor(CvsVfsUtil.getPathFor(directory)); CvsFileUtil.appendLineToFile(file.getName(), cvsignoreFile); CvsEntriesManager.getInstance().clearChachedFiltersFor(directory); } public static File cvsignoreFileFor(String path) { return new File(new File(path), CVS_IGNORE_FILE); } public static File cvsignoreFileFor(File file) { return new File(file, CVS_IGNORE_FILE); } public static void addConflict(File file) { File conflictsFile = getConflictsFile(file); try { Conflicts conflicts = Conflicts.readFrom(conflictsFile); conflicts.addConflictForFile(file.getName()); conflicts.saveTo(conflictsFile); } catch (IOException e) { LOG.error(e); } } private static File getConflictsFile(File file) { return getFileInTheAdminDir(file.getParentFile(), CONFLICTS); } public static void removeConflict(File file) { File conflictsFile = getConflictsFile(file); if (!conflictsFile.exists()) return; try { Conflicts conflicts = Conflicts.readFrom(conflictsFile); conflicts.removeConflictForFile(file.getName()); conflicts.saveTo(conflictsFile); } catch (IOException e) { LOG.error(e); } } public static boolean isLocallyRemoved(File file) { Entry entry = getEntryFor(file); if (entry == null) return false; return entry.isRemoved(); } public static String getRevisionFor(File file) { final Entry entry = getEntryFor(file); if (entry == null) return null; return entry.getRevision(); } public static boolean filesExistInCvs(File[] files) { return allSatisfy(files, new FileCondition() { public boolean verify(File file) { return fileIsUnderCvs(file) && !fileIsLocallyAdded(file); } }); } public static boolean filesAreNotDeleted(File[] files) { return allSatisfy(files, new FileCondition() { public boolean verify(File file) { return fileIsUnderCvs(file) && !fileIsLocallyAdded(file) && !fileIsLocallyDeleted(file); } }); } public static void saveRevisionForMergedFile(VirtualFile parent, final Entry previousEntry, List<String> revisions) { LOG.assertTrue(parent != null); LOG.assertTrue(previousEntry != null); File conflictsFile = getConflictsFile(new File(CvsVfsUtil.getFileFor(parent), previousEntry.getFileName())); try { Conflicts conflicts = Conflicts.readFrom(conflictsFile); LOG.assertTrue(conflicts != null); Date lastModified = previousEntry.getLastModified(); conflicts.setRevisionAndDateForFile(previousEntry.getFileName(), previousEntry.getRevision(), revisions, lastModified == null ? new Date().getTime() : lastModified.getTime()); conflicts.saveTo(conflictsFile); } catch (IOException e) { LOG.error(e); } } public static byte[] getStoredContentForFile(VirtualFile file, final String originalRevision) { File ioFile = CvsVfsUtil.getFileFor(file); try { File storedRevisionFile = new File(ioFile.getParentFile(), ".#" + ioFile.getName() + "." + originalRevision); if (!storedRevisionFile.isFile()) return null; return FileUtil.loadFileBytes(storedRevisionFile); } catch (IOException e) { LOG.error(e); return null; } } public static byte[] getStoredContentForFile(VirtualFile file) { File ioFile = CvsVfsUtil.getFileFor(file); try { File storedRevisionFile = new File(ioFile.getParentFile(), ".#" + ioFile.getName() + "." + getAllRevisionsForFile(file).get(0)); if (!storedRevisionFile.isFile()) return null; return FileUtil.loadFileBytes(storedRevisionFile); } catch (IOException e) { LOG.error(e); return null; } } public static long getUpToDateDateForFile(VirtualFile file) { try { return Conflicts.readFrom(getConflictsFile(CvsVfsUtil.getFileFor(file))).getPreviousEntryTime(file.getName()); } catch (IOException e) { LOG.error(e); return -1; } } public static void resolveConflict(VirtualFile vFile) { File file = CvsVfsUtil.getFileFor(vFile); removeConflict(file); EntriesHandler handler = getEntriesHandlerIn(file.getParentFile()); Entries entries = handler.getEntries(); Entry entry = entries.getEntry(file.getName()); if (entry == null) return; long timeStamp = vFile.getTimeStamp(); final Date date = CvsStatusProvider.createDateDiffersTo(timeStamp); entry.parseConflictString(Entry.getLastModifiedDateFormatter().format(date)); entries.addEntry(entry); try { handler.write(getLineSeparator(), CvsApplicationLevelConfiguration.getCharset()); } catch (IOException e) { LOG.error(e); } } public static String getTemplateFor(FilePath file) { return loadFrom(file.isDirectory() ? file.getIOFile().getParentFile() : file.getIOFile(), TEMPLATE, false); } public static String getRepositoryFor(File file) { String result = loadRepositoryFrom(file); if (result == null) return null; String root = loadRootFrom(file); if (root != null) { final CvsRootParser cvsRootParser = CvsRootParser.valueOf(root, false); String serverRoot = cvsRootParser.REPOSITORY; if (serverRoot != null) { result = getRelativeRepositoryPath(result, serverRoot); } } return result; } public static String getRelativeRepositoryPath(String repository, String serverRoot) { repository = repository.replace(File.separatorChar, '/'); serverRoot = serverRoot.replace(File.separatorChar, '/'); if (repository.startsWith(serverRoot)) { repository = repository.substring(serverRoot.length()); if (repository.startsWith("/")) { repository = repository.substring(1); } } if (repository.startsWith("./")) { repository = repository.substring(2); } return repository; } public static File getCvsLightweightFileForFile(File file) { return new File(getRepositoryFor(file.getParentFile()), file.getName()); } public static List<String> getAllRevisionsForFile(VirtualFile file) { try { return Conflicts.readFrom(getConflictsFile(CvsVfsUtil.getFileFor(file))).getRevisionsFor(file.getName()); } catch (IOException e) { LOG.error(e); return null; } } public static void restoreFile(final VirtualFile file) { CvsEntriesManager cvsEntriesManager = CvsEntriesManager.getInstance(); VirtualFile directory = CvsVfsUtil.getParentFor(file); LOG.assertTrue(directory != null); CvsInfo cvsInfo = cvsEntriesManager.getCvsInfoFor(directory); Entry entry = cvsInfo.getEntryNamed(file.getName()); LOG.assertTrue(entry != null); String revision = entry.getRevision(); LOG.assertTrue(StringUtil.startsWithChar(revision, '-')); String originalRevision = revision.substring(1); String date = Entry.formatLastModifiedDate(CvsStatusProvider.createDateDiffersTo(file.getTimeStamp())); String kwdSubstitution = entry.getOptions() == null ? "" : entry.getOptions(); String stickyDataString = entry.getStickyData(); Entry newEntry = Entry.createEntryForLine("/" + file.getName() + "/" + originalRevision + "/" + date + "/" + kwdSubstitution + "/" + stickyDataString); try { saveEntryForFile(CvsVfsUtil.getFileFor(file), newEntry); cvsEntriesManager.clearCachedEntriesFor(directory); } catch (final IOException e) { SwingUtilities.invokeLater(new Runnable() { public void run() { Messages.showErrorDialog(CvsBundle.message("message.error.restore.entry", file.getPresentableUrl(), e.getLocalizedMessage()), CvsBundle.message("message.error.restore.entry.title")); } }); } } public static boolean fileExistsInCvs(VirtualFile file) { Entry entry = CvsEntriesManager.getInstance().getEntryFor(file); if (entry == null) return false; return !entry.isAddedFile(); } public static boolean fileExistsInCvs(FilePath file) { if (file.isDirectory() && new File(file.getIOFile(), CVS).isDirectory()) return true; Entry entry = CvsEntriesManager.getInstance().getEntryFor(file.getVirtualFileParent(), file.getName()); if (entry == null) return false; return !entry.isAddedFile(); } public static String getOriginalRevisionForFile(VirtualFile file) { try { return Conflicts.readFrom(getConflictsFile(CvsVfsUtil.getFileFor(file))).getOriginalRevisionFor(file.getName()); } catch (IOException e) { LOG.error(e); return null; } } public static boolean storedVersionExists(final String original, final VirtualFile file) { File ioFile = CvsVfsUtil.getFileFor(file); File storedRevisionFile = new File(ioFile.getParentFile(), ".#" + ioFile.getName() + "." + original); return storedRevisionFile.isFile(); } private static interface FileCondition { boolean verify(File file); } private static class ReverseFileCondition implements FileCondition { private final FileCondition myCondition; public ReverseFileCondition(FileCondition condition) { myCondition = condition; } public boolean verify(File file) { return !myCondition.verify(file); } } private static class Conflict { private String myName; private List<String> myRevisions; private long myPreviousTime; private static final String DELIM = ";"; private Conflict(String name, String originalRevision, List<String> revisions, long time) { myName = name; myRevisions = new ArrayList<String>(); myRevisions.add(originalRevision); myRevisions.addAll(revisions); myPreviousTime = time; } private Conflict(String name, List<String> revisions, long time) { myName = name; myRevisions = new ArrayList<String>(); myRevisions.addAll(revisions); myPreviousTime = time; } public String toString() { StringBuffer result = new StringBuffer(); result.append(myName); result.append(DELIM); result.append(String.valueOf(myPreviousTime)); result.append(DELIM); for (int i = 0; i < myRevisions.size(); i++) { if (i > 0) { result.append(DELIM); } result.append(myRevisions.get(i)); } return result.toString(); } public static Conflict readFrom(String line) { try { String[] strings = line.split(DELIM); if (strings.length == 0) return null; String name = strings[0]; long time = strings.length > 1 ? Long.parseLong(strings[1]) : -1; int revisionsSize = strings.length > 2 ? strings.length - 2 : 0; String[] revisions = new String[revisionsSize]; System.arraycopy(strings, 2, revisions, 0, revisions.length); return new Conflict(name, Arrays.asList(revisions), time); } catch (NumberFormatException e) { return null; } } public String getFileName() { return myName; } public long getPreviousEntryTime() { return myPreviousTime; } public List<String> getRevisions() { return new ArrayList<String>(myRevisions); } public void setOriginalRevision(final String originalRevision) { if (!myRevisions.isEmpty()) myRevisions.remove(0); myRevisions.add(0, originalRevision); } public void setRevisions(final List<String> revisions) { if (myRevisions.isEmpty()) { } else { final String originalRevision = myRevisions.remove(0); myRevisions.clear(); myRevisions.add(originalRevision); myRevisions.addAll(revisions); } } } private static class Conflicts { private final Map<String, Conflict> myNameToConflict = new com.intellij.util.containers.HashMap<String, Conflict>(); public static Conflicts readFrom(File file) throws IOException { Conflicts result = new Conflicts(); if (!file.exists()) return result; List lines = CvsFileUtil.readLinesFrom(file); for (final Object line1 : lines) { String line = (String)line1; Conflict conflict = Conflict.readFrom(line); if (conflict != null) { result.addConflict(conflict); } } return result; } public void saveTo(File file) throws IOException { CvsFileUtil.storeLines(getConflictLines(), file); } private List getConflictLines() { ArrayList<String> result = new ArrayList<String>(); for (final Conflict conflict : myNameToConflict.values()) { result.add((conflict).toString()); } return result; } private void addConflict(Conflict conflict) { myNameToConflict.put(conflict.getFileName(), conflict); } public void setRevisionAndDateForFile(String fileName, String originalRevision, List<String> revisions, long time) { if (!myNameToConflict.containsKey(fileName)) { myNameToConflict.put(fileName, new Conflict(fileName, originalRevision, revisions, time)); } myNameToConflict.get(fileName).setOriginalRevision(originalRevision); myNameToConflict.get(fileName).setRevisions(revisions); } public void addConflictForFile(String name) { if (!myNameToConflict.containsKey(name)) { myNameToConflict.put(name, new Conflict(name, "", new ArrayList<String>(), -1)); } } public void removeConflictForFile(String name) { myNameToConflict.remove(name); } public List<String> getRevisionsFor(String name) { if (!myNameToConflict.containsKey(name)) return new ArrayList<String>(); return (myNameToConflict.get(name)).getRevisions(); } public long getPreviousEntryTime(String fileName) { if (!myNameToConflict.containsKey(fileName)) return -1; return (myNameToConflict.get(fileName)).getPreviousEntryTime(); } public String getOriginalRevisionFor(final String name) { if (!myNameToConflict.containsKey(name)) return ""; final List<String> revisions = (myNameToConflict.get(name)).getRevisions(); return revisions.isEmpty() ? "" : revisions.get(0); } } public static CvsConnectionSettings getCvsConnectionSettings(FilePath path){ VirtualFile virtualFile = path.getVirtualFile(); if (virtualFile == null || !path.isDirectory()){ return CvsEntriesManager.getInstance().getCvsConnectionSettingsFor(path.getVirtualFileParent()); } else { return CvsEntriesManager.getInstance().getCvsConnectionSettingsFor(virtualFile); } } }
package com.test.logging.logback; import org.junit.After; import org.junit.Before; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import com.test.logging.common.LoggingTest; import com.test.logging.common.ProfilerOptions; import com.test.logging.common.TestFactoryType; import static com.test.logging.common.Util.sleepForIOCatchup; /** Logback logger test */ public class LogbackTest { /** Profiler options */ private static final ProfilerOptions opts = new ProfilerOptions("Logback Profiler"); /** Different types of tests */ private static final TestFactoryType[] allTypes = TestFactory.getSupportedTypes(); @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { // Stopping the logger context to force flushing the log events LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.stop(); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testSyncFileLogger() { // Synchronous file logger System.out.println("((((((((((((( SYNC FILE LOGGER ))))))))))))))))"); Logger logger = LoggerFactory.getLogger("SyncFileLogger"); // Iterate through all unit work types and execute test scenarios for (TestFactoryType t : allTypes) { new LoggingTest<Logger>(t.toString() + "-Sync", new TestFactory(t, logger), opts).run(); } } @Test public void testAsyncFileLogger() { // Asynchronous file logger System.out.println("((((((((((((( ASYNC FILE LOGGER ))))))))))))))))"); Logger asyncLogger = LoggerFactory.getLogger("AsyncFileLogger"); // Iterate through all unit work types and execute test scenarios for (TestFactoryType t : allTypes) { new LoggingTest<Logger>(t.toString() + "-Async", new TestFactory(t, asyncLogger), opts).run(); } sleepForIOCatchup(); } }
package net.new_liberty.pvpranker; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import net.milkbowl.vault.chat.Chat; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.plugin.RegisteredServiceProvider; /** * PvPRanker listener */ public class PvPListener implements Listener { private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MMMM d, yyyy hh:mm aaa"); private final PvPRanker plugin; private Chat chat; public PvPListener(PvPRanker plugin) { this.plugin = plugin; } public boolean setupChat() { RegisteredServiceProvider<Chat> chatProvider = plugin.getServer().getServicesManager().getRegistration(Chat.class); if (chatProvider != null) { chat = chatProvider.getProvider(); } return (chat != null); } @EventHandler public void onAsyncPlayerChat(AsyncPlayerChatEvent event) { Player p = event.getPlayer(); String fprefix = "[{factions_relcolor}" + ChatColor.BOLD + "{factions_roleprefix}" + ChatColor.RESET + "{factions_relcolor}{factions_name}" + ChatColor.WHITE + "]"; String rank = ChatColor.WHITE + "{" + plugin.getPvPer(p.getName()).getRank(plugin.getMilestone()).getName() + ChatColor.WHITE + "}"; if (p.hasPermission("pvpranker.hiderank")) { rank = ""; } String prefix = ChatColor.translateAlternateColorCodes('&', chat.getPlayerPrefix(p)); String suffix = ChatColor.translateAlternateColorCodes('&', chat.getPlayerSuffix(p)); String format = fprefix + rank + prefix + " " + p.getName() + ": " + suffix + "%2$s"; event.setFormat(format); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); if (player.getHealth() > 0) { return; } if (!(player.getLastDamageCause() instanceof EntityDamageByEntityEvent)) { return; } Entity cause = ((EntityDamageByEntityEvent) player.getLastDamageCause()).getDamager(); if (!(cause instanceof Player)) { return; } Player killer = (Player) cause; final Location loc = player.getLocation(); // Skull handling double chance = plugin.getConfig().getDouble("head-drop-chance", 0.1); if (chance > Math.random()) { ItemStack skull = new ItemStack(Material.SKULL_ITEM); SkullMeta sm = (SkullMeta) skull.getItemMeta(); sm.setOwner(player.getName()); sm.setLore(Arrays.asList(ChatColor.RESET.toString() + ChatColor.WHITE + "Killed by " + ChatColor.AQUA + killer.getName() + ChatColor.WHITE + " on " + ChatColor.YELLOW + DATE_FORMAT.format(new Date()))); skull.setItemMeta(sm); loc.getWorld().dropItemNaturally(loc, skull); } // Our closure final String killedName = player.getName(); final String killerName = killer.getName(); (new KillUpdateTask(plugin, loc, killerName, killedName)).runTaskAsynchronously(plugin); } }
package org.jetbrains.idea.devkit.dom; import com.intellij.spellchecker.xml.NoSpellchecking; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.GenericAttributeValue; import com.intellij.util.xml.Required; import org.jetbrains.annotations.NotNull; public interface ProductDescriptor extends DomElement { @NotNull @Required @NoSpellchecking GenericAttributeValue<String> getCode(); @NotNull @Required GenericAttributeValue<String> getReleaseDate(); @NotNull @Required GenericAttributeValue<Integer> getReleaseVersion(); }
package net.probossgamers.turtlemod; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EnumCreatureType; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.util.EnumHelper; import net.probossgamers.turtlemod.entity.monster.EntityMineTurtle; import net.probossgamers.turtlemod.entity.monster.EntityZombieTurtle; import net.probossgamers.turtlemod.entity.passive.EntityTurtle; import net.probossgamers.turtlemod.item.ItemTurtleArmor; import net.probossgamers.turtlemod.item.ItemTurtleShell; import net.probossgamers.turtlemod.server.ServerProxy; @Mod( modid = TurtleMod.MODID, name = "Turtle Mod", version = TurtleMod.VERSION ) public class TurtleMod { public static final String MODID = "turtlemod"; public static final String VERSION = "Alpha 5.0"; public static CreativeTabs turtleTab; public static int turtleShellid; public static int turtleHelmetid; public static int turtleChestplateid; public static int turtleLeggingsid; public static int turtleBootsid; public Item turtleLeather; public static Item turtleShell; public static Item turtleHelmet; public static Item turtleChestplate; public static Item turtleLeggings; public static Item turtleBoots; public ItemArmor.ArmorMaterial turtleMaterial = EnumHelper.addArmorMaterial("Turtle", 5, new int[]{1, 3, 2, 1}, 15); @Mod.Instance(MODID) public static TurtleMod instance; @SidedProxy(clientSide = "net.probossgamers.turtlemod.client.ClientProxy", serverSide = "net.probossgamers.turtlemod.server.ServerProxy") public static ServerProxy proxy; public static void registerEntity(Class<? extends EntityLiving> entityClass, String name, int par1, int par2, int par3, int par4, int par5, EnumCreatureType CreatureType) { int entityID = EntityRegistry.findGlobalUniqueEntityId(); EntityRegistry.registerGlobalEntityID(entityClass, name, entityID, par1, par2); EntityRegistry.registerModEntity(entityClass, name, entityID, instance, 64, 1, true); EntityRegistry.addSpawn(entityClass, par3, par4, par5, CreatureType, BiomeGenBase.beach, BiomeGenBase.frozenRiver, BiomeGenBase.iceMountains, BiomeGenBase.icePlains, BiomeGenBase.plains, BiomeGenBase.river, BiomeGenBase.swampland, BiomeGenBase.taiga, BiomeGenBase.taigaHills); } @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { proxy.registerRenderers(); turtleTab = new CreativeTabs("turtleTab") { @Override public Item getTabIconItem() { return turtleShell; } }; registerEntity(EntityTurtle.class, "turtle", 0x1e8100, 0x7d3900, 10, 2, 4, EnumCreatureType.creature); registerEntity(EntityZombieTurtle.class, "zombieTurtle", 0x008344, 0x823F02, 10, 2, 4, EnumCreatureType.monster); registerEntity(EntityMineTurtle.class, "mineTurtle", 0x1e8100, 0xef0000, 10, 2, 4, EnumCreatureType.monster); turtleLeather = new Item().setUnlocalizedName("turtleLeather").setTextureName("turtlemod:turtleLeather").setCreativeTab(turtleTab); turtleShell = new ItemTurtleShell(turtleMaterial, turtleShellid, 1).setTextureName("turtlemod:turtleShell").setUnlocalizedName("turtleShell"); turtleHelmet = new ItemTurtleArmor(turtleMaterial, turtleHelmetid, 0).setTextureName("turtlemod:turtleHelmet").setUnlocalizedName("turtleHelmet"); turtleChestplate = new ItemTurtleArmor(turtleMaterial, turtleChestplateid, 1).setTextureName("turtlemod:turtleChestplate").setUnlocalizedName("turtleChestplate"); turtleLeggings = new ItemTurtleArmor(turtleMaterial, turtleLeggingsid, 2).setTextureName("turtlemod:turtleLeggings").setUnlocalizedName("turtleLeggings"); turtleBoots = new ItemTurtleArmor(turtleMaterial, turtleBootsid, 3).setTextureName("turtlemod:turtleBoots").setUnlocalizedName("turtleBoots"); GameRegistry.registerItem(turtleLeather, "Turtle Leather"); GameRegistry.registerItem(turtleShell, "Turtle Shell"); GameRegistry.registerItem(turtleHelmet, "Turtle Helmet"); GameRegistry.registerItem(turtleChestplate, "Turtle Chestplate"); GameRegistry.registerItem(turtleLeggings, "Turtle Leggings"); GameRegistry.registerItem(turtleBoots, "Turtle Boots"); } }
package no.bekk.bekkopen.person; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Random; public class NavnGenerator { private final int caAntallKvinnerSomHarMellomnavnIProsent = 22; private final int caAntallMennSomHarMellomnavnIProsent = 14; private final List<String> kvinnenavn; private final List<String> mannsnavn; private final List<String> etternavn; public NavnGenerator() { kvinnenavn = csv2List(NavnGenerator.class.getResourceAsStream("/fornavn_kvinner.csv")); mannsnavn = csv2List(NavnGenerator.class.getResourceAsStream("/fornavn_menn.csv")); etternavn = csv2List(NavnGenerator.class.getResourceAsStream("/etternavn.csv")); } public Navn genererMannsnavn() { return genererNavn(1, KJONN.MANN).get(0); } public Navn genererKvinnenavn() { return genererNavn(1, KJONN.KVINNE).get(0); } public List<Navn> genererMannsnavn(int antall) { return genererNavn(antall, KJONN.MANN); } public List<Navn> genererKvinnenavn(int antall) { return genererNavn(antall, KJONN.KVINNE); } public List<Navn> genererNavn(int antall) { return genererNavn(antall, KJONN.BEGGE); } private List<Navn> genererNavn(final int antall, final KJONN kjonn) { List<Navn> navneliste = new ArrayList<Navn>(antall); KJONN kjonnSwitch = kjonn; while (navneliste.size() < antall) { if (KJONN.erBegge(kjonn)) { kjonnSwitch = KJONN.byttKjonn(kjonn); } Navn navn = genererNavn(kjonnSwitch); if (!navneliste.contains(navn)) { navneliste.add(navn); } } return navneliste; } private Navn genererNavn(final KJONN kjonn) { String fnavn, mnavn = null, enavn; int indexF = 0; if (KJONN.erKvinne(kjonn)) { indexF = new Random().nextInt(kvinnenavn.size() - 1); fnavn = kvinnenavn.get(indexF); } else { indexF = new Random().nextInt(mannsnavn.size() - 1); fnavn = mannsnavn.get(indexF); } if (genererMellomnavn(kjonn)) { int indexM = new Random().nextInt(etternavn.size() - 1); mnavn = etternavn.get(indexM); } int indexE = new Random().nextInt(etternavn.size() - 1); enavn = etternavn.get(indexE); return new Navn(fnavn, mnavn, enavn); } private boolean genererMellomnavn(KJONN kjonn) { if (KJONN.erKvinne(kjonn)) { if (new Random().nextInt(100) <= caAntallKvinnerSomHarMellomnavnIProsent) { return true; } } else { if (new Random().nextInt(100) <= caAntallMennSomHarMellomnavnIProsent) { return true; } } return false; } private static List<String> csv2List(InputStream is) { InputStreamReader isr = new InputStreamReader(is, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); List<String> vList = new ArrayList<String>(); String[] array; String line; try { while ((line = br.readLine()) != null) { array = line.split("[ ]*,[ ]*"); for (int i = 0; i < array.length; i++) { vList.add(array[i]); } } br.close(); isr.close(); } catch (IOException e) { e.printStackTrace(); } return vList; } protected enum KJONN { MANN, KVINNE, BEGGE; static boolean erMann(final KJONN kjonn) { return kjonn.equals(MANN); } static boolean erKvinne(final KJONN kjonn) { return kjonn.equals(KVINNE); } static boolean erBegge(final KJONN kjonn) { return kjonn.equals(BEGGE); } static KJONN byttKjonn(final KJONN kjonn) { if (erKvinne(kjonn)) { return MANN; } return KVINNE; } } }