answer
stringlengths
17
10.2M
package sunmi.com.sunmiauto; import android.app.Instrumentation; import android.os.Build; import android.os.Environment; import android.os.RemoteException; import android.support.test.InstrumentationRegistry; import android.support.test.uiautomator.By; import android.support.test.uiautomator.UiDevice; import android.support.test.uiautomator.UiObject2; import android.support.test.uiautomator.UiObjectNotFoundException; import android.support.test.uiautomator.UiScrollable; import android.support.test.uiautomator.UiSelector; import android.support.test.uiautomator.Until; import android.util.Log; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.mail.MessagingException; public class SunmiAppStore { static Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); static UiDevice device = UiDevice.getInstance(instrumentation); @Before public void setup() throws RemoteException, UiObjectNotFoundException, IOException { device.executeShellCommand("am start -n woyou.market/store.ui.activity.HomeActivity"); SunmiUtil.sleep(2000); device.findObject(By.text("")).click(); } @After public void teardown() throws RemoteException { SunmiUtil.sleep(1000); device.pressHome(); } @BeforeClass public static void initLiza() throws RemoteException, IOException { File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "app_spoon-screenshots"); Log.v("testDir", Environment.getExternalStorageDirectory() + File.separator + "app_spoon-screenshots"); class Inner { private void deleteAll(File file) { if(!file.exists()){ return; } if (file.isFile() || file.list().length == 0) { file.delete(); } else { File[] files = file.listFiles(); for (File f : files) { deleteAll(f); f.delete(); } } } } new Inner().deleteAll(dir); dir.mkdir(); } @AfterClass public static void clearDown() throws MessagingException, RemoteException { } @Test public void testOpenAppStore() { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),5000); // device.waitForIdle(10000); SunmiUtil.screenshotCap("afterEnter"); UiObject2 suggObj = device.findObject(By.res("woyou.market:id/fab_me")); Assert.assertNotNull("", suggObj); } @Test public void testCheckNewArrive() { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); device.findObject(By.res("woyou.market:id/tv_newest_all").text("")).clickAndWait(Until.newWindow(), 10000); SunmiUtil.screenshotCap("afterClickNewestAll"); UiObject2 newestAllObj = device.findObject(By.res("woyou.market:id/list_view")); Assert.assertNotNull("", newestAllObj); } @Test public void testNewScroll() throws UiObjectNotFoundException { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); UiScrollable newAllScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/recycler_view_newest")); newAllScroll.setAsHorizontalList(); newAllScroll.scrollToBeginning(10, 10); newAllScroll.scrollToEnd(10, 10); newAllScroll.scrollToBeginning(10, 10); UiScrollable newAllScroll1 = new UiScrollable(new UiSelector().resourceId("woyou.market:id/recycler_view_newest")); Assert.assertNotNull("",newAllScroll1); } @Test public void testCheckHotApps() { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); device.findObject(By.res("woyou.market:id/tv_hot_all").text("")).clickAndWait(Until.newWindow(), 10000); SunmiUtil.screenshotCap("afterClickHotAll"); UiObject2 hotAllObj = device.findObject(By.res("woyou.market:id/list_view")); Assert.assertNotNull("reswoyou.market:id/list_view", hotAllObj); } @Test public void testHotScroll() throws UiObjectNotFoundException { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); UiScrollable hotAllScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/linear_hot_view")); hotAllScroll.scrollToEnd(20, 10); hotAllScroll.scrollToBeginning(20, 10); } @Test public void testCheckCategory() throws UiObjectNotFoundException { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); device.findObject(By.text("")).clickAndWait(Until.newWindow(), 10000); SunmiUtil.screenshotCap("enterCategory"); UiScrollable cateScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/recycler_view")); ArrayList<String> appCategory = new ArrayList<>(); switch (Build.DEVICE) { case "V1-B18": Log.v("enterV1-B18", "V1-B18"); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add("EET"); break; case "V1s-G": Log.v("enterV1s-G", "V1s-G"); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add("EET"); break; default: Log.v("enterDefault", "default"); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add("EET"); } for (String s : appCategory ) { boolean b = cateScroll.scrollTextIntoView(s); Assert.assertTrue(s + " } } @Test public void testEnterCategory() throws UiObjectNotFoundException { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); device.findObject(By.text("")).clickAndWait(Until.newWindow(), 10000); SunmiUtil.screenshotCap("enterCategory"); UiScrollable cateScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/recycler_view")); ArrayList<String> appCategory = new ArrayList<>(); switch (Build.DEVICE) { case "V1-B18": Log.v("enterV1-B18", "V1-B18"); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add("EET"); break; case "V1s-G": Log.v("enterV1s-G", "V1s-G"); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add("EET"); break; default: Log.v("enterDefault", "default"); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add(""); appCategory.add("EET"); } for (String s : appCategory ) { boolean b = cateScroll.scrollTextIntoView(s); Assert.assertTrue(s + " UiObject2 sCategoryObj = device.findObject(By.text(s)); sCategoryObj.clickAndWait(Until.newWindow(), 10000); UiObject2 cateNmaeObj = device.findObject(By.res("woyou.market:id/tv_title")); String cateName = cateNmaeObj.getText(); Assert.assertEquals("" + s + "," + cateName, s, cateName); device.pressBack(); } } @Test public void testEnterMine() { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); device.findObject(By.res("woyou.market:id/fab_me")).clickAndWait(Until.newWindow(), 10000); UiObject2 mineObj = device.findObject(By.res("woyou.market:id/tv_title").text("")); Assert.assertNotNull("\"\"", mineObj); } @Test public void testEnterLoginPageFromAppStore() { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); device.findObject(By.res("woyou.market:id/fab_me")).clickAndWait(Until.newWindow(), 10000); device.findObject(By.res("woyou.market:id/item_user_info")).clickAndWait(Until.newWindow(), 10000); SunmiUtil.screenshotCap("enterUserLoginCenter"); String actulPkg = device.getCurrentPackageName(); Assert.assertEquals("com.sunmi.usercenter" + actulPkg, "com.sunmi.usercenter", actulPkg); } @Test public void testInstallAppFromHot() throws UiObjectNotFoundException { // SunmiUtil.screenshotCap();("beforeEnter"); // device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000); SunmiUtil.screenshotCap("afterEnter"); device.findObject(By.res("woyou.market:id/tv_hot_all").text("")).clickAndWait(Until.newWindow(), 10000); SunmiUtil.screenshotCap("afterClickHotAll"); UiScrollable hotAllScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/list_view")); hotAllScroll.scrollTextIntoView(""); device.findObject(By.text("")).click(); } }
package com.bedrock.padder.activity; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; 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.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.WindowHelper; import com.bedrock.padder.model.preferences.Preferences; import com.bedrock.padder.model.preset.Preset; import com.bedrock.padder.model.preset.PresetSchema; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.File; import static com.bedrock.padder.helper.PresetStoreHelper.PROJECT_LOCATION_PRESETS; import static com.bedrock.padder.helper.WindowHelper.getStringFromId; public class MainActivity extends AppCompatActivity implements AboutFragment.OnFragmentInteractionListener, SettingsFragment.OnFragmentInteractionListener { public static final String TAG = "MainActivity"; 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 Preset currentPreset = null; public Preferences preferences = null; // Used for circularReveal // End two is for settings coordinate animation public static int coordinate[] = {0, 0, 0, 0}; final AppCompatActivity a = this; 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; int currentVersionCode; int themeColor = R.color.hello; int color = R.color.cyan_400; int colorDef = R.color.grey; 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 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; private int circularRevealDuration = 400; private int fadeAnimDuration = 200; private Gson gson = new GsonBuilder().setPrettyPrinting().create(); 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); } 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)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize Preferences preferences = new Preferences(this); checkVersion(); // set color from Preferences setColor(); toolbar.setActionBar(this); toolbar.setStatusBarTint(this); a.setVolumeControlStream(AudioManager.STREAM_MUSIC); // Set UI setFab(); setToolbar(); switch (preferences.getStartPage()) { case "recent": // load latest played preset if (preferences.getLastPlayed() != null) { try { currentPreset = gson.fromJson(file.getStringFromFile(getCurrentPresetLocation() + "/about/json"), PresetSchema.class).getPreset(); if (!file.isPresetAvailable(currentPreset)) { // preset corrupted or doesn't exist currentPreset = null; } } catch (Exception e) { // corrupted preset e.printStackTrace(); currentPreset = null; } } break; case "about": // load latest played preset and show about setToolbarVisible(); if (preferences.getLastPlayed() != null) { try { currentPreset = gson.fromJson(file.getStringFromFile(getCurrentPresetLocation() + "/about/json"), PresetSchema.class).getPreset(); if (!file.isPresetAvailable(currentPreset)) { // preset corrupted or doesn't exist currentPreset = null; } } catch (Exception e) { // corrupted preset e.printStackTrace(); currentPreset = null; } } new Handler().postDelayed(new Runnable() { @Override public void run() { coordinate[0] = w.getRect(R.id.toolbar_info, a).centerX(); coordinate[1] = w.getRect(R.id.toolbar_info, a).centerY(); showAboutFragment(); } }, 200); break; case "preset_store": setToolbarVisible(); new Handler().postDelayed(new Runnable() { @Override public void run() { coordinate[0] = w.getRect(R.id.toolbar_preset, a).centerX(); coordinate[1] = w.getRect(R.id.toolbar_preset, a).centerY(); intent.intent(a, "activity.PresetStoreActivity", 0); } }, 200); break; default: // load latest played preset if (preferences.getLastPlayed() != null) { try { currentPreset = gson.fromJson(file.getStringFromFile(getCurrentPresetLocation() + "/about/json"), PresetSchema.class).getPreset(); if (!file.isPresetAvailable(currentPreset)) { // preset corrupted or doesn't exist currentPreset = null; } } catch (Exception e) { // corrupted preset e.printStackTrace(); currentPreset = null; } } break; } // load preset info / sound setPresetInfo(); sound.setDecks(R.color.colorAccent, R.color.grey, a); anim.fadeIn(R.id.actionbar_layout, 0, 200, "background", a); anim.fadeIn(R.id.actionbar_image, 200, 200, "image", a); isPresetLoading = true; loadPreset(400); setButtonLayout(); // Set transparent nav bar w.setStatusBar(R.color.transparent, a); w.setNavigationBar(R.color.transparent, a); //ab.setStatusHeight(a); sound.clear(); } @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; } 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) { // 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 { 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); } } @Override public void onWindowFocusChanged(boolean hasFocus) { Log.i("MainActivity", "onWindowFocusChanged"); sound.stop(); 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 view : tutorial) { w.setInvisible(view, 10, a); } // get changed color values setColor(); if (isPresetVisible) { if (!isAboutVisible && !isSettingVisible) { // preset store visible closePresetStore(); } isPresetVisible = false; } if (isPresetChanged) { currentPreset = null; if (preferences.getLastPlayed() != null) { // preset loaded Log.d(TAG, "changed"); currentPreset = gson.fromJson(file.getStringFromFile(getCurrentPresetLocation() + "/about/json"), PresetSchema.class).getPreset(); loadPreset(0); } else { Log.d(TAG, "removed"); } setPresetInfo(); isPresetChanged = false; } super.onWindowFocusChanged(hasFocus); } @Override public void onPause() { ad.pauseNativeAdView(R.id.adView_main, a); super.onPause(); } @Override public void onResume() { super.onResume(); Log.d("MainActivity", "onResume"); sound.stop(); 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); if (currentPreset != null && !file.isPresetAvailable(currentPreset)) { currentPreset = null; } setPresetInfo(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); sound.stop(); sound.cancelLoad(); ad.destroyNativeAdView(R.id.adView_main, a); super.onDestroy(); } private void checkVersion() { try { currentVersionCode = a.getPackageManager().getPackageInfo(a.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"); } // version checks Intent launcherIntent = getIntent(); if (launcherIntent != null && launcherIntent.getStringExtra("version") != null) { String version = launcherIntent.getStringExtra("version"); if (version.equals("new")) { // new install, show intro intent.intent(a, "activity.MainIntroActivity"); preferences.setVersionCode(currentVersionCode); } else if (version.equals("updated")) { // updated, show changelog new MaterialDialog.Builder(a) .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) { preferences.setVersionCode(currentVersionCode); } }) .show(); } } } 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); } private void setButtonLayout() { int screenWidthPx = (int) (w.getWindowWidthPx(a) * preferences.getDeckMargin()); 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)); } } } Log.i(TAG, "Button layout reset"); } } 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()); } private void setFab() { fab.set(a); fab.setIcon(R.drawable.ic_info_white, a); fab.show(); fab.setOnClickListener(new Runnable() { @Override public void run() { if (isToolbarVisible == false) { //TODO remove this for test Log.i(TAG, w.getRect(R.id.toolbar_info, a).centerX() + " " + w.getRect(R.id.toolbar_info, a).centerY()); fab.hide(0, 200); anim.fadeIn(R.id.toolbar, 200, 100, "toolbarIn", a); 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 setToolbarVisible() { fab.hide(0, 0); anim.fadeIn(R.id.toolbar, 0, 0, "toolbarShow", a); isToolbarVisible = true; } 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) { coordinate[0] = (int) event.getRawX(); coordinate[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, coordinate[0], coordinate[1], 0, (int) Math.hypot(coordinate[0], coordinate[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) { coordinate[0] = (int) event.getRawX(); coordinate[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, coordinate[0], coordinate[1], 0, (int) Math.hypot(coordinate[0], coordinate[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) { coordinate[0] = (int) event.getRawX(); coordinate[1] = (int) event.getRawY(); return false; } }); tutorial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showTutorial(); } }); assert settings != null; settings.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { coordinate[2] = (int) event.getRawX(); coordinate[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, coordinate[2], coordinate[3], 0, (int) Math.hypot(coordinate[2], coordinate[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.show(100, 200); isToolbarVisible = false; } private void closeAbout() { Log.d("closeAbout", "triggered"); anim.circularRevealInPx(R.id.placeholder, coordinate[0], coordinate[1], (int) Math.hypot(coordinate[0], coordinate[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); // reset the touch coordinates coordinate[0] = 0; coordinate[1] = 0; } private void showTutorial() { if (isTutorialVisible == false) { isTutorialVisible = true; if (currentPreset != null) { if (!isPresetLoading && currentPreset.getAbout().getTutorialAvailable()) { String tutorialText = currentPreset.getAbout().getTutorialVideoLink(); if (tutorialText == null || tutorialText.equals("null")) { tutorialText = getStringFromId("dialog_tutorial_text_error", a); } 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, coordinate[2], coordinate[3], (int) Math.hypot(coordinate[2], coordinate[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; } setColor(); clearDeck(); 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 coordinates coordinate[2] = 0; coordinate[3] = 0; } private void closePresetStore() { setPresetInfo(); if (coordinate[0] > 0 && coordinate[1] > 0) { anim.circularRevealInPx(R.id.placeholder, coordinate[0], coordinate[1], (int) Math.hypot(coordinate[0], coordinate[1]) + 200, 0, new AccelerateDecelerateInterpolator(), circularRevealDuration, 200, a); } } private void loadPreset(int delay) { if (currentPreset != null) { Handler preset = new Handler(); preset.postDelayed(new Runnable() { @Override public void run() { sound.load(currentPreset, preferences.getColor(), colorDef, a); } }, delay); } } private void clearDeck() { if (isDeckShouldCleared) { w.setViewBackgroundColor(R.id.tgl1, colorDef, a); w.setViewBackgroundColor(R.id.tgl2, colorDef, a); w.setViewBackgroundColor(R.id.tgl3, colorDef, a); w.setViewBackgroundColor(R.id.tgl4, colorDef, a); w.setViewBackgroundColor(R.id.tgl5, colorDef, a); w.setViewBackgroundColor(R.id.tgl6, colorDef, a); w.setViewBackgroundColor(R.id.tgl7, colorDef, a); w.setViewBackgroundColor(R.id.tgl8, colorDef, a); tgl1 = false; tgl2 = false; tgl3 = false; tgl4 = false; tgl5 = false; tgl6 = false; tgl7 = false; tgl8 = false; // reset the deck margin if (!isPresetLoading) { // only set buttons when preset is not loading setButtonLayout(); sound.clear(); sound.loadColor(preferences.getColor()); w.setInvisible(R.id.base, 0, a); // initialize view View buttonViews[] = { w.getView(R.id.btn00, a), w.getView(R.id.tgl1, a), w.getView(R.id.tgl2, a), w.getView(R.id.tgl3, a), w.getView(R.id.tgl4, a), w.getView(R.id.tgl5, a), w.getView(R.id.tgl6, a), w.getView(R.id.tgl7, a), w.getView(R.id.tgl8, a), w.getView(R.id.btn11, a), w.getView(R.id.btn12, a), w.getView(R.id.btn13, a), w.getView(R.id.btn14, a), w.getView(R.id.btn21, a), w.getView(R.id.btn22, a), w.getView(R.id.btn23, a), w.getView(R.id.btn24, a), w.getView(R.id.btn31, a), w.getView(R.id.btn32, a), w.getView(R.id.btn33, a), w.getView(R.id.btn34, a), w.getView(R.id.btn41, a), w.getView(R.id.btn42, a), w.getView(R.id.btn43, a), w.getView(R.id.btn44, a) }; for (View view : buttonViews) { view.setVisibility(View.INVISIBLE); } new Handler().postDelayed(new Runnable() { @Override public void run() { sound.revealButtonWithAnimation(); } }, 400); } toggleSoundId = 0; isDeckShouldCleared = false; } } private void setPresetInfo() { if (isSettingVisible == false && isAboutVisible == false && currentPreset != null) { themeColor = currentPreset.getAbout().getColor(); toolbar.setActionBarTitle(0); toolbar.setActionBarColor(themeColor, a); toolbar.setActionBarPadding(a); toolbar.setActionBarImage( PROJECT_LOCATION_PRESETS + "/" + currentPreset.getTag() + "/about/artist_icon", this); w.setRecentColor(0, 0, themeColor, a); w.setVisible(R.id.base, 0, a); w.setGone(R.id.main_cardview_preset_store, 0, a); } else if (currentPreset == null || preferences.getLastPlayed() == null) { toolbar.setActionBarTitle(R.string.app_name); toolbar.setActionBarColor(R.color.colorPrimary, a); toolbar.setActionBarPadding(a); toolbar.setActionBarImage(0, this); 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); w.setGone(R.id.base, 0, a); } } public String getCurrentPresetLocation() { if (preferences.getLastPlayed() != null) { return PROJECT_LOCATION_PRESETS + "/" + preferences.getLastPlayed(); } else { return null; } } private boolean isPresetExists(String presetName) { // preset exist File folder = new File(PROJECT_LOCATION_PRESETS + "/" + presetName); // folder check return folder.isDirectory() && folder.exists(); } private void setColor() { color = preferences.getColor(); } }
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.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.AdmobService; import com.bedrock.padder.helper.AnimService; import com.bedrock.padder.helper.AppbarService; import com.bedrock.padder.helper.FabService; import com.bedrock.padder.helper.SoundService; import com.bedrock.padder.helper.ThemeService; import com.bedrock.padder.helper.TutorialService; import com.bedrock.padder.helper.WindowService; 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.Deck; import com.bedrock.padder.model.preset.Music; import com.bedrock.padder.model.preset.Pad; import com.bedrock.padder.model.preset.Preset; import com.google.gson.Gson; import java.lang.reflect.Field; import java.util.ArrayList; import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt; import static com.bedrock.padder.helper.WindowService.APPLICATION_ID; @TargetApi(14) @SuppressWarnings("deprecation") public class MainActivity extends AppCompatActivity implements AboutFragment.OnFragmentInteractionListener, SettingsFragment.OnFragmentInteractionListener { final Activity 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; SharedPreferences prefs = null; int currentVersionCode; int themeColor = R.color.hello; // TODO color int color = R.color.cyan_400; boolean doubleBackToExitPressedOnce = false; MaterialDialog ChangelogDialog; MaterialDialog QuickstartDialog; MaterialDialog PresetDialog; int toggleSoundId = 0; int togglePatternId = 0; private AnimService anim = new AnimService(); private ThemeService t = new ThemeService(); private SoundService sound = new SoundService(); private WindowService w = new WindowService(); private FabService fab = new FabService(); private AppbarService ab = new AppbarService(); private TutorialService tut = new TutorialService(); private AdmobService ad = new AdmobService(); private boolean isToolbarVisible = false; public static boolean isPresetLoading = false; public static boolean isPresetVisible = false; public static boolean isTutorialVisible = false; public static boolean isAboutVisible = false; public static boolean isSettingVisible = false; public static boolean isDeckShouldCleared = false; 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 Gson gson = new Gson(); public static Preset presets[]; 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); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //TODO EDIT //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."); presets = new Preset[] { gson.fromJson(getResources().getString(R.string.json_hello), Preset.class), gson.fromJson(getResources().getString(R.string.json_roses), Preset.class), gson.fromJson(getResources().getString(R.string.json_faded), Preset.class) }; // sharedPrefs Log.d(TAG, "Sharedprefs initialized"); prefs = this.getSharedPreferences(APPLICATION_ID, MODE_PRIVATE); // 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); if (color == R.color.cyan_400) { prefs.edit().putInt("color", R.color.cyan_400).apply(); } 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 isDeckShouldCleared = true; clearToggleButton(); setFab(); setToolbar(); setSchemeInfo(); setToggleButton(R.color.colorAccent); enterAnim(); setButtonLayout(); // Set fragments setSettingsFragment(); // 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 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 (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++) { t.setInvisible(tutorial[i], 10, a); } color = prefs.getInt("color", R.color.cyan_400); 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++) { t.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 setAboutFragment() { AboutFragment aboutFragment = new AboutFragment(); getSupportFragmentManager() .beginTransaction() .add(R.id.fragment_about_container, aboutFragment) .commit(); } private void showAboutFragment() { setAboutFragment(); WindowService w = new WindowService(); w.getView(R.id.fragment_about_container, a).setVisibility(View.VISIBLE); setAboutVisible(true); w.setRecentColor(R.string.about, 0, themeColor, a); } private void setSettingsFragment() { SettingsFragment settingsFragment = new SettingsFragment(); getSupportFragmentManager() .beginTransaction() .add(R.id.fragment_settings_container, settingsFragment) .commit(); } public static void showSettingsFragment(Activity a) { WindowService w = new WindowService(); 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); //TODO: Remove this to not load preset loadPreset(400); //makeJson(); 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 ChangelogDialog = 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); w.setVisible(R.id.fab, 300, activity); fab.setFab(activity); QuickstartDialog = 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.show(); fab.onClick(new Runnable() { @Override public void run() { if (isToolbarVisible == false) { fab.hide(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); Handler preset = new Handler(); preset.postDelayed(new Runnable() { @Override public void run() { showPresetDialog(a); } }, circularRevealDuration); isPresetVisible = true; } } }); 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.show(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() { setSchemeInfo(); 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(); } } public void toggleTutorial() { // TODO add 2gb ram limit if statement if (w.getView(R.id.progress_bar_layout, a).getVisibility() == View.GONE) { // on loading finished // if (isTutorialVisible == false) { // new MaterialDialog.Builder(a) // .title(R.string.dialog_tutorial_warning_title) // .content(R.string.dialog_tutorial_warning_text) // .positiveText(R.string.dialog_tutorial_warning_positive) // .positiveColorRes(R.color.red_500) // .negativeText(R.string.dialog_tutorial_warning_negative) // .negativeColorRes(R.color.dark_secondary) // .onPositive(new MaterialDialog.SingleButtonCallback() { // @Override // public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { // // TODO TUTORIAL // //tut.tutorialStart(a); // tut.initCurrentTiming(); // tut.startTutorial(tut.getCurrentTutorialDeckId(), a); // isTutorialVisible = true; // setTutorialUI(); // if (isSettingVisible == true) { // closeSettings(); // .onNegative(new MaterialDialog.SingleButtonCallback() { // @Override // public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { // isTutorialVisible = false; // setTutorialUI(); // .show(); // } else { // tut.tutorialStop(a); // isTutorialVisible = false; // setTutorialUI(); String tutorialText; if (presets[getScheme()].getAbout().getTutorialLink(a).equals("null")) { tutorialText = w.getStringFromId("dialog_tutorial_text_error", a); } else { tutorialText = presets[getScheme()].getAbout().getTutorialLinkId(); } 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; } } private void setTutorialUI() { if (isTutorialVisible == true) { w.getImageView(R.id.toolbar_tutorial_icon, a).setImageResource(R.drawable.icon_tutorial_quit); w.getImageView(R.id.layout_settings_tutorial_icon, a).setImageResource(R.drawable.settings_tutorial_quit); w.getSwitchCompat(R.id.layout_settings_tutorial_switch, a).setChecked(true); } else { w.getImageView(R.id.toolbar_tutorial_icon, a).setImageResource(R.drawable.icon_tutorial); w.getImageView(R.id.layout_settings_tutorial_icon, a).setImageResource(R.drawable.settings_tutorial); w.getSwitchCompat(R.id.layout_settings_tutorial_switch, a).setChecked(false); } } private void closeSettings() { Log.d("closeSettings", "triggered"); 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); 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 { setSchemeInfo(); } w.getView(R.id.fragment_settings_container, a).setVisibility(View.GONE); } }, fadeAnimDuration); } private void showPresetDialog(final Activity a) { tut.tutorialStop(a); sound.soundAllStop(); final int defaultPreset = getScheme(); int color = currentPreset.getAbout().getActionbarColor(); anim.fade(R.id.placeholder, 1.0f, 0.5f, 0, 200, "phIN", a); PresetDialog = new MaterialDialog.Builder(a) .title(R.string.dialog_preset_title) .items(R.array.presets) .autoDismiss(false) .itemsCallbackSingleChoice(defaultPreset, new MaterialDialog.ListCallbackSingleChoice() { @Override public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { setScheme(which); int selectedPresetColor = presets[which].getAbout().getActionbarColor(); PresetDialog.getBuilder() .widgetColorRes(selectedPresetColor) .positiveColorRes(selectedPresetColor); setSchemeInfo(); return true; } }) .alwaysCallSingleChoiceCallback() .widgetColorRes(color) .positiveText(R.string.dialog_preset_positive) .positiveColorRes(R.color.colorAccent) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { PresetDialog.dismiss(); } }) .negativeText(R.string.dialog_preset_negative) .negativeColorRes(R.color.dark_secondary) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { setScheme(defaultPreset); PresetDialog.dismiss(); } }) .dismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { if (defaultPreset != getScheme()) { // preset changed loadPreset(circularRevealDuration); // deck should be cleared after the preset is cleaned isDeckShouldCleared = true; clearToggleButton(); } anim.fade(R.id.placeholder, 0.5f, 1.0f, 0, 200, "phOUT", a); closeDialogPreset(); setSchemeInfo(); isPresetVisible = false; } }) .show(); } private void closeDialogPreset() { 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) { Handler preset = new Handler(); preset.postDelayed(new Runnable() { @Override public void run() { sound.loadSchemeSound(presets[getScheme()], a); } }, delay); } private void setToggleButton(final int color_id) { final int toggleButtonIds[] = { R.id.tgl1, R.id.tgl2, R.id.tgl3, R.id.tgl4, R.id.tgl5, R.id.tgl6, R.id.tgl7, R.id.tgl8 }; final boolean toggleButtonBool[] = { tgl1, tgl2, tgl3, tgl4, tgl5, tgl6, tgl7, tgl8 }; // 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.setButtonTogglePattern(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.setButtonTogglePattern(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.setButtonTogglePattern(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.setButtonTogglePattern(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.setButtonTogglePattern(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.setButtonTogglePattern(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.setButtonTogglePattern(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.setButtonTogglePattern(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 setSchemeInfo() { if (isSettingVisible == false && isAboutVisible == false) { ab.setNav(0, null, a); w.setRecentColor(0, 0, themeColor, a); currentPreset = presets[getScheme()]; themeColor = currentPreset.getAbout().getActionbarColor(); ab.setColor(themeColor, a); ab.setImage(w.getDrawableId("logo_" + currentPreset.getMusic().getNameId().replace("preset_", "")), a); } } int getScheme() { if (prefs.getInt("scheme", 0) > 2 && prefs.getInt("scheme", 0) < 0) { // TOOD needs fix, why this happens? return 0; } else { return prefs.getInt("scheme", 0); } } private void setScheme(int scheme) { prefs.edit().putInt("scheme", scheme).apply(); } 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", "preset_faded_detail_facebook"), new Item("twitter", "preset_faded_detail_twitter"), new Item("soundcloud", "preset_faded_detail_soundcloud"), new Item("instagram", "preset_faded_detail_instagram"), new Item("google_plus", "preset_faded_detail_google_plus"), new Item("youtube", "preset_faded_detail_youtube"), //new Item("twitch", "preset_faded_detail_twitch"), // only faded new Item("web", "preset_faded_detail_web") }; Detail fadedDetail = new Detail("preset_faded_detail_title", fadedItems); Item fadedSongItems[] = { new Item("soundcloud", "preset_faded_song_detail_soundcloud", false), new Item("youtube", "preset_faded_song_detail_youtube", false), new Item("spotify", "preset_faded_song_detail_spotify", false), new Item("google_play_music", "preset_faded_song_detail_google_play_music", false), new Item("apple", "preset_faded_song_detail_apple", false), new Item("amazon", "preset_faded_song_detail_amazon", false), new Item("pandora", "preset_faded_song_detail_pandora", false) }; Detail fadedSongDetail = new Detail("preset_faded_song_detail_title", fadedSongItems); Bio fadedBio = new Bio( "preset_faded_bio_title", "about_bio_faded", "preset_faded_bio_name", "preset_faded_bio_text", "preset_faded_bio_source" ); Detail fadedDetails[] = { fadedDetail, fadedSongDetail }; About fadedAbout = new About( "preset_faded_title", "about_album_faded", "preset_faded_tutorial_link", fadedBio, fadedDetails, "preset_faded_color_dark", "preset_faded_color" ); // Timings // Integer pt1[][] = { // {42660}, // {null}, // {null}, // {null}, // {null}, // {26658}, // {1333}, // {2666}, // {3998}, // {27991}, // {10664, 21327}, // {11996, 22660}, // {13329, 23993}, // {14662, 25326}, // {29324}, // {15995}, // {17328}, // {18660}, // {19993}, // {30657}, // {5331}, // {6664}, // {7997}, // {9330}, // {42660}, // {34656}, // {37322}, // {45320}, // {47986}, // {47986}, // {35989}, // {38655}, // {46653}, // {49318}, // {50651}, // {36655}, // {39321}, // {47319}, // {49984}, // {45320}, // {35322}, // {37988}, // {45986}, // {48652}, // {31991}, // {31991}, // {39988}, // {42660}, // {50651}, // {37322}, // {33324}, // {41320}, // {43987}, // {51984}, // {39988}, // {33990}, // {41987}, // {44653}, // {52650}, // {34656}, // {32657}, // {40654}, // {43320}, // {51317}, // {43987}, // {null}, // {null}, // {null}, // {null}, // {10664}, // {10664}, // {15995}, // {21327}, // {26658}, // {34656}, // {34656}, // {39988}, // {45320}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null} // Integer pt2[][] = { // {54660}, // {53318}, // {null}, // {75993}, // {null}, // {75993}, // {70660}, // {54660}, // {59993}, // {65326}, // {78659}, // {71326}, // {55327}, // {60660}, // {65993}, // {81325}, // {71993}, // {55994}, // {61327}, // {66660}, // {83992}, // {72660}, // {56660}, // {61993}, // {67326}, // {86659}, // {73326}, // {57327}, // {62660}, // {67993}, // {89325}, // {73993}, // {57993}, // {63327}, // {68660}, // {91992}, // {74660}, // {58660}, // {63993}, // {69326}, // {94658}, // {75326}, // {59324}, // {64659}, // {69991}, // {87992}, // {57662}, // {73660}, // {68329}, // {62994}, // {90658}, // {58329}, // {74327}, // {68995}, // {63660}, // {93325}, // {58995}, // {74996}, // {69661}, // {64330}, // {95992}, // {59662}, // {75663}, // {70328}, // {64997}, // {77326}, // {54997}, // {70994}, // {65663}, // {60328}, // {79993}, // {55664}, // {71661}, // {66330}, // {60995}, // {82659}, // {56330}, // {72327}, // {66996}, // {61661}, // {85326}, // {56996}, // {72994}, // {67663}, // {62328} // Integer pt3[][] = { // {null}, // {null}, // {null}, // {null}, // {null}, // {139993}, // {97325}, // {107994}, // {118660}, // {129327}, // {142659}, // {99991}, // {110660}, // {121326}, // {131993}, // {143992}, // {101325}, // {111994}, // {122660}, // {133326}, // {141326}, // {98658}, // {109327}, // {119993}, // {130659}, // {145326}, // {102658}, // {113327}, // {123993}, // {134659}, // {147992}, // {105325}, // {115994}, // {126660}, // {137326}, // {149326}, // {106658}, // {117327}, // {127993}, // {138659}, // {146659}, // {103991}, // {114660}, // {125326}, // {135993}, // {null}, // {null}, // {null}, // {null}, // {null}, // {139993}, // {97325}, // {107994}, // {118660}, // {129327}, // {142659}, // {99991}, // {110660}, // {121326}, // {131993}, // {97325}, // {102658}, // {107994}, // {113327}, // {118660}, // {129327, 130657, 131997, 133327, 134657, 135987, 137327, 138657}, // {139997, 141327, 142667, 143987}, // {145327, 146657, 147997, 149327}, // {null}, // {null}, // {145326}, // {102658}, // {113327}, // {123993}, // {134659}, // {147992}, // {105325}, // {115994}, // {126660}, // {137326}, // {123993}, // {129327}, // {134659}, // {139993}, // {145326} // Integer pt4[][] = { // {null}, // {150650}, // {null}, // {173325}, // {null}, // {173325}, // {167992}, // {151992}, // {157325}, // {162658}, // {175991}, // {168658}, // {152659}, // {157992}, // {163325}, // {178658}, // {169325}, // {153326}, // {158659}, // {163992}, // {181324}, // {169992}, // {153992}, // {159326}, // {164658}, // {183991}, // {170658}, // {154659}, // {159992}, // {165325}, // {186657}, // {171325}, // {155326}, // {160659}, // {165992}, // {189324}, // {171992}, // {155992}, // {161326}, // {166658}, // {191990}, // {172658}, // {156657}, // {161992}, // {167323}, // {185324}, // {154994}, // {170992}, // {165661}, // {160326}, // {187990}, // {155661}, // {171659}, // {166327}, // {160992}, // {190657}, // {156327}, // {172328}, // {166993}, // {161662}, // {193324}, // {156994}, // {172995}, // {167660}, // {162329}, // {174658}, // {152329}, // {168326}, // {162995}, // {157660}, // {177325}, // {152996}, // {168993}, // {163662}, // {158327}, // {179991}, // {153662}, // {169659}, // {164328}, // {158993}, // {182658}, // {154328}, // {170326}, // {164995}, // {159660} // Integer pt5[][] = { // {null}, // {null}, // {null}, // {null}, // {null}, // {194637}, // {null}, // {null}, // {null}, // {null}, // {195993}, // {null}, // {null}, // {null}, // {null}, // {195326}, // {null}, // {null}, // {null}, // {null}, // {196660}, // {null}, // {null}, // {null}, // {null}, // {197326}, // {null}, // {null}, // {null}, // {null}, // {198660}, // {null}, // {null}, // {null}, // {null}, // {197993}, // {null}, // {null}, // {null}, // {null}, // {199324}, // {null}, // {null}, // {null}, // {null}, // {199993}, // {null}, // {null}, // {null}, // {null}, // {201340}, // {null}, // {null}, // {null}, // {null}, // {200682}, // {null}, // {null}, // {null}, // {null}, // {202128}, // {null}, // {null}, // {null}, // {null}, // {203147}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null}, // {null} // DeckTiming deckTiming[] = { // new DeckTiming( // pt1, 1, 0 // new DeckTiming( // pt2, 2, 52949 // new DeckTiming( // pt3, 3, 96379 // new DeckTiming( // pt4, 2, 149947 // new DeckTiming( // pt5, 4, 193772 //TODO EDIT //Log.d("Array", Arrays.deepToString(deckTiming[0].getDeckTiming())); Music fadedMusic = new Music( "preset_faded", 243, 90, getDeckFromFileName(fileTag), null ); Preset fadedPreset = new Preset(3, fadedMusic, fadedAbout); largeLog("JSON", gson.toJson(fadedPreset)); // //TODO use this on about screen updates // Bio tapadBio = new Bio( // "info_tapad_bio_title", // "about_bio_tapad", // "info_tapad_bio_name", // "info_tapad_bio_text", // "info_tapad_bio_source" // Item tapadInfo[] = { // new Item("info_tapad_info_check_update", "info_tapad_info_check_update_hint", "about_detail_google_play", true), // new Item("info_tapad_info_tester", "info_tapad_info_tester_hint", "about_detail_tester", true), // new Item("info_tapad_info_version", "info_tapad_info_version_hint", ""), // new Item("info_tapad_info_build_date", "info_tapad_info_build_date_hint", ""), // new Item("info_tapad_info_changelog", null, "about_detail_changelog", false), // new Item("info_tapad_info_thanks", null, "about_detail_thanks", false), // new Item("info_tapad_info_dev", "info_tapad_info_dev_hint", "about_detail_dev", false) // // TODO ADD ITEMS // Item tapadOthers[] = { // new Item("info_tapad_others_song", "info_tapad_others_song_hint", "about_detail_others_song", true), // new Item("info_tapad_others_feedback", "info_tapad_others_feedback_hint", "about_detail_others_feedback", true), // new Item("info_tapad_others_report_bug", "info_tapad_others_report_bug_hint", "about_detail_others_report_bug", true), // new Item("info_tapad_others_rate", "info_tapad_others_rate_hint", "about_detail_others_rate", true), // new Item("info_tapad_others_translate", "info_tapad_others_translate_hint", "about_detail_web", false), // new Item("info_tapad_others_recommend", "info_tapad_others_recommend_hint", "about_detail_others_recommend", true) // Detail tapadDetails[] = { // new Detail("info_tapad_info_title", tapadInfo), // new Detail("info_tapad_others_title", tapadOthers) // About tapadAbout = new About( // "info_tapad_title", "about_image_tapad", // tapadBio, tapadDetails, // "info_tapad_color_dark", "info_tapad_color" // largeLog("tapadAboutJSON", gson.toJson(tapadAbout)); // Bio berictBio = new Bio( // "info_berict_bio_title", // null, // "info_berict_bio_name", // "info_berict_bio_text", // "info_berict_bio_source" // Item devItems[] = { // new Item("facebook", "info_berict_detail_facebook"), // new Item("twitter", "info_berict_detail_twitter"), // new Item("google_plus", "info_berict_detail_google_plus"), // new Item("youtube", "info_berict_detail_youtube"), // new Item("web", "info_berict_detail_web") // Item devSupport[] = { // new Item("info_berict_action_report_bug", "info_berict_action_report_bug_hint", "about_detail_others_report_bug", true), // new Item("info_berict_action_rate", "info_berict_action_rate_hint", "about_detail_others_rate", true), // new Item("info_berict_action_translate", "info_berict_action_translate_hint", "about_detail_others_translate", false), // new Item("info_berict_action_donate", "info_berict_action_donate_hint", "about_detail_others_donate", false) // Detail berictDetails[] = { // new Detail("info_berict_detail_title", devItems), // new Detail("info_berict_action_title", devSupport) // About berictAbout = new About( // "info_berict_title", "about_image_berict", // berictBio, berictDetails, // "info_berict_color_dark", "info_berict_color" // largeLog("berictAboutJSON", gson.toJson(berictAbout)); } // TODO change on new preset String fileTag = "alan_walker_faded_"; Deck[] getDeckFromFileName(String fileTag) { Pad part1[] = { getPadsFromFile(fileTag, 0, 0), getPadsFromFile(fileTag, 0, 1), getPadsFromFile(fileTag, 0, 2), getPadsFromFile(fileTag, 0, 3), getPadsFromFile(fileTag, 0, 4), getPadsFromFile(fileTag, 0, 5), getPadsFromFile(fileTag, 0, 6), getPadsFromFile(fileTag, 0, 7), getPadsFromFile(fileTag, 0, 8), getPadsFromFile(fileTag, 0, 9), getPadsFromFile(fileTag, 0, 10), getPadsFromFile(fileTag, 0, 11), getPadsFromFile(fileTag, 0, 12), getPadsFromFile(fileTag, 0, 13), getPadsFromFile(fileTag, 0, 14), getPadsFromFile(fileTag, 0, 15), getPadsFromFile(fileTag, 0, 16), getPadsFromFile(fileTag, 0, 17), getPadsFromFile(fileTag, 0, 18), getPadsFromFile(fileTag, 0, 19), getPadsFromFile(fileTag, 0, 20) }; Pad part2[] = { getPadsFromFile(fileTag, 1, 0), getPadsFromFile(fileTag, 1, 1), getPadsFromFile(fileTag, 1, 2), getPadsFromFile(fileTag, 1, 3), getPadsFromFile(fileTag, 1, 4), getPadsFromFile(fileTag, 1, 5), getPadsFromFile(fileTag, 1, 6), getPadsFromFile(fileTag, 1, 7), getPadsFromFile(fileTag, 1, 8), getPadsFromFile(fileTag, 1, 9), getPadsFromFile(fileTag, 1, 10), getPadsFromFile(fileTag, 1, 11), getPadsFromFile(fileTag, 1, 12), getPadsFromFile(fileTag, 1, 13), getPadsFromFile(fileTag, 1, 14), getPadsFromFile(fileTag, 1, 15), getPadsFromFile(fileTag, 1, 16), getPadsFromFile(fileTag, 1, 17), getPadsFromFile(fileTag, 1, 18), getPadsFromFile(fileTag, 1, 19), getPadsFromFile(fileTag, 1, 20) }; Pad part3[] = { getPadsFromFile(fileTag, 2, 0), getPadsFromFile(fileTag, 2, 1), getPadsFromFile(fileTag, 2, 2), getPadsFromFile(fileTag, 2, 3), getPadsFromFile(fileTag, 2, 4), getPadsFromFile(fileTag, 2, 5), getPadsFromFile(fileTag, 2, 6), getPadsFromFile(fileTag, 2, 7), getPadsFromFile(fileTag, 2, 8), getPadsFromFile(fileTag, 2, 9), getPadsFromFile(fileTag, 2, 10), getPadsFromFile(fileTag, 2, 11), getPadsFromFile(fileTag, 2, 12), getPadsFromFile(fileTag, 2, 13), getPadsFromFile(fileTag, 2, 14), getPadsFromFile(fileTag, 2, 15), getPadsFromFile(fileTag, 2, 16), getPadsFromFile(fileTag, 2, 17), getPadsFromFile(fileTag, 2, 18), getPadsFromFile(fileTag, 2, 19), getPadsFromFile(fileTag, 2, 20) }; Pad part4[] = { getPadsFromFile(fileTag, 3, 0), getPadsFromFile(fileTag, 3, 1), getPadsFromFile(fileTag, 3, 2), getPadsFromFile(fileTag, 3, 3), getPadsFromFile(fileTag, 3, 4), getPadsFromFile(fileTag, 3, 5), getPadsFromFile(fileTag, 3, 6), getPadsFromFile(fileTag, 3, 7), getPadsFromFile(fileTag, 3, 8), getPadsFromFile(fileTag, 3, 9), getPadsFromFile(fileTag, 3, 10), getPadsFromFile(fileTag, 3, 11), getPadsFromFile(fileTag, 3, 12), getPadsFromFile(fileTag, 3, 13), getPadsFromFile(fileTag, 3, 14), getPadsFromFile(fileTag, 3, 15), getPadsFromFile(fileTag, 3, 16), getPadsFromFile(fileTag, 3, 17), getPadsFromFile(fileTag, 3, 18), getPadsFromFile(fileTag, 3, 19), getPadsFromFile(fileTag, 3, 20) }; return new Deck[]{new Deck(part1), new Deck(part2), new Deck(part3), new Deck(part4)}; } String getPadStringFromId(int padId) { switch (padId) { case 0: return "00"; case 1: return "01"; case 2: return "02"; case 3: return "03"; case 4: return "04"; case 5: return "11"; case 6: return "12"; case 7: return "13"; case 8: return "14"; case 9: return "21"; case 10: return "22"; case 11: return "23"; case 12: return "24"; case 13: return "31"; case 14: return "32"; case 15: return "33"; case 16: return "34"; case 17: return "41"; case 18: return "42"; case 19: return "43"; case 20: return "44"; default: return null; } } Pad getPadsFromFile(String fileTag, int deck, int pad) { // if (validateFileName( // fileTag, // Integer.toString(deck + 1), // getPadStringFromId(pad), // Integer.toString(0) // ) == null) { // // the pad is empty from the first gesture == empty // return new Pad("a0_00"); // } else { String fileNameArray[] = { validateFileName( fileTag, Integer.toString(deck + 1), getPadStringFromId(pad), Integer.toString(0) ), validateFileName( fileTag, Integer.toString(deck + 1), getPadStringFromId(pad), Integer.toString(1) ), validateFileName( fileTag, Integer.toString(deck + 1), getPadStringFromId(pad), Integer.toString(2) ), validateFileName( fileTag, Integer.toString(deck + 1), getPadStringFromId(pad), Integer.toString(3) ), validateFileName( fileTag, Integer.toString(deck + 1), getPadStringFromId(pad), Integer.toString(4) ) }; return getPadFromStringArray(fileNameArray); } Pad getPadFromStringArray(String fileName[]) { ArrayList<String> stringArray = new ArrayList<>(); for (int i = 0; i < fileName.length; i++) { if (fileName[i] != null) { stringArray.add(fileName[i]); } else if (i == 0) { stringArray.add("a_null"); } } String padStringArray[] = stringArray.toArray(new String[stringArray.size()]); switch (padStringArray.length) { case 1: return new Pad(padStringArray[0]); case 2: return new Pad(padStringArray[0], padStringArray[1]); case 3: return new Pad(padStringArray[0], padStringArray[1], padStringArray[2]); case 4: return new Pad(padStringArray[0], padStringArray[1], padStringArray[2], padStringArray[3]); case 5: return new Pad(padStringArray[0], padStringArray[1], padStringArray[2], padStringArray[3], padStringArray[4]); default: Log.d(TAG, "getPadFromStringArray : null array"); return null; } } String validateFileName(String fileTag, String realPart, String realPad, String realGesture) { String fileName; if (realGesture.equals("0")) { fileName = fileTag + realPart + "_" + realPad; } else { fileName = fileTag + realPart + "_" + realPad + "_" + realGesture; } try { Class res = R.raw.class; Field field = res.getField(fileName); // legit if (field != null) { return fileName; } else { return null; } } catch (Exception e) { Log.e("getColorId", "Failure to get raw id.", e); // fail return null; } } }
package com.james.status.activities; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.james.status.R; import com.james.status.services.StatusService; import com.james.status.utils.ImageUtils; import com.james.status.utils.PreferenceUtils; import com.james.status.utils.StaticUtils; public class MainActivity extends AppCompatActivity { AppBarLayout appbar; AppCompatButton service; FloatingActionButton fab; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (!StaticUtils.isAccessibilityGranted(this) || !StaticUtils.isNotificationGranted(this) || !StaticUtils.isPermissionsGranted(this)) startActivity(new Intent(this, StartActivity.class)); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); appbar = (AppBarLayout) findViewById(R.id.appbar); service = (AppCompatButton) findViewById(R.id.service); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setImageDrawable(ImageUtils.getVectorDrawable(this, R.drawable.ic_expand)); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { appbar.setExpanded(false, true); } }); service.setText(StaticUtils.isStatusServiceRunning(this) ? R.string.service_stop : R.string.service_start); service.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (StaticUtils.isStatusServiceRunning(MainActivity.this)) { PreferenceUtils.putPreference(MainActivity.this, PreferenceUtils.PreferenceIdentifier.STATUS_ENABLED, false); service.setText(R.string.service_start); Intent intent = new Intent(StatusService.ACTION_STOP); intent.setClass(MainActivity.this, StatusService.class); startService(intent); } else { PreferenceUtils.putPreference(MainActivity.this, PreferenceUtils.PreferenceIdentifier.STATUS_ENABLED, true); service.setText(R.string.service_stop); Intent intent = new Intent(StatusService.ACTION_START); intent.setClass(MainActivity.this, StatusService.class); startService(intent); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); menu.findItem(R.id.action_setup).setIcon(ImageUtils.getVectorDrawable(this, R.drawable.ic_setup)); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_setup: startActivity(new Intent(this, StartActivity.class)); break; } return super.onOptionsItemSelected(item); } }
package com.lucas.exercicio.tela.um; import android.app.Activity; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.lucas.exercicio.R; import com.lucas.exercicio.TargetPicasso; import com.lucas.exercicio.tela.dois.DescricaoActivity; import com.squareup.picasso.Picasso; import java.io.File; /** * @author Lucas Campos * 12/28/15 */ public class LocalAdapter extends RecyclerView.Adapter<LocalAdapter.ViewHolder> { public static final String VENUE = "venue"; public static final String URL_WALLPAPER = "http://aviewfrommyseat.com/wallpaper/"; @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.lista, parent, false); layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RecyclerView recycler = (RecyclerView) context.findViewById(R.id.lista); int itemPosition = recycler.getChildPosition(layout); Intent intent = new Intent(context, DescricaoActivity.class); intent.putExtra(VENUE, modelos.getAvfms().get(itemPosition).getVenue()); context.startActivity(intent); } }); TextView venue = (TextView) layout.findViewById(R.id.venue); TextView note = (TextView) layout.findViewById(R.id.note); TextView view = (TextView) layout.findViewById(R.id.view); ImageView imageView = (ImageView) layout.findViewById(R.id.imagem); return new ViewHolder(layout, venue, note, view, imageView); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Local itemSelecionado = modelos.getAvfms().get(position); File folder = context.getFilesDir(); if (!folder.exists()) { folder.mkdirs(); } File mediaFile = new File(folder.getPath() + File.pathSeparator + itemSelecionado.getImage()); if (!mediaFile.exists()) { Picasso.with(context) .load(URL_WALLPAPER + itemSelecionado.getImage()) .into(new TargetPicasso(itemSelecionado.getImage(), context)); } //TODO ajustar tamanho da imagem Picasso.with(context).load(mediaFile).fit().into(holder.imageView); holder.venue.setText(itemSelecionado.getVenue()); holder.note.setText(itemSelecionado.getNote()); holder.view.setText(String.valueOf(itemSelecionado.getViews())); } @Override public int getItemCount() { return modelos.getAvfms().size(); } private final ListaLocal modelos; private final Activity context; public LocalAdapter(ListaLocal modelos, Activity context) { this.modelos = modelos; this.context = context; } public static class ViewHolder extends RecyclerView.ViewHolder { private TextView venue; private TextView note; private TextView view; private ImageView imageView; public ViewHolder(View layout, TextView venue, TextView note, TextView view, ImageView imageView) { super(layout); this.view = view; this.note = note; this.venue = venue; this.imageView = imageView; } } }
package com.smidur.aventon.model; public class SnappedLocation { double latitude; double longitude; public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } }
package com.veyndan.redditclient; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import java.util.Objects; import butterknife.BindView; import butterknife.ButterKnife; public class ProfileActivity extends BaseActivity { private static final int TAB_COUNT = 4; @BindView(R.id.profile_view_pager) ViewPager viewPager; @BindView(R.id.profile_tabs) TabLayout tabs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.profile_activity); ButterKnife.bind(this); String username; final Intent intent = getIntent(); if (intent != null) { username = intent.getStringExtra("username"); } else { throw new IllegalStateException("Activity started by unknown caller"); } final ActionBar ab = getSupportActionBar(); Objects.requireNonNull(ab, "An ActionBar should be attached to this activity"); ab.setDisplayHomeAsUpEnabled(true); ab.setTitle(username); viewPager.setAdapter(new ProfileSectionAdapter(getSupportFragmentManager())); tabs.setupWithViewPager(viewPager); } private static class ProfileSectionAdapter extends FragmentStatePagerAdapter { private static final String titles[] = {"Overview", "Comments", "Submitted", "Gilded"}; public ProfileSectionAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return ProfileSectionFragment.newInstance(); } @Override public int getCount() { return TAB_COUNT; } @Override public CharSequence getPageTitle(int position) { return titles[position]; } } }
package de.dbremes.dbtradealert; import android.content.Intent; import android.content.SharedPreferences; import android.preference.MultiSelectListPreference; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.text.DateFormatSymbols; import java.util.Locale; import java.util.Set; public class SettingsActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String CLASS_NAME = "SettingsActivity"; private static final String SETTINGS_FRAGMENT_TAG = "SettingsFragmentTag"; private static final String BUSINESS_DAYS_PREFERENCE_KEY = "business_days_preference"; private static final String BUSINESS_HOURS_PREFERENCE_KEY = "business_hours_preference"; private void setBusinessTimesPreferenceSummary(String businessTimesPreferenceKey) { SettingsFragment settingsFragment = (SettingsFragment) getFragmentManager().findFragmentByTag(SETTINGS_FRAGMENT_TAG); MultiSelectListPreference businessTimesPreference = (MultiSelectListPreference) settingsFragment .findPreference(businessTimesPreferenceKey); Set businessDays = businessTimesPreference.getValues(); Utils.BusinessTimesPreferenceExtremes btpe = Utils.getBusinessTimesPreferenceExtremes(businessDays); if (businessTimesPreferenceKey.equals(BUSINESS_DAYS_PREFERENCE_KEY)) { String[] shortDayNames = DateFormatSymbols.getInstance(Locale.US).getShortWeekdays(); businessTimesPreference.setSummary( String.format("Days on which auto refresh is active (%s - %s)", shortDayNames[btpe.getFirstBusinessTime()], shortDayNames[btpe.getLastBusinessTime()])); } else { businessTimesPreference.setSummary( String.format("Hours on which auto refresh is active (%02d - %02d)", btpe.getFirstBusinessTime(), btpe.getLastBusinessTime())); } } // setBusinessTimesPreferenceSummary() @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment(), SETTINGS_FRAGMENT_TAG) .commit(); // Without this findFragmentByTag() would return null! getFragmentManager().executePendingTransactions(); setBusinessTimesPreferenceSummary(BUSINESS_DAYS_PREFERENCE_KEY); setBusinessTimesPreferenceSummary(BUSINESS_HOURS_PREFERENCE_KEY); } // onCreate() @Override protected void onPause() { super.onPause(); PreferenceManager.getDefaultSharedPreferences(this) .unregisterOnSharedPreferenceChangeListener(this); } // onPause() @Override protected void onResume() { super.onResume(); PreferenceManager.getDefaultSharedPreferences(this) .registerOnSharedPreferenceChangeListener(this); } // onResume() public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { final String METHOD_NAME = "onSharedPreferenceChanged"; Log.d(CLASS_NAME, METHOD_NAME + "(): key = " + key); switch (key) { case "auto_refresh_preference": { Intent intent = new Intent(this, QuoteRefreshScheduler.class); sendBroadcast(intent); break; } case BUSINESS_DAYS_PREFERENCE_KEY: case BUSINESS_HOURS_PREFERENCE_KEY: setBusinessTimesPreferenceSummary(key); break; default: Log.e(CLASS_NAME, METHOD_NAME + "(): Unexpected key= " + key); break; } } // onSharedPreferenceChanged() } // class SettingsActivity
package io.akessler.elixircounter; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.CountDownTimer; import android.os.IBinder; import android.support.annotation.Nullable; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.Button; public class OverlayService extends Service { WindowManager windowManager; Button[] counterButtons; Button startButton; CountDownTimer regularElixirTimer; CountDownTimer doubleElixirTimer; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); ElixirStore.createInstance(this, windowManager); // TODO Revisit this design pattern... initTimers(); initStartButton(); // TODO initStopButton(); initCounterButtons(); } @Override public void onDestroy() { super.onDestroy(); regularElixirTimer.cancel(); doubleElixirTimer.cancel(); // FIXME Remove TextView from ElixirStore windowManager.removeView(startButton); for(int i = 0; i< counterButtons.length; i++) { Button b = counterButtons[i]; if(counterButtons[i] != null) { windowManager.removeView(b); } } } private void initTimers() { doubleElixirTimer = new CountDownTimer(120000, 1400) { public void onTick(long millisUntilFinished) { ElixirStore.add(1); } public void onFinish() { System.out.println("2x elixir time complete."); } }; regularElixirTimer = new CountDownTimer(120000, 2800) { public void onTick(long millisUntilFinished) { ElixirStore.add(1); } public void onFinish() { System.out.println("1x elixir time complete."); ElixirStore.add(1); doubleElixirTimer.start(); } }; } private void initStartButton() { startButton = new Button(this); startButton.setText("Start"); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { regularElixirTimer.start(); startButton.setEnabled(false); startButton.setVisibility(View.GONE); } }); WindowManager.LayoutParams buttonParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // FIXME Acts up on certain API versions WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT ); buttonParams.gravity = Gravity.CENTER; buttonParams.x = 0; buttonParams.y = 0; windowManager.addView(startButton, buttonParams); } private void initCounterButtons() { counterButtons = new Button[11]; for(int i = 0; i < counterButtons.length; i++) { int counterValue = i != 0 ? -i : 1; // FIXME There might be a cleaner way... counterButtons[i] = new CounterButton(this, counterValue); WindowManager.LayoutParams buttonParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // FIXME Acts up on certain API versions WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT ); buttonParams.gravity = Gravity.LEFT | Gravity.TOP; // FIXME Change these values to be dynamic, based on dimensions of screen buttonParams.x = 25; buttonParams.y = (counterButtons.length - i) * 150; windowManager.addView(counterButtons[i], buttonParams); } } }
package me.dotteam.dotprod; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PolylineOptions; import me.dotteam.dotprod.data.HikeDataDirector; import me.dotteam.dotprod.data.LocationPoints; import me.dotteam.dotprod.hw.HikeHardwareManager; import me.dotteam.dotprod.loc.HikeLocationEntity; import me.dotteam.dotprod.loc.HikeLocationListener; public class HikeViewPagerActivity extends FragmentActivity implements HikeLocationListener, HikeFragment.HikeFragmentListener, NavigationFragment.NavigationFragmentListener, EnvCondFragment.EnvCondFragmentListener { /** * Activity's TAG for logging */ private String TAG = "HikeViewPagerActivity"; /** * The number of pages the view pager has. */ private static final int NUM_PAGES = 3; /** * The pager widget, which handles animation and allows swiping horizontally to access previous * and next wizard steps. */ private ViewPager mPager; /** * The pager adapter, which provides the pages to the view pager widget. */ private PagerAdapter mPagerAdapter; /** * References to Fragments within the viewpager * This maintains one instance of each fragment throughout the life of this activity */ private HikeFragment mHikeFragment; private EnvCondFragment mEnvCondFragment; private NavigationFragment mNavFragment; /** * HikeFragment variables and UI element references */ private GoogleMap mMap; private PolylineOptions mMapPolylineOptions; private Button mButtonEndHike; private Button mButtonPauseHike; private ImageView mImageViewEnvArrow; private ImageView mImageViewNavArrow; private boolean mGotLocation = false; private boolean mHikeCurrentlyPaused = false; private boolean mEndHikeButtonLocked = true; private boolean mPauseHikeButtonLocked = false; private boolean mMapReady = false; /** * EnvCondFragment variables and UI element references */ private TextView mTextDisplayHumidity; private TextView mTextDisplayTemperature; private TextView mTextDisplayPressure; private String mHumidityString = "0.0"; private String mTemperatureString = "0.0"; private String mPressureString = "0.0"; /** * NavigationFragment variables and UI element references */ private TextView mTextLatitude; private TextView mTextLongitude; private TextView mTextAltitude; private TextView mTextDistanceTraveled; private TextView mTextStepCount; private float mDistanceTravelled = 0; private String mStepCountString = "0"; private Location mLocation; private LocationPoints mLocationPoints; /** * Reference to HikeHardwareManager */ private HikeHardwareManager mHHM; /** * Listener for HikeHardwareManager */ private HikeSensorListener mSensorListener; /** * Reference to HikeLocationEntity */ private HikeLocationEntity mHLE; /** * Reference to HikeDataDirector */ private HikeDataDirector mHDD; /** * A simple pager adapter that represents 3 ScreenSlidePageFragment objects, in * sequence. */ private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { public ScreenSlidePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: { return mNavFragment; } case 1: { return mHikeFragment; } case 2: { return mEnvCondFragment; } default: { return mHikeFragment; } } } @Override public int getCount() { return NUM_PAGES; } } @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate() Called"); super.onCreate(savedInstanceState); setContentView(R.layout.view_pager); // Instantiate Fragments mHikeFragment = new HikeFragment(); mEnvCondFragment = new EnvCondFragment(); mNavFragment = new NavigationFragment(); // Instantiate a ViewPager and a PagerAdapter. mPager = (ViewPager) findViewById(R.id.pager); mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); mPager.setAdapter(mPagerAdapter); // Set ViewPager Page to the HikeFragment mPager.setCurrentItem(1); // Instantiate HikeHardwareManager mHHM = HikeHardwareManager.getInstance(this); // Start SensorTag connection and pedometer mHHM.startSensors(this); // Create Listener for HikeHardwareManager mSensorListener = new HikeSensorListener(this); // Instantiate HikeDataDirector mHDD = HikeDataDirector.getInstance(this); // Begin collecition service mHDD.beginCollectionService(); // Get HLE reference and add listener mHLE = HikeLocationEntity.getInstance(this); // New LocationPoints object to save coordinates mLocationPoints = new LocationPoints(); // Add Listener to HLE mHLE.addListener(this); // Start Location Updates mHLE.startLocationUpdates(this); //Cleanup any garbage Runtime.getRuntime().gc(); System.gc(); } @Override protected void onStart() { Log.d(TAG, "onStart() Called"); super.onStart(); // Add Listener to HHM mHHM.addListener(mSensorListener); mHHM.startCompass(); } @Override protected void onStop() { Log.d(TAG, "onStop() Called"); super.onStop(); // Remove Listener from HHM mHHM.removeListener(mSensorListener); mHHM.stopCompass(); } @Override public void onBackPressed() { if(mPager.getCurrentItem()!=1) { mPager.setCurrentItem(1); } // else{ // //TODO: make this the same as ending the hike! } @Override public void onLocationChanged(Location location, float distance) { Log.d(TAG, "onLocationChanged"); // Set TextViews to new values if (mTextLatitude != null) { mTextLatitude.setText(String.format("%.2f", location.getLatitude())); } if (mTextLongitude != null) { mTextLongitude.setText(String.format("%.2f", location.getLongitude())); } if (mTextAltitude != null) { mTextAltitude.setText(String.format("%.2f", location.getAltitude())); } if (mLocation == null) { mLocation = new Location(location); if (mMapReady) { LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); mapZoomCameraToLocation(latLng); mMapPolylineOptions.add(latLng); mMap.addPolyline(mMapPolylineOptions); } } else { mLocation = location; if (mMapReady) { LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); mMapPolylineOptions.add(latLng); mMap.addPolyline(mMapPolylineOptions); } mDistanceTravelled += distance; if (mTextDistanceTraveled != null) { mTextDistanceTraveled.setText(String.format("%.2f", mDistanceTravelled)); } } } // HikeFragment Methods and Callbacks @Override public void onMapReady(GoogleMap googleMap) { Log.d(TAG, "onMapReady() Called"); mMap = googleMap; mMapPolylineOptions = new PolylineOptions(); mMapReady = true; // Set Maps Settings UiSettings mapSettings = mMap.getUiSettings(); mapSettings.setTiltGesturesEnabled(false); mapSettings.setMyLocationButtonEnabled(true); mapSettings.setCompassEnabled(true); // Enable MyLocation mMap.setMyLocationEnabled(true); // Set Map Type to Terrain SharedPreferences prefMan=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if(prefMan.contains("display_maptype")){ mMap.setMapType( Integer.parseInt(prefMan.getString( "display_maptype", Integer.toString(GoogleMap.MAP_TYPE_TERRAIN)))); } else { mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); } } @Override public void onHikeFragmentReady() { Log.d(TAG, "onHikeFragmentReady() Called"); // Get references to UI elements mButtonEndHike = mHikeFragment.getButtonEndHike(); mButtonPauseHike = mHikeFragment.getButtonPauseHike(); mImageViewEnvArrow = mHikeFragment.getImageViewEnvArrow(); mImageViewNavArrow = mHikeFragment.getImageViewNavArrow(); // Set callback for End Hike Button mButtonEndHike.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Button currently locked if (!mEndHikeButtonLocked) { AlertDialog.Builder builder = new AlertDialog.Builder(HikeViewPagerActivity.this); builder.setPositiveButton("End Hike", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //End the Hike mHHM.resetPedometer(); mHLE.removeListener(HikeViewPagerActivity.this); mHLE.stopLocationUpdates(); Intent intentResults = new Intent(HikeViewPagerActivity.this, ResultsActivity.class); startActivity(intentResults); mHDD.endCollectionService(); mHHM.stopSensors(); finish(); } }); builder.setNegativeButton("Continue Hike", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Continue the Hike } }); builder.setMessage("Are you sure you would like to end the Hike?"); builder.setTitle("End Hike"); AlertDialog EndHikeAlert = builder.create(); EndHikeAlert.show(); //Unlocking Button } else { mEndHikeButtonLocked = false; mPauseHikeButtonLocked = true; mHikeFragment.setButtonEndHIke(0.2f); mHikeFragment.setButtonPauseHIke(0.8f); } } }); // Set callback for Pause Hike Button mButtonPauseHike.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mPauseHikeButtonLocked) { if (!mHikeCurrentlyPaused) { //Pause the collection and saving of data mHLE.stopLocationUpdates(); mHHM.stopSensors(); mHHM.startCompass(); //keep compass on mHDD.setPauseStatus(true); mHikeCurrentlyPaused = true; AlertDialog.Builder builder = new AlertDialog.Builder(HikeViewPagerActivity.this); builder.setPositiveButton("Resume", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //UnPause the collection and saving of data mHLE.startLocationUpdates(HikeViewPagerActivity.this); mHHM.startSensors(HikeViewPagerActivity.this); mHDD.setPauseStatus(false); mHikeCurrentlyPaused = false; } }); builder.setMessage("The Hike is Paused, would you like to resume?"); builder.setTitle("Hike Paused"); AlertDialog pauseAlert = builder.create(); pauseAlert.setCancelable(false); pauseAlert.setCanceledOnTouchOutside(false); pauseAlert.show(); } } else{ //Unlocking Button mEndHikeButtonLocked = true; mPauseHikeButtonLocked = false; mHikeFragment.setButtonEndHIke(0.8f); mHikeFragment.setButtonPauseHIke(0.2f); } } }); //Set callback for Nav-Arrow ImageView mImageViewNavArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPager.setCurrentItem(0); } }); //Set callback for Env-Arrow ImageView mImageViewEnvArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPager.setCurrentItem(2); } }); } private void mapZoomCameraToLocation(final LatLng latlng) { runOnUiThread(new Runnable() { @Override public void run() { mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(17)); mGotLocation = true; } }); } private void mapZoomCameraToLocation(Location location) { LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); mapZoomCameraToLocation(latLng); } void updateTemperature(final String temp) { mTemperatureString = temp; runOnUiThread(new Runnable() { @Override public void run() { if (mTextDisplayTemperature != null) { mTextDisplayTemperature.setText(temp); } } }); } void updateHumidity(final String hum) { mHumidityString = hum; runOnUiThread(new Runnable() { @Override public void run() { if (mTextDisplayHumidity != null) { mTextDisplayHumidity.setText(hum); } } }); } void updatePressure(final String pressure) { mPressureString = pressure; runOnUiThread(new Runnable() { @Override public void run() { if (mTextDisplayPressure != null) { mTextDisplayPressure.setText(pressure); } } }); } void updateStepCount(final String stepcount) { mStepCountString = stepcount; runOnUiThread(new Runnable() { @Override public void run() { if (mTextStepCount != null) { mTextStepCount.setText(stepcount); } } }); } void updateCompass(double degrees){ //Send it of to the fragment mHikeFragment.updateCompass(degrees); } // EnvCondFragment Methods and Callbacks @Override public void onEnvCondFragmentReady() { Log.d(TAG, "onEnvCondFragmentReady() Called"); // Get references to UI elements mTextDisplayHumidity = mEnvCondFragment.getTextDisplayHumidity(); mTextDisplayPressure = mEnvCondFragment.getTextDisplayPressure(); mTextDisplayTemperature = mEnvCondFragment.getTextDisplayTemperature(); // Set Text Initial Values mTextDisplayHumidity.setText(mHumidityString); mTextDisplayPressure.setText(mPressureString); mTextDisplayTemperature.setText(mTemperatureString); } // NavigationFragment Methods and Callbacks @Override public void onNavigationFragmentReady() { Log.d(TAG, "onNavigationFragmentReady() Called"); mTextLatitude = mNavFragment.getTextLatitude(); mTextLongitude = mNavFragment.getTextLongitude(); mTextAltitude = mNavFragment.getTextAltitude(); mTextDistanceTraveled = mNavFragment.getTextDistanceTraveled(); mTextStepCount = mNavFragment.getTextStepCount(); // Set Values to previous values if (mLocation != null) { mTextLatitude.setText(String.format("%.2f", mLocation.getLatitude())); mTextLongitude.setText(String.format("%.2f", mLocation.getLongitude())); mTextAltitude.setText(String.format("%.2f",mLocation.getAltitude())); } else { mTextLatitude.setText("0.0"); mTextLongitude.setText("0.0"); mTextAltitude.setText("0.0"); } mTextDistanceTraveled.setText(String.valueOf(mDistanceTravelled)); mTextStepCount.setText(mStepCountString); } }
package mozilla.org.webmaker; import android.app.Application; import android.content.res.Resources; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; import mozilla.org.webmaker.activity.*; import mozilla.org.webmaker.router.Router; public class WebmakerApplication extends Application { private WebmakerApplication singleton; private GoogleAnalytics analytics; private Tracker tracker; public WebmakerApplication getInstance() { return singleton; } public GoogleAnalytics getAnalytics() { return analytics; } public Tracker getTracker() { return tracker; } @Override public void onCreate() { super.onCreate(); singleton = this; Resources res = getResources(); // Dry run allows you to debug Google Analytics locally without sending data to any servers. analytics = GoogleAnalytics.getInstance(this); analytics.setDryRun(BuildConfig.DEBUG); tracker = analytics.newTracker(R.xml.app_tracker); tracker.setAppId(res.getString(R.string.ga_appId)); tracker.setAppName(res.getString(R.string.ga_appName)); tracker.enableAutoActivityTracking(true); tracker.enableExceptionReporting(true); Router.sharedRouter().setContext(getApplicationContext()); Router.sharedRouter().map("/main", MainActivity.class); Router.sharedRouter().map("/main/:tab", MainActivity.class); Router.sharedRouter().map("/projects/:project", Project.class); Router.sharedRouter().map("/projects/:project/pages/:page", Page.class); Router.sharedRouter().map("/projects/:project/pages/:page/elements/:element/editor/:editor", Element.class); Router.sharedRouter().map("/projects/:project/pages/:page/elements/:element/attributes/:attribute/editor/:editor", Tinker.class); Router.sharedRouter().map("/projects/:project/settings", ProjectSettings.class); Router.sharedRouter().map("/projects/:project/:mode", Play.class); // @todo Restore state } @Override public void onLowMemory() { super.onLowMemory(); } @Override public void onTerminate() { super.onTerminate(); } }
package pwittchen.com.icsl.activity; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; import com.pwitchen.icsl.library.InternetConnectionStateListener; import com.pwitchen.icsl.library.event.ConnectivityStatusChangedEvent; import com.squareup.otto.Subscribe; import pwittchen.com.icsl.R; import pwittchen.com.icsl.eventbus.BusProvider; public class MainActivity extends Activity { private InternetConnectionStateListener internetConnectionStateListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating new instance of InternetConnectionStateListener class // passing Context and instance of Otto Event Bus internetConnectionStateListener = new InternetConnectionStateListener(this, BusProvider.getInstance()); // register InternetConnectionStateListener internetConnectionStateListener.register(); } @Override protected void onResume() { super.onResume(); BusProvider.getInstance().register(this); } @Override protected void onPause() { super.onPause(); BusProvider.getInstance().unregister(this); } @Override protected void onDestroy() { super.onDestroy(); // unregister InternetConnectionStateListener internetConnectionStateListener.unregister(); } @Subscribe public void connectivityStatusChanged(ConnectivityStatusChangedEvent event) { // subscribing for ConnectivityStatusChangedEvent // when Connectivity status changes, we can perform any action we want to // in this case, we are simply displaying toast with connectivity status Toast.makeText(this, event.getConnectivityStatus().toString(), Toast.LENGTH_SHORT).show(); } }
package tomas_vycital.eet.android_app.items; import android.support.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; import java.text.DecimalFormat; import tomas_vycital.eet.android_app.VAT; public class Item implements Comparable<Item> { public static DecimalFormat priceFormat = new DecimalFormat("0.00"); private final int price; private final String name; private final VAT vat; Item(String name, int price, VAT vat) { this.name = name; this.price = price; this.vat = vat; } public Item(String name, String priceStr, VAT vat) { String[] priceParts = priceStr.replaceAll("[^\\d,.]", "").split("[,.]"); int price = Integer.valueOf(priceParts[0]) * 100; if (priceParts.length > 1) { switch (priceParts[1].length()) { case 0: priceParts[1] = "0"; break; case 1: priceParts[1] += "0"; break; case 2: break; default: priceParts[1] = priceParts[1].substring(0, 2); } price += Integer.valueOf(priceParts[1]); } this.name = name; this.price = price; this.vat = vat; } Item(JSONObject object) throws JSONException { this.name = (String) object.get("name"); this.price = (int) object.get("price"); this.vat = VAT.fromID((Integer) object.get("VAT")); } JSONObject toJSON() throws JSONException { JSONObject json = new JSONObject(); json.put("name", this.name); json.put("price", this.price); json.put("VAT", this.vat.getID()); return json; } public String getName() { return name; } public int getPrice() { return price; } public String getPriceStr() { return Item.priceFormat.format(this.price / 100.0) + " kč"; } public String getPriceRawStr() { return Item.priceFormat.format(this.price / 100.0); } public VAT getVAT() { return this.vat; } public int getVATPercentage() { return this.vat.getPercentage(); } public String getDPHStr() { return this.vat.toString(); } public String getBrief() { return this.name + " (" + this.price / 100f + ",-)"; } @Override public int compareTo(@NonNull Item another) { return this.name.compareTo(another.name); } }
package uk.co.pilllogger.activities; import android.app.ActionBar; import android.app.Fragment; import android.app.FragmentTransaction; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.Toast; import com.crashlytics.android.Crashlytics; import java.util.Date; import java.util.HashMap; import java.util.List; import uk.co.pilllogger.R; import uk.co.pilllogger.adapters.SlidePagerAdapter; import uk.co.pilllogger.animations.FadeBackgroundPageTransformer; import uk.co.pilllogger.dialogs.ThemeChoiceDialog; import uk.co.pilllogger.fragments.ConsumptionListFragment; import uk.co.pilllogger.fragments.PillListFragment; import uk.co.pilllogger.fragments.StatsFragment; import uk.co.pilllogger.helpers.FeedbackHelper; import uk.co.pilllogger.helpers.TrackerHelper; import uk.co.pilllogger.models.Consumption; import uk.co.pilllogger.models.Pill; import uk.co.pilllogger.state.Observer; import uk.co.pilllogger.state.State; import uk.co.pilllogger.tasks.GetFavouritePillsTask; import uk.co.pilllogger.tasks.GetPillsTask; import uk.co.pilllogger.tasks.GetTutorialSeenTask; import uk.co.pilllogger.tasks.InsertConsumptionTask; import uk.co.pilllogger.themes.ITheme; import uk.co.pilllogger.themes.ProfessionalTheme; import uk.co.pilllogger.themes.RainbowTheme; import uk.co.pilllogger.tutorial.ConsumptionListTutorialPage; import uk.co.pilllogger.tutorial.PillsListTutorialPage; import uk.co.pilllogger.tutorial.TutorialPage; import uk.co.pilllogger.tutorial.TutorialService; import uk.co.pilllogger.views.ColourIndicator; import uk.co.pilllogger.views.MyViewPager; import uk.co.pilllogger.widget.MyAppWidgetProvider; public class MainActivity extends PillLoggerActivityBase implements GetPillsTask.ITaskComplete, Observer.IPillsUpdated, GetFavouritePillsTask.ITaskComplete, GetTutorialSeenTask.ITaskComplete, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = "MainActivity"; private MyViewPager _fragmentPager; private PagerAdapter _fragmentPagerAdapter; private int _colour1 = Color.argb(120, 0, 233, 255); private int _colour2 = Color.argb(120, 204, 51, 153); private int _colour3 = Color.argb(120, 81, 81, 81); View _colourBackground; private Menu _menu; Fragment _consumptionFragment; private TutorialService _tutorialService; private boolean _themeChanged; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); boolean isDebuggable = ( 0 != ( getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE ) ); if(!isDebuggable) Crashlytics.start(this); _themeChanged = false; SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); updateTheme(getString(R.string.pref_key_theme_list)); ViewGroup wrapper = setContentViewWithWrapper(R.layout.activity_main); this.setTitle("Consumption"); _colourBackground = findViewById(R.id.colour_background); Typeface ttf = Typeface.create("sans-serif-condensed", Typeface.NORMAL); State.getSingleton().setTypeface(ttf); _consumptionFragment = new ConsumptionListFragment(); final Fragment fragment2 = new PillListFragment(); final Fragment fragment3 = new StatsFragment(); _fragmentPager = (MyViewPager)findViewById(R.id.fragment_pager); final MainActivity activity = this; _fragmentPager.setOffscreenPageLimit(2); _fragmentPager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageScrollStateChanged(int state) { super.onPageScrollStateChanged(state); if (state == ViewPager.SCROLL_STATE_IDLE) { setBackgroundColour(); } } @Override public void onPageSelected(int position) { super.onPageSelected(position); String fragment = ""; switch (position) { case 0: fragment = ConsumptionListFragment.TAG; break; case 1: fragment = PillListFragment.TAG; break; } new GetTutorialSeenTask(MainActivity.this, fragment, activity).execute(); } }); _fragmentPagerAdapter = new SlidePagerAdapter(getFragmentManager(), _consumptionFragment, fragment2, fragment3); _fragmentPager.setAdapter(_fragmentPagerAdapter); if(savedInstanceState != null) { Log.d(TAG, "Loading instance"); _fragmentPager.setCurrentItem(savedInstanceState.getInt("item")); setBackgroundColour(); } View tutorial = findViewById(R.id.tutorial_layout); ViewGroup parent = (ViewGroup) tutorial.getParent(); if(parent != null){ parent.removeView(tutorial); } FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); tutorial.setLayoutParams(params); wrapper.addView(tutorial); setupChrome(); int tabMaskColour = getResources().getColor(State.getSingleton().getTheme().getTabMaskColourResourceId()); _fragmentPager.setPageTransformer(true, new FadeBackgroundPageTransformer(_colourBackground, this, tabMaskColour)); Observer.getSingleton().registerPillsUpdatedObserver(this); defaultSharedPreferences.registerOnSharedPreferenceChangeListener(this); new GetPillsTask(this, this).execute(); Integer gradientBackgroundResourceId = State.getSingleton().getTheme().getWindowBackgroundResourceId(); Drawable background = gradientBackgroundResourceId == null ? null : getResources().getDrawable(gradientBackgroundResourceId); getWindow().setBackgroundDrawable(background); } @Override protected void onResume(){ super.onResume(); if(_themeChanged){ finish(); Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } } @Override protected void onPostResume() { SetupTutorial(); super.onPostResume(); } private void showChangesDialog(){ Intent composeIntent = new Intent(this, WebViewActivity.class); composeIntent.putExtra(getString(R.string.key_show_feedback_button), true); composeIntent.putExtra(getString(R.string.key_web_address), "file:///android_asset/html/changelog.html"); startActivity(composeIntent); } private void setBackgroundColour(){ int page = _fragmentPager.getCurrentItem(); Log.d(TAG, "Set currentItem to " + page); // TODO: This code will break when colours change in fragments, needs to be updated switch(page) { case 0: _colourBackground.setBackgroundColor(_colour1); break; case 1: _colourBackground.setBackgroundColor(_colour2); break; case 2: _colourBackground.setBackgroundColor(_colour3); break; } } private void setupChrome(){ final ActionBar actionBar = getActionBar(); if(actionBar != null){ //actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); // Specify that tabs should be displayed in the action bar. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); final ActionBar actionBar1 = actionBar; // Create a tab listener that is called when the user changes tabs. ActionBar.TabListener tabListener = new ActionBar.TabListener() { public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { _fragmentPager.setCurrentItem(tab.getPosition()); } public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { } public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { // probably ignore this event } }; actionBar.addTab( actionBar.newTab() .setCustomView(R.layout.tab_icon_consumptions) .setTabListener(tabListener)); actionBar.addTab( actionBar.newTab() .setCustomView(R.layout.tab_icon_pills) .setTabListener(tabListener)); actionBar.addTab( actionBar.newTab() .setCustomView(R.layout.tab_icon_charts) .setTabListener(tabListener)); View view = findViewById(R.id.main_gradient); if(view != null) view.setBackgroundResource(State.getSingleton().getTheme().getGradientBackgroundResourceId()); } } private ViewGroup setContentViewWithWrapper(int resContent) { ViewGroup decorView = (ViewGroup) this.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0); // Removing decorChild, we'll add it back soon decorView.removeAllViews(); ViewGroup wrapperView = new FrameLayout(this); // You should set some ID, if you'll want to reference this wrapper in that manner later // The ID, such as "R.id.ACTIVITY_LAYOUT_WRAPPER" can be set at a resource file, such as: // <item type="id" name="ACTIVITY_LAYOUT_WRAPPER"/> // </resources> wrapperView.setId(R.id.activity_layout_wrapper); // Now we are rebuilding the DecorView, but this time we // have our wrapper view to stand between the real content and the decor decorView.addView(wrapperView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT); wrapperView.addView(decorChild, decorChild.getLayoutParams()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2){ LayoutInflater.from(this).inflate(resContent, (ViewGroup)((FrameLayout)wrapperView.getChildAt(0)).getChildAt(0), true);} //This is for KitKat and Jelly 4.3 else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ LayoutInflater.from(this).inflate(resContent, (ViewGroup) (((ViewGroup) wrapperView.getChildAt(0)).getChildAt(0)), true);} return wrapperView; } private void SetupTutorial(){ HashMap<String, TutorialPage> pages = new HashMap<String, TutorialPage>(); View tutorialLayout = findViewById(R.id.tutorial_layout); TutorialPage consumptionTutorial = new ConsumptionListTutorialPage(this, tutorialLayout); TutorialPage pillsTutorial = new PillsListTutorialPage(this, tutorialLayout); pages.put(ConsumptionListFragment.TAG, consumptionTutorial); pages.put(PillListFragment.TAG, pillsTutorial); _tutorialService = new TutorialService(pages); new GetTutorialSeenTask(MainActivity.this, ConsumptionListFragment.TAG, this).execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_main_menu, menu); _menu = menu; new GetFavouritePillsTask(this, this).execute(); return super.onCreateOptionsMenu(menu); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.d(TAG, "Saving instance"); outState.putInt("item", _fragmentPager.getCurrentItem()); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.add_consumption: startAddConsumptionActivity(); return true; case R.id.action_settings: startSettingsActivity(); return true; case R.id.action_feedback: sendFeedbackIntent(); return true; default: return super.onOptionsItemSelected(item); } } private void startSettingsActivity() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } private void sendFeedbackIntent(){ FeedbackHelper.sendFeedbackIntent(this); } private void startAddConsumptionActivity(){ Intent intent = new Intent(this, AddConsumptionActivity.class); this.startActivity(intent); } @Override public void pillsReceived(List<Pill> pills) { try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); int version = pInfo.versionCode; SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); if(pills.size() > 0) { // if they've setup a pill (ie. they are using the app). Show recent changes int seenVersion = defaultSharedPreferences.getInt(getString(R.string.seenVersionKey), 0); if (version > seenVersion) showChangesDialog(); if(defaultSharedPreferences.getString(getString(R.string.pref_key_theme_list), "").equals("")) { new ThemeChoiceDialog().show(getFragmentManager(), "ThemeChoiceDialog"); } } else{ SharedPreferences.Editor editor = defaultSharedPreferences.edit(); editor.putInt(getString(R.string.seenVersionKey), version); editor.putString(getString(R.string.pref_key_theme_list), getString(R.string.professionalTheme)); editor.apply(); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } private void addPillToMenu(Pill pill){ MenuItem item = _menu.findItem(pill.getId()); if(item == null) item = _menu.add(Menu.NONE, pill.getId(), Menu.NONE, "Take " + pill.getName()); item.setTitleCondensed(pill.getName().substring(0, 1)); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = item.getActionView(); if(v == null) v = layoutInflater.inflate(R.layout.favourite_pill, null); if(pill.getName().length() > 0){ ColourIndicator letter = (ColourIndicator) v.findViewById(R.id.colour); letter.setColour(pill.getColour()); item.setActionView(v); final Pill p = pill; letter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View item) { addConsumption(p); } }); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { addConsumption(p); return false; } }); } } private void addConsumption(Pill pill){ Consumption consumption = new Consumption(pill, new Date()); new InsertConsumptionTask(MainActivity.this, consumption).execute(); TrackerHelper.addConsumptionEvent(MainActivity.this, "FavouriteMenu"); Toast.makeText(MainActivity.this, "Added consumption of " + pill.getName(), Toast.LENGTH_SHORT).show(); } @Override public void pillsUpdated(final Pill pill) { if(_menu == null || pill == null) return; runOnUiThread(new Runnable(){ public void run(){ if(pill.isFavourite()){ addPillToMenu(pill); } else{ _menu.removeItem(pill.getId()); } } }); Intent intent = new Intent(this, MyAppWidgetProvider.class); intent.setAction("android.appwidget.action.APPWIDGET_UPDATE"); int ids[] = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), MyAppWidgetProvider.class)); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); sendBroadcast(intent); } @Override public void favouritePillsReceived(List<Pill> pills) { if(_menu == null) return; for (Pill pill : pills) { if (_menu.findItem(pill.getId()) == null) { addPillToMenu(pill); } } } public void startTutorial(String tag) { final TutorialPage page = _tutorialService.getTutorialPage(tag); if(page == null) { return; // no tutorial available for this page } if(page.getLayout() == null || page.getTutorialText() == null) return; // we can't be tutorialling if the views aren't there! if(page.isFinished()){ return; } page.resetPage(); page.getLayout().setAlpha(0f); page.getLayout().setVisibility(View.VISIBLE); page.getLayout().animate() .alpha(1f) .setDuration(500) .setListener(null); page.getLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { page.nextHint(); } }); } @Override public void isTutorialSeen(Boolean seen, String tag) { if(!seen) // comment this line out to force tutorial startTutorial(tag); } private boolean updateTheme(String key){ if(key.equals(getString(R.string.pref_key_theme_list))) { String themeKey = PreferenceManager.getDefaultSharedPreferences(this).getString(key, getString(R.string.professionalTheme)); ITheme theme = new ProfessionalTheme(); if (themeKey.equals(getString(R.string.rainbowTheme))) { theme = new RainbowTheme(); } if (themeKey.equals(getString(R.string.professionalTheme))) { theme = new ProfessionalTheme(); } State.getSingleton().setTheme(theme); _colour1 = getResources().getColor(theme.getConsumptionListBackgroundResourceId()); _colour2 = getResources().getColor(theme.getPillListBackgroundResourceId()); _colour3 = getResources().getColor(theme.getStatsBackgroundResourceId()); setTheme(State.getSingleton().getTheme().getStyleResourceId()); return true; } return false; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { _themeChanged = updateTheme(key); } }
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.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(); String[] randomAnswers = generateRandomAnswers(); 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); 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(randomAnswers[randIndex]); 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; } /** * Generates an invalid random answers * which is not the same as the answer * * @return answerArray - generated random array of answers */ private String[] generateRandomAnswers() { String[] answerArray = new String[3]; ArrayList<QnA> originalList = QnaState.getInstance().getQnaList(true); String answer = mQnaList.get(mQnaIndex).getAnswer(); Random random = new Random(); for (int i = 0; i < answerArray.length; i++) { String randomAnswer = ""; while (randomAnswer.equals("") || randomAnswer.equalsIgnoreCase(answer) || doesRandomAnswerExists(answerArray, randomAnswer)) { int rand = random.nextInt(originalList.size()); randomAnswer = originalList.get(rand).getAnswer(); } answerArray[i] = randomAnswer; } return answerArray; } /** * Checks if the newly generated random answer exists * on the array of random answer * * @param answerArray the array of random answers * @param randomAnswer the newly generated random answer * @return true if the generated random answer is already at the array */ private boolean doesRandomAnswerExists(String[] answerArray, String randomAnswer) { for (String answer : answerArray) { if (answer == null) return false; if (answer.equalsIgnoreCase(randomAnswer)) return true; } return false; } /** * Resets the states of the variables, for resetting QnA */ private void resetQnA() { mQnaIndex = 0; mCorrect = 0; mMistake = 0; mQnaList = QnaState.getInstance().getQnaList(true); Collections.shuffle(mQnaList); 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 && mCorrect != 0) assessment = "Passed!"; startActivity(QnaResultActivity .getStartIntent(this, assessment, mCorrect)); finish(); } }
package org.zordius.ssidlogger; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ToggleButton; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); syncStatus(); } public void syncStatus() { ((ToggleButton) findViewById(R.id.logSwitch)).setChecked(WifiReceiver .isEnabled(this)); ((EditText) findViewById(R.id.editFilename)).setText("test", TextView.BufferType.EDITABLE); } public void onClickLog(View v) { WifiReceiver.toggleScan(this, ((ToggleButton) v).isChecked()); } public void onClickScan(View v) { WifiReceiver.doScan(this); } }
package com.lenddo.sample; import com.google.gson.JsonArray; import com.lenddo.javaapi.LenddoApiCallback; import com.lenddo.javaapi.LenddoScoreApi; import com.lenddo.javaapi.WhiteLabelApi; import com.lenddo.javaapi.models.*; import com.lenddo.javaapi.utils.ApiUtils; public class Sample { public Sample () {} public static class Credentials { public String api_key; public String api_secret; public String partner_script_id; Credentials (String api_key, String api_secret, String partner_script_id) { this.api_key = api_key; this.api_secret = api_secret; this.partner_script_id = partner_script_id; } } public static void main(String[] args) { // Enter your credentials here: String api_key = "YOUR LENDDO PROVIDED API KEY"; String api_secret = "YOUR LENDDO PROVIDED API SECRET"; String partner_script_id = "YOUR LENDDO PROVIDED PARTNER SCRIPT ID"; Credentials credentials = new Credentials(api_key, api_secret, partner_script_id); // Test ApplicationScore API String applicationId = "YOUR APPLICATION ID"; getApplicationScore(credentials, applicationId); // Test ApplicationVerification API getApplicationVerification(credentials, applicationId); // Test Whitelable API String provider = WhiteLabelApi.PROVIDER_WINDOWSLIVE; samplePostPartnerToken(credentials, applicationId, provider); } // TEST CODE FOR GETTING APPLICATION SCORE private static void getApplicationScore(Credentials credentials, String applicationId) { LenddoScoreApi lenddoapi = new LenddoScoreApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id); // Set this to true to see debug messages during debug build. lenddoapi.debugMode(true); lenddoapi.getApplicationScore(applicationId, new LenddoApiCallback<ClientScore>() { @Override public void onResponse(ClientScore clientScore) { System.out.println("Resulting application score: "+ clientScore.score); System.out.println("Resulting application flags: "+ clientScore.flags); } @Override public void onFailure(Throwable throwable) { System.out.println("Network Connection Failed: "+ throwable.getMessage()); } @Override public void onError(String errormessage) { System.out.println("Returned error: "+ errormessage); } }); } // TEST CODE FOR GETTING APPLICATION VERIFICATION private static void getApplicationVerification(Credentials credentials, String applicationId) { LenddoScoreApi lenddoapi = new LenddoScoreApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id); // Set this to true to see debug messages during debug build. lenddoapi.debugMode(true); lenddoapi.getApplicationVerification(applicationId, new LenddoApiCallback<ClientVerification>() { @Override public void onResponse(ClientVerification response) { // Sample responses System.out.println("ApplicationVerification: "+ ApiUtils.convertObjectToJsonString(response)); System.out.println("probes: "+ ApiUtils.convertObjectToJsonString(response.probes)); System.out.println("probe name: "+ response.probes.name); System.out.println("probe firstname: "+ response.probes.name.get(0)); } @Override public void onFailure(Throwable throwable) { System.out.println("Network Connection Failed: "+ throwable.getMessage()); } @Override public void onError(String errormessage) { System.out.println("Returned error: "+ errormessage); } }); } // TEST CODE FOR PARTNERTOKEN API private static void samplePostPartnerToken(final Credentials credentials, final String applicationId, String provider) { WhiteLabelApi whiteLabelApi = new WhiteLabelApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id); WhitelabelRequestBody.WLPartnerTokenRqBody.token_data td = new WhitelabelRequestBody.WLPartnerTokenRqBody.token_data(); // add a token in the td.key and a secret in td.secret td.key = "ACCESS TOKEN FROM YOUR CHOSEN PROVIDER"; // td.secret = "SECRET FROM YOUR CHOSEN PROVIDER (IF APPLICABLE)"; whiteLabelApi.postPartnerToken(applicationId, provider, td, new LenddoApiCallback<PartnerToken>() { @Override public void onResponse(PartnerToken response) { System.out.println("response="+ response.profile_id); // get the profile ids from the response and use postCommitPartnerJob() to send the profile ids. samplePostCommitPartnerJob(credentials, applicationId, response.profile_id); } @Override public void onFailure(Throwable t) { System.out.println("Connection Failure: "+t.getMessage()); } @Override public void onError(String errormessage) { System.out.println("Returned error: "+errormessage); } }); } // TEST CODE FOR COMMITPARTNERJOB API private static void samplePostCommitPartnerJob(Credentials credentials, String applicationId, String profileId) { WhiteLabelApi whiteLabelApi = new WhiteLabelApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id); JsonArray profile_ids = new JsonArray(); profile_ids.add(profileId); Verification verification = new Verification(); // at this point, you need to add details for the verification object. (name, employer, etc). verification.name.first="firstname"; verification.name.last="lastname"; whiteLabelApi.postCommitPartnerJob(applicationId, profile_ids, verification, new LenddoApiCallback() { @Override public void onResponse(Object response) { System.out.println("response="+ ApiUtils.convertObjectToJsonString(response)); } @Override public void onFailure(Throwable t) { System.out.println("Connection Failure: "+t.getMessage()); } @Override public void onError(String errormessage) { System.out.println("Returned error: "+errormessage); } }); } }
package org.basex.query.func; import static org.basex.core.Text.*; import static org.basex.query.QueryError.*; import static org.basex.query.func.Function.*; import static org.junit.Assert.*; import java.util.*; import org.basex.core.*; import org.basex.core.cmd.*; import org.basex.core.cmd.Set; import org.basex.core.parse.Commands.*; import org.basex.io.*; import org.basex.query.*; import org.basex.util.*; import org.basex.util.http.*; import org.basex.util.list.*; import org.basex.util.options.*; import org.junit.*; import org.junit.Test; public final class DbModuleTest extends AdvancedQueryTest { /** Test file. */ private static final String XML = "src/test/resources/input.xml"; /** Test file. */ private static final String CSV = "src/test/resources/input.csv"; /** Test folder. */ private static final String FLDR = "src/test/resources/dir/"; /** Number of XML files for folder. */ private static final int XMLFILES; static { int files = 0; for(final IOFile file : new IOFile(FLDR).children()) { if(file.name().endsWith(IO.XMLSUFFIX)) ++files; } XMLFILES = files; } /** * Initializes a test. */ @Before public void initTest() { execute(new CreateDB(NAME, XML)); } /** * Finalizes tests. */ @After public void finish() { set(MainOptions.TEXTINCLUDE, ""); set(MainOptions.ATTRINCLUDE, ""); set(MainOptions.TOKENINCLUDE, ""); set(MainOptions.FTINCLUDE, ""); execute(new DropDB(NAME)); } /** * Test method. */ @Test public void open() { query(COUNT.args(_DB_OPEN.args(NAME)), "1"); query(COUNT.args(_DB_OPEN.args(NAME, "")), "1"); query(COUNT.args(_DB_OPEN.args(NAME, "unknown")), "0"); // close database instance execute(new Close()); query(COUNT.args(_DB_OPEN.args(NAME, "unknown")), "0"); query(_DB_OPEN.args(NAME) + "//title/text()", "XML"); // reference invalid path if(Prop.WIN) error(_DB_OPEN.args(NAME, "*"), RESINV_X); // run function on non-existing database execute(new DropDB(NAME)); error(_DB_OPEN.args(NAME), BXDB_OPEN_X); } /** Test method. */ @Test public void openPre() { query(_DB_OPEN_PRE.args(NAME, 0) + "//title/text()", "XML"); error(_DB_OPEN_PRE.args(NAME, -1), BXDB_RANGE_X_X_X); error(_DB_OPEN_PRE.args(NAME, Integer.MAX_VALUE), BXDB_RANGE_X_X_X); } /** Test method. */ @Test public void openId() { query(_DB_OPEN_ID.args(NAME, 0) + "//title/text()", "XML"); error(_DB_OPEN_ID.args(NAME, -1), BXDB_RANGE_X_X_X); error(_DB_OPEN_ID.args(NAME, Integer.MAX_VALUE), BXDB_RANGE_X_X_X); } /** Test method. */ @Test public void text() { // run function without and with index execute(new DropIndex(CmdIndex.TEXT)); error(_DB_TEXT.args(NAME, "XML"), BXDB_INDEX_X); execute(new CreateIndex(CmdIndex.TEXT)); query(_DB_TEXT.args(NAME, "XML"), "XML"); query(_DB_TEXT.args(NAME, "XXX"), ""); } /** Test method. */ @Test public void textRange() { // run function without and with index execute(new DropIndex(CmdIndex.TEXT)); error(_DB_TEXT_RANGE.args(NAME, "Exercise", "Fun"), BXDB_INDEX_X); execute(new CreateIndex(CmdIndex.TEXT)); query(_DB_TEXT_RANGE.args(NAME, "Exercise", "Fun"), "Exercise 1\nExercise 2"); query(_DB_TEXT_RANGE.args(NAME, "XXX", "XXX"), ""); } /** Test method. */ @Test public void attribute() { // run function without and with index execute(new DropIndex(CmdIndex.ATTRIBUTE)); error(DATA.args(_DB_ATTRIBUTE.args(NAME, "0")), BXDB_INDEX_X); execute(new CreateIndex(CmdIndex.ATTRIBUTE)); query(DATA.args(_DB_ATTRIBUTE.args(NAME, "0")), "0"); query(DATA.args(_DB_ATTRIBUTE.args(NAME, "0", "id")), "0"); query(DATA.args(_DB_ATTRIBUTE.args(NAME, "0", "XXX")), ""); query(DATA.args(_DB_ATTRIBUTE.args(NAME, "XXX")), ""); } /** Test method. */ @Test public void attributeRange() { // run function without and with index execute(new DropIndex(CmdIndex.ATTRIBUTE)); error(_DB_ATTRIBUTE_RANGE.args(NAME, "0", "9") + "/data()", BXDB_INDEX_X); execute(new CreateIndex(CmdIndex.ATTRIBUTE)); query(_DB_ATTRIBUTE_RANGE.args(NAME, "0", "9") + "/data()", "0\n1"); query(_DB_ATTRIBUTE_RANGE.args(NAME, "XXX", "XXX"), ""); } /** Test method. */ @Test public void token() { // run function without and with index execute(new DropIndex(CmdIndex.TOKEN)); error(DATA.args(_DB_TOKEN.args(NAME, "0")), BXDB_INDEX_X); execute(new CreateIndex(CmdIndex.TOKEN)); query(DATA.args(_DB_TOKEN.args(NAME, "0")), "0"); query(DATA.args(_DB_TOKEN.args(NAME, "0", "id")), "0"); query(DATA.args(_DB_TOKEN.args(NAME, "0", "XXX")), ""); query(DATA.args(_DB_TOKEN.args(NAME, "XXX")), ""); } /** Test method. */ @Test public void list() { // add documents execute(new Add("test/docs", FLDR)); contains(_DB_LIST.args(NAME), "test/docs"); contains(_DB_LIST.args(NAME, "test/"), "test/docs"); contains(_DB_LIST.args(NAME, "test/docs/input.xml"), "input.xml"); query(_DB_STORE.args(NAME, "bin/b", "b")); query(_DB_LIST.args(NAME, "bin/"), "bin/b"); query(_DB_LIST.args(NAME, "bin/b"), "bin/b"); // create two other database and compare substring execute(new CreateDB(NAME + 1)); execute(new CreateDB(NAME + 2)); contains(_DB_LIST.args(), NAME + 1 + '\n' + NAME + 2); execute(new DropDB(NAME + 1)); execute(new DropDB(NAME + 2)); } /** Test method. */ @Test public void listDetails() { query(_DB_LIST_DETAILS.args() + "/@resources/string()", "1"); query(_DB_ADD.args(NAME, "\"<a/>\"", "xml")); query(_DB_STORE.args(NAME, "raw", "bla")); final String xmlCall = _DB_LIST_DETAILS.args(NAME, "xml"); query(xmlCall + "/@raw/data()", "false"); query(xmlCall + "/@content-type/data()", MediaType.APPLICATION_XML.toString()); query(xmlCall + "/@modified-date/xs:dateTime(.)"); query(xmlCall + "/@size/data()", "2"); query(xmlCall + "/text()", "xml"); final String rawCall = _DB_LIST_DETAILS.args(NAME, "raw"); query(rawCall + "/@raw/data()", "true"); query(rawCall + "/@content-type/data()", MediaType.APPLICATION_OCTET_STREAM.toString()); query(rawCall + "/@modified-date/xs:dateTime(.) > " + "xs:dateTime('1971-01-01T00:00:01')", "true"); query(rawCall + "/@size/data()", "3"); query(rawCall + "/text()", "raw"); query(_DB_LIST_DETAILS.args(NAME, "test"), ""); error(_DB_LIST_DETAILS.args("mostProbablyNotAvailable"), BXDB_OPEN_X); } /** Test method. */ @Test public void backups() { query(COUNT.args(_DB_BACKUPS.args(NAME)), "0"); execute(new CreateBackup(NAME)); query(COUNT.args(_DB_BACKUPS.args()), "1"); query(COUNT.args(_DB_BACKUPS.args(NAME)), "1"); query(COUNT.args(_DB_BACKUPS.args(NAME) + "/(@database, @date, @size)"), "3"); query(COUNT.args(_DB_BACKUPS.args(NAME + 'X')), "0"); execute(new DropBackup(NAME)); query(COUNT.args(_DB_BACKUPS.args(NAME)), "0"); } /** Test method. */ @Test public void system() { contains(_DB_SYSTEM.args(), Prop.VERSION); } /** Test method. */ @Test public void info() { query("count(" + _DB_INFO.args(NAME) + " SIZE.replaceAll(" |-", "").toLowerCase(Locale.ENGLISH) + ')', 1); } /** Test method. */ @Test public void nodeID() { query(_DB_NODE_ID.args(" /html"), "1"); query(_DB_NODE_ID.args(" / | /html"), "0\n1"); } /** Test method. */ @Test public void nodePre() { query(_DB_NODE_PRE.args(" /html"), "1"); query(_DB_NODE_PRE.args(" / | /html"), "0\n1"); } /** Test method. */ @Test public void output() { query(_DB_OUTPUT.args("x"), "x"); query(_DB_OUTPUT.args("('x','y')"), "x\ny"); query(_DB_OUTPUT.args("<a/>"), "<a/>"); error(_DB_OUTPUT.args("x") + ",1", UPALL); error(_DB_OUTPUT.args(" count#1"), BASX_FITEM_X); error("copy $c := <a/> modify " + _DB_OUTPUT.args("x") + " return $c", BASX_DBTRANSFORM); } /** Test method. */ @Test public void outputCache() { query(_DB_OUTPUT_CACHE.args(), ""); query(_DB_OUTPUT.args("x") + ',' + _DB_OUTPUT.args(_DB_OUTPUT_CACHE.args()), "x\nx"); } /** Test method. */ @Test public void add() { query(COUNT.args(COLLECTION.args(NAME)), "1"); query(_DB_ADD.args(NAME, XML)); query(COUNT.args(COLLECTION.args(NAME)), "2"); query(_DB_ADD.args(NAME, "\"<root/>\"", "t1.xml")); query(COUNT.args(COLLECTION.args(NAME + "/t1.xml") + "/root"), "1"); query(_DB_ADD.args(NAME, " document { <root/> }", "t2.xml")); query(COUNT.args(COLLECTION.args(NAME + "/t2.xml") + "/root"), "1"); query(_DB_ADD.args(NAME, " <root/>", "test/t3.xml")); query(COUNT.args(COLLECTION.args(NAME + "/test/t3.xml") + "/root"), "1"); query(_DB_ADD.args(NAME, XML, "in/")); query(COUNT.args(COLLECTION.args(NAME + "/in/input.xml") + "/html"), "1"); query(_DB_ADD.args(NAME, XML, "test/t4.xml")); query(COUNT.args(COLLECTION.args(NAME + "/test/t4.xml") + "/html"), "1"); query(_DB_ADD.args(NAME, FLDR, "test/dir")); query(COUNT.args(COLLECTION.args(NAME + "/test/dir")), XMLFILES); query("for $f in " + _FILE_LIST.args(FLDR, true, "*.xml") + " return " + _DB_ADD.args(NAME, " '" + FLDR + "' || $f", "dir")); query(COUNT.args(COLLECTION.args(NAME + "/dir")), XMLFILES); query("for $i in 1 to 3 return " + _DB_ADD.args(NAME, "\"<root/>\"", "\"doc\" || $i")); query(COUNT.args(" for $i in 1 to 3 return " + COLLECTION.args('"' + NAME + "/doc\" || $i")), 3); // specify parsing options query(_DB_ADD.args(NAME, " '<a> </a>'", "chop.xml", " map { 'chop':true() }")); query(_DB_OPEN.args(NAME, "chop.xml"), "<a/>"); query(_DB_ADD.args(NAME, " '<a> </a>'", "nochop.xml", " map { 'chop':false() }")); query(_DB_OPEN.args(NAME, "nochop.xml"), "<a> </a>"); // specify parsing options query(_DB_ADD.args(NAME, CSV, "csv.xml", " map { 'parser':'csv','csvparser': 'header=true' }")); query(EXISTS.args(_DB_OPEN.args(NAME, "csv.xml") + "//City"), "true"); query(_DB_ADD.args(NAME, CSV, "csv.xml", " map { 'parser':'csv','csvparser': map { 'header': 'true' } }")); query(EXISTS.args(_DB_OPEN.args(NAME, "csv.xml") + "//City"), "true"); query(_DB_ADD.args(NAME, CSV, "csv.xml", " map { 'parser':'csv','csvparser': map { 'header': true() } }")); query(EXISTS.args(_DB_OPEN.args(NAME, "csv.xml") + "//City"), "true"); error(_DB_ADD.args(NAME, CSV, "csv.xml", " map { 'parser':('csv','html') }"), INVALIDOPT_X); error(_DB_ADD.args(NAME, CSV, "csv.xml", " map { 'parser':'csv','csvparser': map { 'header': ('true','false') } }"), INVALIDOPT_X); error(_DB_ADD.args(NAME, CSV, "csv.xml", " map { 'parser':'csv','csvparser': map { 'headr': 'true' } }"), BASX_WHICH_X); error(_DB_ADD.args(NAME, CSV, "csv.xml", " map { 'parser':'csv','csvparser': 'headr=true' }"), BASX_WHICH_X); } /** Test method. */ @Test public void addWithNS() { query(_DB_ADD.args(NAME, " document { <x xmlns:a='a' a:y='' /> }", "x")); } /** Test method. */ @Test public void delete() { execute(new Add("test/docs", FLDR)); query(_DB_DELETE.args(NAME, "test")); query(COUNT.args(COLLECTION.args(NAME + "/test")), 0); } /** Test method. */ @Test public void create() { execute(new Close()); // create DB without initial content query(_DB_CREATE.args(NAME)); query(_DB_EXISTS.args(NAME), true); // create DB w/ initial content query(_DB_CREATE.args(NAME, "<dummy/>", "t1.xml")); query(_DB_OPEN.args(NAME) + "/root()", "<dummy/>"); // create DB w/ initial content via document constructor query(_DB_CREATE.args(NAME, " document { <dummy/> }", "t2.xml")); query(_DB_OPEN.args(NAME) + "/root()", "<dummy/>"); // create DB w/ initial content given as string query(_DB_CREATE.args(NAME, "\"<dummy/>\"", "t1.xml")); query(_DB_OPEN.args(NAME) + "/root()", "<dummy/>"); // create DB w/ initial content multiple times query(_DB_CREATE.args(NAME, "<dummy/>", "t1.xml")); query(_DB_CREATE.args(NAME, "<dummy/>", "t1.xml")); query(_DB_OPEN.args(NAME) + "/root()", "<dummy/>"); // try to create DB twice during same query error(_DB_CREATE.args(NAME) + ',' + _DB_CREATE.args(NAME), BXDB_ONCE_X_X); // create DB from file query(_DB_CREATE.args(NAME, XML, "in/")); query(COUNT.args(COLLECTION.args(NAME + "/in/input.xml") + "/html"), "1"); // create DB from folder query(_DB_CREATE.args(NAME, FLDR, "test/dir")); query(COUNT.args(COLLECTION.args(NAME + "/test/dir")), XMLFILES); // create DB w/ more than one input query(_DB_CREATE.args(NAME, "(<a/>,<b/>)", "('1.xml','2.xml')")); query(_DB_CREATE.args(NAME, "(<a/>,'" + XML + "')", "('1.xml','2.xml')")); error(_DB_CREATE.args(NAME, "()", "1.xml"), BXDB_CREATEARGS_X_X); error(_DB_CREATE.args(NAME, "(<a/>,<b/>)", "1.xml"), BXDB_CREATEARGS_X_X); // create and drop more than one database query("for $i in 1 to 5 return " + _DB_CREATE.args(" '" + NAME + "' || $i")); query("for $i in 1 to 5 return " + _DB_DROP.args(" '" + NAME + "' || $i")); // create DB with initial EMPTY content error(_DB_CREATE.args(""), BXDB_NAME_X); // try to access non-existing DB query(_DB_DROP.args(NAME)); error(_DB_CREATE.args(NAME) + ',' + _DB_DROP.args(NAME), BXDB_WHICH_X); // run update on existing DB then drop it and create a new one query(_DB_CREATE.args(NAME, "<a/>", "a.xml")); query("insert node <dummy/> into " + _DB_OPEN.args(NAME)); query(_DB_CREATE.args(NAME, "<dummy/>", "t1.xml") + ", insert node <dummy/> into " + _DB_OPEN.args(NAME) + ',' + _DB_DROP.args(NAME)); query(_DB_OPEN.args(NAME) + "/root()", "<dummy/>"); // eventually drop database query(_DB_DROP.args(NAME)); // specify index options for(final boolean b : new boolean[] { false, true }) { query(_DB_CREATE.args(NAME, "()", "()", " map { 'updindex':" + b + "() }")); query(_DB_INFO.args(NAME) + "//updindex/text()", b); } assertEquals(context.options.get(MainOptions.UPDINDEX), false); final String[] nopt = { "maxcats", "maxlen", "indexsplitsize", "ftindexsplitsize" }; for(final String k : nopt) { query(_DB_CREATE.args(NAME, "()", "()", " map { '" + k + "':1 }")); } final String[] bopt = { "textindex", "attrindex", "ftindex", "stemming", "casesens", "diacritics" }; for(final String k : bopt) { for(final boolean v : new boolean[] { true, false }) { query(_DB_CREATE.args(NAME, "()", "()", " map { '" + k + "':" + v + "() }")); } } final String[] sopt = { "language", "stopwords" }; for(final String k : sopt) { query(_DB_CREATE.args(NAME, "()", "()", " map { '" + k + "':'' }")); } // specify parsing options query(_DB_CREATE.args(NAME, " '<a> </a>'", "a.xml", " map { 'chop':true() }")); query(_DB_OPEN.args(NAME), "<a/>"); query(_DB_CREATE.args(NAME, " '<a> </a>'", "a.xml", " map { 'chop':false() }")); query(_DB_OPEN.args(NAME), "<a> </a>"); // specify unknown or invalid options error(_DB_CREATE.args(NAME, "()", "()", " map { 'xyz':'abc' }"), BASX_OPTIONS_X); error(_DB_CREATE.args(NAME, "()", "()", " map { 'maxlen':-1 }"), BASX_VALUE_X_X); error(_DB_CREATE.args(NAME, "()", "()", " map { 'maxlen':'a' }"), BASX_VALUE_X_X); error(_DB_CREATE.args(NAME, "()", "()", " map { 'textindex':'nope' }"), BASX_VALUE_X_X); } /** Test method. */ @Test public void drop() { // non-existing DB name final String dbname = NAME + "DBCreate"; // drop existing DB query(_DB_CREATE.args(dbname, "<dummy/>", "doc.xml")); query(_DB_DROP.args(dbname)); query(_DB_EXISTS.args(dbname), "false"); // invalid name error(_DB_DROP.args(" ''"), BXDB_NAME_X); // try to drop non-existing DB error(_DB_DROP.args(dbname), BXDB_WHICH_X); } /** Test method. */ @Test public void createCommand() { final String dbname = NAME + "DBCreate"; query(_DB_CREATE.args(dbname)); execute(new Open(dbname)); error(_DB_CREATE.args(dbname), BXDB_OPENED_X); // close and try again execute(new Close()); query(_DB_CREATE.args(dbname)); // eventually drop database query(_DB_DROP.args(dbname)); } /** Test method. */ @Test public void rename() { execute(new Add("test/docs", FLDR)); query(COUNT.args(COLLECTION.args(NAME + "/test")), XMLFILES); // rename document query(_DB_RENAME.args(NAME, "test", "newtest")); query(COUNT.args(COLLECTION.args(NAME + "/test")), 0); query(COUNT.args(COLLECTION.args(NAME + "/newtest")), XMLFILES); // invalid target error(_DB_RENAME.args(NAME, "input.xml", " ''"), BXDB_PATH_X); error(_DB_RENAME.args(NAME, "input.xml", " '/'"), BXDB_PATH_X); error(_DB_RENAME.args(NAME, "input.xml", " '.'"), BXDB_PATH_X); // rename paths query(_DB_RENAME.args(NAME, "", "x")); query(COUNT.args(COLLECTION.args(NAME + "/x/newtest")), XMLFILES); // rename binary file query(_DB_STORE.args(NAME, "file1", "")); query(_DB_RENAME.args(NAME, "file1", "file2")); query(_DB_RETRIEVE.args(NAME, "file2")); error(_DB_RETRIEVE.args(NAME, "file1"), WHICHRES_X); query(_DB_RENAME.args(NAME, "file2", "dir1/file3")); query(_DB_RETRIEVE.args(NAME, "dir1/file3")); query(_DB_RENAME.args(NAME, "dir1", "dir2")); query(_DB_RETRIEVE.args(NAME, "dir2/file3")); error(_DB_RETRIEVE.args(NAME, "dir1"), WHICHRES_X); query(_DB_STORE.args(NAME, "file4", "")); query(_DB_STORE.args(NAME, "dir3/file5", "")); error(_DB_RENAME.args(NAME, "dir2", "file4"), BXDB_PATH_X); error(_DB_RENAME.args(NAME, "file4", "dir2"), BXDB_PATH_X); // move files in directories query(_DB_RENAME.args(NAME, "dir2", "dir3")); query(_DB_RETRIEVE.args(NAME, "dir3/file3")); query(_DB_RETRIEVE.args(NAME, "dir3/file5")); } /** Test method. */ @Test public void replace() { execute(new Add("test", XML)); query(_DB_REPLACE.args(NAME, XML, "\"<R1/>\"")); query(COUNT.args(COLLECTION.args(NAME + '/' + XML) + "/R1"), 1); query(COUNT.args(COLLECTION.args(NAME + '/' + XML) + "/R2"), 0); query(_DB_REPLACE.args(NAME, XML, " document { <R2/> }")); query(COUNT.args(COLLECTION.args(NAME + '/' + XML) + "/R1"), 0); query(COUNT.args(COLLECTION.args(NAME + '/' + XML) + "/R2"), 1); query(_DB_REPLACE.args(NAME, XML, XML)); query(COUNT.args(COLLECTION.args(NAME + '/' + XML) + "/R1"), 0); query(COUNT.args(COLLECTION.args(NAME + '/' + XML) + "/R2"), 0); query(COUNT.args(COLLECTION.args(NAME + '/' + XML) + "/html"), 1); } /** Test method. */ @Test public void optimize() { // simple optimize call query(_DB_OPTIMIZE.args(NAME)); query(_DB_OPTIMIZE.args(NAME)); // opened database cannot be fully optimized error(_DB_OPTIMIZE.args(NAME, true), UPDBOPTERR_X); execute(new Close()); query(_DB_OPTIMIZE.args(NAME, true)); // commands final CmdIndex[] cis = { CmdIndex.TEXT, CmdIndex.ATTRIBUTE, CmdIndex.TOKEN, CmdIndex.FULLTEXT }; // options final String[] numberOptions = lc(MainOptions.MAXCATS, MainOptions.MAXLEN, MainOptions.INDEXSPLITSIZE, MainOptions.FTINDEXSPLITSIZE); final String[] boolOptions = lc(MainOptions.TEXTINDEX, MainOptions.ATTRINDEX, MainOptions.TOKENINDEX, MainOptions.FTINDEX, MainOptions.STEMMING, MainOptions.CASESENS, MainOptions.DIACRITICS); final String[] stringOptions = lc(MainOptions.LANGUAGE, MainOptions.STOPWORDS); final String[] indexes = lc(MainOptions.TEXTINDEX, MainOptions.ATTRINDEX, MainOptions.TOKENINDEX, MainOptions.FTINDEX); final String[] includes = lc(MainOptions.TEXTINCLUDE, MainOptions.ATTRINCLUDE, MainOptions.TOKENINCLUDE, MainOptions.FTINCLUDE); // check single options for(final String option : numberOptions) query(_DB_OPTIMIZE.args(NAME, false, " map { '" + option + "': 1 }")); for(final String option : boolOptions) { for(final boolean bool : new boolean[] { true, false }) query(_DB_OPTIMIZE.args(NAME, false, " map { '" + option + "':" + bool + "() }")); } for(final String option : stringOptions) query(_DB_OPTIMIZE.args(NAME, false, " map { '" + option + "':'' }")); // ensure that option in context was not changed assertEquals(context.options.get(MainOptions.TEXTINDEX), true); // check invalid options error(_DB_OPTIMIZE.args(NAME, false, " map { 'xyz': 'abc' }"), BASX_OPTIONS_X); error(_DB_OPTIMIZE.args(NAME, false, " map { 'updindex': 1 }"), BASX_OPTIONS_X); error(_DB_OPTIMIZE.args(NAME, false, " map { 'maxlen': -1 }"), BASX_VALUE_X_X); error(_DB_OPTIMIZE.args(NAME, false, " map { 'maxlen': 'a' }"), BASX_VALUE_X_X); error(_DB_OPTIMIZE.args(NAME, false, " map { 'textindex':'nope' }"), BASX_VALUE_X_X); // check if optimize call adopts original options query(_DB_OPTIMIZE.args(NAME)); for(final String ind : indexes) query(_DB_INFO.args(NAME) + "//" + ind + "/text()", "false"); for(final String inc : includes) query(_DB_INFO.args(NAME) + "//" + inc + "/text()", ""); // check if options in context are adopted execute(new Open(NAME)); for(final String inc : includes) execute(new Set(inc, "a")); for(final CmdIndex ci : cis) execute(new CreateIndex(ci)); execute(new Close()); query(_DB_OPTIMIZE.args(NAME)); for(final String ind : indexes) query(_DB_INFO.args(NAME) + "//" + ind + "/text()", "true"); for(final String inc : includes) query(_DB_INFO.args(NAME) + "//" + inc + "/text()", "a"); // check if options in context are adopted, even if database is closed (reset options) execute(new Open(NAME)); for(final String inc : includes) execute(new Set(inc, "")); for(final CmdIndex cmd : cis) execute(new DropIndex(cmd)); for(final String ind : indexes) query(_DB_INFO.args(NAME) + "//" + ind + "/text()", "false"); for(final String inc : includes) query(_DB_INFO.args(NAME) + "//" + inc + "/text()", ""); execute(new Close()); query(_DB_OPTIMIZE.args(NAME)); for(final String ind : indexes) query(_DB_INFO.args(NAME) + "//" + ind + "/text()", "false"); for(final String inc : includes) query(_DB_INFO.args(NAME) + "//" + inc + "/text()", ""); // check if options specified in map are adopted query(_DB_OPTIMIZE.args(NAME, true, " map {" + "'textindex':true(),'attrindex':true(),'ftindex':true(),'tokenindex':true()," + "'updindex':true(),'textinclude':'a','attrinclude':'a','tokeninclude':'a','ftinclude':'a'" + " }")); for(final String ind : indexes) query(_DB_INFO.args(NAME) + "//" + ind + "/text()", "true"); for(final String inc : includes) query(_DB_INFO.args(NAME) + "//" + inc + "/text()", "a"); query(_DB_INFO.args(NAME) + "//updindex/text()", "true"); } /** Test method. */ @Test public void retrieve() { error(_DB_RETRIEVE.args(NAME, "raw"), WHICHRES_X); query(_DB_STORE.args(NAME, "raw", "xs:hexBinary('41')")); query("xs:hexBinary(" + _DB_RETRIEVE.args(NAME, "raw") + ')', "A"); query(_DB_DELETE.args(NAME, "raw")); error(_DB_RETRIEVE.args(NAME, "raw"), WHICHRES_X); } /** Test method. */ @Test public void store() { query(_DB_STORE.args(NAME, "raw1", "xs:hexBinary('41')")); query(_DB_STORE.args(NAME, "raw2", "b")); query(_DB_RETRIEVE.args(NAME, "raw2"), "b"); query(_DB_STORE.args(NAME, "raw3", 123)); query(_DB_RETRIEVE.args(NAME, "raw3"), "123"); } /** Test method. */ @Test public void flush() { query(_DB_FLUSH.args(NAME)); error(_DB_FLUSH.args(NAME + "unknown"), BXDB_OPEN_X); } /** Test method. */ @Test public void isRaw() { query(_DB_ADD.args(NAME, "\"<a/>\"", "xml")); query(_DB_STORE.args(NAME, "raw", "bla")); query(_DB_IS_RAW.args(NAME, "xml"), "false"); query(_DB_IS_RAW.args(NAME, "raw"), "true"); query(_DB_IS_RAW.args(NAME, "xxx"), "false"); } /** Test method. */ @Test public void exists() { query(_DB_ADD.args(NAME, "\"<a/>\"", "x/xml")); query(_DB_STORE.args(NAME, "x/raw", "bla")); // checks if the specified resources exist (false expected for directories) query(_DB_EXISTS.args(NAME), "true"); query(_DB_EXISTS.args(NAME, "x/xml"), "true"); query(_DB_EXISTS.args(NAME, "x/raw"), "true"); query(_DB_EXISTS.args(NAME, "xxx"), "false"); query(_DB_EXISTS.args(NAME, "x"), "false"); query(_DB_EXISTS.args(NAME, ""), "false"); // false expected for missing database execute(new DropDB(NAME)); query(_DB_EXISTS.args(NAME), "false"); } /** Test method. */ @Test public void isXML() { query(_DB_ADD.args(NAME, "\"<a/>\"", "xml")); query(_DB_STORE.args(NAME, "raw", "bla")); query(_DB_IS_XML.args(NAME, "xml"), "true"); query(_DB_IS_XML.args(NAME, "raw"), "false"); query(_DB_IS_XML.args(NAME, "xxx"), "false"); } /** Test method. */ @Test public void contentType() { query(_DB_ADD.args(NAME, "\"<a/>\"", "xml")); query(_DB_STORE.args(NAME, "raw", "bla")); query(_DB_CONTENT_TYPE.args(NAME, "xml"), MediaType.APPLICATION_XML.toString()); query(_DB_CONTENT_TYPE.args(NAME, "raw"), MediaType.APPLICATION_OCTET_STREAM.toString()); error(_DB_CONTENT_TYPE.args(NAME, "test"), WHICHRES_X); } /** Test method. */ @Test public void export() { // exports the database query(_DB_EXPORT.args(NAME, new IOFile(Prop.TMP, NAME))); final IOFile f = new IOFile(new IOFile(Prop.TMP, NAME), XML.replaceAll(".*/", "")); query(_FILE_EXISTS.args(f)); // serializes as text; ensures that the output contains no angle bracket query(_DB_EXPORT.args(NAME, new IOFile(Prop.TMP, NAME), " map {'method':'text'}")); query("0[" + CONTAINS.args(_FILE_READ_TEXT.args(f), "&lt;") + ']', ""); // deletes the exported file query(_FILE_DELETE.args(f)); } /** Test method. */ @Test public void name() { query(_DB_NAME.args(_DB_OPEN.args(NAME)), NAME); /** Test method. */ query(_DB_NAME.args(_DB_OPEN.args(NAME) + "/*"), NAME); } @Test public void path() { query(_DB_PATH.args(_DB_OPEN.args(NAME)), XML.replaceAll(".*/", "")); query(_DB_PATH.args(_DB_OPEN.args(NAME) + "/*"), XML.replaceAll(".*/", "")); query(_DB_PATH.args("<x/> update ()"), ""); } /** Test method. */ @Test public void createBackup() { query(COUNT.args(_DB_BACKUPS.args(NAME)), "0"); query(_DB_CREATE_BACKUP.args(NAME)); query(COUNT.args(_DB_BACKUPS.args(NAME)), "1"); // invalid name error(_DB_CREATE_BACKUP.args(" ''"), BXDB_NAME_X); // try to backup non-existing database error(_DB_CREATE_BACKUP.args(NAME + "backup"), BXDB_WHICH_X); } /** Test method. */ @Test public void dropBackup() { // create and drop backup query(_DB_CREATE_BACKUP.args(NAME)); query(_DB_DROP_BACKUP.args(NAME)); query(COUNT.args(_DB_BACKUPS.args(NAME)), "0"); // create and drop backup file query(_DB_CREATE_BACKUP.args(NAME)); query(_DB_DROP_BACKUP.args(query(_DB_BACKUPS.args(NAME)))); // invalid name error(_DB_DROP_BACKUP.args(" ''"), BXDB_NAME_X); // backup file does not exist error(_DB_DROP_BACKUP.args(NAME), BXDB_WHICHBACK_X); // check if drop is called before create error(_DB_CREATE_BACKUP.args(NAME) + ',' + _DB_DROP_BACKUP.args(NAME), BXDB_WHICHBACK_X); } /** Test method. */ @Test public void copy() { // close database in global context execute(new Close()); // copy database to new name and vice versa query(_DB_COPY.args(NAME, NAME + 'c')); try { query(_DB_COPY.args(NAME + 'c', NAME)); } finally { query(_DB_DROP.args(NAME + 'c')); } // invalid names error(_DB_COPY.args("x", " ''"), BXDB_NAME_X); error(_DB_COPY.args(" ''", "x"), BXDB_NAME_X); // same name is disallowed error(_DB_COPY.args(NAME, NAME), BXDB_SAME_X); // source database does not exist error(_DB_COPY.args(NAME + "copy", NAME), BXDB_WHICH_X); } /** Test method. */ @Test public void alter() { // close database in global context execute(new Close()); // rename database to new name and vice versa query(_DB_ALTER.args(NAME, NAME + 'a')); query(_DB_ALTER.args(NAME + 'a', NAME)); // invalid names error(_DB_ALTER.args("x", " ''"), BXDB_NAME_X); error(_DB_ALTER.args(" ''", "x"), BXDB_NAME_X); // same name is disallowed error(_DB_ALTER.args(NAME, NAME), BXDB_SAME_X); // source database does not exist error(_DB_ALTER.args(NAME + "alter", NAME), BXDB_WHICH_X); } /** Test method. */ @Test public void restore() { execute(new Close()); // backup and restore file query(_DB_CREATE_BACKUP.args(NAME)); query(_DB_RESTORE.args(NAME)); query(_DB_RESTORE.args(NAME)); // drop backups query(_DB_DROP_BACKUP.args(NAME)); error(_DB_RESTORE.args(NAME), BXDB_NOBACKUP_X); // invalid names error(_DB_RESTORE.args(" ''"), BXDB_NAME_X); } /** * Returns lower-case representations of the specified options. * @param options options * @return string */ private String[] lc(final Option<?>... options) { final StringList sl = new StringList(); for(final Option<?> option : options) sl.add(option.name().toLowerCase(Locale.ENGLISH)); return sl.finish(); } }
package org.intermine.bio.ontology; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.io.StringReader; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import org.apache.commons.collections.map.MultiValueMap; import org.apache.commons.io.IOUtils; public class OboParserTest extends TestCase { private OboParser parser; public OboParserTest(String arg) { super(arg); } public void setUp() { parser = new OboParser(); } public void testBasicStructure() throws Exception { parser.processOntology(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("OboParserTest.obo"))); Set terms = parser.getOboTerms(); assertEquals("GO:0000004", ((OboTerm) terms.iterator().next()).getId()); terms = new HashSet(parser.terms.values()); assertEquals(4, terms.size()); // 4 terms total OboTerm dt1 = (OboTerm) parser.terms.get("GO:0000001"); OboTerm dt2 = (OboTerm) parser.terms.get("GO:0000002"); OboTerm dt3 = (OboTerm) parser.terms.get("GO:0000003"); OboTerm dt4 = (OboTerm) parser.terms.get("GO:0000004"); assertNotNull(dt1); assertNotNull(dt2); assertNotNull(dt3); assertNotNull(dt4); // assertTrue(dt1.getChildren().contains(dt2)); // assertTrue(dt1.getChildren().contains(dt4)); // assertTrue(dt2.getChildren().contains(dt3)); // assertTrue(dt1.getComponents().contains(dt3)); } public void testSynonyms() throws Exception { parser.processOntology(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("OboParserTest.obo"))); OboTerm dt3 = (OboTerm) parser.terms.get("GO:0000003"); assertEquals(5, dt3.getSynonyms().size()); HashSet expSyns = new HashSet(); expSyns.add(new OboTermSynonym("some_value", "synonym")); expSyns.add(new OboTermSynonym("exact_value", "exact_synonym")); expSyns.add(new OboTermSynonym("related_value", "related_synonym")); expSyns.add(new OboTermSynonym("broad_value", "broad_synonym")); expSyns.add(new OboTermSynonym("narrow_value", "narrow_synonym")); assertEquals(expSyns, dt3.getSynonyms()); } public void testDescriptions() throws Exception { parser.processOntology(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("OboParserTest.obo"))); OboTerm dt1 = (OboTerm) parser.terms.get("GO:0000001"); OboTerm dt2 = (OboTerm) parser.terms.get("GO:0000002"); OboTerm dt3 = (OboTerm) parser.terms.get("GO:0000003"); assertEquals("iosis, mediated byhe cytoskeleton.", dt1.getDescription()); assertEquals("The maintenance of the structure and integrity of the mitochondrial genome.", dt2.getDescription()); assertEquals("", dt3.getDescription()); } public void testNamespaces() throws Exception { parser.processOntology(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("OboParserTest.obo"))); OboTerm dt1 = (OboTerm) parser.terms.get("GO:0000001"); OboTerm dt2 = (OboTerm) parser.terms.get("GO:0000002"); OboTerm dt3 = (OboTerm) parser.terms.get("GO:0000003"); assertEquals("gene_ontology", dt1.getNamespace()); assertEquals("other_namespace", dt2.getNamespace()); assertEquals("gene_ontology", dt3.getNamespace()); } // public void testNoDefaultNS() throws Exception { // "saved-by: midori\n" + // "[Term]\n" + // "id: GO:0000001\n" + // "name: mitochondrion inheritance\n"; // Set terms = parser.processOntology(new StringReader(noDefaultNS)); // assertEquals(1, terms.size()); // OboTerm dt1 = (OboTerm) parser.terms.get("GO:0000001"); // assertEquals("", dt1.getNamespace()); public void testGetTermIdNameMap() throws Exception { String test = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("OboParserTest.obo")); Map idNames = parser.getTermIdNameMap(new StringReader(test)); HashMap expecting = new HashMap(); expecting.put("GO:0000001", "mitochondrion inheritance"); expecting.put("GO:0000002", "mitochondrial genome maintenance"); expecting.put("GO:0000003", "reproduction"); expecting.put("GO:0000004", "partoftest"); assertEquals(expecting, idNames); } // public void testGetTermToParentTermSetMap() throws Exception { // String test = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("OboParserTest.obo")); // parser.readTerms(new BufferedReader(new StringReader(test))); // Map<String, Set> expected = new HashMap<String, Set>(); // expected.put("GO:0000001", new HashSet()); // expected.put("GO:0000002", new HashSet(Arrays.asList(new Object[] {"GO:0000001"}))); // expected.put("GO:0000003", new HashSet(Arrays.asList(new Object[] {"GO:0000001", "GO:0000002"}))); // expected.put("GO:0000004", new HashSet(Arrays.asList(new Object[] {"GO:0000001", "GO:0000002", "GO:0000003"}))); // assertEquals(expected, parser.getTermToParentTermSetMap()); public void testUnescape() { assertEquals("\n", parser.unescape("\\n")); assertEquals(" ", parser.unescape("\\W")); assertEquals("\t", parser.unescape("\\t")); assertEquals(":", parser.unescape("\\:")); assertEquals(",", parser.unescape("\\,")); assertEquals("\"", parser.unescape("\\\"")); assertEquals("\\", parser.unescape("\\\\")); assertEquals("()", parser.unescape("\\(\\)")); assertEquals("[]", parser.unescape("\\[\\]")); assertEquals("{}", parser.unescape("\\{\\}")); // pass-thru assertEquals("\n", parser.unescape("\n")); assertEquals(" ", parser.unescape(" ")); assertEquals("\t", parser.unescape("\t")); assertEquals(":", parser.unescape(":")); assertEquals(",", parser.unescape(",")); assertEquals("\"", parser.unescape("\"")); assertEquals("()", parser.unescape("()")); assertEquals("[]", parser.unescape("[]")); assertEquals("{}", parser.unescape("{}")); assertEquals("a\\bc:d,e[f)g{h i\tj\nk", parser.unescape("a\\\\b\\c\\:d\\,e\\[f\\)g\\{h\\Wi\\tj\\nk")); } public void testAddSynonyms() { OboTerm term = new OboTerm("id", "name"); parser.addSynonyms(term, Arrays.asList(new String[]{"\"no escapes\" []", " \"one \\\" escape\" [asdf]", " \"late quotes\" [as\\\"df] \"", "\"nothing trailing\""}), "synonym_type"); assertEquals(4, term.getSynonyms().size()); HashSet expect = new HashSet(); expect.add(new OboTermSynonym("no escapes", "synonym_type")); expect.add(new OboTermSynonym("one \" escape", "synonym_type")); expect.add(new OboTermSynonym("late quotes", "synonym_type")); expect.add(new OboTermSynonym("nothing trailing", "synonym_type")); assertEquals(expect, term.getSynonyms()); } public void testDodgySynonym() { OboTerm term = new OboTerm("id", "name"); parser.addSynonyms(term, Arrays.asList(new String[]{"xxxxxxxx"}), "synonym_type"); assertEquals(0, term.getSynonyms().size()); } // public void testIsObsolete() { // Map tagValues; // tagValues = new MultiValueMap(); // tagValues.put("is_obsolete", "true"); // assertTrue(OboParser.isObsolete(tagValues)); // tagValues = new MultiValueMap(); // tagValues.put("is_obsolete", "TRUE"); // assertTrue(OboParser.isObsolete(tagValues)); // tagValues = new MultiValueMap(); // tagValues.put("is_obsolete", "true"); // tagValues.put("is_obsolete", "false"); // assertTrue(OboParser.isObsolete(tagValues)); // tagValues = new MultiValueMap(); // tagValues.put("is_obsolete", "FALSE"); // assertFalse(OboParser.isObsolete(tagValues)); // tagValues = new MultiValueMap(); // tagValues.put("is_obsolete", "false"); // assertFalse(OboParser.isObsolete(tagValues)); // tagValues = new MultiValueMap(); // tagValues.put("is_obsolete", "FALSE"); // tagValues.put("is_obsolete", "true"); // assertFalse(OboParser.isObsolete(tagValues)); // tagValues = new MultiValueMap(); // assertFalse(OboParser.isObsolete(tagValues)); }
package bt.processor; import bt.metainfo.IMetadataService; import bt.module.ClientExecutor; import bt.module.MessagingAgents; import bt.net.IMessageDispatcher; import bt.net.IPeerConnectionPool; import bt.peer.IPeerRegistry; import bt.processor.magnet.FetchMetadataStage; import bt.processor.magnet.InitializeMagnetTorrentProcessingStage; import bt.processor.magnet.MagnetContext; import bt.processor.magnet.ProcessMagnetTorrentStage; import bt.processor.torrent.CreateSessionStage; import bt.processor.torrent.FetchTorrentStage; import bt.processor.torrent.InitializeTorrentProcessingStage; import bt.processor.torrent.ProcessTorrentStage; import bt.processor.torrent.TorrentContext; import bt.runtime.Config; import bt.torrent.TorrentRegistry; import bt.torrent.data.IDataWorkerFactory; import bt.tracker.ITrackerService; import com.google.inject.Inject; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; public class TorrentProcessorFactory implements ProcessorFactory { private TorrentRegistry torrentRegistry; private IDataWorkerFactory dataWorkerFactory; private ITrackerService trackerService; private ExecutorService executor; private IPeerRegistry peerRegistry; private IPeerConnectionPool connectionPool; private IMessageDispatcher messageDispatcher; private Set<Object> messagingAgents; private IMetadataService metadataService; private Config config; private final Map<Class<?>, ProcessingStage<?>> processors; @Inject public TorrentProcessorFactory(TorrentRegistry torrentRegistry, IDataWorkerFactory dataWorkerFactory, ITrackerService trackerService, @ClientExecutor ExecutorService executor, IPeerRegistry peerRegistry, IPeerConnectionPool connectionPool, IMessageDispatcher messageDispatcher, @MessagingAgents Set<Object> messagingAgents, IMetadataService metadataService, Config config) { this.torrentRegistry = torrentRegistry; this.dataWorkerFactory = dataWorkerFactory; this.trackerService = trackerService; this.executor = executor; this.peerRegistry = peerRegistry; this.connectionPool = connectionPool; this.messageDispatcher = messageDispatcher; this.messagingAgents = messagingAgents; this.metadataService = metadataService; this.config = config; this.processors = processors(); } private Map<Class<?>, ProcessingStage<?>> processors() { Map<Class<?>, ProcessingStage<?>> processors = new HashMap<>(); processors.put(TorrentContext.class, createTorrentProcessor()); processors.put(MagnetContext.class, createMagnetProcessor()); return processors; } protected ProcessingStage<TorrentContext> createTorrentProcessor() { ProcessingStage<TorrentContext> stage3 = new ProcessTorrentStage<>(null, torrentRegistry, trackerService, executor); ProcessingStage<TorrentContext> stage2 = new InitializeTorrentProcessingStage<>(stage3, torrentRegistry, dataWorkerFactory, config); ProcessingStage<TorrentContext> stage1 = new CreateSessionStage<>(stage2, torrentRegistry, peerRegistry, connectionPool, messageDispatcher, messagingAgents, config); ProcessingStage<TorrentContext> stage0 = new FetchTorrentStage(stage1); return stage0; } protected ProcessingStage<MagnetContext> createMagnetProcessor() { ProcessingStage<MagnetContext> stage3 = new ProcessMagnetTorrentStage(null, torrentRegistry, trackerService, executor); ProcessingStage<MagnetContext> stage2 = new InitializeMagnetTorrentProcessingStage(stage3, torrentRegistry, dataWorkerFactory, config); ProcessingStage<MagnetContext> stage1 = new FetchMetadataStage(stage2, metadataService, torrentRegistry, trackerService); ProcessingStage<MagnetContext> stage0 = new CreateSessionStage<>(stage1, torrentRegistry, peerRegistry, connectionPool, messageDispatcher, messagingAgents, config); return stage0; } @SuppressWarnings("unchecked") @Override public <C extends ProcessingContext> ProcessingStage<C> processor(Class<C> contextType) { return (ProcessingStage<C>) processors.get(contextType); } }
package ru.job4j.jsoup; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Locale; /** * Create by dinis of 26.09.17. */ public class ParserJsoup { /** * logge. */ private static final Logger Log = LoggerFactory.getLogger(ParserJsoup.class); /** * date format. */ private SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yy", new Locale("ru", "RU")); /** * url of sql.ru website with java vacancy. */ private String url = "http: public void startParse(DBManager db) { } }
package StevenDimDoors.mod_pocketDim.helpers; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.regex.Pattern; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.world.World; import StevenDimDoors.mod_pocketDim.DDProperties; import StevenDimDoors.mod_pocketDim.DungeonGenerator; import StevenDimDoors.mod_pocketDim.LinkData; import StevenDimDoors.mod_pocketDim.mod_pocketDim; import StevenDimDoors.mod_pocketDim.helpers.jnbt.ByteArrayTag; import StevenDimDoors.mod_pocketDim.helpers.jnbt.CompoundTag; import StevenDimDoors.mod_pocketDim.helpers.jnbt.ListTag; import StevenDimDoors.mod_pocketDim.helpers.jnbt.NBTOutputStream; import StevenDimDoors.mod_pocketDim.helpers.jnbt.ShortTag; import StevenDimDoors.mod_pocketDim.helpers.jnbt.Tag; public class DungeonHelper { private static DungeonHelper instance = null; private static DDProperties properties = null; public static final Pattern NamePattern = Pattern.compile("[A-Za-z0-9_]+"); private static final String SCHEMATIC_FILE_EXTENSION = ".schematic"; private static final int DEFAULT_DUNGEON_WEIGHT = 100; private static final int MAX_DUNGEON_WEIGHT = 10000; //Used to prevent overflows and math breaking down private static final String HUB_DUNGEON_TYPE = "Hub"; private static final String TRAP_DUNGEON_TYPE = "Trap"; private static final String SIMPLE_HALL_DUNGEON_TYPE = "SimpleHall"; private static final String COMPLEX_HALL_DUNGEON_TYPE = "ComplexHall"; private static final String EXIT_DUNGEON_TYPE = "Exit"; private static final String DEAD_END_DUNGEON_TYPE = "DeadEnd"; private static final String MAZE_DUNGEON_TYPE = "Maze"; //The list of dungeon types will be kept as an array for now. If we allow new //dungeon types in the future, then this can be changed to an ArrayList. private static final String[] DUNGEON_TYPES = new String[] { HUB_DUNGEON_TYPE, TRAP_DUNGEON_TYPE, SIMPLE_HALL_DUNGEON_TYPE, COMPLEX_HALL_DUNGEON_TYPE, EXIT_DUNGEON_TYPE, DEAD_END_DUNGEON_TYPE, MAZE_DUNGEON_TYPE }; private Random rand = new Random(); public HashMap<Integer, LinkData> customDungeonStatus = new HashMap<Integer, LinkData>(); public ArrayList<DungeonGenerator> customDungeons = new ArrayList<DungeonGenerator>(); public ArrayList<DungeonGenerator> registeredDungeons = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> weightedDungeonGenList = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> simpleHalls = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> complexHalls = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> deadEnds = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> hubs = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> mazes = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> pistonTraps = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> exits = new ArrayList<DungeonGenerator>(); public ArrayList<Integer> metadataFlipList = new ArrayList<Integer>(); public ArrayList<Integer> metadataNextList = new ArrayList<Integer>(); public DungeonGenerator defaultBreak = new DungeonGenerator(0, "/schematic/somethingBroke.schematic", true); public DungeonGenerator defaultUp = new DungeonGenerator(0, "/schematic/simpleStairsUp.schematic", true); private HashSet<String> dungeonTypeChecker; private HashMap<String, ArrayList<DungeonGenerator>> dungeonTypeMapping; private DungeonHelper() { //Load the dungeon type checker with the list of all types in lowercase. //Capitalization matters for matching in a hash set. dungeonTypeChecker = new HashSet<String>(); for (String dungeonType : DUNGEON_TYPES) { dungeonTypeChecker.add(dungeonType.toLowerCase()); } //Add all the basic dungeon types to dungeonTypeMapping dungeonTypeMapping = new HashMap<String, ArrayList<DungeonGenerator>>(); dungeonTypeMapping.put(SIMPLE_HALL_DUNGEON_TYPE, simpleHalls); dungeonTypeMapping.put(COMPLEX_HALL_DUNGEON_TYPE, complexHalls); dungeonTypeMapping.put(HUB_DUNGEON_TYPE, hubs); dungeonTypeMapping.put(EXIT_DUNGEON_TYPE, exits); dungeonTypeMapping.put(DEAD_END_DUNGEON_TYPE, deadEnds); dungeonTypeMapping.put(MAZE_DUNGEON_TYPE, mazes); dungeonTypeMapping.put(TRAP_DUNGEON_TYPE, pistonTraps); //Load our reference to the DDProperties singleton if (properties == null) properties = DDProperties.instance(); initializeDungeons(); } private void initializeDungeons() { File file = new File(properties.CustomSchematicDirectory); if (file.exists() || file.mkdir()) { copyfile.copyFile("/mods/DimDoors/How_to_add_dungeons.txt", file.getAbsolutePath() + "/How_to_add_dungeons.txt"); } registerFlipBlocks(); importCustomDungeons(properties.CustomSchematicDirectory); registerBaseDungeons(); } public static DungeonHelper initialize() { if (instance == null) { instance = new DungeonHelper(); } else { throw new IllegalStateException("Cannot initialize DungeonHelper twice"); } return instance; } public static DungeonHelper instance() { if (instance == null) { //This is to prevent some frustrating bugs that could arise when classes //are loaded in the wrong order. Trust me, I had to squash a few... throw new IllegalStateException("Instance of DungeonHelper requested before initialization"); } return instance; } public boolean validateSchematicName(String name) { String[] dungeonData = name.split("_"); //Check for a valid number of parts if (dungeonData.length < 3 || dungeonData.length > 4) return false; //Check if the dungeon type is valid if (!dungeonTypeChecker.contains(dungeonData[0].toLowerCase())) return false; //Check if the name is valid if (!NamePattern.matcher(dungeonData[1]).matches()) return false; //Check if the open/closed flag is present if (!dungeonData[2].equalsIgnoreCase("open") && !dungeonData[2].equalsIgnoreCase("closed")) return false; //If the weight is present, check that it is valid if (dungeonData.length == 4) { try { int weight = Integer.parseInt(dungeonData[3]); if (weight < 0 || weight > MAX_DUNGEON_WEIGHT) return false; } catch (NumberFormatException e) { //Not a number return false; } } return true; } public void registerCustomDungeon(File schematicFile) { String name = schematicFile.getName(); String path = schematicFile.getAbsolutePath(); try { if (name.endsWith(SCHEMATIC_FILE_EXTENSION) && validateSchematicName(name)) { //Strip off the file extension while splitting the file name String[] dungeonData = name.substring(0, name.length() - SCHEMATIC_FILE_EXTENSION.length()).split("_"); String dungeonType = dungeonData[0].toLowerCase(); boolean open = dungeonData[2].equals("open"); int weight = (dungeonData.length == 4) ? Integer.parseInt(dungeonData[3]) : DEFAULT_DUNGEON_WEIGHT; //Add this custom dungeon to the list corresponding to its type DungeonGenerator generator = new DungeonGenerator(weight, path, open); dungeonTypeMapping.get(dungeonType).add(generator); weightedDungeonGenList.add(generator); registeredDungeons.add(generator); customDungeons.add(generator); System.out.println("Imported " + name); } else { System.out.println("Could not parse dungeon filename, not adding dungeon to generation lists"); customDungeons.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, path, true)); System.out.println("Imported " + name); } } catch(Exception e) { e.printStackTrace(); System.out.println("Failed to import " + name); } } public void importCustomDungeons(String dir) { File file = new File(dir); File[] schematicNames = file.listFiles(); if (schematicNames!=null) { for(File schematicFile: schematicNames) { this.registerCustomDungeon(schematicFile); } } } public void registerFlipBlocks() { this.metadataFlipList.add(Block.dispenser.blockID); this.metadataFlipList.add(Block.stairsStoneBrick.blockID); this.metadataFlipList.add(Block.lever.blockID); this.metadataFlipList.add(Block.stoneButton.blockID); this.metadataFlipList.add(Block.redstoneRepeaterIdle.blockID); this.metadataFlipList.add(Block.redstoneRepeaterActive.blockID); this.metadataFlipList.add(Block.tripWireSource.blockID); this.metadataFlipList.add(Block.torchWood.blockID); this.metadataFlipList.add(Block.torchRedstoneIdle.blockID); this.metadataFlipList.add(Block.torchRedstoneActive.blockID); this.metadataFlipList.add(Block.doorIron.blockID); this.metadataFlipList.add(Block.doorWood.blockID); this.metadataFlipList.add(Block.pistonBase.blockID); this.metadataFlipList.add(Block.pistonStickyBase.blockID); this.metadataFlipList.add(Block.pistonExtension.blockID); this.metadataFlipList.add(Block.redstoneComparatorIdle.blockID); this.metadataFlipList.add(Block.redstoneComparatorActive.blockID); this.metadataFlipList.add(Block.signPost.blockID); this.metadataFlipList.add(Block.signWall.blockID); this.metadataFlipList.add(Block.skull.blockID); this.metadataFlipList.add(Block.ladder.blockID); this.metadataFlipList.add(Block.vine.blockID); this.metadataFlipList.add(Block.anvil.blockID); this.metadataFlipList.add(Block.chest.blockID); this.metadataFlipList.add(Block.chestTrapped.blockID); this.metadataFlipList.add(Block.hopperBlock.blockID); this.metadataFlipList.add(Block.stairsNetherBrick.blockID); this.metadataFlipList.add(Block.stairsCobblestone.blockID); this.metadataFlipList.add(Block.stairsNetherBrick.blockID); this.metadataFlipList.add(Block.stairsNetherQuartz.blockID); this.metadataFlipList.add(Block.stairsSandStone.blockID); this.metadataNextList.add(Block.redstoneRepeaterIdle.blockID); this.metadataNextList.add(Block.redstoneRepeaterActive.blockID); } public void registerBaseDungeons() { this.hubs.add(new DungeonGenerator(0, "/schematics/4WayBasicHall.schematic", false)); this.hubs.add(new DungeonGenerator(0, "/schematics/4WayBasicHall.schematic", false)); this.hubs.add(new DungeonGenerator(0, "/schematics/doorTotemRuins.schematic", true)); this.hubs.add(new DungeonGenerator(0, "/schematics/hallwayTrapRooms1.schematic", false)); this.hubs.add(new DungeonGenerator(0, "/schematics/longDoorHallway.schematic", false)); this.hubs.add(new DungeonGenerator(0, "/schematics/smallRotundaWithExit.schematic", false)); this.hubs.add(new DungeonGenerator(0, "/schematics/fortRuins.schematic", true)); this.hubs.add(new DungeonGenerator(0, "/schematics/4WayHallExit.schematic", false)); this.hubs.add(new DungeonGenerator(0, "/schematics/4WayHallExit.schematic", false)); this.simpleHalls.add(new DungeonGenerator(0, "/schematics/collapsedSingleTunnel1.schematic", false)); this.simpleHalls.add(new DungeonGenerator(0, "/schematics/singleStraightHall1.schematic", false)); this.simpleHalls.add(new DungeonGenerator(0, "/schematics/smallBranchWithExit.schematic", false)); this.simpleHalls.add(new DungeonGenerator(0, "/schematics/smallSimpleLeft.schematic", false)); this.simpleHalls.add(new DungeonGenerator(0, "/schematics/smallSimpleRight.schematic", false)); this.simpleHalls.add(new DungeonGenerator(0, "/schematics/simpleStairsUp.schematic", false)); this.simpleHalls.add(new DungeonGenerator(0, "/schematics/simpleStairsDown.schematic", false)); this.simpleHalls.add(new DungeonGenerator(0, "/schematics/simpleSmallT1.schematic", false)); this.complexHalls.add(new DungeonGenerator(0, "/schematics/tntPuzzleTrap.schematic", false)); this.complexHalls.add(new DungeonGenerator(0, "/schematics/brokenPillarsO.schematic", true)); this.complexHalls.add(new DungeonGenerator(0, "/schematics/buggyTopEntry1.schematic", true)); this.complexHalls.add(new DungeonGenerator(0, "/schematics/exitRuinsWithHiddenDoor.schematic", true)); this.complexHalls.add(new DungeonGenerator(0, "/schematics/hallwayHiddenTreasure.schematic", false)); this.complexHalls.add(new DungeonGenerator(0, "/schematics/mediumPillarStairs.schematic", true)); this.complexHalls.add(new DungeonGenerator(0, "/schematics/ruinsO.schematic", true)); this.complexHalls.add(new DungeonGenerator(0, "/schematics/pitStairs.schematic", true)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/azersDungeonO.schematic", false)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/diamondTowerTemple1.schematic", true)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/fallingTrapO.schematic", false)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/hiddenStaircaseO.schematic", true)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/lavaTrapO.schematic", true)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/randomTree.schematic", true)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/smallHiddenTowerO.schematic", true)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/smallSilverfishRoom.schematic", false)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/tntTrapO.schematic", true)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/smallDesert.schematic", true)); this.deadEnds.add(new DungeonGenerator(0, "/schematics/smallPond.schematic", true)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/fakeTNTTrap.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/hallwayPitFallTrap.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/hallwayPitFallTrap.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/pistonFallRuins.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/pistonFloorHall.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/pistonFloorHall.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/pistonSmasherHall.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/simpleDropHall.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/wallFallcomboPistonHall.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/wallFallcomboPistonHall.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/fallingTNThall.schematic", false)); this.pistonTraps.add(new DungeonGenerator(0, "/schematics/lavaPyramid.schematic", true)); this.mazes.add(new DungeonGenerator(0, "/schematics/smallMaze1.schematic", false)); this.mazes.add(new DungeonGenerator(0, "/schematics/smallMultilevelMaze.schematic", false)); this.exits.add(new DungeonGenerator(0, "/schematics/exitCube.schematic", true)); this.exits.add(new DungeonGenerator(0, "/schematics/lockingExitHall.schematic", false)); this.exits.add(new DungeonGenerator(0, "/schematics/smallExitPrison.schematic", true)); this.exits.add(new DungeonGenerator(0, "/schematics/lockingExitHall.schematic", false)); this.weightedDungeonGenList.addAll(this.simpleHalls); this.weightedDungeonGenList.addAll(this.exits); this.weightedDungeonGenList.addAll(this.pistonTraps); this.weightedDungeonGenList.addAll(this.mazes); this.weightedDungeonGenList.addAll(this.deadEnds); this.weightedDungeonGenList.addAll(this.complexHalls); this.weightedDungeonGenList.addAll(this.hubs); for(DungeonGenerator data : this.weightedDungeonGenList) { if(!this.registeredDungeons.contains(data)) { this.registeredDungeons.add(data); } } } public boolean exportDungeon(World world, int xI, int yI, int zI, String exportPath) { int xMin; int yMin; int zMin; int xMax; int yMax; int zMax; xMin=xMax=xI; yMin=yMax=yI; zMin=zMax=zI; for (int count = 0; count < 50; count++) { if(world.getBlockId(xMin, yI, zI)!=properties.PermaFabricBlockID) { xMin } if(world.getBlockId(xI, yMin, zI)!=properties.PermaFabricBlockID) { yMin } if(world.getBlockId(xI, yI, zMin)!=properties.PermaFabricBlockID) { zMin } if(world.getBlockId(xMax, yI, zI)!=properties.PermaFabricBlockID) { xMax++; } if(world.getBlockId(xI, yMax, zI)!=properties.PermaFabricBlockID) { yMax++; } if(world.getBlockId(xI, yI, zMax)!=properties.PermaFabricBlockID) { zMax++; } } short width =(short) (xMax-xMin); short height= (short) (yMax-yMin); short length= (short) (zMax-zMin); //ArrayList<NBTTagCompound> tileEntities = new ArrayList<NBTTagCompound>(); ArrayList<Tag> tileEntites = new ArrayList<Tag>(); byte[] blocks = new byte[width * height * length]; byte[] addBlocks = null; byte[] blockData = new byte[width * height * length]; for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { for (int z = 0; z < length; ++z) { int index = y * width * length + z * width + x; int blockID = world.getBlockId(x+xMin, y+yMin, z+zMin); int meta= world.getBlockMetadata(x+xMin, y+yMin, z+zMin); if(blockID==properties.DimensionalDoorID) { blockID=Block.doorIron.blockID; } if(blockID==properties.WarpDoorID) { blockID=Block.doorWood.blockID; } // Save 4096 IDs in an AddBlocks section if (blockID > 255) { if (addBlocks == null) { // Lazily create section addBlocks = new byte[(blocks.length >> 1) + 1]; } addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? addBlocks[index >> 1] & 0xF0 | (blockID >> 8) & 0xF : addBlocks[index >> 1] & 0xF | ((blockID >> 8) & 0xF) << 4); } blocks[index] = (byte) blockID; blockData[index] = (byte) meta; if (Block.blocksList[blockID] instanceof BlockContainer) { //TODO fix this /** TileEntity tileEntityBlock = world.getBlockTileEntity(x+xMin, y+yMin, z+zMin); NBTTagCompound tag = new NBTTagCompound(); tileEntityBlock.writeToNBT(tag); CompoundTag tagC = new CompoundTag("TileEntity",Map.class.cast(tag.getTags())); // Get the list of key/values from the block if (tagC != null) { tileEntites.add(tagC); } **/ } } } } /** * * this.nbtdata.setShort("Width", width); this.nbtdata.setShort("Height", height); this.nbtdata.setShort("Length", length); this.nbtdata.setByteArray("Blocks", blocks); this.nbtdata.setByteArray("Data", blockData); */ HashMap<String, Tag> schematic = new HashMap<String, Tag>(); schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); schematic.put("Data", new ByteArrayTag("Data", blockData)); schematic.put("Width", new ShortTag("Width", (short) width)); schematic.put("Length", new ShortTag("Length", (short) length)); schematic.put("Height", new ShortTag("Height", (short) height)); schematic.put("TileEntites", new ListTag("TileEntities", CompoundTag.class,tileEntites)); if (addBlocks != null) { schematic.put("AddBlocks", new ByteArrayTag("AddBlocks", addBlocks)); } CompoundTag schematicTag = new CompoundTag("Schematic", schematic); try { NBTOutputStream stream = new NBTOutputStream(new FileOutputStream(exportPath)); stream.writeTag(schematicTag); stream.close(); return true; } catch(Exception e) { e.printStackTrace(); return false; } } public void generateDungeonlink(LinkData incoming) { //DungeonGenerator dungeon = mod_pocketDim.registeredDungeons.get(new Random().nextInt(mod_pocketDim.registeredDungeons.size())); DungeonGenerator dungeon; int depth = dimHelper.instance.getDimDepth(incoming.locDimID)+2; int depthWeight = rand.nextInt(depth)+rand.nextInt(depth)-2; depth = depth - 2; boolean flag = true; int count = 10; try { if (dimHelper.dimList.get(incoming.destDimID) != null&&dimHelper.dimList.get(incoming.destDimID).dungeonGenerator!=null) { mod_pocketDim.loader.init(incoming); //TODO: Check this! //What the hell? Isn't this line saying X = X..? ~SenseiKiwi dimHelper.dimList.get(incoming.destDimID).dungeonGenerator=dimHelper.dimList.get(incoming.destDimID).dungeonGenerator; return; } if(incoming.destYCoord>15) { do { count flag = true; dungeon = this.weightedDungeonGenList.get(rand.nextInt(weightedDungeonGenList.size())); if(depth<=1) { if(rand.nextBoolean()) { dungeon = complexHalls.get(rand.nextInt(complexHalls.size())); } else if(rand.nextBoolean()) { dungeon = hubs.get(rand.nextInt(hubs.size())); } else if(rand.nextBoolean()) { dungeon = hubs.get(rand.nextInt(hubs.size())); } else if(deadEnds.contains(dungeon)||exits.contains(dungeon)) { flag=false; } } else if (depth<=3&&(deadEnds.contains(dungeon)||exits.contains(dungeon)||rand.nextBoolean())) { if(rand.nextBoolean()) { dungeon = hubs.get(rand.nextInt(hubs.size())); } else if(rand.nextBoolean()) { dungeon = mazes.get(rand.nextInt(mazes.size())); } else if(rand.nextBoolean()) { dungeon = pistonTraps.get(rand.nextInt(pistonTraps.size())); } else { flag=false; } } else if(rand.nextInt(3)==0&&!complexHalls.contains(dungeon)) { if(rand.nextInt(3)==0) { dungeon = simpleHalls.get(rand.nextInt(simpleHalls.size())); } else if(rand.nextBoolean()) { dungeon = pistonTraps.get(rand.nextInt(pistonTraps.size())); } else if(depth<4) { dungeon = hubs.get(rand.nextInt(hubs.size())); } } else if(depthWeight-depthWeight/2>depth-4&&(deadEnds.contains(dungeon)||exits.contains(dungeon))) { if(rand.nextBoolean()) { dungeon = simpleHalls.get(rand.nextInt(simpleHalls.size())); } else if(rand.nextBoolean()) { dungeon = complexHalls.get(rand.nextInt(complexHalls.size())); } else if(rand.nextBoolean()) { dungeon = pistonTraps.get(rand.nextInt(pistonTraps.size())); } else { flag=false; } } else if(depthWeight>7&&hubs.contains(dungeon)) { if(rand.nextInt(12)+5<depthWeight) { if(rand.nextBoolean()) { dungeon = exits.get(rand.nextInt(exits.size())); } else if(rand.nextBoolean()) { dungeon = deadEnds.get(rand.nextInt(deadEnds.size())); } else { dungeon = pistonTraps.get(rand.nextInt(pistonTraps.size())); } } else { flag = false; } } else if(depth>10&&hubs.contains(dungeon)) { flag = false; } } while (!flag && count > 0); } else { dungeon = defaultUp; } } catch (Exception e) { e.printStackTrace(); if (weightedDungeonGenList.size() > 0) { dungeon = weightedDungeonGenList.get(rand.nextInt(weightedDungeonGenList.size())); } else { return; } } dimHelper.dimList.get(incoming.destDimID).dungeonGenerator = dungeon; } }
//! \file ImageCache.java //! \brief package rhcad.touchvg.view.internal; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Picture; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.PictureDrawable; import android.support.v4.util.LruCache; import android.util.Log; import android.view.View; import com.caverock.androidsvg.SVG; import com.caverock.androidsvg.SVGParseException; public class ImageCache extends Object { public static final boolean USE_SVG = false; // Use androidsvg-xxx.jar? private static final String TAG = "touchvg"; public static final String BITMAP_PREFIX = "bmp:"; public static final String SVG_PREFIX = "svg:"; private static final int CACHE_SIZE = 2 * 1024 * 1024; // 2MB private LruCache<String, Drawable> mCache; private String mPath; private String mPlayPath; public ImageCache() { } protected void finalize() { Log.d(TAG, "ImageCache finalize"); } private boolean createCache() { try { mCache = new LruCache<String, Drawable>(CACHE_SIZE) { @Override protected int sizeOf(String key, Drawable d) { int size = 1; // TODO: SVG size? if (d.getClass().isInstance(BitmapDrawable.class)) { size = ((BitmapDrawable) d).getBitmap().getByteCount(); } return size; } }; } catch (NoClassDefFoundError e) { Log.e(TAG, "Need android-support-v4.jar in application"); } return mCache != null; } private void addToCache(String name, Drawable drawable) { if (mCache != null || createCache()) { mCache.put(name, drawable); } } public String getImagePath() { return mPath; } public void setImagePath(String path) { this.mPath = path; } public void setPlayPath(String path) { this.mPlayPath = path; } public static int getWidth(Drawable drawable) { try { return ((BitmapDrawable) drawable).getBitmap().getWidth(); } catch (ClassCastException e) { } try { return ((PictureDrawable) drawable).getPicture().getWidth(); } catch (ClassCastException e) { } return 0; } public static int getHeight(Drawable drawable) { try { return ((BitmapDrawable) drawable).getBitmap().getHeight(); } catch (ClassCastException e) { } try { return ((PictureDrawable) drawable).getPicture().getHeight(); } catch (ClassCastException e) { } return 0; } public void clear() { if (mCache != null) mCache.evictAll(); } public Drawable getImage(View view, String name) { Drawable drawable = mCache != null ? mCache.get(name) : null; if (drawable == null && view != null) { if (name.indexOf(BITMAP_PREFIX) == 0) { // R.drawable.resName final String resName = name.substring(BITMAP_PREFIX.length()); int id = view.getResources().getIdentifier(resName, "drawable", view.getContext().getPackageName()); drawable = this.addBitmap(view.getResources(), id, name); } else if (name.indexOf(SVG_PREFIX) == 0) { // R.raw.resName final String resName = name.substring(SVG_PREFIX.length()); int id = view.getResources().getIdentifier(resName, "raw", view.getContext().getPackageName()); drawable = this.addSVG(view.getResources(), id, name); } else if (name.endsWith(".svg")) { drawable = this.addSVGFile(getImagePath(name), name); } else { drawable = this.addBitmapFile(view.getResources(), getImagePath(name), name); } } return drawable; } private String getImagePath(String name) { if (mPlayPath != null && !mPlayPath.isEmpty()) { final File f = new File(mPlayPath, name); if (f.exists()) return f.getPath(); } if (mPath != null && !mPath.isEmpty()) { final File f = new File(mPath, name); if (!f.exists()) { Log.d(TAG, "File not exist: " + f.getPath()); } return f.getPath(); } return name; } public Drawable addBitmap(Resources res, int id, String name) { Drawable drawable = mCache != null ? mCache.get(name) : null; if (drawable == null && id != 0) { final Bitmap bitmap = BitmapFactory.decodeResource(res, id); if (bitmap != null && bitmap.getWidth() > 0) { drawable = new BitmapDrawable(res, bitmap); addToCache(name, drawable); } } return drawable; } //! SVG @SuppressWarnings("unused") public Drawable addSVG(Resources res, int id, String name) { Drawable drawable = mCache != null ? mCache.get(name) : null; if (drawable == null && id != 0 && USE_SVG) { try { final Picture picture = SVG.getFromResource(res, id).renderToPicture(); if (picture != null && picture.getWidth() > 0) { drawable = new PictureDrawable(picture); addToCache(name, drawable); } } catch (SVGParseException e) { e.printStackTrace(); } } return drawable; } //! PNG public Drawable addBitmapFile(Resources res, String filename, String name) { Drawable drawable = mCache != null ? mCache.get(name) : null; if (drawable == null && new File(filename).exists()) { final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(filename, opts); opts.inJustDecodeBounds = false; if (opts.outWidth > 1600 || opts.outHeight > 1600) { opts.inSampleSize = 4; } else if (opts.outWidth > 600 || opts.outHeight > 600) { opts.inSampleSize = 2; } final Bitmap bitmap = BitmapFactory.decodeFile(filename, opts); if (bitmap != null && bitmap.getWidth() > 0) { drawable = new BitmapDrawable(res, bitmap); addToCache(name, drawable); } } return drawable; } //! SVG @SuppressWarnings("unused") public Drawable addSVGFile(String filename, String name) { Drawable drawable = mCache != null ? mCache.get(name) : null; if (drawable == null && name.endsWith(".svg") && USE_SVG) { try { final InputStream data = new FileInputStream(new File(filename)); final Picture picture = SVG.getFromInputStream(data).renderToPicture(); if (picture != null && picture.getWidth() > 0) { drawable = new PictureDrawable(picture); addToCache(name, drawable); } data.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SVGParseException e) { e.printStackTrace(); } } return drawable; } public static boolean copyFileTo(String srcpath, String destpath) { final File srcfile = new File(srcpath); return copyFile(srcfile, new File(destpath, srcfile.getName())); } public static boolean copyFileTo(String srcpath, String name, String destpath) { final File srcfile = new File(srcpath, name); return copyFile(srcfile, new File(destpath, name)); } public static boolean copyFile(String srcpath, String destpath) { return copyFile(new File(srcpath), new File(destpath)); } public static boolean copyFile(File srcfile, File destfile) { FileInputStream fis = null; FileOutputStream fos = null; boolean ret = false; if (srcfile.exists() && !destfile.exists()) { if (!destfile.getParentFile().exists()) { destfile.getParentFile().mkdir(); } try { fis = new FileInputStream(srcfile); fos = new FileOutputStream(destfile); final byte[] buf = new byte[1024]; int len; while ((len = fis.read(buf)) > 0) { fos.write(buf, 0, len); } ret = true; } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { ret = false; e.printStackTrace(); } } } } return ret; } }
package br.com.redesocial.modelo.dao; import br.com.redesocial.modelo.dto.Pais; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class PaisDAO extends DAOCRUDBase<Pais> { @Override public void inserir(Pais p) throws Exception{ Connection conexao = getConexao(); if(p.getNome().trim().equals("")){ throw new Exception("O campo país não pode estar vazio!"); } preparedStatement pstmt; pstmt = conexao.prepareStatement("inserir into paises (nome) values(?)"); pstmt.setString(1, p.getNome()); pstmt.executeUpdate(); } @Override public void alterar(Pais p) throws Exception { Connection conexao = getConexao(); if (p.getNome().trim().equals("")){ throw new Exception("A descrição não pode estar vazia!"); } PreparedStatement pstmt; pstmt = conexao.prepareStatement("update paises set nome = ? where id = ?"); pstmt.setString(1, p.getNome()); pstmt.setInt(2, p.getId()); pstmt.executeUpdate(); } @Override public void excluir(int id) throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("delete from paises where id = ?"); pstmt.setInt(1, id); pstmt.executeUpdate(); } @Override public Pais selecionar(int id) throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("select * from paises where id = ?"); pstmt.setInt(1, id); ResultSet rs; rs = pstmt.executeQuery(); if(rs.next()){ Pais p = new Pais(); p.setId(id); p.setNome(rs.getString("nome")); return p; }else{ return null; } } @Override public List listar() throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("select * from paises order by nome asc"); ResultSet rs; rs = pstmt.executeQuery(); List lista; lista = new ArrayList(); while (rs.next()){ Pais p = new Pais(); p.setId(rs.getInt("id")); p.setNome(rs.getString("nome")); lista.add(p); } return lista; } }
package edu.umd.cs.piccolox.swt; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.RenderingHints.Key; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderableImage; import java.text.AttributedCharacterIterator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; /** * An extension to Graphics2D to support an SWT Piccolo Canvas with little modification to the current Piccolo architecture * * There is an outstanding SWT bug request #33319 for more efficient polyline/polygon rendering methods. It also appears that * most of the code below could be made obselete by bug fix #6490 * * A lot of this may also be duplicated in GEF - the eclipse Graphical Editor Framework * * @author Lance Good */ public class SWTGraphics2D extends Graphics2D { protected static int CACHE_COUNT = 0; protected static HashMap FONT_CACHE = new HashMap(); protected static HashMap COLOR_CACHE = new HashMap(); protected static HashMap SHAPE_CACHE = new HashMap(); protected static BufferedImage BUFFER = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB); static Point PT = new Point(); static Rectangle2D RECT = new Rectangle2D.Double(); static Rectangle2D LINE_RECT = new Rectangle2D.Double(); static org.eclipse.swt.graphics.Rectangle SWT_RECT = new org.eclipse.swt.graphics.Rectangle(0,0,0,0); protected GC gc; protected Device device; protected AffineTransform transform = new AffineTransform(); protected org.eclipse.swt.graphics.Font curFont; protected double lineWidth = 1.0; /** * Constructor for SWTGraphics2D. */ public SWTGraphics2D(GC gc, Device device) { super(); this.gc = gc; this.device = device; } // GET CLIP /** * @see java.awt.Graphics#getClipBounds() */ public Rectangle getClipBounds() { org.eclipse.swt.graphics.Rectangle rect = gc.getClipping(); Rectangle aRect = new Rectangle(rect.x,rect.y,rect.width,rect.height); try { SWTShapeManager.transform(aRect,transform.createInverse()); } catch (Exception e) {e.printStackTrace();} return aRect; } public void clipRect(int x, int y, int width, int height) { RECT.setRect(x,y,width,height); SWTShapeManager.transform(RECT,transform); SWTShapeManager.awtToSWT(RECT,SWT_RECT); org.eclipse.swt.graphics.Rectangle clip = gc.getClipping(); clip = clip.intersection(SWT_RECT); gc.setClipping(clip); } public void setClip(int x, int y, int width, int height) { RECT.setRect(x,y,width,height); SWTShapeManager.transform(RECT,transform); SWTShapeManager.awtToSWT(RECT,SWT_RECT); gc.setClipping(SWT_RECT); } /** * This method isn't really supported by SWT - so will use the shape bounds */ public void clip(Shape s) { Rectangle2D clipBds = s.getBounds2D(); SWTShapeManager.transform(clipBds,transform); SWTShapeManager.awtToSWT(clipBds,SWT_RECT); org.eclipse.swt.graphics.Rectangle clip = gc.getClipping(); clip = clip.intersection(SWT_RECT); gc.setClipping(SWT_RECT); } /** * This method isn't really supported by SWT - so will use the shape bounds */ public void setClip(Shape clip) { if (clip == null) { gc.setClipping((org.eclipse.swt.graphics.Rectangle)null); } else { Rectangle2D clipBds = clip.getBounds2D(); SWTShapeManager.transform(clipBds,transform); SWTShapeManager.awtToSWT(clipBds,SWT_RECT); gc.setClipping(SWT_RECT); } } public Shape getClip() { org.eclipse.swt.graphics.Rectangle rect = gc.getClipping(); Rectangle2D aRect = new Rectangle2D.Double(rect.x,rect.y,rect.width,rect.height); try { SWTShapeManager.transform(aRect,transform.createInverse()); } catch (Exception e) {e.printStackTrace();} return aRect; } // DEVICE SPECIFIC public GraphicsConfiguration getDeviceConfiguration() { return ((Graphics2D)BUFFER.getGraphics()).getDeviceConfiguration(); } // COLOR METHODS public Paint getPaint() { return getColor(); } public void setPaint(Paint paint) { if (paint instanceof Color) { setColor((Color)paint); } } public Color getColor() { org.eclipse.swt.graphics.Color color = gc.getForeground(); Color awtColor = new Color(color.getRed(),color.getGreen(),color.getBlue()); return awtColor; } public void setColor(Color c) { org.eclipse.swt.graphics.Color cachedColor = (org.eclipse.swt.graphics.Color)COLOR_CACHE.get(c); if (cachedColor == null) { cachedColor = new org.eclipse.swt.graphics.Color(device,c.getRed(),c.getGreen(),c.getBlue()); COLOR_CACHE.put(c,cachedColor); } gc.setForeground(cachedColor); } public void setColor(org.eclipse.swt.graphics.Color c) { gc.setForeground(c); } public void setBackground(Color c) { org.eclipse.swt.graphics.Color cachedColor = (org.eclipse.swt.graphics.Color)COLOR_CACHE.get(c); if (cachedColor == null) { cachedColor = new org.eclipse.swt.graphics.Color(device,c.getRed(),c.getGreen(),c.getBlue()); COLOR_CACHE.put(c,cachedColor); } gc.setBackground(cachedColor); } public void setBackground(org.eclipse.swt.graphics.Color c) { gc.setBackground(c); } public Color getBackground() { org.eclipse.swt.graphics.Color color = gc.getBackground(); Color awtColor = new Color(color.getRed(),color.getGreen(),color.getBlue()); return awtColor; } // FONT METHODS public org.eclipse.swt.graphics.Font getSWTFont() { return curFont; } public org.eclipse.swt.graphics.FontMetrics getSWTFontMetrics() { gc.setFont(curFont); return gc.getFontMetrics(); } public Font getFont() { if (curFont != null) { int style = Font.PLAIN; FontData[] fd = curFont.getFontData(); if (fd.length > 0) { if ((fd[0].getStyle() & SWT.BOLD) != 0) { style = style | Font.BOLD; } if ((fd[0].getStyle() & SWT.ITALIC) != 0) { style = style | SWT.ITALIC; } return new Font(fd[0].getName(),style,(int)fd[0].height); } return null; } else { return null; } } public void setFont(Font font) { String fontString = "name="+font.getFamily()+";bold="+font.isBold()+";italic="+font.isItalic()+";size="+font.getSize(); curFont = getFont(fontString); } public void setFont(org.eclipse.swt.graphics.Font font) { curFont = font; } public org.eclipse.swt.graphics.Font getFont(String fontString) { org.eclipse.swt.graphics.Font cachedFont = (org.eclipse.swt.graphics.Font)FONT_CACHE.get(fontString); if (cachedFont == null) { int style = 0; if (fontString.indexOf("bold=true") != -1) { style = style | SWT.BOLD; } if (fontString.indexOf("italic=true") != -1) { style = style | SWT.ITALIC; } String name = fontString.substring(0,fontString.indexOf(";")); String size = fontString.substring(fontString.lastIndexOf(";")+1,fontString.length()); int sizeInt = 12; try { sizeInt = Integer.parseInt(size.substring(size.indexOf("=")+1,size.length())); } catch (Exception e) {e.printStackTrace();} cachedFont = new org.eclipse.swt.graphics.Font(device,name.substring(name.indexOf("=")+1,name.length()),sizeInt,style); FONT_CACHE.put(fontString,cachedFont); } return cachedFont; } protected org.eclipse.swt.graphics.Font getTransformedFont() { if (curFont != null) { FontData fontData = curFont.getFontData()[0]; int height = fontData.getHeight(); RECT.setRect(0,0,height,height); SWTShapeManager.transform(RECT,transform); height = (int)(RECT.getHeight()+0.5); String fontString = "name="+fontData.getName()+";bold="+((fontData.getStyle() & SWT.BOLD) != 0)+";italic="+((fontData.getStyle() & SWT.ITALIC) != 0)+";size="+height; return getFont(fontString); } return null; } // AFFINE TRANSFORM METHODS public void translate(int x, int y) { transform.translate(x,y); } public void translate(double tx, double ty) { transform.translate(tx,ty); } public void rotate(double theta) { transform.rotate(theta); } public void rotate(double theta, double x, double y) { transform.rotate(theta,x,y); } public void scale(double sx, double sy) { transform.scale(sx,sy); } public void shear(double shx, double shy) { transform.shear(shx,shy); } public void transform(AffineTransform Tx) { transform.concatenate(Tx); } public void setTransform(AffineTransform Tx) { transform = (AffineTransform)Tx.clone(); } public AffineTransform getTransform() { return (AffineTransform)transform.clone(); } // DRAWING AND FILLING METHODS public void clearRect(int x, int y, int width, int height) { fillRect(x,y,width,height); } public void draw(Shape s) { if (s instanceof Rectangle2D) { Rectangle2D r2 = (Rectangle2D)s; drawRect(r2.getX(),r2.getY(),r2.getWidth(),r2.getHeight()); } else if (s instanceof Ellipse2D) { Ellipse2D e2 = (Ellipse2D)s; drawOval(e2.getX(),e2.getY(),e2.getWidth(),e2.getHeight()); } else if (s instanceof RoundRectangle2D) { RoundRectangle2D r2 = (RoundRectangle2D)s; drawRoundRect(r2.getX(),r2.getY(),r2.getWidth(),r2.getHeight(),r2.getArcWidth(),r2.getArcHeight()); } else if (s instanceof Arc2D) { Arc2D a2 = (Arc2D)s; drawArc(a2.getX(),a2.getY(),a2.getWidth(),a2.getHeight(),a2.getAngleStart(),a2.getAngleExtent()); } else { double[] pts = (double[])SHAPE_CACHE.get(s); if (pts == null) { pts = SWTShapeManager.shapeToPolyline(s); SHAPE_CACHE.put(s,pts); } drawPolyline(pts); } } public void fill(Shape s) { if (s instanceof Rectangle2D) { Rectangle2D r2 = (Rectangle2D)s; fillRect(r2.getX(),r2.getY(),r2.getWidth(),r2.getHeight()); } else if (s instanceof Ellipse2D) { Ellipse2D e2 = (Ellipse2D)s; fillOval(e2.getX(),e2.getY(),e2.getWidth(),e2.getHeight()); } else if (s instanceof RoundRectangle2D) { RoundRectangle2D r2 = (RoundRectangle2D)s; fillRoundRect(r2.getX(),r2.getY(),r2.getWidth(),r2.getHeight(),r2.getArcWidth(),r2.getArcHeight()); } else if (s instanceof Arc2D) { Arc2D a2 = (Arc2D)s; fillArc(a2.getX(),a2.getY(),a2.getWidth(),a2.getHeight(),a2.getAngleStart(),a2.getAngleExtent()); } else { double[] pts = (double[])SHAPE_CACHE.get(s); if (pts == null) { pts = SWTShapeManager.shapeToPolyline(s); SHAPE_CACHE.put(s,pts); } fillPolygon(pts); } } public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) { int[] ptArray = new int[2*nPoints]; for(int i=0; i<nPoints; i++) { PT.setLocation(xPoints[i],yPoints[i]); transform.transform(PT,PT); ptArray[2*i] = xPoints[i]; ptArray[2*i+1] = yPoints[i]; } gc.setLineWidth(getTransformedLineWidth()); gc.drawPolyline(ptArray); } public void drawPolyline(double[] pts) { int[] intPts = SWTShapeManager.transform(pts,transform); gc.drawPolyline(intPts); } public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) { int[] ptArray = new int[2*nPoints]; for(int i=0; i<nPoints; i++) { PT.setLocation(xPoints[i],yPoints[i]); transform.transform(PT,PT); ptArray[2*i] = xPoints[i]; ptArray[2*i+1] = yPoints[i]; } gc.drawPolygon(ptArray); } public void fillPolygon(double[] pts) { int[] intPts = SWTShapeManager.transform(pts,transform); gc.fillPolygon(intPts); } public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) { int[] ptArray = new int[2*nPoints]; for(int i=0; i<nPoints; i++) { PT.setLocation(xPoints[i],yPoints[i]); transform.transform(PT,PT); ptArray[2*i] = xPoints[i]; ptArray[2*i+1] = yPoints[i]; } gc.fillPolygon(ptArray); } public void drawLine(int x1, int y1, int x2, int y2) { drawLine((double)x1,(double)y1,(double)x2,(double)y2); } public void drawLine(double x1, double y1, double x2, double y2) { PT.setLocation(x1,y1); transform.transform(PT,PT); x1 = (int)PT.getX(); y1 = (int)PT.getY(); PT.setLocation(x2,y2); transform.transform(PT,PT); x2 = (int)PT.getX(); y2 = (int)PT.getY(); gc.setLineWidth(getTransformedLineWidth()); gc.drawLine((int)(x1+0.5),(int)(y1+0.5),(int)(x2+0.5),(int)(y2+0.5)); } /** * @see java.awt.Graphics#drawString(AttributedCharacterIterator, int, int) */ public void drawString(AttributedCharacterIterator iterator, int x, int y) { } /** * @see java.awt.Graphics2D#drawString(AttributedCharacterIterator, float, float) */ public void drawString(AttributedCharacterIterator iterator, float x, float y) { } /** * @see java.awt.Graphics2D#drawGlyphVector(GlyphVector, float, float) */ public void drawGlyphVector(GlyphVector g, float x, float y) { } /** * @see java.awt.Graphics2D#hit(Rectangle, Shape, boolean) */ public boolean hit(Rectangle rect, Shape s, boolean onStroke) { return false; } /** * @see java.awt.Graphics2D#setComposite(Composite) */ public void setComposite(Composite comp) { } /** * @see java.awt.Graphics2D#setStroke(Stroke) */ public void setStroke(Stroke s) { } public void setRenderingHint(Key hintKey, Object hintValue) { } public Object getRenderingHint(Key hintKey) { return null; } /** * @see java.awt.Graphics2D#setRenderingHints(Map) */ public void setRenderingHints(Map hints) { } /** * @see java.awt.Graphics2D#addRenderingHints(Map) */ public void addRenderingHints(Map hints) { } /** * @see java.awt.Graphics2D#getRenderingHints() */ public RenderingHints getRenderingHints() { return null; } /** * @see java.awt.Graphics2D#getComposite() */ public Composite getComposite() { return null; } /** * @see java.awt.Graphics2D#getStroke() */ public Stroke getStroke() { return null; } /** * @see java.awt.Graphics2D#getFontRenderContext() */ public FontRenderContext getFontRenderContext() { return null; } /** * @see java.awt.Graphics#create() */ public Graphics create() { return null; } /** * @see java.awt.Graphics#setPaintMode() */ public void setPaintMode() { } /** * @see java.awt.Graphics#setXORMode(Color) */ public void setXORMode(Color c1) { } /** * @see java.awt.Graphics#getFontMetrics(Font) */ public FontMetrics getFontMetrics(Font f) { return null; } /** * @see java.awt.Graphics2D#drawImage(Image, AffineTransform, ImageObserver) */ public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) { return false; } /** * @see java.awt.Graphics2D#drawImage(BufferedImage, BufferedImageOp, int, int) */ public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) { } /** * @see java.awt.Graphics2D#drawRenderedImage(RenderedImage, AffineTransform) */ public void drawRenderedImage(RenderedImage img, AffineTransform xform) { } /** * @see java.awt.Graphics2D#drawRenderableImage(RenderableImage, AffineTransform) */ public void drawRenderableImage(RenderableImage img, AffineTransform xform) { } /** * @see java.awt.Graphics#drawImage(Image, int, int, ImageObserver) */ public boolean drawImage(Image img, int x, int y, ImageObserver observer) { return false; } /** * @see java.awt.Graphics#drawImage(Image, int, int, int, int, ImageObserver) */ public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) { return false; } /** * @see java.awt.Graphics#drawImage(Image, int, int, Color, ImageObserver) */ public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) { return false; } /** * @see java.awt.Graphics#drawImage(Image, int, int, int, int, Color, ImageObserver) */ public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) { return false; } /** * @see java.awt.Graphics#drawImage(Image, int, int, int, int, int, int, int, int, ImageObserver) */ public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) { return false; } /** * @see java.awt.Graphics#drawImage(Image, int, int, int, int, int, int, int, int, Color, ImageObserver) */ public boolean drawImage( Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) { return false; } /** * DO NOTHING - DISPOSED IN RENDERING CLASS */ public void dispose() { } // CLEAN-UP METHODS public static void incrementGCCount() { CACHE_COUNT++; } public static void decrementGCCount() { CACHE_COUNT if (CACHE_COUNT == 0) { synchronized(FONT_CACHE){ for(Iterator i=FONT_CACHE.values().iterator(); i.hasNext();) { org.eclipse.swt.graphics.Font font = (org.eclipse.swt.graphics.Font)i.next(); font.dispose(); } FONT_CACHE.clear(); } synchronized(COLOR_CACHE){ for(Iterator i=COLOR_CACHE.values().iterator(); i.hasNext();) { org.eclipse.swt.graphics.Color color = (org.eclipse.swt.graphics.Color)i.next(); color.dispose(); } COLOR_CACHE.clear(); } } } }
package com.saucelabs.common; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class SauceHelperTests { private SauceHelper sauceHelper; @Before public void runBeforeEveryTest() { sauceHelper = new SauceHelper(); } @Test public void shouldReturnPassedForTrueResult() { assertStringsEqual("sauce:job-result=", true); } @Test public void shouldReturnFailedForFalseResult() { assertStringsEqual("sauce:job-result=", false); } @Test public void shouldReturnCorrectStringForTestName() { String testName = "MyTestName"; assertEquals("sauce:job-name=" + testName, sauceHelper.getTestNameString(testName)); } @Test public void shouldReturnSauceContextString() { String comment = "This is a comment"; assertEquals("sauce:context=" + comment, sauceHelper.getCommentString(comment)); } private void assertStringsEqual(String s, boolean b) { assertEquals(s + b, sauceHelper.getTestResultString(b)); } }
package loci.formats.in; import java.io.File; import java.io.IOException; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.ArrayList; import java.util.Calendar; import java.util.TimeZone; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.xml.XMLTools; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffIFDEntry; import loci.formats.tiff.TiffParser; import loci.formats.tiff.TiffRational; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; import ome.xml.model.primitives.Timestamp; public class MetamorphReader extends BaseTiffReader { // -- Constants -- /** Logger for this class. */ private static final Logger LOGGER = LoggerFactory.getLogger(MetamorphReader.class); public static final String SHORT_DATE_FORMAT = "yyyyMMdd HH:mm:ss"; public static final String MEDIUM_DATE_FORMAT = "yyyyMMdd HH:mm:ss.SSS"; public static final String LONG_DATE_FORMAT = "dd/MM/yyyy HH:mm:ss:SSS"; public static final String[] ND_SUFFIX = {"nd"}; public static final String[] STK_SUFFIX = {"stk", "tif", "tiff"}; // IFD tag numbers of important fields private static final int METAMORPH_ID = 33628; private static final int UIC1TAG = METAMORPH_ID; private static final int UIC2TAG = 33629; private static final int UIC3TAG = 33630; private static final int UIC4TAG = 33631; // -- Fields -- /** The TIFF's name */ private String imageName; /** The TIFF's creation date */ private String imageCreationDate; /** The TIFF's emWavelength */ private long[] emWavelength; private double[] wave; private String binning; private double zoom, stepSize; private Double exposureTime; private Vector<String> waveNames; private Vector<String> stageNames; private long[] internalStamps; private double[] zDistances, stageX, stageY; private double zStart; private Double sizeX = null, sizeY = null; private double tempZ; private boolean validZ; private Double gain; private int mmPlanes; //number of metamorph planes private MetamorphReader[][] stkReaders; /** List of STK files in the dataset. */ private String[][] stks; private String ndFilename; private boolean canLookForND = true; private boolean[] firstSeriesChannels; private boolean bizarreMultichannelAcquisition = false; // -- Constructor -- /** Constructs a new Metamorph reader. */ public MetamorphReader() { super("Metamorph STK", new String[] {"stk", "nd", "tif", "tiff"}); domains = new String[] {FormatTools.LM_DOMAIN}; hasCompanionFiles = true; suffixSufficient = false; datasetDescription = "One or more .stk or .tif/.tiff files plus an " + "optional .nd file"; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { Location location = new Location(name); if (!location.exists()) { return false; } if (checkSuffix(name, "nd")) return true; if (open) { location = location.getAbsoluteFile(); Location parent = location.getParentFile(); String baseName = location.getName(); while (baseName.indexOf("_") >= 0) { baseName = baseName.substring(0, baseName.lastIndexOf("_")); if (checkSuffix(name, suffixes) && (new Location(parent, baseName + ".nd").exists() || new Location(parent, baseName + ".ND").exists())) { return true; } if (checkSuffix(name, suffixes) && (new Location(parent, baseName + ".htd").exists() || new Location(parent, baseName + ".HTD").exists())) { return false; } } } return super.isThisType(name, open); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; String software = ifd.getIFDTextValue(IFD.SOFTWARE); boolean validSoftware = software != null && software.trim().toLowerCase().startsWith("metamorph"); return validSoftware || (ifd.containsKey(UIC1TAG) && ifd.containsKey(UIC3TAG) && ifd.containsKey(UIC4TAG)); } /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return !checkSuffix(id, ND_SUFFIX); } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { if (checkSuffix(id, ND_SUFFIX)) return FormatTools.MUST_GROUP; Location l = new Location(id).getAbsoluteFile(); String[] files = l.getParentFile().list(); for (String file : files) { if (checkSuffix(file, ND_SUFFIX) && l.getName().startsWith(file.substring(0, file.lastIndexOf(".")))) { return FormatTools.MUST_GROUP; } } return FormatTools.CANNOT_GROUP; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (!noPixels && stks == null) return new String[] {currentId}; else if (stks == null) return new String[0]; Vector<String> v = new Vector<String>(); if (ndFilename != null) v.add(ndFilename); if (!noPixels) { for (String stk : stks[getSeries()]) { if (stk != null && new Location(stk).exists()) { v.add(stk); } } } return v.toArray(new String[v.size()]); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (stks == null) { return super.openBytes(no, buf, x, y, w, h); } int[] coords = FormatTools.getZCTCoords(this, no % getSizeZ()); int ndx = no / getSizeZ(); if (bizarreMultichannelAcquisition) { int[] pos = getZCTCoords(no); ndx = getIndex(pos[0], 0, pos[2]) / getSizeZ(); } if (stks[getSeries()].length == 1) ndx = 0; String file = stks[getSeries()][ndx]; if (file == null) return buf; // the original file is a .nd file, so we need to construct a new reader // for the constituent STK files stkReaders[getSeries()][ndx].setMetadataOptions( new DefaultMetadataOptions(MetadataLevel.MINIMUM)); stkReaders[getSeries()][ndx].setId(file); int plane = stks[getSeries()].length == 1 ? no : coords[0]; if (bizarreMultichannelAcquisition) { int realX = getZCTCoords(no)[1] == 0 ? x : x + getSizeX(); stkReaders[getSeries()][ndx].openBytes(plane, buf, realX, y, w, h); } else { stkReaders[getSeries()][ndx].openBytes(plane, buf, x, y, w, h); } if (plane == stkReaders[getSeries()][ndx].getImageCount() - 1) { stkReaders[getSeries()][ndx].close(); } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (stkReaders != null) { for (MetamorphReader[] s : stkReaders) { if (s != null) { for (MetamorphReader reader : s) { if (reader != null) reader.close(fileOnly); } } } } if (!fileOnly) { imageName = imageCreationDate = null; emWavelength = null; stks = null; mmPlanes = 0; ndFilename = null; wave = null; binning = null; zoom = stepSize = 0; exposureTime = null; waveNames = stageNames = null; internalStamps = null; zDistances = stageX = stageY = null; firstSeriesChannels = null; sizeX = sizeY = null; tempZ = 0d; validZ = false; stkReaders = null; gain = null; bizarreMultichannelAcquisition = false; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (checkSuffix(id, ND_SUFFIX)) { LOGGER.info("Initializing " + id); // find an associated STK file String stkFile = id.substring(0, id.lastIndexOf(".")); if (stkFile.indexOf(File.separator) != -1) { stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1); } Location parent = new Location(id).getAbsoluteFile().getParentFile(); LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath()); String[] dirList = parent.list(true); for (String f : dirList) { int underscore = f.indexOf("_"); if (underscore < 0) underscore = f.indexOf("."); if (underscore < 0) underscore = f.length(); String prefix = f.substring(0, underscore); if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) { stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath(); break; } } if (!checkSuffix(stkFile, STK_SUFFIX)) { throw new FormatException("STK file not found in " + parent.getAbsolutePath() + "."); } super.initFile(stkFile); } else super.initFile(id); Location ndfile = null; if (checkSuffix(id, ND_SUFFIX)) ndfile = new Location(id); else if (canLookForND && isGroupFiles()) { // an STK file was passed to initFile // let's check the parent directory for an .nd file Location stk = new Location(id).getAbsoluteFile(); String stkName = stk.getName(); String stkPrefix = stkName; if (stkPrefix.indexOf("_") >= 0) { stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf("_") + 1); } Location parent = stk.getParentFile(); String[] list = parent.list(true); int matchingChars = 0; for (String f : list) { if (checkSuffix(f, ND_SUFFIX)) { String prefix = f.substring(0, f.lastIndexOf(".")); if (prefix.indexOf("_") >= 0) { prefix = prefix.substring(0, prefix.indexOf("_") + 1); } if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) { int charCount = 0; for (int i=0; i<f.length(); i++) { if (i >= stkName.length()) { break; } if (f.charAt(i) == stkName.charAt(i)) { charCount++; } else { break; } } if (charCount > matchingChars || (charCount == matchingChars && f.charAt(charCount) == '.')) { ndfile = new Location(parent, f).getAbsoluteFile(); matchingChars = charCount; } } } } } String creationTime = null; if (ndfile != null && ndfile.exists() && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) { // parse key/value pairs from .nd file int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT(); int nstages = 0; String z = null, c = null, t = null; Vector<Boolean> hasZ = new Vector<Boolean>(); waveNames = new Vector<String>(); stageNames = new Vector<String>(); boolean useWaveNames = true; ndFilename = ndfile.getAbsolutePath(); String[] lines = DataTools.readFile(ndFilename).split("\n"); boolean globalDoZ = true; boolean doTimelapse = false; StringBuilder currentValue = new StringBuilder(); String key = ""; for (String line : lines) { int comma = line.indexOf(","); if (comma <= 0) { currentValue.append("\n"); currentValue.append(line); continue; } String value = currentValue.toString(); addGlobalMeta(key, value); if (key.equals("NZSteps")) z = value; else if (key.equals("DoTimelapse")) { doTimelapse = Boolean.parseBoolean(value); } else if (key.equals("NWavelengths")) c = value; else if (key.equals("NTimePoints")) t = value; else if (key.startsWith("WaveDoZ")) { hasZ.add(new Boolean(value.toLowerCase())); } else if (key.startsWith("WaveName")) { String waveName = value.substring(1, value.length() - 1); if (waveName.equals("Both lasers") || waveName.startsWith("DUAL")) { bizarreMultichannelAcquisition = true; } waveNames.add(waveName); } else if (key.startsWith("Stage")) { stageNames.add(value); } else if (key.startsWith("StartTime")) { creationTime = value; } else if (key.equals("ZStepSize")) { char separator = new DecimalFormatSymbols().getDecimalSeparator(); value = value.replace('.', separator); value = value.replace(',', separator); stepSize = Double.parseDouble(value); } else if (key.equals("NStagePositions")) { nstages = Integer.parseInt(value); } else if (key.equals("WaveInFileName")) { useWaveNames = Boolean.parseBoolean(value); } else if (key.equals("DoZSeries")) { globalDoZ = new Boolean(value.toLowerCase()); } key = line.substring(1, comma - 1).trim(); currentValue.delete(0, currentValue.length()); currentValue.append(line.substring(comma + 1).trim()); } // figure out how many files we need if (z != null) zc = Integer.parseInt(z); if (c != null) cc = Integer.parseInt(c); if (t != null) tc = Integer.parseInt(t); if (cc == 0) cc = 1; if (cc == 1 && bizarreMultichannelAcquisition) { cc = 2; } int numFiles = cc * tc; if (nstages > 0) numFiles *= nstages; // determine series count int seriesCount = nstages == 0 ? 1 : nstages; firstSeriesChannels = new boolean[cc]; Arrays.fill(firstSeriesChannels, true); boolean differentZs = false; for (int i=0; i<cc; i++) { boolean hasZ1 = i < hasZ.size() && hasZ.get(i).booleanValue(); boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1).booleanValue(); if (i > 0 && hasZ1 != hasZ2 && globalDoZ) { if (!differentZs) seriesCount *= 2; differentZs = true; } } int channelsInFirstSeries = cc; if (differentZs) { channelsInFirstSeries = 0; for (int i=0; i<cc; i++) { if (hasZ.get(i).booleanValue()) channelsInFirstSeries++; else firstSeriesChannels[i] = false; } } stks = new String[seriesCount][]; if (seriesCount == 1) stks[0] = new String[numFiles]; else if (differentZs) { int stages = nstages == 0 ? 1 : nstages; for (int i=0; i<stages; i++) { stks[i * 2] = new String[channelsInFirstSeries * tc]; stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc]; } } else { for (int i=0; i<stks.length; i++) { stks[i] = new String[numFiles / stks.length]; } } String prefix = ndfile.getPath(); prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf(".")); // build list of STK files boolean anyZ = hasZ.contains(Boolean.TRUE); int[] pt = new int[seriesCount]; for (int i=0; i<tc; i++) { int ns = nstages == 0 ? 1 : nstages; for (int s=0; s<ns; s++) { for (int j=0; j<cc; j++) { boolean validZ = j >= hasZ.size() || hasZ.get(j).booleanValue(); int seriesNdx = s * (seriesCount / ns); if ((seriesCount != 1 && !validZ) || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) { if (anyZ && j > 0 && seriesNdx < seriesCount - 1 && (!validZ || !hasZ.get(0))) { seriesNdx++; } } if (seriesNdx >= stks.length || seriesNdx >= pt.length || pt[seriesNdx] >= stks[seriesNdx].length) { continue; } stks[seriesNdx][pt[seriesNdx]] = prefix; if (j < waveNames.size() && waveNames.get(j) != null) { stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1); if (useWaveNames) { String waveName = waveNames.get(j); // If there are underscores in the wavelength name, translate // them to hyphens. (See #558) waveName = waveName.replace('_', '-'); // If there are slashes (forward or backward) in the wavelength // name, translate them to hyphens. (See #5922) waveName = waveName.replace('/', '-'); waveName = waveName.replace('\\', '-'); waveName = waveName.replace('(', '-'); waveName = waveName.replace(')', '-'); stks[seriesNdx][pt[seriesNdx]] += waveName; } } if (nstages > 0) { stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1); } if (tc > 1 || doTimelapse) { stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK"; } else stks[seriesNdx][pt[seriesNdx]] += ".STK"; pt[seriesNdx]++; } } } ndfile = ndfile.getAbsoluteFile(); // check that each STK file exists for (int s=0; s<stks.length; s++) { for (int f=0; f<stks[s].length; f++) { Location l = new Location(ndfile.getParent(), stks[s][f]); stks[s][f] = getRealSTKFile(l); } } String file = locateFirstValidFile(); if (file == null) { throw new FormatException( "Unable to locate at lease one valid STK file!"); } RandomAccessInputStream s = new RandomAccessInputStream(file); TiffParser tp = new TiffParser(s); IFD ifd = tp.getFirstIFD(); CoreMetadata ms0 = core.get(0); s.close(); ms0.sizeX = (int) ifd.getImageWidth(); ms0.sizeY = (int) ifd.getImageLength(); if (bizarreMultichannelAcquisition) { ms0.sizeX /= 2; } ms0.sizeZ = hasZ.size() > 0 && !hasZ.get(0) ? 1 : zc; ms0.sizeC = cc; ms0.sizeT = tc; ms0.imageCount = getSizeZ() * getSizeC() * getSizeT(); ms0.dimensionOrder = "XYZCT"; if (stks != null && stks.length > 1) { // Note that core can't be replaced with newCore until the end of this block. ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>(); for (int i=0; i<stks.length; i++) { CoreMetadata ms = new CoreMetadata(); newCore.add(ms); ms.sizeX = getSizeX(); ms.sizeY = getSizeY(); ms.sizeZ = getSizeZ(); ms.sizeC = getSizeC(); ms.sizeT = getSizeT(); ms.pixelType = getPixelType(); ms.imageCount = getImageCount(); ms.dimensionOrder = getDimensionOrder(); ms.rgb = isRGB(); ms.littleEndian = isLittleEndian(); ms.interleaved = isInterleaved(); ms.orderCertain = true; } if (stks.length > nstages) { int ns = nstages == 0 ? 1 : nstages; for (int j=0; j<ns; j++) { int idx = j * 2 + 1; CoreMetadata midx = newCore.get(idx); CoreMetadata pmidx = newCore.get(j * 2); pmidx.sizeC = stks[j * 2].length / getSizeT(); midx.sizeC = stks[idx].length / midx.sizeT; midx.sizeZ = hasZ.size() > 1 && hasZ.get(1) && core.get(0).sizeZ == 1 ? zc : 1; pmidx.imageCount = pmidx.sizeC * pmidx.sizeT * pmidx.sizeZ; midx.imageCount = midx.sizeC * midx.sizeT * midx.sizeZ; } } core = newCore; } } if (stks == null) { stkReaders = new MetamorphReader[1][1]; stkReaders[0][0] = new MetamorphReader(); stkReaders[0][0].setCanLookForND(false); } else { stkReaders = new MetamorphReader[stks.length][]; for (int i=0; i<stks.length; i++) { stkReaders[i] = new MetamorphReader[stks[i].length]; for (int j=0; j<stkReaders[i].length; j++) { stkReaders[i][j] = new MetamorphReader(); stkReaders[i][j].setCanLookForND(false); if (j > 0) { stkReaders[i][j].setMetadataOptions( new DefaultMetadataOptions(MetadataLevel.MINIMUM)); } } } } Vector<String> timestamps = null; MetamorphHandler handler = null; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); String detectorID = MetadataTools.createLSID("Detector", 0, 0); for (int i=0; i<getSeriesCount(); i++) { setSeries(i); handler = new MetamorphHandler(getSeriesMetadata()); String instrumentID = MetadataTools.createLSID("Instrument", i); store.setInstrumentID(instrumentID, i); store.setImageInstrumentRef(instrumentID, i); if (i == 0) { store.setDetectorID(detectorID, 0, 0); store.setDetectorType(getDetectorType("Other"), 0, 0); } String comment = getFirstComment(i); if (comment != null && comment.startsWith("<MetaData>")) { try { XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler); } catch (IOException e) { } } if (creationTime != null) { String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), 0); } } store.setImageName(makeImageName(i).trim(), i); if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { continue; } store.setImageDescription("", i); store.setImagingEnvironmentTemperature(handler.getTemperature(), i); if (sizeX == null) sizeX = handler.getPixelSizeX(); if (sizeY == null) sizeY = handler.getPixelSizeY(); if (sizeX > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(sizeX), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", sizeX); } if (sizeY > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(sizeY), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeY; got {}", sizeY); } if (zDistances != null) { stepSize = zDistances[0]; } if (stepSize > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(stepSize), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}", stepSize); } int waveIndex = 0; for (int c=0; c<getEffectiveSizeC(); c++) { if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) { waveIndex = c; } else if (firstSeriesChannels != null) { int s = i % 2; while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) { waveIndex++; } } if (waveNames != null && waveIndex < waveNames.size()) { store.setChannelName(waveNames.get(waveIndex).trim(), i, c); } if (handler.getBinning() != null) binning = handler.getBinning(); if (binning != null) { store.setDetectorSettingsBinning(getBinning(binning), i, c); } if (handler.getReadOutRate() != 0) { store.setDetectorSettingsReadOutRate(handler.getReadOutRate(), i, c); } if (gain == null) { gain = handler.getGain(); } if (gain != null) { store.setDetectorSettingsGain(gain, i, c); } store.setDetectorSettingsID(detectorID, i, c); if (wave != null && waveIndex < wave.length) { if ((int) wave[waveIndex] >= 1) { store.setChannelLightSourceSettingsWavelength( new PositiveInteger((int) wave[waveIndex]), i, c); // link LightSource to Image String lightSourceID = MetadataTools.createLSID("LightSource", i, c); store.setLaserID(lightSourceID, i, c); store.setChannelLightSourceSettingsID(lightSourceID, i, c); store.setLaserType(getLaserType("Other"), i, c); store.setLaserLaserMedium(getLaserMedium("Other"), i, c); } else { LOGGER.warn("Expected positive value for Wavelength; got {}", wave[waveIndex]); } } waveIndex++; } timestamps = handler.getTimestamps(); for (int t=0; t<timestamps.size(); t++) { addSeriesMetaList("timestamp", DateTools.formatDate(timestamps.get(t), MEDIUM_DATE_FORMAT)); } long startDate = 0; if (timestamps.size() > 0) { startDate = DateTools.getTime(timestamps.get(0), MEDIUM_DATE_FORMAT); } Double positionX = new Double(handler.getStagePositionX()); Double positionY = new Double(handler.getStagePositionY()); Vector<Double> exposureTimes = handler.getExposures(); if (exposureTimes.size() == 0) { for (int p=0; p<getImageCount(); p++) { exposureTimes.add(exposureTime); } } else if (exposureTimes.size() == 1 && exposureTimes.size() < getSizeC()) { for (int c=1; c<getSizeC(); c++) { MetamorphHandler channelHandler = new MetamorphHandler(); String channelComment = getComment(i, c); if (channelComment != null && channelComment.startsWith("<MetaData>")) { try { XMLTools.parseXML(XMLTools.sanitizeXML(channelComment), channelHandler); } catch (IOException e) { } } Vector<Double> channelExpTime = channelHandler.getExposures(); exposureTimes.add(channelExpTime.get(0)); } } int lastFile = -1; IFDList lastIFDs = null; IFD lastIFD = null; long[] lastOffsets = null; double distance = zStart; TiffParser tp = null; RandomAccessInputStream stream = null; for (int p=0; p<getImageCount(); p++) { int[] coords = getZCTCoords(p); Double deltaT = new Double(0); Double expTime = exposureTime; Double xmlZPosition = null; int fileIndex = getIndex(0, 0, coords[2]) / getSizeZ(); if (fileIndex >= 0) { String file = stks == null ? currentId : stks[i][fileIndex]; if (file != null) { if (fileIndex != lastFile) { if (stream != null) { stream.close(); } stream = new RandomAccessInputStream(file); tp = new TiffParser(stream); tp.checkHeader(); lastFile = fileIndex; lastIFDs = tp.getIFDs(); } lastIFD = lastIFDs.get(p % lastIFDs.size()); Object commentEntry = lastIFD.get(IFD.IMAGE_DESCRIPTION); if (commentEntry != null) { if (commentEntry instanceof String) { comment = (String) commentEntry; } else if (commentEntry instanceof TiffIFDEntry) { comment = tp.getIFDValue((TiffIFDEntry) commentEntry).toString(); } } if (comment != null) comment = comment.trim(); if (comment != null && comment.startsWith("<MetaData>")) { String[] lines = comment.split("\n"); timestamps = new Vector<String>(); for (String line : lines) { line = line.trim(); if (line.startsWith("<prop")) { int firstQuote = line.indexOf("\"") + 1; int lastQuote = line.lastIndexOf("\""); String key = line.substring(firstQuote, line.indexOf("\"", firstQuote)); String value = line.substring( line.lastIndexOf("\"", lastQuote - 1) + 1, lastQuote); if (key.equals("z-position")) { xmlZPosition = new Double(value); } else if (key.equals("acquisition-time-local")) { timestamps.add(value); } } } } } } int index = 0; if (timestamps.size() > 0) { if (coords[2] < timestamps.size()) index = coords[2]; String stamp = timestamps.get(index); long ms = DateTools.getTime(stamp, MEDIUM_DATE_FORMAT); deltaT = new Double((ms - startDate) / 1000.0); } else if (internalStamps != null && p < internalStamps.length) { long delta = internalStamps[p] - internalStamps[0]; deltaT = new Double(delta / 1000.0); if (coords[2] < exposureTimes.size()) index = coords[2]; } if (index == 0 && p > 0 && exposureTimes.size() > 0) { index = coords[1] % exposureTimes.size(); } if (index < exposureTimes.size()) { expTime = exposureTimes.get(index); } store.setPlaneDeltaT(deltaT, i, p); store.setPlaneExposureTime(expTime, i, p); if (stageX != null && p < stageX.length) { store.setPlanePositionX(stageX[p], i, p); } else if (positionX != null) { store.setPlanePositionX(positionX, i, p); } if (stageY != null && p < stageY.length) { store.setPlanePositionY(stageY[p], i, p); } else if (positionY != null) { store.setPlanePositionY(positionY, i, p); } if (zDistances != null && p < zDistances.length) { if (p > 0) { if (zDistances[p] != 0d) distance += zDistances[p]; else distance += zDistances[0]; } store.setPlanePositionZ(distance, i, p); } else if (xmlZPosition != null) { store.setPlanePositionZ(xmlZPosition, i, p); } } if (stream != null) { stream.close(); } } setSeries(0); } // -- Internal BaseTiffReader API methods -- /* @see BaseTiffReader#initStandardMetadata() */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); CoreMetadata ms0 = core.get(0); ms0.sizeZ = 1; ms0.sizeT = 0; int rgbChannels = getSizeC(); // Now that the base TIFF standard metadata has been parsed, we need to // parse out the STK metadata from the UIC4TAG. TiffIFDEntry uic1tagEntry = null; TiffIFDEntry uic2tagEntry = null; TiffIFDEntry uic4tagEntry = null; try { uic1tagEntry = tiffParser.getFirstIFDEntry(UIC1TAG); uic2tagEntry = tiffParser.getFirstIFDEntry(UIC2TAG); uic4tagEntry = tiffParser.getFirstIFDEntry(UIC4TAG); } catch (IllegalArgumentException exc) { LOGGER.debug("Unknown tag", exc); } try { if (uic4tagEntry != null) { mmPlanes = uic4tagEntry.getValueCount(); } if (uic2tagEntry != null) { parseUIC2Tags(uic2tagEntry.getValueOffset()); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (uic4tagEntry != null) { parseUIC4Tags(uic4tagEntry.getValueOffset()); } if (uic1tagEntry != null) { parseUIC1Tags(uic1tagEntry.getValueOffset(), uic1tagEntry.getValueCount()); } } in.seek(uic4tagEntry.getValueOffset()); } catch (NullPointerException exc) { LOGGER.debug("", exc); } catch (IOException exc) { LOGGER.debug("Failed to parse proprietary tags", exc); } try { // copy ifds into a new array of Hashtables that will accommodate the // additional image planes IFD firstIFD = ifds.get(0); long[] uic2 = firstIFD.getIFDLongArray(UIC2TAG); if (uic2 == null) { throw new FormatException("Invalid Metamorph file. Tag " + UIC2TAG + " not found."); } ms0.imageCount = uic2.length; Object entry = firstIFD.getIFDValue(UIC3TAG); TiffRational[] uic3 = entry instanceof TiffRational[] ? (TiffRational[]) entry : new TiffRational[] {(TiffRational) entry}; wave = new double[uic3.length]; Vector<Double> uniqueWavelengths = new Vector<Double>(); for (int i=0; i<uic3.length; i++) { wave[i] = uic3[i].doubleValue(); addSeriesMeta("Wavelength [" + intFormatMax(i, mmPlanes) + "]", wave[i]); Double v = new Double(wave[i]); if (!uniqueWavelengths.contains(v)) uniqueWavelengths.add(v); } if (getSizeC() == 1) { ms0.sizeC = uniqueWavelengths.size(); } IFDList tempIFDs = new IFDList(); long[] oldOffsets = firstIFD.getStripOffsets(); long[] stripByteCounts = firstIFD.getStripByteCounts(); int rowsPerStrip = (int) firstIFD.getRowsPerStrip()[0]; int stripsPerImage = getSizeY() / rowsPerStrip; if (stripsPerImage * rowsPerStrip != getSizeY()) stripsPerImage++; PhotoInterp check = firstIFD.getPhotometricInterpretation(); if (check == PhotoInterp.RGB_PALETTE) { firstIFD.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION, PhotoInterp.BLACK_IS_ZERO); } emWavelength = firstIFD.getIFDLongArray(UIC3TAG); // for each image plane, construct an IFD hashtable IFD temp; for (int i=0; i<getImageCount(); i++) { // copy data from the first IFD temp = new IFD(firstIFD); // now we need a StripOffsets entry - the original IFD doesn't have this long[] newOffsets = new long[stripsPerImage]; if (stripsPerImage * (i + 1) <= oldOffsets.length) { System.arraycopy(oldOffsets, stripsPerImage * i, newOffsets, 0, stripsPerImage); } else { System.arraycopy(oldOffsets, 0, newOffsets, 0, stripsPerImage); long image = (stripByteCounts[0] / rowsPerStrip) * getSizeY(); for (int q=0; q<stripsPerImage; q++) { newOffsets[q] += i * image; } } temp.putIFDValue(IFD.STRIP_OFFSETS, newOffsets); long[] newByteCounts = new long[stripsPerImage]; if (stripsPerImage * i < stripByteCounts.length) { System.arraycopy(stripByteCounts, stripsPerImage * i, newByteCounts, 0, stripsPerImage); } else { Arrays.fill(newByteCounts, stripByteCounts[0]); } temp.putIFDValue(IFD.STRIP_BYTE_COUNTS, newByteCounts); tempIFDs.add(temp); } ifds = tempIFDs; } catch (IllegalArgumentException exc) { LOGGER.debug("Unknown tag", exc); } catch (NullPointerException exc) { LOGGER.debug("", exc); } catch (FormatException exc) { LOGGER.debug("Failed to build list of IFDs", exc); } // parse (mangle) TIFF comment String descr = ifds.get(0).getComment(); if (descr != null) { String[] lines = descr.split("\n"); StringBuffer sb = new StringBuffer(); for (int i=0; i<lines.length; i++) { String line = lines[i].trim(); int colon = line.indexOf(": "); String descrValue = null; if (colon < 0) { // normal line (not a key/value pair) if (line.length() > 0) { // not a blank line descrValue = line; } } else { if (i == 0) { // first line could be mangled; make a reasonable guess int dot = line.lastIndexOf(".", colon); if (dot >= 0) { descrValue = line.substring(0, dot + 1); } line = line.substring(dot + 1); colon -= dot + 1; } // append value to description if (descrValue != null) { sb.append(descrValue); if (!descrValue.endsWith(".")) sb.append("."); sb.append(" "); } // add key/value pair embedded in comment as separate metadata String key = line.substring(0, colon); String value = line.substring(colon + 2); addSeriesMeta(key, value); if (key.equals("Exposure")) { if (value.indexOf("=") != -1) { value = value.substring(value.indexOf("=") + 1).trim(); } if (value.indexOf(" ") != -1) { value = value.substring(0, value.indexOf(" ")); } try { char separator = new DecimalFormatSymbols().getDecimalSeparator(); value = value.replace('.', separator); value = value.replace(',', separator); double exposure = Double.parseDouble(value); exposureTime = new Double(exposure / 1000); } catch (NumberFormatException e) { } } else if (key.equals("Bit Depth")) { if (value.indexOf("-") != -1) { value = value.substring(0, value.indexOf("-")); } try { ms0.bitsPerPixel = Integer.parseInt(value); } catch (NumberFormatException e) { } } else if (key.equals("Gain")) { int space = value.indexOf(" "); if (space != -1) { int nextSpace = value.indexOf(" ", space + 1); if (nextSpace < 0) { nextSpace = value.length(); } try { gain = new Double(value.substring(space, nextSpace)); } catch (NumberFormatException e) { } } } } } // replace comment with trimmed version descr = sb.toString().trim(); if (descr.equals("")) metadata.remove("Comment"); else addSeriesMeta("Comment", descr); } ms0.sizeT = getImageCount() / (getSizeZ() * (getSizeC() / rgbChannels)); if (getSizeT() * getSizeZ() * (getSizeC() / rgbChannels) != getImageCount()) { ms0.sizeT = 1; ms0.sizeZ = getImageCount() / (getSizeC() / rgbChannels); } // if '_t' is present in the file name, swap Z and T sizes // this file was probably part of a larger dataset, but the .nd file is // missing String filename = currentId.substring(currentId.lastIndexOf(File.separator) + 1); if (filename.indexOf("_t") != -1 && getSizeT() > 1) { int z = getSizeZ(); ms0.sizeZ = getSizeT(); ms0.sizeT = z; } if (getSizeZ() == 0) ms0.sizeZ = 1; if (getSizeT() == 0) ms0.sizeT = 1; if (getSizeZ() * getSizeT() * (isRGB() ? 1 : getSizeC()) != getImageCount()) { ms0.sizeZ = getImageCount(); ms0.sizeT = 1; if (!isRGB()) ms0.sizeC = 1; } } // -- Helper methods -- /** * Check that the given STK file exists. If it does, then return the * absolute path. If it does not, then apply various formatting rules until * an existing file is found. * * @return the absolute path of an STK file, or null if no STK file is found. */ private String getRealSTKFile(Location l) { if (l.exists()) return l.getAbsolutePath(); String name = l.getName(); String parent = l.getParent(); if (name.indexOf("_") > 0) { String prefix = name.substring(0, name.indexOf("_")); String suffix = name.substring(name.indexOf("_")); String basePrefix = new Location(currentId).getName(); int end = basePrefix.indexOf("_"); if (end < 0) end = basePrefix.indexOf("."); basePrefix = basePrefix.substring(0, end); if (!basePrefix.equals(prefix)) { name = basePrefix + suffix; Location p = new Location(parent, name); if (p.exists()) return p.getAbsolutePath(); } } // '%' can be converted to '-' if (name.indexOf("%") != -1) { name = name.replaceAll("%", "-"); l = new Location(parent, name); if (!l.exists()) { // try replacing extension name = name.substring(0, name.lastIndexOf(".")) + ".TIF"; l = new Location(parent, name); if (!l.exists()) { name = name.substring(0, name.lastIndexOf(".")) + ".tif"; l = new Location(parent, name); return l.exists() ? l.getAbsolutePath() : null; } } } if (!l.exists()) { // try replacing extension int index = name.lastIndexOf("."); if (index < 0) index = name.length(); name = name.substring(0, index) + ".TIF"; l = new Location(parent, name); if (!l.exists()) { name = name.substring(0, name.lastIndexOf(".")) + ".tif"; l = new Location(parent, name); if (!l.exists()) { name = name.substring(0, name.lastIndexOf(".")) + ".stk"; l = new Location(parent, name); return l.exists() ? l.getAbsolutePath() : null; } } } return l.getAbsolutePath(); } /** * Returns the TIFF comment from the first IFD of the first STK file in the * given series. */ private String getFirstComment(int i) throws IOException { return getComment(i, 0); } private String getComment(int i, int no) throws IOException { if (stks != null && stks[i][no] != null) { RandomAccessInputStream stream = new RandomAccessInputStream(stks[i][no]); TiffParser tp = new TiffParser(stream); String comment = tp.getComment(); stream.close(); return comment; } return ifds.get(0).getComment(); } /** Create an appropriate name for the given series. */ private String makeImageName(int i) { String name = ""; if (stageNames != null && stageNames.size() > 0) { int stagePosition = i / (getSeriesCount() / stageNames.size()); name += "Stage " + stageNames.get(stagePosition) + "; "; } if (firstSeriesChannels != null) { for (int c=0; c<firstSeriesChannels.length; c++) { if (firstSeriesChannels[c] == ((i % 2) == 0) && c < waveNames.size()) { name += waveNames.get(c) + "/"; } } if (name.length() > 0) { name = name.substring(0, name.length() - 1); } } return name; } /** * Populates metadata fields with some contained in MetaMorph UIC2 Tag. * (for each plane: 6 integers: * zdistance numerator, zdistance denominator, * creation date, creation time, modif date, modif time) * @param uic2offset offset to UIC2 (33629) tag entries * * not a regular tiff tag (6*N entries, N being the tagCount) * @throws IOException */ void parseUIC2Tags(long uic2offset) throws IOException { long saveLoc = in.getFilePointer(); in.seek(uic2offset); /*number of days since the 1st of January 4713 B.C*/ String cDate; /*milliseconds since 0:00*/ String cTime; /*z step, distance separating previous slice from current one*/ String iAsString; zDistances = new double[mmPlanes]; internalStamps = new long[mmPlanes]; for (int i=0; i<mmPlanes; i++) { iAsString = intFormatMax(i, mmPlanes); if (in.getFilePointer() + 8 > in.length()) break; zDistances[i] = readRational(in).doubleValue(); addSeriesMeta("zDistance[" + iAsString + "]", zDistances[i]); if (zDistances[i] != 0.0) core.get(0).sizeZ++; cDate = decodeDate(in.readInt()); cTime = decodeTime(in.readInt()); internalStamps[i] = DateTools.getTime(cDate + " " + cTime, LONG_DATE_FORMAT); addSeriesMeta("creationDate[" + iAsString + "]", cDate); addSeriesMeta("creationTime[" + iAsString + "]", cTime); // modification date and time are skipped as they all seem equal to 0...? in.skip(8); } if (getSizeZ() == 0) core.get(0).sizeZ = 1; in.seek(saveLoc); } /** * UIC4 metadata parser * * UIC4 Table contains per-plane blocks of metadata * stage X/Y positions, * camera chip offsets, * stage labels... * @param long uic4offset: offset of UIC4 table (not tiff-compliant) * @throws IOException */ private void parseUIC4Tags(long uic4offset) throws IOException { long saveLoc = in.getFilePointer(); in.seek(uic4offset); if (in.getFilePointer() + 2 >= in.length()) return; tempZ = 0d; validZ = false; short id = in.readShort(); while (id != 0) { switch (id) { case 28: readStagePositions(); break; case 29: readRationals( new String[] {"cameraXChipOffset", "cameraYChipOffset"}); break; case 37: readStageLabels(); break; case 40: readRationals(new String[] {"UIC4 absoluteZ"}); break; case 41: readAbsoluteZValid(); break; case 46: in.skipBytes(mmPlanes * 8); // TODO break; default: in.skipBytes(4); } id = in.readShort(); } in.seek(saveLoc); if (validZ) zStart = tempZ; } private void readStagePositions() throws IOException { stageX = new double[mmPlanes]; stageY = new double[mmPlanes]; String pos; for (int i=0; i<mmPlanes; i++) { pos = intFormatMax(i, mmPlanes); stageX[i] = readRational(in).doubleValue(); stageY[i] = readRational(in).doubleValue(); addSeriesMeta("stageX[" + pos + "]", stageX[i]); addSeriesMeta("stageY[" + pos + "]", stageY[i]); addGlobalMeta("X position for position #" + (getSeries() + 1), stageX[i]); addGlobalMeta("Y position for position #" + (getSeries() + 1), stageY[i]); } } private void readRationals(String[] labels) throws IOException { String pos; for (int i=0; i<mmPlanes; i++) { pos = intFormatMax(i, mmPlanes); for (int q=0; q<labels.length; q++) { double v = readRational(in).doubleValue(); if (labels[q].endsWith("absoluteZ") && i == 0) { tempZ = v; } addSeriesMeta(labels[q] + "[" + pos + "]", v); } } } void readStageLabels() throws IOException { int strlen; String iAsString; for (int i=0; i<mmPlanes; i++) { iAsString = intFormatMax(i, mmPlanes); strlen = in.readInt(); addSeriesMeta("stageLabel[" + iAsString + "]", in.readString(strlen)); } } void readAbsoluteZValid() throws IOException { for (int i=0; i<mmPlanes; i++) { int valid = in.readInt(); addSeriesMeta("absoluteZValid[" + intFormatMax(i, mmPlanes) + "]", valid); if (i == 0) { validZ = valid == 1; } } } /** * UIC1 entry parser * @throws IOException * @param long uic1offset : offset as found in the tiff tag 33628 (UIC1Tag) * @param int uic1count : number of entries in UIC1 table (not tiff-compliant) */ private void parseUIC1Tags(long uic1offset, int uic1count) throws IOException { // Loop through and parse out each field. A field whose // code is "0" represents the end of the fields so we'll stop // when we reach that; much like a NULL terminated C string. long saveLoc = in.getFilePointer(); in.seek(uic1offset); int currentID; long valOrOffset; // variable declarations, because switch is dumb int num, denom; String thedate, thetime; long lastOffset; tempZ = 0d; validZ = false; for (int i=0; i<uic1count; i++) { if (in.getFilePointer() >= in.length()) break; currentID = in.readInt(); valOrOffset = in.readInt() & 0xffffffffL; lastOffset = in.getFilePointer(); String key = getKey(currentID); Object value = String.valueOf(valOrOffset); switch (currentID) { case 3: value = valOrOffset != 0 ? "on" : "off"; break; case 4: case 5: case 21: case 22: case 23: case 24: case 38: case 39: value = readRational(in, valOrOffset); break; case 6: case 25: in.seek(valOrOffset); num = in.readInt(); if (num + in.getFilePointer() >= in.length()) { num = (int) (in.length() - in.getFilePointer() - 1); } value = in.readString(num); break; case 7: in.seek(valOrOffset); num = in.readInt(); imageName = in.readString(num); value = imageName; break; case 8: if (valOrOffset == 1) value = "inside"; else if (valOrOffset == 2) value = "outside"; else value = "off"; break; case 17: // oh how we hate you Julian format... in.seek(valOrOffset); thedate = decodeDate(in.readInt()); thetime = decodeTime(in.readInt()); imageCreationDate = thedate + " " + thetime; value = imageCreationDate; break; case 16: in.seek(valOrOffset); thedate = decodeDate(in.readInt()); thetime = decodeTime(in.readInt()); value = thedate + " " + thetime; break; case 26: in.seek(valOrOffset); int standardLUT = in.readInt(); switch (standardLUT) { case 0: value = "monochrome"; break; case 1: value = "pseudocolor"; break; case 2: value = "Red"; break; case 3: value = "Green"; break; case 4: value = "Blue"; break; case 5: value = "user-defined"; break; default: value = "monochrome"; } break; case 34: value = String.valueOf(in.readInt()); break; case 46: in.seek(valOrOffset); int xBin = in.readInt(); int yBin = in.readInt(); binning = xBin + "x" + yBin; value = binning; break; case 40: if (valOrOffset != 0) { in.seek(valOrOffset); readRationals(new String[] {"UIC1 absoluteZ"}); } break; case 41: if (valOrOffset != 0) { in.seek(valOrOffset); readAbsoluteZValid(); } break; case 49: in.seek(valOrOffset); readPlaneData(); break; } addSeriesMeta(key, value); in.seek(lastOffset); if ("Zoom".equals(key) && value != null) { zoom = Double.parseDouble(value.toString()); } if ("XCalibration".equals(key) && value != null) { if (value instanceof TiffRational) { sizeX = ((TiffRational) value).doubleValue(); } else sizeX = new Double(value.toString()); } if ("YCalibration".equals(key) && value != null) { if (value instanceof TiffRational) { sizeY = ((TiffRational) value).doubleValue(); } else sizeY = new Double(value.toString()); } } in.seek(saveLoc); if (validZ) zStart = tempZ; } // -- Utility methods -- /** Converts a Julian date value into a human-readable string. */ public static String decodeDate(int julian) { long a, b, c, d, e, alpha, z; short day, month, year; // code reused from the Metamorph data specification z = julian + 1; if (z < 2299161L) a = z; else { alpha = (long) ((z - 1867216.25) / 36524.25); a = z + 1 + alpha - alpha / 4; } b = (a > 1721423L ? a + 1524 : a + 1158); c = (long) ((b - 122.1) / 365.25); d = (long) (365.25 * c); e = (long) ((b - d) / 30.6001); day = (short) (b - d - (long) (30.6001 * e)); month = (short) ((e < 13.5) ? e - 1 : e - 13); year = (short) ((month > 2.5) ? (c - 4716) : c - 4715); return intFormat(day, 2) + "/" + intFormat(month, 2) + "/" + year; } /** Converts a time value in milliseconds into a human-readable string. */ public static String decodeTime(int millis) { Calendar time = Calendar.getInstance(TimeZone.getTimeZone("GMT")); time.setTimeInMillis(millis); String hours = intFormat(time.get(Calendar.HOUR_OF_DAY), 2); String minutes = intFormat(time.get(Calendar.MINUTE), 2); String seconds = intFormat(time.get(Calendar.SECOND), 2); String ms = intFormat(time.get(Calendar.MILLISECOND), 3); return hours + ":" + minutes + ":" + seconds + ":" + ms; } /** Formats an integer value with leading 0s if needed. */ public static String intFormat(int myint, int digits) { return String.format("%0" + digits + "d", myint); } /** * Formats an integer with leading 0 using maximum sequence number. * * @param myint integer to format * @param maxint max of "myint" * @return String */ public static String intFormatMax(int myint, int maxint) { return intFormat(myint, String.valueOf(maxint).length()); } /** * Locates the first valid file in the STK arrays. * @return Path to the first valid file. */ private String locateFirstValidFile() { for (int q = 0; q < stks.length; q++) { for (int f = 0; f < stks.length; f++) { if (stks[q][f] != null) { return stks[q][f]; } } } return null; } private TiffRational readRational(RandomAccessInputStream s) throws IOException { return readRational(s, s.getFilePointer()); } private TiffRational readRational(RandomAccessInputStream s, long offset) throws IOException { s.seek(offset); int num = s.readInt(); int denom = s.readInt(); return new TiffRational(num, denom); } private void setCanLookForND(boolean v) { FormatTools.assertId(currentId, false, 1); canLookForND = v; } private void readPlaneData() throws IOException { in.skipBytes(4); int keyLength = in.read(); String key = in.readString(keyLength); in.skipBytes(4); int type = in.read(); int index = 0; switch (type) { case 1: in.skipBytes(1); while (getGlobalMeta("Channel #" + index + " " + key) != null) { index++; } addGlobalMeta("Channel #" + index + " " + key, in.readDouble()); break; case 2: int valueLength = in.read(); String value = in.readString(valueLength); if (valueLength == 0) { in.skipBytes(4); valueLength = in.read(); value = in.readString(valueLength); } while (getGlobalMeta("Channel #" + index + " " + key) != null) { index++; } addGlobalMeta("Channel #" + index + " " + key, value); if (key.equals("_IllumSetting_")) { if (waveNames == null) waveNames = new Vector<String>(); waveNames.add(value); } break; } core.get(0).sizeC = index + 1; } private String getKey(int id) { switch (id) { case 0: return "AutoScale"; case 1: return "MinScale"; case 2: return "MaxScale"; case 3: return "Spatial Calibration"; case 4: return "XCalibration"; case 5: return "YCalibration"; case 6: return "CalibrationUnits"; case 7: return "Name"; case 8: return "ThreshState"; case 9: return "ThreshStateRed"; // there is no 10 case 11: return "ThreshStateGreen"; case 12: return "ThreshStateBlue"; case 13: return "ThreshStateLo"; case 14: return "ThreshStateHi"; case 15: return "Zoom"; case 16: return "DateTime"; case 17: return "LastSavedTime"; case 18: return "currentBuffer"; case 19: return "grayFit"; case 20: return "grayPointCount"; case 21: return "grayX"; case 22: return "grayY"; case 23: return "grayMin"; case 24: return "grayMax"; case 25: return "grayUnitName"; case 26: return "StandardLUT"; case 27: return "Wavelength"; case 28: return "StagePosition"; case 29: return "CameraChipOffset"; case 30: return "OverlayMask"; case 31: return "OverlayCompress"; case 32: return "Overlay"; case 33: return "SpecialOverlayMask"; case 34: return "SpecialOverlayCompress"; case 35: return "SpecialOverlay"; case 36: return "ImageProperty"; case 38: return "AutoScaleLoInfo"; case 39: return "AutoScaleHiInfo"; case 40: return "AbsoluteZ"; case 41: return "AbsoluteZValid"; case 42: return "Gamma"; case 43: return "GammaRed"; case 44: return "GammaGreen"; case 45: return "GammaBlue"; case 46: return "CameraBin"; case 47: return "NewLUT"; case 48: return "ImagePropertyEx"; case 49: return "PlaneProperty"; case 50: return "UserLutTable"; case 51: return "RedAutoScaleInfo"; case 52: return "RedAutoScaleLoInfo"; case 53: return "RedAutoScaleHiInfo"; case 54: return "RedMinScaleInfo"; case 55: return "RedMaxScaleInfo"; case 56: return "GreenAutoScaleInfo"; case 57: return "GreenAutoScaleLoInfo"; case 58: return "GreenAutoScaleHiInfo"; case 59: return "GreenMinScaleInfo"; case 60: return "GreenMaxScaleInfo"; case 61: return "BlueAutoScaleInfo"; case 62: return "BlueAutoScaleLoInfo"; case 63: return "BlueAutoScaleHiInfo"; case 64: return "BlueMinScaleInfo"; case 65: return "BlueMaxScaleInfo"; case 66: return "OverlayPlaneColor"; } return null; } }
package org.zstack.compute.vm; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.compute.allocator.HostAllocatorManager; import org.zstack.core.cascade.CascadeConstant; import org.zstack.core.cascade.CascadeFacade; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.Q; import org.zstack.core.db.SQLBatch; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.defer.Defer; import org.zstack.core.defer.Deferred; import org.zstack.core.jsonlabel.JsonLabel; import org.zstack.core.notification.N; import org.zstack.core.thread.ChainTask; import org.zstack.core.thread.SyncTaskChain; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.allocator.*; import org.zstack.header.apimediator.ApiMessageInterceptionException; import org.zstack.header.cluster.ClusterInventory; import org.zstack.header.cluster.ClusterVO; import org.zstack.header.cluster.ClusterVO_; import org.zstack.header.configuration.*; import org.zstack.header.core.Completion; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.NopeCompletion; import org.zstack.header.core.ReturnValueCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.*; import org.zstack.header.image.ImageConstant.ImageMediaType; import org.zstack.header.image.ImageEO; import org.zstack.header.image.ImageInventory; import org.zstack.header.image.ImageStatus; import org.zstack.header.image.ImageVO; import org.zstack.header.message.*; import org.zstack.header.network.l3.*; import org.zstack.header.storage.primary.*; import org.zstack.header.storage.snapshot.MarkRootVolumeAsSnapshotMsg; import org.zstack.header.storage.snapshot.VolumeSnapshotConstant; import org.zstack.header.vm.*; import org.zstack.header.vm.ChangeVmMetaDataMsg.AtomicHostUuid; import org.zstack.header.vm.ChangeVmMetaDataMsg.AtomicVmState; import org.zstack.header.vm.VmAbnormalLifeCycleStruct.VmAbnormalLifeCycleOperation; import org.zstack.header.vm.VmInstanceConstant.Capability; import org.zstack.header.vm.VmInstanceConstant.Params; import org.zstack.header.vm.VmInstanceConstant.VmOperation; import org.zstack.header.vm.VmInstanceDeletionPolicyManager.VmInstanceDeletionPolicy; import org.zstack.header.vm.VmInstanceSpec.HostName; import org.zstack.header.vm.VmInstanceSpec.IsoSpec; import org.zstack.header.volume.*; import org.zstack.identity.AccountManager; import org.zstack.tag.SystemTagCreator; import org.zstack.utils.CollectionUtils; import org.zstack.utils.DebugUtils; import org.zstack.utils.ObjectUtils; import org.zstack.utils.Utils; import org.zstack.utils.data.SizeUnit; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.function.Function; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import javax.persistence.TypedQuery; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.zstack.core.Platform.err; import static org.zstack.core.Platform.operr; import static org.zstack.utils.CollectionDSL.*; public class VmInstanceBase extends AbstractVmInstance { protected static final CLogger logger = Utils.getLogger(VmInstanceBase.class); @Autowired protected CloudBus bus; @Autowired protected DatabaseFacade dbf; @Autowired protected ThreadFacade thdf; @Autowired protected VmInstanceManager vmMgr; @Autowired protected VmInstanceExtensionPointEmitter extEmitter; @Autowired protected VmInstanceNotifyPointEmitter notifyEmitter; @Autowired protected CascadeFacade casf; @Autowired protected AccountManager acntMgr; @Autowired protected EventFacade evtf; @Autowired protected PluginRegistry pluginRgty; @Autowired protected VmInstanceDeletionPolicyManager deletionPolicyMgr; @Autowired private HostAllocatorManager hostAllocatorMgr; protected VmInstanceVO self; protected VmInstanceVO originalCopy; protected String syncThreadName; private void checkState(final String hostUuid, final NoErrorCompletion completion) { CheckVmStateOnHypervisorMsg msg = new CheckVmStateOnHypervisorMsg(); msg.setVmInstanceUuids(list(self.getUuid())); msg.setHostUuid(hostUuid); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.send(msg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { N.New(VmInstanceVO.class, self.getUuid()).warn_("unable to check state of the vm[uuid:%s] on the host[uuid:%s], %s;" + "put the VM into the Unknown state", self.getUuid(), hostUuid, reply.getError()); self = dbf.reload(self); changeVmStateInDb(VmInstanceStateEvent.unknown); completion.done(); return; } CheckVmStateOnHypervisorReply r = reply.castReply(); String state = r.getStates().get(self.getUuid()); self = dbf.reload(self); if (state == null) { changeVmStateInDb(VmInstanceStateEvent.unknown); } if (VmInstanceState.Running.toString().equals(state)) { self.setHostUuid(hostUuid); changeVmStateInDb(VmInstanceStateEvent.running); } else if (VmInstanceState.Stopped.toString().equals(state) && self.getState().equals(VmInstanceState.Destroying)) { changeVmStateInDb(VmInstanceStateEvent.destroyed); } else if (VmInstanceState.Stopped.toString().equals(state)) { changeVmStateInDb(VmInstanceStateEvent.stopped); } else { throw new CloudRuntimeException(String.format( "CheckVmStateOnHypervisorMsg should only report states[Running or Stopped]," + "but it reports %s for the vm[uuid:%s] on the host[uuid:%s]", state, self.getUuid(), hostUuid)); } completion.done(); } }); } protected void destroy(final VmInstanceDeletionPolicy deletionPolicy, final Completion completion) { if (deletionPolicy == VmInstanceDeletionPolicy.DBOnly) { completion.success(); return; } if (deletionPolicy == VmInstanceDeletionPolicy.KeepVolume && self.getState().equals(VmInstanceState.Destroyed)) { completion.success(); return; } final VmInstanceInventory inv = VmInstanceInventory.valueOf(self); VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Destroy); self = changeVmStateInDb(VmInstanceStateEvent.destroying); FlowChain chain = getDestroyVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("destroy-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(Params.DeletionPolicy, deletionPolicy); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { if (originalCopy.getState() == VmInstanceState.Running) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self = dbf.reload(self); changeVmStateInDb(VmInstanceStateEvent.unknown); completion.fail(errCode); } } }).start(); } protected VmInstanceVO getSelf() { return self; } protected VmInstanceInventory getSelfInventory() { return VmInstanceInventory.valueOf(self); } public VmInstanceBase(VmInstanceVO vo) { this.self = vo; this.syncThreadName = "Vm-" + vo.getUuid(); this.originalCopy = ObjectUtils.newAndCopy(vo, vo.getClass()); } protected VmInstanceVO refreshVO() { return refreshVO(false); } protected VmInstanceVO refreshVO(boolean noException) { VmInstanceVO vo = self; self = dbf.findByUuid(self.getUuid(), VmInstanceVO.class); if (self == null && noException) { return null; } if (self == null) { throw new OperationFailureException(operr("vm[uuid:%s, name:%s] has been deleted", vo.getUuid(), vo.getName())); } originalCopy = ObjectUtils.newAndCopy(vo, vo.getClass()); return self; } protected FlowChain getCreateVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getCreateVmWorkFlowChain(inv); } protected FlowChain getStopVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getStopVmWorkFlowChain(inv); } protected FlowChain getRebootVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getRebootVmWorkFlowChain(inv); } protected FlowChain getStartVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getStartVmWorkFlowChain(inv); } protected FlowChain getDestroyVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getDestroyVmWorkFlowChain(inv); } protected FlowChain getExpungeVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getExpungeVmWorkFlowChain(inv); } protected FlowChain getMigrateVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getMigrateVmWorkFlowChain(inv); } protected FlowChain getAttachUninstantiatedVolumeWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getAttachUninstantiatedVolumeWorkFlowChain(inv); } protected FlowChain getAttachIsoWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getAttachIsoWorkFlowChain(inv); } protected FlowChain getDetachIsoWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getDetachIsoWorkFlowChain(inv); } protected FlowChain getPauseVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getPauseWorkFlowChain(inv); } protected FlowChain getResumeVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getResumeVmWorkFlowChain(inv); } protected VmInstanceVO changeVmStateInDb(VmInstanceStateEvent stateEvent) { VmInstanceState bs = self.getState(); final VmInstanceState state = self.getState().nextState(stateEvent); if (state == VmInstanceState.Stopped) { // cleanup the hostUuid if the VM is stopped if (self.getHostUuid() != null) { self.setLastHostUuid(self.getHostUuid()); } self.setHostUuid(null); } self.setState(state); self = dbf.updateAndRefresh(self); if (bs != state) { logger.debug(String.format("vm[uuid:%s] changed state from %s to %s in db", self.getUuid(), bs, self.getState())); VmCanonicalEvents.VmStateChangedData data = new VmCanonicalEvents.VmStateChangedData(); data.setVmUuid(self.getUuid()); data.setOldState(bs.toString()); data.setNewState(state.toString()); data.setInventory(getSelfInventory()); evtf.fire(VmCanonicalEvents.VM_FULL_STATE_CHANGED_PATH, data); VmInstanceInventory inv = getSelfInventory(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmStateChangedExtensionPoint.class), new ForEachFunction<VmStateChangedExtensionPoint>() { @Override public void run(VmStateChangedExtensionPoint ext) { ext.vmStateChanged(inv, bs, self.getState()); } }); //TODO: remove this notifyEmitter.notifyVmStateChange(VmInstanceInventory.valueOf(self), bs, state); } return self; } @Override @MessageSafe public void handleMessage(final Message msg) { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } protected void handleLocalMessage(Message msg) { if (msg instanceof StartNewCreatedVmInstanceMsg) { handle((StartNewCreatedVmInstanceMsg) msg); } else if (msg instanceof StartVmInstanceMsg) { handle((StartVmInstanceMsg) msg); } else if (msg instanceof StopVmInstanceMsg) { handle((StopVmInstanceMsg) msg); } else if (msg instanceof RebootVmInstanceMsg) { handle((RebootVmInstanceMsg) msg); } else if (msg instanceof ChangeVmStateMsg) { handle((ChangeVmStateMsg) msg); } else if (msg instanceof DestroyVmInstanceMsg) { handle((DestroyVmInstanceMsg) msg); } else if (msg instanceof AttachNicToVmMsg) { handle((AttachNicToVmMsg) msg); } else if (msg instanceof CreateTemplateFromVmRootVolumeMsg) { handle((CreateTemplateFromVmRootVolumeMsg) msg); } else if (msg instanceof VmInstanceDeletionMsg) { handle((VmInstanceDeletionMsg) msg); } else if (msg instanceof VmAttachNicMsg) { handle((VmAttachNicMsg) msg); } else if (msg instanceof MigrateVmMsg) { handle((MigrateVmMsg) msg); } else if (msg instanceof DetachDataVolumeFromVmMsg) { handle((DetachDataVolumeFromVmMsg) msg); } else if (msg instanceof AttachDataVolumeToVmMsg) { handle((AttachDataVolumeToVmMsg) msg); } else if (msg instanceof GetVmMigrationTargetHostMsg) { handle((GetVmMigrationTargetHostMsg) msg); } else if (msg instanceof ChangeVmMetaDataMsg) { handle((ChangeVmMetaDataMsg) msg); } else if (msg instanceof LockVmInstanceMsg) { handle((LockVmInstanceMsg) msg); } else if (msg instanceof DetachNicFromVmMsg) { handle((DetachNicFromVmMsg) msg); } else if (msg instanceof VmStateChangedOnHostMsg) { handle((VmStateChangedOnHostMsg) msg); } else if (msg instanceof VmCheckOwnStateMsg) { handle((VmCheckOwnStateMsg) msg); } else if (msg instanceof ExpungeVmMsg) { handle((ExpungeVmMsg) msg); } else if (msg instanceof HaStartVmInstanceMsg) { handle((HaStartVmInstanceMsg) msg); } else if (msg instanceof OverlayMessage) { handle((OverlayMessage) msg); } else if (msg instanceof ReimageVmInstanceMsg) { handle((ReimageVmInstanceMsg) msg); } else if (msg instanceof GetVmStartingCandidateClustersHostsMsg) { handle((GetVmStartingCandidateClustersHostsMsg) msg); } else { VmInstanceBaseExtensionFactory ext = vmMgr.getVmInstanceBaseExtensionFactory(msg); if (ext != null) { VmInstance v = ext.getVmInstance(self); v.handleMessage(msg); } else { bus.dealWithUnknownMessage(msg); } } } private void handle(final APIGetVmStartingCandidateClustersHostsMsg msg) { APIGetVmStartingCandidateClustersHostsReply reply = new APIGetVmStartingCandidateClustersHostsReply(); final GetVmStartingCandidateClustersHostsMsg gmsg = new GetVmStartingCandidateClustersHostsMsg(); gmsg.setUuid(msg.getUuid()); bus.makeLocalServiceId(gmsg, VmInstanceConstant.SERVICE_ID); bus.send(gmsg, new CloudBusCallBack(msg) { @Override public void run(MessageReply re) { GetVmStartingCandidateClustersHostsReply greply = (GetVmStartingCandidateClustersHostsReply) re; if (!re.isSuccess()) { reply.setSuccess(false); reply.setError(re.getError()); if (greply.getHostInventories() != null) { reply.setHostInventories(greply.getHostInventories()); reply.setClusterInventories(greply.getClusterInventories()); } } else { reply.setHostInventories(greply.getHostInventories()); reply.setClusterInventories(greply.getClusterInventories()); } bus.reply(msg, reply); } }); } private void handle(final GetVmStartingCandidateClustersHostsMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { GetVmStartingCandidateClustersHostsReply reply = new GetVmStartingCandidateClustersHostsReply(); getStartingCandidateHosts(msg, new ReturnValueCompletion<AllocateHostDryRunReply>(chain) { @Override public void success(AllocateHostDryRunReply returnValue) { List<HostInventory> hosts = ((AllocateHostDryRunReply) returnValue).getHosts(); if (!hosts.isEmpty()) { List<String> cuuids = CollectionUtils.transformToList(hosts, new Function<String, HostInventory>() { @Override public String call(HostInventory arg) { return arg.getClusterUuid(); } }); SimpleQuery<ClusterVO> cq = dbf.createQuery(ClusterVO.class); cq.add(ClusterVO_.uuid, Op.IN, cuuids); List<ClusterVO> cvos = cq.list(); reply.setClusterInventories(ClusterInventory.valueOf(cvos)); reply.setHostInventories(hosts); } else { reply.setHostInventories(hosts); reply.setClusterInventories(new ArrayList<>()); } bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { if (HostAllocatorError.NO_AVAILABLE_HOST.toString().equals(errorCode.getCode())) { reply.setHostInventories(new ArrayList<>()); reply.setClusterInventories(new ArrayList<>()); } else { reply.setError(errorCode); } reply.setSuccess(false); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "get-starting-candidate-hosts"; } }); } private void getStartingCandidateHosts(final NeedReplyMessage msg, final ReturnValueCompletion completion) { refreshVO(); ErrorCode err = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (err != null) { throw new OperationFailureException(err); } final DesignatedAllocateHostMsg amsg = new DesignatedAllocateHostMsg(); amsg.setCpuCapacity(self.getCpuNum()); amsg.setMemoryCapacity(self.getMemorySize()); amsg.setVmInstance(VmInstanceInventory.valueOf(self)); amsg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID)); amsg.setAllocatorStrategy(self.getAllocatorStrategy()); amsg.setVmOperation(VmOperation.Start.toString()); amsg.setL3NetworkUuids(CollectionUtils.transformToList(self.getVmNics(), new Function<String, VmNicVO>() { @Override public String call(VmNicVO arg) { return arg.getL3NetworkUuid(); } })); amsg.setDryRun(true); amsg.setListAllHosts(true); bus.send(amsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply re) { if (!re.isSuccess()) { completion.fail(re.getError()); } else { completion.success(re); } } }); } private void handle(final HaStartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { refreshVO(); HaStartVmJudger judger; try { Class clz = Class.forName(msg.getJudgerClassName()); judger = (HaStartVmJudger) clz.newInstance(); } catch (Exception e) { throw new CloudRuntimeException(e); } final HaStartVmInstanceReply reply = new HaStartVmInstanceReply(); if (!judger.whetherStartVm(getSelfInventory())) { bus.reply(msg, reply); chain.next(); return; } logger.debug(String.format("HaStartVmJudger[%s] says the VM[uuid:%s, name:%s] is qualified for HA start, now we are starting it", judger.getClass(), self.getUuid(), self.getName())); self.setState(VmInstanceState.Stopped); dbf.update(self); startVm(msg, new Completion(msg, chain) { @Override public void success() { reply.setInventory(getSelfInventory()); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "ha-start-vm"; } }); } private void changeVmIp(final String l3Uuid, final String ip, final Completion completion) { final VmNicVO targetNic = CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return l3Uuid.equals(arg.getL3NetworkUuid()) ? arg : null; } }); if (targetNic == null) { throw new OperationFailureException(operr("the vm[uuid:%s] has no nic on the L3 network[uuid:%s]", self.getUuid(), l3Uuid)); } if (ip.equals(targetNic.getIp())) { completion.success(); return; } final UsedIpInventory oldIp = new UsedIpInventory(); oldIp.setIp(targetNic.getIp()); oldIp.setGateway(targetNic.getGateway()); oldIp.setNetmask(targetNic.getNetmask()); oldIp.setL3NetworkUuid(targetNic.getL3NetworkUuid()); oldIp.setUuid(targetNic.getUsedIpUuid()); final FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("change-vm-ip-to-%s-l3-%s-vm-%s", ip, l3Uuid, self.getUuid())); chain.then(new ShareFlow() { UsedIpInventory newIp; String oldIpUuid = targetNic.getUsedIpUuid(); @Override public void setup() { flow(new Flow() { String __name__ = "acquire-new-ip"; @Override public void run(final FlowTrigger trigger, Map data) { AllocateIpMsg amsg = new AllocateIpMsg(); amsg.setL3NetworkUuid(l3Uuid); amsg.setRequiredIp(ip); bus.makeTargetServiceIdByResourceUuid(amsg, L3NetworkConstant.SERVICE_ID, l3Uuid); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); } else { AllocateIpReply r = reply.castReply(); newIp = r.getIpInventory(); trigger.next(); } } }); } @Override public void rollback(FlowRollback trigger, Map data) { if (newIp != null) { ReturnIpMsg rmsg = new ReturnIpMsg(); rmsg.setL3NetworkUuid(newIp.getL3NetworkUuid()); rmsg.setUsedIpUuid(newIp.getUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, L3NetworkConstant.SERVICE_ID, newIp.getL3NetworkUuid()); bus.send(rmsg); } trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = "change-ip-in-database"; @Override public void run(FlowTrigger trigger, Map data) { targetNic.setUsedIpUuid(newIp.getUuid()); targetNic.setGateway(newIp.getGateway()); targetNic.setNetmask(newIp.getNetmask()); targetNic.setIp(newIp.getIp()); dbf.update(targetNic); trigger.next(); } }); flow(new NoRollbackFlow() { String __name__ = "return-old-ip"; @Override public void run(FlowTrigger trigger, Map data) { ReturnIpMsg rmsg = new ReturnIpMsg(); rmsg.setUsedIpUuid(oldIpUuid); rmsg.setL3NetworkUuid(targetNic.getL3NetworkUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, L3NetworkConstant.SERVICE_ID, targetNic.getL3NetworkUuid()); bus.send(rmsg); trigger.next(); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { final VmInstanceInventory vm = getSelfInventory(); final VmNicInventory nic = VmNicInventory.valueOf(targetNic); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmIpChangedExtensionPoint.class), new ForEachFunction<VmIpChangedExtensionPoint>() { @Override public void run(VmIpChangedExtensionPoint ext) { ext.vmIpChanged(vm, nic, oldIp, newIp); } }); completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } private void handle(final ExpungeVmMsg msg) { final ExpungeVmReply reply = new ExpungeVmReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { expunge(msg, new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "expunge-vm"; } }); } private void expunge(Message msg, final Completion completion) { refreshVO(); final VmInstanceInventory inv = getSelfInventory(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmBeforeExpungeExtensionPoint.class), arg -> arg.vmBeforeExpunge(inv)); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } if (inv.getAllVolumes().size() > 1) { throw new CloudRuntimeException(String.format("why the deleted vm[uuid:%s] has data volumes??? %s", self.getUuid(), JSONObjectUtil.toJsonString(inv.getAllVolumes()))); } VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Expunge); FlowChain chain = getExpungeVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("expunge-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(Params.DeletionPolicy, VmInstanceDeletionPolicy.Direct); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmAfterExpungeExtensionPoint.class), arg -> arg.vmAfterExpunge(inv)); callVmJustBeforeDeleteFromDbExtensionPoint(); dbf.removeCollection(self.getVmNics(), VmNicVO.class); dbf.remove(self); logger.debug(String.format("successfully expunged the vm[uuid:%s]", self.getUuid())); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } private void handle(final VmCheckOwnStateMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { refreshVO(); final VmCheckOwnStateReply reply = new VmCheckOwnStateReply(); if (self.getHostUuid() == null) { // no way to check bus.reply(msg, reply); chain.next(); return; } final CheckVmStateOnHypervisorMsg cmsg = new CheckVmStateOnHypervisorMsg(); cmsg.setVmInstanceUuids(list(self.getUuid())); cmsg.setHostUuid(self.getHostUuid()); bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(cmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply r) { if (!r.isSuccess()) { reply.setError(r.getError()); bus.reply(msg, r); chain.next(); return; } CheckVmStateOnHypervisorReply cr = r.castReply(); String s = cr.getStates().get(self.getUuid()); VmInstanceState state = VmInstanceState.valueOf(s); if (state != self.getState()) { VmStateChangedOnHostMsg vcmsg = new VmStateChangedOnHostMsg(); vcmsg.setHostUuid(self.getHostUuid()); vcmsg.setVmInstanceUuid(self.getUuid()); vcmsg.setStateOnHost(state); bus.makeTargetServiceIdByResourceUuid(vcmsg, VmInstanceConstant.SERVICE_ID, self.getUuid()); bus.send(vcmsg); } bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "check-state"; } }); } private void handle(final VmStateChangedOnHostMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { vmStateChangeOnHost(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("vm-%s-state-change-on-the-host-%s", self.getUuid(), msg.getHostUuid()); } }); } private VmAbnormalLifeCycleOperation getVmAbnormalLifeCycleOperation(String originalHostUuid, String currentHostUuid, VmInstanceState originalState, VmInstanceState currentState) { if (originalState == VmInstanceState.Stopped && currentState == VmInstanceState.Running) { return VmAbnormalLifeCycleOperation.VmRunningOnTheHost; } if (originalState == VmInstanceState.Running && currentState == VmInstanceState.Stopped && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmStoppedOnTheSameHost; } if (VmInstanceState.intermediateStates.contains(originalState) && currentState == VmInstanceState.Running) { return VmAbnormalLifeCycleOperation.VmRunningFromIntermediateState; } if (VmInstanceState.intermediateStates.contains(originalState) && currentState == VmInstanceState.Stopped) { return VmAbnormalLifeCycleOperation.VmStoppedFromIntermediateState; } if (originalState == VmInstanceState.Running && currentState == VmInstanceState.Paused && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmPausedFromRunningStateHostNotChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Paused && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmPausedFromUnknownStateHostNotChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Running && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostNotChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Running && !currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Stopped && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmStoppedOnTheSameHost; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Stopped && originalHostUuid == null && currentHostUuid.equals(self.getLastHostUuid())) { return VmAbnormalLifeCycleOperation.VmStoppedFromUnknownStateHostNotChanged; } if (originalState == VmInstanceState.Running && originalState == currentState && !currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmMigrateToAnotherHost; } if (originalState == VmInstanceState.Paused && currentState == VmInstanceState.Running && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmRunningFromPausedStateHostNotChanged; } if (originalState == VmInstanceState.Paused && currentState == VmInstanceState.Stopped && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmStoppedFromPausedStateHostNotChanged; } throw new CloudRuntimeException(String.format("unknown VM[uuid:%s] abnormal state combination[original state: %s," + " current state: %s, original host:%s, current host:%s]", self.getUuid(), originalState, currentState, originalHostUuid, currentHostUuid)); } private void vmStateChangeOnHost(final VmStateChangedOnHostMsg msg, final NoErrorCompletion completion) { final VmStateChangedOnHostReply reply = new VmStateChangedOnHostReply(); if (refreshVO(true) == null) { // the vm has been deleted reply.setError(operr("the vm has been deleted")); bus.reply(msg, reply); completion.done(); return; } if (msg.getVmStateAtTracingMoment() != null) { // the vm tracer periodically reports vms's state. It catches an old state // before an vm operation(start, stop, reboot, migrate) completes. Ignore this VmInstanceState expected = VmInstanceState.valueOf(msg.getVmStateAtTracingMoment()); if (expected != self.getState()) { bus.reply(msg, reply); completion.done(); return; } } final String originalHostUuid = self.getHostUuid(); final String currentHostUuid = msg.getHostUuid(); final VmInstanceState originalState = self.getState(); final VmInstanceState currentState = VmInstanceState.valueOf(msg.getStateOnHost()); if (originalState == currentState && originalHostUuid != null && currentHostUuid.equals(originalHostUuid)) { logger.debug(String.format("vm[uuid:%s]'s state[%s] is inline with its state on the host[uuid:%s], ignore VmStateChangeOnHostMsg", self.getUuid(), originalState, originalHostUuid)); bus.reply(msg, reply); completion.done(); return; } if (originalState == VmInstanceState.Stopped && currentState == VmInstanceState.Unknown) { bus.reply(msg, reply); completion.done(); return; } final Runnable fireEvent = () -> { VmTracerCanonicalEvents.VmStateChangedOnHostData data = new VmTracerCanonicalEvents.VmStateChangedOnHostData(); data.setVmUuid(self.getUuid()); data.setFrom(originalState); data.setTo(self.getState()); data.setOriginalHostUuid(originalHostUuid); data.setCurrentHostUuid(self.getHostUuid()); evtf.fire(VmTracerCanonicalEvents.VM_STATE_CHANGED_PATH, data); }; if (currentState == VmInstanceState.Unknown) { changeVmStateInDb(VmInstanceStateEvent.unknown); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } VmAbnormalLifeCycleOperation operation = getVmAbnormalLifeCycleOperation(originalHostUuid, currentHostUuid, originalState, currentState); if (operation == VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostNotChanged) { // the vm is detected on the host again. It's largely because the host disconnected before // and now reconnected self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.running); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmStoppedFromUnknownStateHostNotChanged) { // the vm comes out of the unknown state to the stopped state // it happens when an operation failure led the vm from the stopped state to the unknown state, // and later on the vm was detected as stopped on the host again self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.stopped); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmStoppedFromPausedStateHostNotChanged) { self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.stopped); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmPausedFromUnknownStateHostNotChanged) { //some reason led vm to unknown state and the paused vm are detected on the host again self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.paused); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmPausedFromRunningStateHostNotChanged) { // just synchronize database self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.paused); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmRunningFromPausedStateHostNotChanged) { // just synchronize database self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.running); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } List<VmAbnormalLifeCycleExtensionPoint> exts = pluginRgty.getExtensionList(VmAbnormalLifeCycleExtensionPoint.class); VmAbnormalLifeCycleStruct struct = new VmAbnormalLifeCycleStruct(); struct.setCurrentHostUuid(currentHostUuid); struct.setCurrentState(currentState); struct.setOriginalHostUuid(originalHostUuid); struct.setOriginalState(originalState); struct.setVmInstance(getSelfInventory()); struct.setOperation(operation); logger.debug(String.format("the vm[uuid:%s]'s state changed abnormally on the host[uuid:%s]," + " ZStack is going to take the operation[%s]," + "[original state: %s, current state: %s, original host: %s, current host:%s]", self.getUuid(), currentHostUuid, operation, originalState, currentState, originalHostUuid, currentHostUuid)); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("handle-abnormal-lifecycle-of-vm-%s", self.getUuid())); chain.getData().put(Params.AbnormalLifeCycleStruct, struct); chain.allowEmptyFlow(); for (VmAbnormalLifeCycleExtensionPoint ext : exts) { Flow flow = ext.createVmAbnormalLifeCycleHandlingFlow(struct); chain.then(flow); } chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { if (currentState == VmInstanceState.Running) { self.setHostUuid(currentHostUuid); changeVmStateInDb(VmInstanceStateEvent.running); } else if (currentState == VmInstanceState.Stopped) { self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.stopped); } fireEvent.run(); bus.reply(msg, reply); completion.done(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { N.New(VmInstanceVO.class, self.getUuid()).warn_("failed to handle abnormal lifecycle of the vm[uuid:%s, original state: %s, current state:%s," + "original host: %s, current host: %s], %s", self.getUuid(), originalState, currentState, originalHostUuid, currentHostUuid, errCode); reply.setError(errCode); bus.reply(msg, reply); completion.done(); } }).start(); } private String buildUserdata() { return new UserdataBuilder().buildByVmUuid(self.getUuid()); } private void handle(final DetachNicFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final DetachNicFromVmReply reply = new DetachNicFromVmReply(); refreshVO(); if (self.getState() == VmInstanceState.Destroyed) { // the cascade framework may send this message when // the vm has been destroyed VmNicVO nic = CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return msg.getVmNicUuid().equals(arg.getUuid()) ? arg : null; } }); if (nic != null) { dbf.remove(nic); } bus.reply(msg, reply); chain.next(); return; } final ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { reply.setError(allowed); bus.reply(msg, reply); chain.next(); return; } detachNic(msg.getVmNicUuid(), new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "detach-nic"; } }); } private void handle(final LockVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { logger.debug(String.format("locked vm[uuid:%s] for %s", self.getUuid(), msg.getReason())); evtf.on(LockResourceMessage.UNLOCK_CANONICAL_EVENT_PATH, new AutoOffEventCallback() { @Override public boolean run(Map tokens, Object data) { if (msg.getUnlockKey().equals(data)) { logger.debug(String.format("unlocked vm[uuid:%s] that was locked by %s", self.getUuid(), msg.getReason())); chain.next(); return true; } return false; } }); LockVmInstanceReply reply = new LockVmInstanceReply(); bus.reply(msg, reply); } @Override public String getName() { return String.format("lock-vm-%s", self.getUuid()); } }); } private void handle(final ChangeVmMetaDataMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { changeMetaData(msg); chain.next(); } @Override public String getName() { return String.format("change-meta-data-of-vm-%s", self.getUuid()); } }); } private void changeMetaData(ChangeVmMetaDataMsg msg) { ChangeVmMetaDataReply reply = new ChangeVmMetaDataReply(); refreshVO(); if (self == null) { bus.reply(msg, reply); return; } AtomicVmState s = msg.getState(); AtomicHostUuid h = msg.getHostUuid(); if (msg.isNeedHostAndStateBothMatch()) { if (s != null && h != null && s.getExpected() == self.getState()) { if ((h.getExpected() == null && self.getHostUuid() == null) || (h.getExpected() != null && h.getExpected().equals(self.getHostUuid()))) { changeVmStateInDb(s.getValue().getDrivenEvent()); reply.setChangeStateDone(true); self.setHostUuid(h.getValue()); dbf.update(self); reply.setChangeHostUuidDone(true); } } } else { if (s != null && s.getExpected() == self.getState()) { changeVmStateInDb(s.getValue().getDrivenEvent()); reply.setChangeStateDone(true); } if (h != null) { if ((h.getExpected() == null && self.getHostUuid() == null) || (h.getExpected() != null && h.getExpected().equals(self.getHostUuid()))) { self.setHostUuid(h.getValue()); dbf.update(self); reply.setChangeHostUuidDone(true); } } } bus.reply(msg, reply); } private void getVmMigrationTargetHost(Message msg, final ReturnValueCompletion<List<HostInventory>> completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.MIGRATE_ERROR); if (allowed != null) { completion.fail(allowed); return; } if (self.getVmNics().size() == 0) { completion.fail(operr("cannot get target migration host without any nics on vm")); return; } final DesignatedAllocateHostMsg amsg = new DesignatedAllocateHostMsg(); amsg.setCpuCapacity(self.getCpuNum()); amsg.setMemoryCapacity(self.getMemorySize()); amsg.getAvoidHostUuids().add(self.getHostUuid()); if (msg instanceof GetVmMigrationTargetHostMsg) { GetVmMigrationTargetHostMsg gmsg = (GetVmMigrationTargetHostMsg) msg; if (gmsg.getAvoidHostUuids() != null) { amsg.getAvoidHostUuids().addAll(gmsg.getAvoidHostUuids()); } } amsg.setVmInstance(VmInstanceInventory.valueOf(self)); amsg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID)); amsg.setAllocatorStrategy(HostAllocatorConstant.MIGRATE_VM_ALLOCATOR_TYPE); amsg.setVmOperation(VmOperation.Migrate.toString()); amsg.setL3NetworkUuids(CollectionUtils.transformToList(self.getVmNics(), new Function<String, VmNicVO>() { @Override public String call(VmNicVO arg) { return arg.getL3NetworkUuid(); } })); amsg.setDryRun(true); amsg.setAllowNoL3Networks(true); bus.send(amsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply re) { if (!re.isSuccess()) { if (HostAllocatorError.NO_AVAILABLE_HOST.toString().equals(re.getError().getCode())) { completion.success(new ArrayList<HostInventory>()); } else { completion.fail(re.getError()); } } else { completion.success(((AllocateHostDryRunReply) re).getHosts()); } } }); } private void handle(final GetVmMigrationTargetHostMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final GetVmMigrationTargetHostReply reply = new GetVmMigrationTargetHostReply(); getVmMigrationTargetHost(msg, new ReturnValueCompletion<List<HostInventory>>(msg, chain) { @Override public void success(List<HostInventory> returnValue) { reply.setHosts(returnValue); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return String.format("get-migration-target-host-for-vm-%s", self.getUuid()); } }); } private void handle(final AttachDataVolumeToVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { attachDataVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-volume-%s-to-vm-%s", msg.getVolume().getUuid(), msg.getVmInstanceUuid()); } }); } private void handle(final DetachDataVolumeFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { detachVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("detach-volume-%s-from-vm-%s", msg.getVolume().getUuid(), msg.getVmInstanceUuid()); } }); } private void handle(final MigrateVmMsg msg) { final MigrateVmReply reply = new MigrateVmReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { migrateVm(msg, new Completion(chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return String.format("migrate-vm-%s", self.getUuid()); } }); } private void attachNic(final Message msg, final String l3Uuid, final ReturnValueCompletion<VmNicInventory> completion) { thdf.chainSubmit(new ChainTask(completion) { @Override public String getSyncSignature() { return syncThreadName; } @Override @Deferred public void run(final SyncTaskChain chain) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { completion.fail(allowed); return; } class SetDefaultL3Network { private boolean isSet = false; void set() { if (self.getDefaultL3NetworkUuid() == null) { self.setDefaultL3NetworkUuid(l3Uuid); self = dbf.updateAndRefresh(self); isSet = true; } } void rollback() { if (isSet) { self.setDefaultL3NetworkUuid(null); dbf.update(self); } } } class SetStaticIp { private boolean isSet = false; void set() { if (!(msg instanceof APIAttachL3NetworkToVmMsg)) { return; } APIAttachL3NetworkToVmMsg amsg = (APIAttachL3NetworkToVmMsg) msg; if (amsg.getStaticIp() == null) { return; } new StaticIpOperator().setStaticIp(self.getUuid(), amsg.getL3NetworkUuid(), amsg.getStaticIp()); isSet = true; } void rollback() { if (isSet) { APIAttachL3NetworkToVmMsg amsg = (APIAttachL3NetworkToVmMsg) msg; new StaticIpOperator().deleteStaticIpByVmUuidAndL3Uuid(self.getUuid(), amsg.getL3NetworkUuid()); } } } final SetDefaultL3Network setDefaultL3Network = new SetDefaultL3Network(); setDefaultL3Network.set(); Defer.guard(new Runnable() { @Override public void run() { setDefaultL3Network.rollback(); } }); final SetStaticIp setStaticIp = new SetStaticIp(); setStaticIp.set(); Defer.guard(new Runnable() { @Override public void run() { setStaticIp.rollback(); } }); final VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.AttachNic); spec.setVmInventory(VmInstanceInventory.valueOf(self)); L3NetworkVO l3vo = dbf.findByUuid(l3Uuid, L3NetworkVO.class); final L3NetworkInventory l3 = L3NetworkInventory.valueOf(l3vo); final VmInstanceInventory vm = getSelfInventory(); for (VmPreAttachL3NetworkExtensionPoint ext : pluginRgty.getExtensionList(VmPreAttachL3NetworkExtensionPoint.class)) { ext.vmPreAttachL3Network(vm, l3); } spec.setL3Networks(list(l3)); spec.setDestNics(new ArrayList<VmNicInventory>()); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmBeforeAttachL3NetworkExtensionPoint.class), new ForEachFunction<VmBeforeAttachL3NetworkExtensionPoint>() { @Override public void run(VmBeforeAttachL3NetworkExtensionPoint arg) { arg.vmBeforeAttachL3Network(vm, l3); } }); FlowChain flowChain = FlowChainBuilder.newSimpleFlowChain(); setFlowMarshaller(flowChain); flowChain.setName(String.format("attachNic-vm-%s-l3-%s", self.getUuid(), l3Uuid)); flowChain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); flowChain.then(new VmAllocateNicFlow()); flowChain.then(new VmSetDefaultL3NetworkOnAttachingFlow()); if (self.getState() == VmInstanceState.Running) { flowChain.then(new VmInstantiateResourceOnAttachingNicFlow()); flowChain.then(new VmAttachNicOnHypervisorFlow()); } flowChain.done(new FlowDoneHandler(chain) { @Override public void handle(Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmAfterAttachL3NetworkExtensionPoint.class), new ForEachFunction<VmAfterAttachL3NetworkExtensionPoint>() { @Override public void run(VmAfterAttachL3NetworkExtensionPoint arg) { arg.vmAfterAttachL3Network(vm, l3); } }); VmNicInventory nic = spec.getDestNics().get(0); completion.success(nic); chain.next(); } }).error(new FlowErrorHandler(chain) { @Override public void handle(final ErrorCode errCode, Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmFailToAttachL3NetworkExtensionPoint.class), new ForEachFunction<VmFailToAttachL3NetworkExtensionPoint>() { @Override public void run(VmFailToAttachL3NetworkExtensionPoint arg) { arg.vmFailToAttachL3Network(vm, l3, errCode); } }); setDefaultL3Network.rollback(); setStaticIp.rollback(); completion.fail(errCode); chain.next(); } }).start(); } @Override public String getName() { return String.format("attachNic-vm-%s-l3-%s", self.getUuid(), l3Uuid); } }); } private void handle(final VmAttachNicMsg msg) { final VmAttachNicReply reply = new VmAttachNicReply(); attachNic(msg, msg.getL3NetworkUuid(), new ReturnValueCompletion<VmNicInventory>(msg) { @Override public void success(VmNicInventory nic) { reply.setInventroy(nic); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void callVmJustBeforeDeleteFromDbExtensionPoint() { VmInstanceInventory inv = getSelfInventory(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmJustBeforeDeleteFromDbExtensionPoint.class), p -> p.vmJustBeforeDeleteFromDb(inv)); } protected void doDestroy(final VmInstanceDeletionPolicy deletionPolicy, final Completion completion) { final VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.beforeDestroyVm(inv); destroy(deletionPolicy, new Completion(completion) { @Override public void success() { extEmitter.afterDestroyVm(inv); logger.debug(String.format("successfully deleted vm instance[name:%s, uuid:%s]", self.getName(), self.getUuid())); if (deletionPolicy == VmInstanceDeletionPolicy.Direct) { self = dbf.reload(self); changeVmStateInDb(VmInstanceStateEvent.destroyed); callVmJustBeforeDeleteFromDbExtensionPoint(); dbf.remove(getSelf()); } else if (deletionPolicy == VmInstanceDeletionPolicy.DBOnly || deletionPolicy == VmInstanceDeletionPolicy.KeepVolume) { new SQLBatch() { @Override protected void scripts() { callVmJustBeforeDeleteFromDbExtensionPoint(); sql(VmNicVO.class).eq(VmNicVO_.vmInstanceUuid, self.getUuid()).hardDelete(); sql(VolumeVO.class).eq(VolumeVO_.vmInstanceUuid, self.getUuid()) .eq(VolumeVO_.type, VolumeType.Root) .hardDelete(); sql(VmInstanceVO.class).eq(VmInstanceVO_.uuid, self.getUuid()).hardDelete(); } }.execute(); } else if (deletionPolicy == VmInstanceDeletionPolicy.Delay) { self = dbf.reload(self); self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.destroyed); } else if (deletionPolicy == VmInstanceDeletionPolicy.Never) { logger.warn(String.format("the vm[uuid:%s] is deleted, but by it's deletion policy[Never]," + " the root volume is not deleted on the primary storage", self.getUuid())); self = dbf.reload(self); self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.destroyed); } completion.success(); } @Override public void fail(ErrorCode errorCode) { extEmitter.failedToDestroyVm(inv, errorCode); logger.debug(String.format("failed to delete vm instance[name:%s, uuid:%s], because %s", self.getName(), self.getUuid(), errorCode)); completion.fail(errorCode); } }); } private VmInstanceDeletionPolicy getVmDeletionPolicy(final VmInstanceDeletionMsg msg) { if (self.getState() == VmInstanceState.Created) { return VmInstanceDeletionPolicy.DBOnly; } return msg.getDeletionPolicy() == null ? deletionPolicyMgr.getDeletionPolicy(self.getUuid()) : VmInstanceDeletionPolicy.valueOf(msg.getDeletionPolicy()); } private void handle(final VmInstanceDeletionMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { final VmInstanceDeletionReply r = new VmInstanceDeletionReply(); final VmInstanceDeletionPolicy deletionPolicy = getVmDeletionPolicy(msg); self = dbf.findByUuid(self.getUuid(), VmInstanceVO.class); if (self == null || self.getState() == VmInstanceState.Destroyed) { // the vm has been destroyed, most likely by rollback if (deletionPolicy != VmInstanceDeletionPolicy.DBOnly && deletionPolicy != VmInstanceDeletionPolicy.KeepVolume) { bus.reply(msg, r); chain.next(); return; } } destroyHook(deletionPolicy, new Completion(msg, chain) { @Override public void success() { bus.reply(msg, r); chain.next(); } @Override public void fail(ErrorCode errorCode) { r.setError(errorCode); bus.reply(msg, r); chain.next(); } }); } @Override public String getName() { return "delete-vm"; } }); } protected void destroyHook(VmInstanceDeletionPolicy deletionPolicy, Completion completion) { doDestroy(deletionPolicy, completion); } private void handle(final RebootVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("reboot-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { rebootVm(msg, chain); } }); } private void rebootVm(final RebootVmInstanceMsg msg, final SyncTaskChain chain) { rebootVm(msg, new Completion(chain) { @Override public void success() { RebootVmInstanceReply reply = new RebootVmInstanceReply(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); reply.setInventory(inv); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { RebootVmInstanceReply reply = new RebootVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.REBOOT_ERROR, errorCode)); bus.reply(msg, reply); chain.next(); } }); } private void handle(final StopVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("stop-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { stopVm(msg, chain); } }); } private void stopVm(final StopVmInstanceMsg msg, final SyncTaskChain chain) { stopVm(msg, new Completion(chain) { @Override public void success() { StopVmInstanceReply reply = new StopVmInstanceReply(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); reply.setInventory(inv); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { StopVmInstanceReply reply = new StopVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.STOP_ERROR, errorCode)); bus.reply(msg, reply); chain.next(); } }); } private void handle(final StartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("start-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVm(msg, chain); } }); } private void createTemplateFromRootVolume(final CreateTemplateFromVmRootVolumeMsg msg, final SyncTaskChain chain) { boolean callNext = true; try { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } final CreateTemplateFromVmRootVolumeReply reply = new CreateTemplateFromVmRootVolumeReply(); CreateTemplateFromVolumeOnPrimaryStorageMsg cmsg = new CreateTemplateFromVolumeOnPrimaryStorageMsg(); cmsg.setVolumeInventory(msg.getRootVolumeInventory()); cmsg.setBackupStorageUuid(msg.getBackupStorageUuid()); cmsg.setImageInventory(msg.getImageInventory()); bus.makeTargetServiceIdByResourceUuid(cmsg, PrimaryStorageConstant.SERVICE_ID, msg.getRootVolumeInventory().getPrimaryStorageUuid()); bus.send(cmsg, new CloudBusCallBack(chain) { private void fail(ErrorCode errorCode) { String err = String.format("failed to create template from root volume[uuid:%s] on primary storage[uuid:%s]", msg.getRootVolumeInventory().getUuid(), msg.getRootVolumeInventory().getPrimaryStorageUuid()); logger.warn(err); reply.setError(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, err, errorCode)); bus.reply(msg, reply); } @Override public void run(MessageReply r) { if (!r.isSuccess()) { fail(r.getError()); } else { CreateTemplateFromVolumeOnPrimaryStorageReply creply = (CreateTemplateFromVolumeOnPrimaryStorageReply) r; reply.setInstallPath(creply.getTemplateBackupStorageInstallPath()); reply.setFormat(creply.getFormat()); bus.reply(msg, reply); } chain.next(); } }); callNext = false; } finally { if (callNext) { chain.next(); } } } private void handle(final CreateTemplateFromVmRootVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("create-template-from-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { createTemplateFromRootVolume(msg, chain); } }); } private void handle(final AttachNicToVmMsg msg) { ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } AttachNicToVmOnHypervisorMsg amsg = new AttachNicToVmOnHypervisorMsg(); amsg.setVmUuid(self.getUuid()); amsg.setHostUuid(self.getHostUuid()); amsg.setNics(msg.getNics()); bus.makeTargetServiceIdByResourceUuid(amsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(amsg, new CloudBusCallBack(msg) { @Override public void run(MessageReply reply) { if (self.getDefaultL3NetworkUuid() == null) { self.setDefaultL3NetworkUuid(msg.getNics().get(0).getL3NetworkUuid()); self = dbf.updateAndRefresh(self); logger.debug(String.format("set the VM[uuid: %s]'s default L3 network[uuid:%s], as it doen't have one before", self.getUuid(), self.getDefaultL3NetworkUuid())); } AttachNicToVmReply r = new AttachNicToVmReply(); if (!reply.isSuccess()) { r.setError(errf.instantiateErrorCode(VmErrors.ATTACH_NETWORK_ERROR, r.getError())); } bus.reply(msg, r); } }); } private void handle(final DestroyVmInstanceMsg msg) { final DestroyVmInstanceReply reply = new DestroyVmInstanceReply(); final String issuer = VmInstanceVO.class.getSimpleName(); VmDeletionStruct s = new VmDeletionStruct(); s.setDeletionPolicy(deletionPolicyMgr.getDeletionPolicy(self.getUuid())); s.setInventory(getSelfInventory()); final List<VmDeletionStruct> ctx = list(s); final FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("destory-vm-%s", self.getUuid())); chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion()); bus.reply(msg, reply); } }).error(new FlowErrorHandler(msg) { @Override public void handle(final ErrorCode errCode, Map data) { reply.setError(errCode); bus.reply(msg, reply); } }).start(); } protected void handle(final ChangeVmStateMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("change-vm-state-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override @Deferred public void run(SyncTaskChain chain) { refreshVO(); Defer.defer(new Runnable() { @Override public void run() { ChangeVmStateReply reply = new ChangeVmStateReply(); bus.reply(msg, reply); } }); if (self == null) { // vm has been deleted by previous request // this happens when delete vm request queued before // change state request from vm tracer. // in this case, ignore change state request logger.debug(String.format("vm[uuid:%s] has been deleted, ignore change vm state request from vm tracer", msg.getVmInstanceUuid())); chain.next(); return; } changeVmStateInDb(VmInstanceStateEvent.valueOf(msg.getStateEvent())); chain.next(); } }); } protected void setFlowMarshaller(FlowChain chain) { chain.setFlowMarshaller(new FlowMarshaller() { @Override public Flow marshalTheNextFlow(String previousFlowClassName, String nextFlowClassName, FlowChain chain, Map data) { Flow nflow = null; for (MarshalVmOperationFlowExtensionPoint mext : pluginRgty.getExtensionList(MarshalVmOperationFlowExtensionPoint.class)) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); nflow = mext.marshalVmOperationFlow(previousFlowClassName, nextFlowClassName, chain, spec); if (nflow != null) { logger.debug(String.format("a VM[uuid: %s, operation: %s] operation flow[%s] is changed to the flow[%s] by %s", self.getUuid(), spec.getCurrentVmOperation(), nextFlowClassName, nflow.getClass(), mext.getClass())); break; } } return nflow; } }); } protected void selectBootOrder(VmInstanceSpec spec) { if (spec.getCurrentVmOperation() == null) { throw new CloudRuntimeException("selectBootOrder must be called after VmOperation is set"); } if (spec.getCurrentVmOperation() == VmOperation.NewCreate && spec.getDestIso() != null) { spec.setBootOrders(list(VmBootDevice.CdRom.toString())); } else { String order = VmSystemTags.BOOT_ORDER.getTokenByResourceUuid(self.getUuid(), VmSystemTags.BOOT_ORDER_TOKEN); if (order == null) { spec.setBootOrders(list(VmBootDevice.HardDisk.toString())); } else { spec.setBootOrders(list(order.split(","))); } } } protected void startVmFromNewCreate(final StartNewCreatedVmInstanceMsg msg, final SyncTaskChain taskChain) { refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } error = extEmitter.preStartNewCreatedVm(msg.getVmInstanceInventory()); if (error != null) { throw new OperationFailureException(error); } StartNewCreatedVmInstanceReply reply = new StartNewCreatedVmInstanceReply(); startVmFromNewCreate(StartVmFromNewCreatedStruct.fromMessage(msg), new Completion(msg, taskChain) { @Override public void success() { self = dbf.reload(self); reply.setVmInventory(getSelfInventory()); bus.reply(msg, reply); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); taskChain.next(); } }); } protected void handle(final StartNewCreatedVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("create-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVmFromNewCreate(msg, chain); } }); } protected void handleApiMessage(APIMessage msg) { if (msg instanceof APIStopVmInstanceMsg) { handle((APIStopVmInstanceMsg) msg); } else if (msg instanceof APIRebootVmInstanceMsg) { handle((APIRebootVmInstanceMsg) msg); } else if (msg instanceof APIDestroyVmInstanceMsg) { handle((APIDestroyVmInstanceMsg) msg); } else if (msg instanceof APIStartVmInstanceMsg) { handle((APIStartVmInstanceMsg) msg); } else if (msg instanceof APIMigrateVmMsg) { handle((APIMigrateVmMsg) msg); } else if (msg instanceof APIAttachL3NetworkToVmMsg) { handle((APIAttachL3NetworkToVmMsg) msg); } else if (msg instanceof APIGetVmMigrationCandidateHostsMsg) { handle((APIGetVmMigrationCandidateHostsMsg) msg); } else if (msg instanceof APIGetVmAttachableDataVolumeMsg) { handle((APIGetVmAttachableDataVolumeMsg) msg); } else if (msg instanceof APIUpdateVmInstanceMsg) { handle((APIUpdateVmInstanceMsg) msg); } else if (msg instanceof APIChangeInstanceOfferingMsg) { handle((APIChangeInstanceOfferingMsg) msg); } else if (msg instanceof APIDetachL3NetworkFromVmMsg) { handle((APIDetachL3NetworkFromVmMsg) msg); } else if (msg instanceof APIGetVmAttachableL3NetworkMsg) { handle((APIGetVmAttachableL3NetworkMsg) msg); } else if (msg instanceof APIAttachIsoToVmInstanceMsg) { handle((APIAttachIsoToVmInstanceMsg) msg); } else if (msg instanceof APIDetachIsoFromVmInstanceMsg) { handle((APIDetachIsoFromVmInstanceMsg) msg); } else if (msg instanceof APIExpungeVmInstanceMsg) { handle((APIExpungeVmInstanceMsg) msg); } else if (msg instanceof APIRecoverVmInstanceMsg) { handle((APIRecoverVmInstanceMsg) msg); } else if (msg instanceof APISetVmBootOrderMsg) { handle((APISetVmBootOrderMsg) msg); } else if (msg instanceof APISetVmConsolePasswordMsg) { handle((APISetVmConsolePasswordMsg) msg); } else if (msg instanceof APIGetVmBootOrderMsg) { handle((APIGetVmBootOrderMsg) msg); } else if (msg instanceof APIDeleteVmConsolePasswordMsg) { handle((APIDeleteVmConsolePasswordMsg) msg); } else if (msg instanceof APIGetVmConsolePasswordMsg) { handle((APIGetVmConsolePasswordMsg) msg); } else if (msg instanceof APIGetVmConsoleAddressMsg) { handle((APIGetVmConsoleAddressMsg) msg); } else if (msg instanceof APISetVmHostnameMsg) { handle((APISetVmHostnameMsg) msg); } else if (msg instanceof APIDeleteVmHostnameMsg) { handle((APIDeleteVmHostnameMsg) msg); } else if (msg instanceof APISetVmStaticIpMsg) { handle((APISetVmStaticIpMsg) msg); } else if (msg instanceof APIDeleteVmStaticIpMsg) { handle((APIDeleteVmStaticIpMsg) msg); } else if (msg instanceof APIGetVmHostnameMsg) { handle((APIGetVmHostnameMsg) msg); } else if (msg instanceof APIGetVmStartingCandidateClustersHostsMsg) { handle((APIGetVmStartingCandidateClustersHostsMsg) msg); } else if (msg instanceof APIGetVmCapabilitiesMsg) { handle((APIGetVmCapabilitiesMsg) msg); } else if (msg instanceof APISetVmSshKeyMsg) { handle((APISetVmSshKeyMsg) msg); } else if (msg instanceof APIGetVmSshKeyMsg) { handle((APIGetVmSshKeyMsg) msg); } else if (msg instanceof APIDeleteVmSshKeyMsg) { handle((APIDeleteVmSshKeyMsg) msg); } else if (msg instanceof APIGetCandidateIsoForAttachingVmMsg) { handle((APIGetCandidateIsoForAttachingVmMsg) msg); } else if (msg instanceof APIPauseVmInstanceMsg) { handle((APIPauseVmInstanceMsg) msg); } else if (msg instanceof APIResumeVmInstanceMsg) { handle((APIResumeVmInstanceMsg) msg); } else if (msg instanceof APIReimageVmInstanceMsg) { handle((APIReimageVmInstanceMsg) msg); } else { VmInstanceBaseExtensionFactory ext = vmMgr.getVmInstanceBaseExtensionFactory(msg); if (ext != null) { VmInstance v = ext.getVmInstance(self); v.handleMessage(msg); } else { bus.dealWithUnknownMessage(msg); } } } @Transactional(readOnly = true) private void handle(APIGetCandidateIsoForAttachingVmMsg msg) { APIGetCandidateIsoForAttachingVmReply reply = new APIGetCandidateIsoForAttachingVmReply(); if (self.getState() != VmInstanceState.Running && self.getState() != VmInstanceState.Stopped) { reply.setInventories(new ArrayList<>()); bus.reply(msg, reply); return; } String psUuid = getSelfInventory().getRootVolume().getPrimaryStorageUuid(); PrimaryStorageVO ps = dbf.getEntityManager().find(PrimaryStorageVO.class, psUuid); PrimaryStorageType psType = PrimaryStorageType.valueOf(ps.getType()); List<String> bsUuids = psType.findBackupStorage(psUuid); if (bsUuids == null) { String sql = "select img" + " from ImageVO img, ImageBackupStorageRefVO ref, BackupStorageVO bs, BackupStorageZoneRefVO bsRef" + " where ref.imageUuid = img.uuid" + " and img.mediaType = :imgType" + " and img.status = :status" + " and bs.uuid = ref.backupStorageUuid" + " and bs.type in (:bsTypes)" + " and bs.uuid = bsRef.backupStorageUuid" + " and bsRef.zoneUuid = :zoneUuid"; TypedQuery<ImageVO> q = dbf.getEntityManager().createQuery(sql, ImageVO.class); q.setParameter("zoneUuid", getSelfInventory().getZoneUuid()); q.setParameter("imgType", ImageMediaType.ISO); q.setParameter("status", ImageStatus.Ready); q.setParameter("bsTypes", hostAllocatorMgr.getBackupStorageTypesByPrimaryStorageTypeFromMetrics(ps.getType())); reply.setInventories(ImageInventory.valueOf(q.getResultList())); } else if (!bsUuids.isEmpty()) { String sql = "select img" + " from ImageVO img, ImageBackupStorageRefVO ref, BackupStorageVO bs, BackupStorageZoneRefVO bsRef" + " where ref.imageUuid = img.uuid" + " and img.mediaType = :imgType" + " and img.status = :status" + " and bs.uuid = ref.backupStorageUuid" + " and bs.uuid in (:bsUuids)" + " and bs.uuid = bsRef.backupStorageUuid" + " and bsRef.zoneUuid = :zoneUuid"; TypedQuery<ImageVO> q = dbf.getEntityManager().createQuery(sql, ImageVO.class); q.setParameter("zoneUuid", getSelfInventory().getZoneUuid()); q.setParameter("imgType", ImageMediaType.ISO); q.setParameter("status", ImageStatus.Ready); q.setParameter("bsUuids", bsUuids); reply.setInventories(ImageInventory.valueOf(q.getResultList())); } else { reply.setInventories(new ArrayList<>()); } bus.reply(msg, reply); } private void handle(APIGetVmCapabilitiesMsg msg) { APIGetVmCapabilitiesReply reply = new APIGetVmCapabilitiesReply(); Map<String, Object> ret = new HashMap<>(); checkPrimaryStorageCapabilities(ret); checkImageMediaTypeCapabilities(ret); reply.setCapabilities(ret); bus.reply(msg, reply); } private void checkPrimaryStorageCapabilities(Map<String, Object> ret) { VolumeInventory rootVolume = getSelfInventory().getRootVolume(); if (rootVolume == null) { ret.put(Capability.LiveMigration.toString(), false); ret.put(Capability.VolumeMigration.toString(), false); } else { SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.type); q.add(PrimaryStorageVO_.uuid, Op.EQ, rootVolume.getPrimaryStorageUuid()); String type = q.findValue(); PrimaryStorageType psType = PrimaryStorageType.valueOf(type); ret.put(Capability.LiveMigration.toString(), psType.isSupportVmLiveMigration()); ret.put(Capability.VolumeMigration.toString(), psType.isSupportVolumeMigration()); } } private void checkImageMediaTypeCapabilities(Map<String, Object> ret) { ImageVO vo = null; ImageMediaType imageMediaType; if (self.getImageUuid() != null) { vo = dbf.findByUuid(self.getImageUuid(), ImageVO.class); } if (vo == null) { imageMediaType = null; } else { imageMediaType = vo.getMediaType(); } if (imageMediaType == ImageMediaType.ISO || imageMediaType == null) { ret.put(Capability.Reimage.toString(), false); } else { ret.put(Capability.Reimage.toString(), true); } } private void handle(APIGetVmHostnameMsg msg) { String hostname = VmSystemTags.HOSTNAME.getTokenByResourceUuid(self.getUuid(), VmSystemTags.HOSTNAME_TOKEN); APIGetVmHostnameReply reply = new APIGetVmHostnameReply(); reply.setHostname(hostname); bus.reply(msg, reply); } private void handle(final APIDeleteVmStaticIpMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { APIDeleteVmStaticIpEvent evt = new APIDeleteVmStaticIpEvent(msg.getId()); new StaticIpOperator().deleteStaticIpByVmUuidAndL3Uuid(self.getUuid(), msg.getL3NetworkUuid()); bus.publish(evt); chain.next(); } @Override public String getName() { return "delete-static-ip"; } }); } private void handle(final APISetVmStaticIpMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { setStaticIp(msg, new NoErrorCompletion(msg, chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "set-static-ip"; } }); } private void setStaticIp(final APISetVmStaticIpMsg msg, final NoErrorCompletion completion) { refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } final APISetVmStaticIpEvent evt = new APISetVmStaticIpEvent(msg.getId()); changeVmIp(msg.getL3NetworkUuid(), msg.getIp(), new Completion(msg, completion) { @Override public void success() { new StaticIpOperator().setStaticIp(self.getUuid(), msg.getL3NetworkUuid(), msg.getIp()); bus.publish(evt); completion.done(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); completion.done(); } }); } private void handle(APIDeleteVmHostnameMsg msg) { APIDeleteVmHostnameEvent evt = new APIDeleteVmHostnameEvent(msg.getId()); VmSystemTags.HOSTNAME.delete(self.getUuid()); bus.publish(evt); } private void handle(APISetVmHostnameMsg msg) { if (!VmSystemTags.HOSTNAME.hasTag(self.getUuid())) { SystemTagCreator creator = VmSystemTags.HOSTNAME.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map( e(VmSystemTags.HOSTNAME_TOKEN, msg.getHostname()) )); creator.create(); } else { VmSystemTags.HOSTNAME.update(self.getUuid(), VmSystemTags.HOSTNAME.instantiateTag( map(e(VmSystemTags.HOSTNAME_TOKEN, msg.getHostname())) )); } APISetVmHostnameEvent evt = new APISetVmHostnameEvent(msg.getId()); bus.publish(evt); } private void handle(final APIGetVmConsoleAddressMsg msg) { ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } final APIGetVmConsoleAddressReply creply = new APIGetVmConsoleAddressReply(); GetVmConsoleAddressFromHostMsg hmsg = new GetVmConsoleAddressFromHostMsg(); hmsg.setHostUuid(self.getHostUuid()); hmsg.setVmInstanceUuid(self.getUuid()); bus.makeTargetServiceIdByResourceUuid(hmsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(hmsg, new CloudBusCallBack(msg) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { creply.setError(reply.getError()); } else { GetVmConsoleAddressFromHostReply hr = reply.castReply(); creply.setHostIp(hr.getHostIp()); creply.setPort(hr.getPort()); creply.setProtocol(hr.getProtocol()); } bus.reply(msg, creply); } }); } private void handle(APIGetVmBootOrderMsg msg) { APIGetVmBootOrderReply reply = new APIGetVmBootOrderReply(); String order = VmSystemTags.BOOT_ORDER.getTokenByResourceUuid(self.getUuid(), VmSystemTags.BOOT_ORDER_TOKEN); if (order == null) { reply.setOrder(list(VmBootDevice.HardDisk.toString())); } else { reply.setOrder(list(order.split(","))); } bus.reply(msg, reply); } private void handle(APISetVmBootOrderMsg msg) { APISetVmBootOrderEvent evt = new APISetVmBootOrderEvent(msg.getId()); if (msg.getBootOrder() != null) { SystemTagCreator creator = VmSystemTags.BOOT_ORDER.newSystemTagCreator(self.getUuid()); creator.inherent = true; creator.recreate = true; creator.setTagByTokens(map(e(VmSystemTags.BOOT_ORDER_TOKEN, StringUtils.join(msg.getBootOrder(), ",")))); creator.create(); } else { VmSystemTags.BOOT_ORDER.deleteInherentTag(self.getUuid()); } evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(APISetVmConsolePasswordMsg msg) { APISetVmConsolePasswordEvent evt = new APISetVmConsolePasswordEvent(msg.getId()); SystemTagCreator creator = VmSystemTags.CONSOLE_PASSWORD.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(VmSystemTags.CONSOLE_PASSWORD_TOKEN, msg.getConsolePassword()))); creator.recreate = true; creator.create(); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(APIGetVmConsolePasswordMsg msg) { APIGetVmConsolePasswordReply reply = new APIGetVmConsolePasswordReply(); String consolePassword = VmSystemTags.CONSOLE_PASSWORD.getTokenByResourceUuid(self.getUuid(), VmSystemTags.CONSOLE_PASSWORD_TOKEN); reply.setConsolePassword(consolePassword); bus.reply(msg, reply); } private void handle(APIDeleteVmConsolePasswordMsg msg) { APIDeleteVmConsolePasswordEvent evt = new APIDeleteVmConsolePasswordEvent(msg.getId()); VmSystemTags.CONSOLE_PASSWORD.delete(self.getUuid()); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(APISetVmSshKeyMsg msg) { APISetVmSshKeyEvent evt = new APISetVmSshKeyEvent(msg.getId()); SystemTagCreator creator = VmSystemTags.SSHKEY.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(VmSystemTags.SSHKEY_TOKEN, msg.getSshKey()))); creator.recreate = true; creator.create(); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(APIGetVmSshKeyMsg msg) { APIGetVmSshKeyReply reply = new APIGetVmSshKeyReply(); String sshKey = VmSystemTags.SSHKEY.getTokenByResourceUuid(self.getUuid(), VmSystemTags.SSHKEY_TOKEN); reply.setSshKey(sshKey); bus.reply(msg, reply); } private void handle(APIDeleteVmSshKeyMsg msg) { APIDeleteVmSshKeyEvent evt = new APIDeleteVmSshKeyEvent(msg.getId()); VmSystemTags.SSHKEY.delete(self.getUuid()); evt.setInventory(getSelfInventory()); bus.publish(evt); } private boolean ipExists(final String l3uuid, final String ipAddress) { SimpleQuery<VmNicVO> q = dbf.createQuery(VmNicVO.class); q.add(VmNicVO_.l3NetworkUuid, Op.EQ, l3uuid); q.add(VmNicVO_.ip, Op.EQ, ipAddress); return q.isExists(); } // If the VM is assigned static IP and it is now occupied, we will // remove the static IP tag so that it can acquire IP dynamically. // c.f. issue #1639 private void checkIpConflict(final String vmUuid) { StaticIpOperator ipo = new StaticIpOperator(); for (Map.Entry<String, String> entry : ipo.getStaticIpbyVmUuid(vmUuid).entrySet()) { if (ipExists(entry.getKey(), entry.getValue())) { ipo.deleteStaticIpByVmUuidAndL3Uuid(vmUuid, entry.getKey()); } } } private void recoverVm(final Completion completion) { final VmInstanceInventory vm = getSelfInventory(); final List<RecoverVmExtensionPoint> exts = pluginRgty.getExtensionList(RecoverVmExtensionPoint.class); for (RecoverVmExtensionPoint ext : exts) { ext.preRecoverVm(vm); } CollectionUtils.forEach(exts, new ForEachFunction<RecoverVmExtensionPoint>() { @Override public void run(RecoverVmExtensionPoint ext) { ext.beforeRecoverVm(vm); } }); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("recover-vm-%s", self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "check-ip-conflict"; @Override public void run(FlowTrigger trigger, Map data) { checkIpConflict(vm.getUuid()); trigger.next(); } }); flow(new NoRollbackFlow() { String __name__ = "recover-root-volume"; @Override public void run(final FlowTrigger trigger, Map data) { RecoverVolumeMsg msg = new RecoverVolumeMsg(); msg.setVolumeUuid(self.getRootVolumeUuid()); bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, self.getRootVolumeUuid()); bus.send(msg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); } else { trigger.next(); } } }); } }); flow(new NoRollbackFlow() { String __name__ = "recover-vm"; @Override public void run(FlowTrigger trigger, Map data) { self = changeVmStateInDb(VmInstanceStateEvent.stopped); CollectionUtils.forEach(exts, new ForEachFunction<RecoverVmExtensionPoint>() { @Override public void run(RecoverVmExtensionPoint ext) { ext.afterRecoverVm(vm); } }); trigger.next(); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } private void handle(final APIRecoverVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIRecoverVmInstanceEvent evt = new APIRecoverVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { evt.setError(error); bus.publish(evt); chain.next(); return; } recoverVm(new Completion(msg, chain) { @Override public void success() { evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "recover-vm"; } }); } private void handle(final APIExpungeVmInstanceMsg msg) { final APIExpungeVmInstanceEvent evt = new APIExpungeVmInstanceEvent(msg.getId()); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { expunge(msg, new Completion(msg, chain) { @Override public void success() { bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "expunge-vm-by-api"; } }); } private void handle(final APIDetachIsoFromVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIDetachIsoFromVmInstanceEvent evt = new APIDetachIsoFromVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setError(allowed); bus.publish(evt); chain.next(); return; } detachIso(new Completion(msg, chain) { @Override public void success() { self = dbf.reload(self); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("detach-iso-from-vm-%s", self.getUuid()); } }); } private void detachIso(final Completion completion) { if (self.getState() == VmInstanceState.Stopped) { new IsoOperator().detachIsoFromVm(self.getUuid()); completion.success(); return; } if (!new IsoOperator().isIsoAttachedToVm(self.getUuid())) { completion.success(); return; } VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.DetachIso); if (spec.getDestIso() == null) { // the image ISO has been deleted from backup storage // try to detach it from the VM anyway String isoUuid = new IsoOperator().getIsoUuidByVmUuid(self.getUuid()); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); logger.debug(String.format("the iso[uuid:%s] has been deleted, try to detach it from the VM[uuid:%s] anyway", isoUuid, self.getUuid())); } FlowChain chain = getDetachIsoWorkFlowChain(spec.getVmInventory()); chain.setName(String.format("detach-iso-%s-from-vm-%s", spec.getDestIso().getImageUuid(), self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); setFlowMarshaller(chain); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { new IsoOperator().detachIsoFromVm(self.getUuid()); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } @Transactional(readOnly = true) private List<L3NetworkInventory> getAttachableL3Network(String accountUuid) { List<String> l3Uuids = acntMgr.getResourceUuidsCanAccessByAccount(accountUuid, L3NetworkVO.class); if (l3Uuids != null && l3Uuids.isEmpty()) { return new ArrayList<L3NetworkInventory>(); } String sql; TypedQuery<L3NetworkVO> q; if (self.getVmNics().isEmpty()) { if (l3Uuids == null) { // accessed by a system admin sql = "select l3" + " from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where vm.uuid = :uuid" + " and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid" + " and l2.uuid = l3.l2NetworkUuid" + " and l3.state = :l3State" + " group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); } else { // accessed by a normal account sql = "select l3" + " from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where vm.uuid = :uuid" + " and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid" + " and l2.uuid = l3.l2NetworkUuid" + " and l3.state = :l3State" + " and l3.uuid in (:l3uuids)" + " group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); q.setParameter("l3uuids", l3Uuids); } } else { if (l3Uuids == null) { // accessed by a system admin sql = "select l3" + " from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where l3.uuid not in" + " (select nic.l3NetworkUuid from VmNicVO nic where nic.vmInstanceUuid = :uuid)" + " and vm.uuid = :uuid" + " and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid" + " and l2.uuid = l3.l2NetworkUuid" + " and l3.state = :l3State" + " group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); } else { // accessed by a normal account sql = "select l3" + " from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where l3.uuid not in" + " (select nic.l3NetworkUuid from VmNicVO nic where nic.vmInstanceUuid = :uuid)" + " and vm.uuid = :uuid" + " and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid" + " and l2.uuid = l3.l2NetworkUuid" + " and l3.state = :l3State" + " and l3.uuid in (:l3uuids)" + " group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); q.setParameter("l3uuids", l3Uuids); } } q.setParameter("l3State", L3NetworkState.Enabled); q.setParameter("uuid", self.getUuid()); List<L3NetworkVO> l3s = q.getResultList(); return L3NetworkInventory.valueOf(l3s); } private void handle(APIGetVmAttachableL3NetworkMsg msg) { APIGetVmAttachableL3NetworkReply reply = new APIGetVmAttachableL3NetworkReply(); reply.setInventories(getAttachableL3Network(msg.getSession().getAccountUuid())); bus.reply(msg, reply); } private void handle(final APIAttachIsoToVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIAttachIsoToVmInstanceEvent evt = new APIAttachIsoToVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setError(allowed); bus.publish(evt); chain.next(); return; } attachIso(msg.getIsoUuid(), new Completion(msg, chain) { @Override public void success() { self = dbf.reload(self); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("attach-iso-%s-to-vm-%s", msg.getIsoUuid(), self.getUuid()); } }); } private void attachIso(final String isoUuid, final Completion completion) { checkIfIsoAttachable(isoUuid); if (self.getState() == VmInstanceState.Stopped) { new IsoOperator().attachIsoToVm(self.getUuid(), isoUuid); completion.success(); return; } VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.AttachIso); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); FlowChain chain = getAttachIsoWorkFlowChain(spec.getVmInventory()); chain.setName(String.format("attach-iso-%s-to-vm-%s", isoUuid, self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); setFlowMarshaller(chain); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { new IsoOperator().attachIsoToVm(self.getUuid(), isoUuid); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } @Transactional(readOnly = true) private void checkIfIsoAttachable(String isoUuid) { String psUuid = getSelfInventory().getRootVolume().getPrimaryStorageUuid(); String sql = "select count(i)" + " from ImageCacheVO i" + " where i.primaryStorageUuid = :psUuid" + " and i.imageUuid = :isoUuid"; TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("psUuid", psUuid); q.setParameter("isoUuid", isoUuid); Long count = q.getSingleResult(); if (count > 0) { // on the same primary storage return; } PrimaryStorageVO psvo = dbf.getEntityManager().find(PrimaryStorageVO.class, psUuid); PrimaryStorageType type = PrimaryStorageType.valueOf(psvo.getType()); List<String> bsUuids = type.findBackupStorage(psUuid); if (bsUuids == null) { List<String> possibleBsTypes = hostAllocatorMgr.getBackupStorageTypesByPrimaryStorageTypeFromMetrics(psvo.getType()); sql = "select count(bs)" + " from BackupStorageVO bs, ImageBackupStorageRefVO ref" + " where bs.uuid = ref.backupStorageUuid" + " and ref.imageUuid = :imgUuid" + " and bs.type in (:bsTypes)"; q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("imgUuid", isoUuid); q.setParameter("bsTypes", possibleBsTypes); count = q.getSingleResult(); if (count > 0) { return; } } else if (!bsUuids.isEmpty()) { sql = "select count(bs)" + " from BackupStorageVO bs, ImageBackupStorageRefVO ref" + " where bs.uuid = ref.backupStorageUuid" + " and ref.imageUuid = :imgUuid" + " and bs.uuid in (:bsUuids)"; q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("imgUuid", isoUuid); q.setParameter("bsUuids", bsUuids); count = q.getSingleResult(); if (count > 0) { return; } } throw new OperationFailureException(operr("the ISO[uuid:%s] is on backup storage that is not compatible of the primary storage[uuid:%s]" + " where the VM[name:%s, uuid:%s] is on", isoUuid, psUuid, self.getName(), self.getUuid())); } private void handle(final APIDetachL3NetworkFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIDetachL3NetworkFromVmEvent evt = new APIDetachL3NetworkFromVmEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setError(allowed); bus.publish(evt); chain.next(); return; } FlowChain fchain = FlowChainBuilder.newSimpleFlowChain(); fchain.setName(String.format("detach-l3-network-to-vm-%s", msg.getVmInstanceUuid())); fchain.then(new NoRollbackFlow() { String __name__ = "before-detach-nic"; @Override public void run(FlowTrigger trigger, Map data) { VmNicInventory nic = VmNicInventory.valueOf((VmNicVO) Q.New(VmNicVO.class).eq(VmNicVO_.uuid, msg.getVmNicUuid()).find()); beforeDetachNic(nic, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { String __name__ = "detach-nic"; @Override public void run(FlowTrigger trigger, Map data) { detachNic(msg.getVmNicUuid(), new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.next(); } }); } }).done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { self = dbf.reload(self); evt.setInventory(VmInstanceInventory.valueOf(self)); bus.publish(evt); chain.next(); } }).error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { evt.setError(errCode); bus.publish(evt); chain.next(); } }).start(); } @Override public String getName() { return "detach-nic"; } }); } protected void beforeDetachNic(VmNicInventory nicInventory, Completion completion) { completion.success(); } // switch vm default nic if vm current default nic is input parm nic protected void selectDefaultL3(VmNicInventory nic) { if (self.getDefaultL3NetworkUuid() != null && !self.getDefaultL3NetworkUuid().equals(nic.getL3NetworkUuid())) { return; } final VmInstanceInventory vm = getSelfInventory(); final String previousDefaultL3 = vm.getDefaultL3NetworkUuid(); // the nic has been removed, reload self = dbf.reload(self); final VmNicVO candidate = CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return arg.getUuid().equals(nic.getUuid()) ? null : arg; } }); if (candidate != null) { CollectionUtils.safeForEach( pluginRgty.getExtensionList(VmDefaultL3NetworkChangedExtensionPoint.class), new ForEachFunction<VmDefaultL3NetworkChangedExtensionPoint>() { @Override public void run(VmDefaultL3NetworkChangedExtensionPoint ext) { ext.vmDefaultL3NetworkChanged(vm, previousDefaultL3, candidate.getL3NetworkUuid()); } }); self.setDefaultL3NetworkUuid(candidate.getL3NetworkUuid()); logger.debug(String.format( "after detaching the nic[uuid:%s, L3 uuid:%s], change the default L3 of the VM[uuid:%s]" + " to the L3 network[uuid: %s]", nic.getUuid(), nic.getL3NetworkUuid(), self.getUuid(), candidate.getL3NetworkUuid())); } else { self.setDefaultL3NetworkUuid(null); logger.debug(String.format( "after detaching the nic[uuid:%s, L3 uuid:%s], change the default L3 of the VM[uuid:%s]" + " to null, as the VM has no other nics", nic.getUuid(), nic.getL3NetworkUuid(), self.getUuid())); } self = dbf.updateAndRefresh(self); } private void detachNic(final String nicUuid, final Completion completion) { final VmNicInventory nic = VmNicInventory.valueOf( CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return arg.getUuid().equals(nicUuid) ? arg : null; } }) ); for (VmDetachNicExtensionPoint ext : pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class)) { ext.preDetachNic(nic); } CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.beforeDetachNic(nic); } }); final VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.DetachNic); spec.setVmInventory(VmInstanceInventory.valueOf(self)); spec.setDestNics(list(nic)); spec.setL3Networks(list(L3NetworkInventory.valueOf(dbf.findByUuid(nic.getL3NetworkUuid(), L3NetworkVO.class)))); FlowChain flowChain = FlowChainBuilder.newSimpleFlowChain(); flowChain.setName(String.format("detachNic-vm-%s-nic-%s", self.getUuid(), nicUuid)); setFlowMarshaller(flowChain); flowChain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); if (self.getState() == VmInstanceState.Running) { flowChain.then(new VmDetachNicOnHypervisorFlow()); } flowChain.then(new VmReleaseResourceOnDetachingNicFlow()); flowChain.then(new VmDetachNicFlow()); flowChain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { selectDefaultL3(nic); removeStaticIp(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.afterDetachNic(nic); } }); completion.success(); } private void removeStaticIp() { new StaticIpOperator().deleteStaticIpByVmUuidAndL3Uuid(self.getUuid(), nic.getL3NetworkUuid()); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.failedToDetachNic(nic, errCode); } }); completion.fail(errCode); } }).start(); } private void handle(final APIChangeInstanceOfferingMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { APIChangeInstanceOfferingEvent evt = new APIChangeInstanceOfferingEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { throw new OperationFailureException(operr("operation is not allowed to vm[uuid:%s] which is in the state of state:%s", self.getUuid(), self.getState())); } changeOffering(msg, new Completion(msg, chain) { @Override public void success() { self.setInstanceOfferingUuid(msg.getInstanceOfferingUuid()); dbf.updateAndRefresh(self); refreshVO(); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "change-instance-offering"; } }); } private void changeOffering(APIChangeInstanceOfferingMsg msg, final Completion completion) { final InstanceOfferingVO newOfferingVO = dbf.findByUuid(msg.getInstanceOfferingUuid(), InstanceOfferingVO.class); final InstanceOfferingInventory inv = InstanceOfferingInventory.valueOf(newOfferingVO); final VmInstanceInventory vm = getSelfInventory(); List<ChangeInstanceOfferingExtensionPoint> exts = pluginRgty.getExtensionList(ChangeInstanceOfferingExtensionPoint.class); for (ChangeInstanceOfferingExtensionPoint ext : exts) { ext.preChangeInstanceOffering(vm, inv); } CollectionUtils.safeForEach(exts, new ForEachFunction<ChangeInstanceOfferingExtensionPoint>() { @Override public void run(ChangeInstanceOfferingExtensionPoint arg) { arg.beforeChangeInstanceOffering(vm, inv); } }); if (self.getState() == VmInstanceState.Stopped) { changeCpuAndMemoryForStoppedVm(newOfferingVO.getCpuNum(), newOfferingVO.getMemorySize()); completion.success(); } else if (self.getState() == VmInstanceState.Running) { changeCpuAndMemoryForRunningVm(newOfferingVO.getCpuNum(), newOfferingVO.getMemorySize(), completion); } CollectionUtils.safeForEach(exts, new ForEachFunction<ChangeInstanceOfferingExtensionPoint>() { @Override public void run(ChangeInstanceOfferingExtensionPoint arg) { arg.afterChangeInstanceOffering(vm, inv); } }); } private void changeCpuAndMemoryForStoppedVm(final int cpuNum, final long memorySize) { self.setCpuNum(cpuNum); self.setMemorySize(memorySize); self = dbf.updateAndRefresh(self); } private void changeCpuAndMemoryForRunningVm(final int cpuNum, final long memorySize, final Completion completion) { final int oldCpuNum = self.getCpuNum(); final long oldMemorySize = self.getMemorySize(); class AlignmentStruct { long alignedMemory; } final AlignmentStruct struct = new AlignmentStruct(); struct.alignedMemory = memorySize; FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("change-cpu-and-memory-of-vm-%s", self.getUuid())); chain.then(new NoRollbackFlow() { String __name__ = "align-memory"; @Override public void run(FlowTrigger chain, Map data) { // align memory long increaseMemory = memorySize - oldMemorySize; long remainderMemory = increaseMemory % SizeUnit.MEGABYTE.toByte(128); if (increaseMemory != 0 && remainderMemory != 0) { if (remainderMemory < SizeUnit.MEGABYTE.toByte(128) / 2) { increaseMemory = increaseMemory / SizeUnit.MEGABYTE.toByte(128) * SizeUnit.MEGABYTE.toByte(128); } else { increaseMemory = (increaseMemory / SizeUnit.MEGABYTE.toByte(128) + 1) * SizeUnit.MEGABYTE.toByte(128); } if (increaseMemory == 0) { struct.alignedMemory = oldMemorySize + SizeUnit.MEGABYTE.toByte(128); } else { struct.alignedMemory = oldMemorySize + increaseMemory; } N.New(VmInstanceVO.class, self.getUuid()).info_("automatically align memory from %s to %s", memorySize, struct.alignedMemory); } chain.next(); } }).then(new Flow() { String __name__ = String.format("allocate-host-capacity-on-host-%s", self.getHostUuid()); boolean result = false; @Override public void run(FlowTrigger chain, Map data) { DesignatedAllocateHostMsg msg = new DesignatedAllocateHostMsg(); msg.setCpuCapacity(cpuNum - oldCpuNum); msg.setMemoryCapacity(struct.alignedMemory - oldMemorySize); msg.setAllocatorStrategy(HostAllocatorConstant.DESIGNATED_HOST_ALLOCATOR_STRATEGY_TYPE); msg.setVmInstance(VmInstanceInventory.valueOf(self)); msg.setHostUuid(self.getHostUuid()); msg.setL3NetworkUuids(CollectionUtils.transformToList(self.getVmNics(), new Function<String, VmNicVO>() { @Override public String call(VmNicVO arg) { return arg.getL3NetworkUuid(); } })); msg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID)); bus.send(msg, new CloudBusCallBack(chain) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { ErrorCode err = operr("host[uuid:%s] capacity is not enough to offer cpu[%s], memory[%s bytes]", self.getHostUuid(), cpuNum - oldCpuNum, struct.alignedMemory - oldMemorySize); err.setCause(reply.getError()); chain.fail(err); } else { result = true; logger.debug(String.format("reserve memory %s bytes and cpu %s on host[uuid:%s]", memorySize - self.getMemorySize(), cpuNum - self.getCpuNum(), self.getHostUuid())); chain.next(); } } }); } @Override public void rollback(FlowRollback chain, Map data) { if (result) { ReturnHostCapacityMsg msg = new ReturnHostCapacityMsg(); msg.setCpuCapacity(cpuNum - oldCpuNum); msg.setMemoryCapacity(struct.alignedMemory - oldMemorySize); msg.setHostUuid(self.getHostUuid()); msg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID)); bus.send(msg); } chain.rollback(); } }).then(new NoRollbackFlow() { String __name__ = String.format("change-cpu-of-vm-%s", self.getUuid()); @Override public void run(FlowTrigger chain, Map data) { if (cpuNum != self.getCpuNum()) { IncreaseVmCpuMsg msg = new IncreaseVmCpuMsg(); msg.setVmInstanceUuid(self.getUuid()); msg.setHostUuid(self.getHostUuid()); msg.setCpuNum(cpuNum); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(msg, new CloudBusCallBack(chain) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { logger.error("failed to update cpu"); chain.fail(reply.getError()); } else { IncreaseVmCpuReply r = reply.castReply(); self.setCpuNum(r.getCpuNum()); chain.next(); } } }); } else { chain.next(); } } }).then(new NoRollbackFlow() { String __name__ = String.format("change-memory-of-vm-%s", self.getUuid()); @Override public void run(FlowTrigger chain, Map data) { if (struct.alignedMemory != self.getMemorySize()) { IncreaseVmMemoryMsg msg = new IncreaseVmMemoryMsg(); msg.setVmInstanceUuid(self.getUuid()); msg.setHostUuid(self.getHostUuid()); msg.setMemorySize(struct.alignedMemory); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(msg, new CloudBusCallBack(chain) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { logger.error("failed to update memory"); chain.fail(reply.getError()); } else { IncreaseVmMemoryReply r = reply.castReply(); self.setMemorySize(r.getMemorySize()); chain.next(); } } }); } else { chain.next(); } } }).done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { dbf.update(self); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } private void handle(final APIUpdateVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { APIUpdateVmInstanceEvent evt = new APIUpdateVmInstanceEvent(msg.getId()); refreshVO(); List<Runnable> extensions = new ArrayList<Runnable>(); final VmInstanceInventory vm = getSelfInventory(); boolean update = false; if (msg.getName() != null) { self.setName(msg.getName()); update = true; } if (msg.getDescription() != null) { self.setDescription(msg.getDescription()); update = true; } if (msg.getState() != null) { self.setState(VmInstanceState.valueOf(msg.getState())); update = true; if (!vm.getState().equals(msg.getState())) { extensions.add(new Runnable() { @Override public void run() { logger.debug(String.format("vm[uuid:%s] changed state from %s to %s", self.getUuid(), vm.getState(), msg.getState())); VmCanonicalEvents.VmStateChangedData data = new VmCanonicalEvents.VmStateChangedData(); data.setVmUuid(self.getUuid()); data.setOldState(vm.getState()); data.setNewState(msg.getState()); data.setInventory(getSelfInventory()); evtf.fire(VmCanonicalEvents.VM_FULL_STATE_CHANGED_PATH, data); } }); } } if (msg.getDefaultL3NetworkUuid() != null) { self.setDefaultL3NetworkUuid(msg.getDefaultL3NetworkUuid()); update = true; if (!msg.getDefaultL3NetworkUuid().equals(vm.getDefaultL3NetworkUuid())) { extensions.add(new Runnable() { @Override public void run() { for (VmDefaultL3NetworkChangedExtensionPoint ext : pluginRgty.getExtensionList(VmDefaultL3NetworkChangedExtensionPoint.class)) { ext.vmDefaultL3NetworkChanged(vm, vm.getDefaultL3NetworkUuid(), msg.getDefaultL3NetworkUuid()); } } }); } } if (msg.getPlatform() != null) { self.setPlatform(msg.getPlatform()); update = true; } if (update) { dbf.update(self); } CollectionUtils.safeForEach(extensions, new ForEachFunction<Runnable>() { @Override public void run(Runnable arg) { arg.run(); } }); if (msg.getCpuNum() != null || msg.getMemorySize() != null) { changeCpuAndMemory(msg, new Completion(msg, chain) { @Override public void success() { refreshVO(); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } else { evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } } @Override public String getName() { return "update-vm-info"; } }); } @Transactional(readOnly = true) private List<VolumeVO> getAttachableVolume(String accountUuid) { List<String> volUuids = acntMgr.getResourceUuidsCanAccessByAccount(accountUuid, VolumeVO.class); if (volUuids != null && volUuids.isEmpty()) { return new ArrayList<>(); } List<String> formats = VolumeFormat.getVolumeFormatSupportedByHypervisorTypeInString(self.getHypervisorType()); if (formats.isEmpty()) { throw new CloudRuntimeException(String.format("cannot find volume formats for the hypervisor type[%s]", self.getHypervisorType())); } String sql; List<VolumeVO> vos; if (volUuids == null) { // accessed by a system admin sql = "select vol" + " from VolumeVO vol, VmInstanceVO vm, PrimaryStorageClusterRefVO ref" + " where vol.type = :type" + " and vol.state = :volState" + " and vol.status = :volStatus" + " and vol.format in (:formats)" + " and vol.vmInstanceUuid is null" + " and vm.clusterUuid = ref.clusterUuid" + " and ref.primaryStorageUuid = vol.primaryStorageUuid" + " and vm.uuid = :vmUuid" + " group by vol.uuid"; TypedQuery<VolumeVO> q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.Ready); q.setParameter("formats", formats); q.setParameter("vmUuid", self.getUuid()); q.setParameter("type", VolumeType.Data); vos = q.getResultList(); sql = "select vol" + " from VolumeVO vol" + " where vol.type = :type" + " and vol.status = :volStatus" + " and vol.state = :volState" + " group by vol.uuid"; q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("type", VolumeType.Data); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.NotInstantiated); vos.addAll(q.getResultList()); } else { // accessed by a normal account sql = "select vol" + " from VolumeVO vol, VmInstanceVO vm, PrimaryStorageClusterRefVO ref" + " where vol.type = :type" + " and vol.state = :volState" + " and vol.status = :volStatus" + " and vol.format in (:formats)" + " and vol.vmInstanceUuid is null" + " and vm.clusterUuid = ref.clusterUuid" + " and ref.primaryStorageUuid = vol.primaryStorageUuid" + " and vol.uuid in (:volUuids)" + " and vm.uuid = :vmUuid" + " group by vol.uuid"; TypedQuery<VolumeVO> q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.Ready); q.setParameter("vmUuid", self.getUuid()); q.setParameter("formats", formats); q.setParameter("type", VolumeType.Data); q.setParameter("volUuids", volUuids); vos = q.getResultList(); sql = "select vol" + " from VolumeVO vol" + " where vol.type = :type" + " and vol.status = :volStatus" + " and vol.state = :volState" + " and vol.uuid in (:volUuids)" + " group by vol.uuid"; q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("type", VolumeType.Data); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volUuids", volUuids); q.setParameter("volStatus", VolumeStatus.NotInstantiated); vos.addAll(q.getResultList()); } for (GetAttachableVolumeExtensionPoint ext : pluginRgty.getExtensionList(GetAttachableVolumeExtensionPoint.class)) { if (!vos.isEmpty()) { vos = ext.returnAttachableVolumes(getSelfInventory(), vos); } } return vos; } private void changeCpuAndMemory(APIUpdateVmInstanceMsg msg, Completion completion) { // add some systemTag and can be appliance for the next start int cpuNum = msg.getCpuNum() == null ? self.getCpuNum() : msg.getCpuNum(); long memory = msg.getMemorySize() == null ? self.getMemorySize() : msg.getMemorySize(); if (self.getState().equals(VmInstanceState.Running)) { changeCpuAndMemoryForRunningVm(cpuNum, memory, completion); } else if (self.getState().equals(VmInstanceState.Stopped)) { changeCpuAndMemoryForStoppedVm(cpuNum, memory); completion.success(); } } private void handle(APIGetVmAttachableDataVolumeMsg msg) { APIGetVmAttachableDataVolumeReply reply = new APIGetVmAttachableDataVolumeReply(); reply.setInventories(VolumeInventory.valueOf(getAttachableVolume(msg.getSession().getAccountUuid()))); bus.reply(msg, reply); } private void handle(final APIGetVmMigrationCandidateHostsMsg msg) { final APIGetVmMigrationCandidateHostsReply reply = new APIGetVmMigrationCandidateHostsReply(); getVmMigrationTargetHost(msg, new ReturnValueCompletion<List<HostInventory>>(msg) { @Override public void success(List<HostInventory> returnValue) { reply.setInventories(returnValue); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handle(final APIAttachL3NetworkToVmMsg msg) { final APIAttachL3NetworkToVmEvent evt = new APIAttachL3NetworkToVmEvent(msg.getId()); final String vmNicInvKey = "vmNicInventory"; FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("attach-l3-network-to-vm-%s", msg.getVmInstanceUuid())); chain.then(new NoRollbackFlow() { String __name__ = "attach-nic"; @Override public void run(FlowTrigger trigger, Map data) { attachNic(msg, msg.getL3NetworkUuid(), new ReturnValueCompletion<VmNicInventory>(msg) { @Override public void success(VmNicInventory returnValue) { data.put(vmNicInvKey, returnValue); trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { String __name__ = "after-attach-nic"; @Override public void run(FlowTrigger trigger, Map data) { afterAttachNic((VmNicInventory) data.get(vmNicInvKey), new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { self = dbf.reload(self); evt.setInventory(VmInstanceInventory.valueOf(self)); bus.publish(evt); } }).error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { evt.setError(errCode); bus.publish(evt); } }).start(); } protected void afterAttachNic(VmNicInventory nicInventory, Completion completion) { completion.success(); } private void detachVolume(final DetachDataVolumeFromVmMsg msg, final NoErrorCompletion completion) { final DetachDataVolumeFromVmReply reply = new DetachDataVolumeFromVmReply(); refreshVO(true); if (self == null || VmInstanceState.Destroyed == self.getState()) { // the vm is destroyed, the data volume must have been detached bus.reply(msg, reply); completion.done(); return; } ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.DETACH_VOLUME_ERROR); if (allowed != null) { throw new OperationFailureException(allowed); } final VolumeInventory volume = msg.getVolume(); extEmitter.preDetachVolume(getSelfInventory(), volume); extEmitter.beforeDetachVolume(getSelfInventory(), volume); if (self.getState() == VmInstanceState.Stopped) { extEmitter.afterDetachVolume(getSelfInventory(), volume); bus.reply(msg, reply); completion.done(); return; } // VmInstanceState.Running String hostUuid = self.getHostUuid(); DetachVolumeFromVmOnHypervisorMsg dmsg = new DetachVolumeFromVmOnHypervisorMsg(); dmsg.setVmInventory(VmInstanceInventory.valueOf(self)); dmsg.setInventory(volume); dmsg.setHostUuid(hostUuid); bus.makeTargetServiceIdByResourceUuid(dmsg, HostConstant.SERVICE_ID, hostUuid); bus.send(dmsg, new CloudBusCallBack(msg, completion) { @Override public void run(final MessageReply r) { if (!r.isSuccess()) { reply.setError(r.getError()); extEmitter.failedToDetachVolume(getSelfInventory(), volume, r.getError()); } else { extEmitter.afterDetachVolume(getSelfInventory(), volume); } bus.reply(msg, reply); completion.done(); } }); } protected void attachDataVolume(final AttachDataVolumeToVmMsg msg, final NoErrorCompletion completion) { final AttachDataVolumeToVmReply reply = new AttachDataVolumeToVmReply(); refreshVO(); ErrorCode err = validateOperationByState(msg, self.getState(), VmErrors.ATTACH_VOLUME_ERROR); if (err != null) { throw new OperationFailureException(err); } final VolumeInventory volume = msg.getVolume(); new VmAttachVolumeValidator().validate(msg.getVmInstanceUuid(), volume.getUuid()); extEmitter.preAttachVolume(getSelfInventory(), volume); extEmitter.beforeAttachVolume(getSelfInventory(), volume); VmInstanceSpec spec = new VmInstanceSpec(); spec.setMessage(msg); spec.setVmInventory(VmInstanceInventory.valueOf(self)); spec.setCurrentVmOperation(VmOperation.AttachVolume); spec.setDestDataVolumes(list(volume)); FlowChain chain; if (volume.getStatus().equals(VolumeStatus.Ready.toString())) { chain = FlowChainBuilder.newSimpleFlowChain(); chain.then(new VmAssignDeviceIdToAttachingVolumeFlow()); chain.then(new VmAttachVolumeOnHypervisorFlow()); } else { chain = getAttachUninstantiatedVolumeWorkFlowChain(spec.getVmInventory()); } setFlowMarshaller(chain); chain.setName(String.format("vm-%s-attach-volume-%s", self.getUuid(), volume.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(VmInstanceConstant.Params.AttachingVolumeInventory.toString(), volume); chain.done(new FlowDoneHandler(msg, completion) { @Override public void handle(Map data) { extEmitter.afterAttachVolume(getSelfInventory(), volume); reply.setHypervisorType(self.getHypervisorType()); bus.reply(msg, reply); completion.done(); } }).error(new FlowErrorHandler(msg, completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToAttachVolume(getSelfInventory(), volume, errCode); reply.setError(errf.instantiateErrorCode(VmErrors.ATTACH_VOLUME_ERROR, errCode)); bus.reply(msg, reply); completion.done(); } }).start(); } protected void migrateVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.MIGRATE_ERROR); if (allowed != null) { completion.fail(allowed); return; } VmInstanceInventory pinv = getSelfInventory(); for (VmPreMigrationExtensionPoint ext : pluginRgty.getExtensionList(VmPreMigrationExtensionPoint.class)) { ext.preVmMigration(pinv); } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Migrate); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.migrating); spec.setMessage(msg); FlowChain chain = getMigrateVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("migrate-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); HostInventory host = spec.getDestHost(); self.setZoneUuid(host.getZoneUuid()); self.setClusterUuid(host.getClusterUuid()); self.setLastHostUuid(self.getHostUuid()); self.setHostUuid(host.getUuid()); self = changeVmStateInDb(VmInstanceStateEvent.running); VmInstanceInventory vm = VmInstanceInventory.valueOf(self); extEmitter.afterMigrateVm(vm, vm.getLastHostUuid()); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToMigrateVm(VmInstanceInventory.valueOf(self), spec.getDestHost().getUuid(), errCode); if (HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void handle(final APIMigrateVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("migrate-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { migrateVm(msg, new Completion(chain) { @Override public void success() { APIMigrateVmEvent evt = new APIMigrateVmEvent(msg.getId()); evt.setInventory(VmInstanceInventory.valueOf(self)); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { APIMigrateVmEvent evt = new APIMigrateVmEvent(msg.getId()); evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } }); } protected void startVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } if (self.getState() == VmInstanceState.Created) { StartVmFromNewCreatedStruct struct = new JsonLabel().get( StartVmFromNewCreatedStruct.makeLabelKey(self.getUuid()), StartVmFromNewCreatedStruct.class); startVmFromNewCreate(struct, completion); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preStart = extEmitter.preStartVm(inv); if (preStart != null) { completion.fail(preStart); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Start); spec.setMessage(msg); if (msg instanceof APIStartVmInstanceMsg) { APIStartVmInstanceMsg amsg = (APIStartVmInstanceMsg) msg; spec.setRequiredClusterUuid(amsg.getClusterUuid()); spec.setRequiredHostUuid(amsg.getHostUuid()); spec.setUsbRedirect(VmSystemTags.USB_REDIRECT.getTokenByResourceUuid(self.getUuid(), VmSystemTags.USB_REDIRECT_TOKEN)); spec.setEnableRDP(VmSystemTags.RDP_ENABLE.getTokenByResourceUuid(self.getUuid(), VmSystemTags.RDP_ENABLE_TOKEN)); spec.setVDIMonitorNumber(VmSystemTags.VDI_MONITOR_NUMBER.getTokenByResourceUuid(self.getUuid(), VmSystemTags.VDI_MONITOR_NUMBER_TOKEN)); } if (spec.getDestNics().isEmpty()) { throw new OperationFailureException(operr("unable to start the vm[uuid:%s]." + " It doesn't have any nic, please attach a nic and try again", self.getUuid())); } final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.starting); extEmitter.beforeStartVm(VmInstanceInventory.valueOf(self)); FlowChain chain = getStartVmWorkFlowChain(inv); setFlowMarshaller(chain); String recentHostUuid = self.getHostUuid() == null ? self.getLastHostUuid() : self.getHostUuid(); String vmHostUuid = self.getHostUuid(); String vmLastHostUuid = self.getLastHostUuid(); chain.setName(String.format("start-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); // reload self because some nics may have been deleted in start phase because a former L3Network deletion. // reload to avoid JPA EntityNotFoundException self = dbf.reload(self); self.setLastHostUuid(recentHostUuid); self.setHostUuid(spec.getDestHost().getUuid()); self.setClusterUuid(spec.getDestHost().getClusterUuid()); self.setZoneUuid(spec.getDestHost().getZoneUuid()); self = changeVmStateInDb(VmInstanceStateEvent.running); logger.debug(String.format("vm[uuid:%s] is running ..", self.getUuid())); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStartVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { // reload self because some nics may have been deleted in start phase because a former L3Network deletion. // reload to avoid JPA EntityNotFoundException self = dbf.reload(self); extEmitter.failedToStartVm(VmInstanceInventory.valueOf(self), errCode); VmInstanceSpec spec = (VmInstanceSpec) data.get(Params.VmInstanceSpec.toString()); if (HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(spec.getDestHost().getUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self.setHostUuid(vmHostUuid); self.setLastHostUuid(vmLastHostUuid); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } private void startVmFromNewCreate(StartVmFromNewCreatedStruct struct, Completion completion) { VmInstanceInventory inv = getSelfInventory(); final VmInstanceSpec spec = new VmInstanceSpec(); spec.setRequiredPrimaryStorageUuidForRootVolume(struct.getPrimaryStorageUuidForRootVolume()); spec.setRequiredPrimaryStorageUuidForDataVolume(struct.getPrimaryStorageUuidForDataVolume()); spec.setVmInventory(inv); if (struct.getL3NetworkUuids() != null && !struct.getL3NetworkUuids().isEmpty()) { SimpleQuery<L3NetworkVO> nwquery = dbf.createQuery(L3NetworkVO.class); nwquery.add(L3NetworkVO_.uuid, Op.IN, struct.getL3NetworkUuids()); List<L3NetworkVO> vos = nwquery.list(); List<L3NetworkInventory> nws = L3NetworkInventory.valueOf(vos); // order L3 networks by the order they specified in the API List<L3NetworkInventory> l3s = new ArrayList<>(nws.size()); for (final String l3Uuid : struct.getL3NetworkUuids()) { L3NetworkInventory l3 = CollectionUtils.find(nws, new Function<L3NetworkInventory, L3NetworkInventory>() { @Override public L3NetworkInventory call(L3NetworkInventory arg) { return arg.getUuid().equals(l3Uuid) ? arg : null; } }); if(l3 == null){ completion.fail(err( SysErrors.OPERATION_ERROR, "Unable to find L3Network[uuid:%s] to start the current vm, it may have been deleted, Operation suggestion: delete this vm, recreate a new vm", l3Uuid)); return; } DebugUtils.Assert(l3 != null, "where is the L3???"); l3s.add(l3); } spec.setL3Networks(l3s); } else { spec.setL3Networks(new ArrayList<>()); } if (struct.getDataDiskOfferingUuids() != null && !struct.getDataDiskOfferingUuids().isEmpty()) { SimpleQuery<DiskOfferingVO> dquery = dbf.createQuery(DiskOfferingVO.class); dquery.add(DiskOfferingVO_.uuid, SimpleQuery.Op.IN, struct.getDataDiskOfferingUuids()); List<DiskOfferingVO> vos = dquery.list(); // allow create multiple data volume from the same disk offering List<DiskOfferingInventory> disks = new ArrayList<>(); for (final String duuid : struct.getDataDiskOfferingUuids()) { DiskOfferingVO dvo = CollectionUtils.find(vos, new Function<DiskOfferingVO, DiskOfferingVO>() { @Override public DiskOfferingVO call(DiskOfferingVO arg) { if (duuid.equals(arg.getUuid())) { return arg; } return null; } }); disks.add(DiskOfferingInventory.valueOf(dvo)); } spec.setDataDiskOfferings(disks); } else { spec.setDataDiskOfferings(new ArrayList<>()); } if (struct.getRootDiskOfferingUuid() != null) { DiskOfferingVO rootDisk = dbf.findByUuid(struct.getRootDiskOfferingUuid(), DiskOfferingVO.class); spec.setRootDiskOffering(DiskOfferingInventory.valueOf(rootDisk)); } ImageVO imvo = dbf.findByUuid(spec.getVmInventory().getImageUuid(), ImageVO.class); if (imvo.getMediaType() == ImageMediaType.ISO) { new IsoOperator().attachIsoToVm(self.getUuid(), imvo.getUuid()); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(imvo.getUuid()); spec.setDestIso(isoSpec); } spec.getImageSpec().setInventory(ImageInventory.valueOf(imvo)); spec.setCurrentVmOperation(VmOperation.NewCreate); if (self.getClusterUuid() != null || self.getHostUuid() != null) { spec.setHostAllocatorStrategy(HostAllocatorConstant.DESIGNATED_HOST_ALLOCATOR_STRATEGY_TYPE); } buildHostname(spec); spec.setUserdata(buildUserdata()); selectBootOrder(spec); spec.setConsolePassword(VmSystemTags.CONSOLE_PASSWORD. getTokenByResourceUuid(self.getUuid(), VmSystemTags.CONSOLE_PASSWORD_TOKEN)); spec.setUsbRedirect(VmSystemTags.USB_REDIRECT.getTokenByResourceUuid(self.getUuid(), VmSystemTags.USB_REDIRECT_TOKEN)); changeVmStateInDb(VmInstanceStateEvent.starting); CollectionUtils.safeForEach(pluginRgty.getExtensionList(BeforeStartNewCreatedVmExtensionPoint.class), new ForEachFunction<BeforeStartNewCreatedVmExtensionPoint>() { @Override public void run(BeforeStartNewCreatedVmExtensionPoint ext) { ext.beforeStartNewCreatedVm(spec); } }); extEmitter.beforeStartNewCreatedVm(VmInstanceInventory.valueOf(self)); FlowChain chain = getCreateVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("create-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); self.setLastHostUuid(spec.getDestHost().getUuid()); self.setHostUuid(spec.getDestHost().getUuid()); self.setClusterUuid(spec.getDestHost().getClusterUuid()); self.setZoneUuid(spec.getDestHost().getZoneUuid()); self.setHypervisorType(spec.getDestHost().getHypervisorType()); self.setRootVolumeUuid(spec.getDestRootVolume().getUuid()); changeVmStateInDb(VmInstanceStateEvent.running); logger.debug(String.format("vm[uuid:%s] is running ..", self.getUuid())); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStartNewCreatedVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToStartNewCreatedVm(VmInstanceInventory.valueOf(self), errCode); dbf.remove(self); // clean up EO, otherwise API-retry may cause conflict if // the resource uuid is set dbf.eoCleanup(VmInstanceVO.class); completion.fail(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, errCode)); } }).start(); } protected void startVm(final StartVmInstanceMsg msg, final SyncTaskChain taskChain) { startVm(msg, new Completion(taskChain) { @Override public void success() { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); StartVmInstanceReply reply = new StartVmInstanceReply(); reply.setInventory(inv); bus.reply(msg, reply); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { StartVmInstanceReply reply = new StartVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.START_ERROR, errorCode)); bus.reply(msg, reply); taskChain.next(); } }); } protected void startVm(final APIStartVmInstanceMsg msg, final SyncTaskChain taskChain) { startVm(msg, new Completion(taskChain) { @Override public void success() { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); APIStartVmInstanceEvent evt = new APIStartVmInstanceEvent(msg.getId()); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIStartVmInstanceEvent evt = new APIStartVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.START_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void handle(final APIStartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("start-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVm(msg, chain); } }); } protected void handle(final APIDestroyVmInstanceMsg msg) { final APIDestroyVmInstanceEvent evt = new APIDestroyVmInstanceEvent(msg.getId()); destroyVm(msg, new Completion(msg) { @Override public void success() { bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); } }); } private void destroyVm(APIDestroyVmInstanceMsg msg, final Completion completion) { final String issuer = VmInstanceVO.class.getSimpleName(); final List<VmDeletionStruct> ctx = new ArrayList<VmDeletionStruct>(); VmDeletionStruct s = new VmDeletionStruct(); s.setInventory(getSelfInventory()); s.setDeletionPolicy(deletionPolicyMgr.getDeletionPolicy(self.getUuid())); ctx.add(s); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("delete-vm-%s", msg.getUuid())); if (msg.getDeletionMode() == APIDeleteMessage.DeletionMode.Permissive) { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_CHECK_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } else { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } chain.done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion()); completion.success(); } }).error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errf.instantiateErrorCode(SysErrors.DELETE_RESOURCE_ERROR, errCode)); } }).start(); } protected void buildHostname(VmInstanceSpec spec) { String defaultHostname = VmSystemTags.HOSTNAME.getTag(self.getUuid()); if (defaultHostname == null) { return; } HostName dhname = new HostName(); dhname.setL3NetworkUuid(self.getDefaultL3NetworkUuid()); dhname.setHostname(VmSystemTags.HOSTNAME.getTokenByTag(defaultHostname, VmSystemTags.HOSTNAME_TOKEN)); spec.getHostnames().add(dhname); } protected VmInstanceSpec buildSpecFromInventory(VmInstanceInventory inv, VmOperation operation) { VmInstanceSpec spec = new VmInstanceSpec(); spec.setUserdata(buildUserdata()); // for L3Network that has been deleted List<String> nicUuidToDel = CollectionUtils.transformToList(inv.getVmNics(), new Function<String, VmNicInventory>() { @Override public String call(VmNicInventory arg) { return arg.getL3NetworkUuid() == null ? arg.getUuid() : null; } }); if (!nicUuidToDel.isEmpty()) { dbf.removeByPrimaryKeys(nicUuidToDel, VmNicVO.class); self = dbf.findByUuid(inv.getUuid(), VmInstanceVO.class); inv = VmInstanceInventory.valueOf(self); } spec.setDestNics(inv.getVmNics()); List<String> l3Uuids = CollectionUtils.transformToList(inv.getVmNics(), new Function<String, VmNicInventory>() { @Override public String call(VmNicInventory arg) { return arg.getL3NetworkUuid(); } }); spec.setL3Networks(L3NetworkInventory.valueOf(dbf.listByPrimaryKeys(l3Uuids, L3NetworkVO.class))); String huuid = inv.getHostUuid() == null ? inv.getLastHostUuid() : inv.getHostUuid(); if (huuid != null) { HostVO hvo = dbf.findByUuid(huuid, HostVO.class); if (hvo != null) { spec.setDestHost(HostInventory.valueOf(hvo)); } } List<VolumeInventory> dataVols = new ArrayList<VolumeInventory>(); for (VolumeInventory vol : inv.getAllVolumes()) { if (vol.getUuid().equals(inv.getRootVolumeUuid())) { spec.setDestRootVolume(vol); spec.setRequiredPrimaryStorageUuidForRootVolume(vol.getPrimaryStorageUuid()); } else { dataVols.add(vol); } } List<BuildVolumeSpecExtensionPoint> exts = pluginRgty.getExtensionList( BuildVolumeSpecExtensionPoint.class); String vmUuid = inv.getUuid(); exts.forEach(e -> dataVols.addAll(e.supplyAdditionalVolumesForVmInstance(vmUuid))); spec.setDestDataVolumes(dataVols); // When starting an imported VM, we might not have an image UUID. if (inv.getImageUuid() != null) { ImageVO imgvo = dbf.findByUuid(inv.getImageUuid(), ImageVO.class); ImageInventory imginv = null; if (imgvo == null) { // the image has been deleted, use EO instead ImageEO imgeo = dbf.findByUuid(inv.getImageUuid(), ImageEO.class); imginv = ImageInventory.valueOf(imgeo); } else { imginv = ImageInventory.valueOf(imgvo); } spec.getImageSpec().setInventory(imginv); } spec.setVmInventory(inv); buildHostname(spec); String isoUuid = new IsoOperator().getIsoUuidByVmUuid(inv.getUuid()); if (isoUuid != null) { if (dbf.isExist(isoUuid, ImageVO.class)) { IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); } else { //TODO logger.warn(String.format("iso[uuid:%s] is deleted, however, the VM[uuid:%s] still has it attached", isoUuid, self.getUuid())); } } spec.setCurrentVmOperation(operation); selectBootOrder(spec); spec.setConsolePassword(VmSystemTags.CONSOLE_PASSWORD. getTokenByResourceUuid(self.getUuid(), VmSystemTags.CONSOLE_PASSWORD_TOKEN)); return spec; } protected void rebootVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preReboot = extEmitter.preRebootVm(inv); if (preReboot != null) { completion.fail(preReboot); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Reboot); spec.setDestHost(HostInventory.valueOf(dbf.findByUuid(self.getHostUuid(), HostVO.class))); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.rebooting); extEmitter.beforeRebootVm(VmInstanceInventory.valueOf(self)); spec.setMessage(msg); FlowChain chain = getRebootVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("reboot-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { self = changeVmStateInDb(VmInstanceStateEvent.running); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterRebootVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToRebootVm(VmInstanceInventory.valueOf(self), errCode); if (HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR.isEqual(errCode.getCode()) || HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void rebootVm(final APIRebootVmInstanceMsg msg, final SyncTaskChain taskChain) { rebootVm(msg, new Completion(taskChain) { @Override public void success() { APIRebootVmInstanceEvent evt = new APIRebootVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIRebootVmInstanceEvent evt = new APIRebootVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.REBOOT_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void handle(final APIRebootVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("reboot-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { rebootVm(msg, chain); } }); } protected void stopVm(final APIStopVmInstanceMsg msg, final SyncTaskChain taskChain) { stopVm(msg, new Completion(taskChain) { @Override public void success() { APIStopVmInstanceEvent evt = new APIStopVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIStopVmInstanceEvent evt = new APIStopVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.STOP_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } private void stopVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } if (self.getState() == VmInstanceState.Stopped) { completion.success(); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preStop = extEmitter.preStopVm(inv); if (preStop != null) { completion.fail(preStop); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Stop); spec.setMessage(msg); if (msg instanceof StopVmInstanceMsg) { spec.setGcOnStopFailure(((StopVmInstanceMsg) msg).isGcOnFailure()); } final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.stopping); extEmitter.beforeStopVm(VmInstanceInventory.valueOf(self)); FlowChain chain = getStopVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("stop-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { self.setLastHostUuid(self.getHostUuid()); self.setHostUuid(null); self = changeVmStateInDb(VmInstanceStateEvent.stopped); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStopVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.failedToStopVm(inv, errCode); if (HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void handle(final APIStopVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("stop-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { stopVm(msg, chain); } }); } protected void pauseVm(final APIPauseVmInstanceMsg msg, final SyncTaskChain taskChain) { pauseVm(msg, new Completion(taskChain) { @Override public void success() { APIPauseVmInstanceEvent evt = new APIPauseVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIPauseVmInstanceEvent evt = new APIPauseVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.SUSPEND_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void pauseVm(final Message msg, Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } if (self.getState() == VmInstanceState.Paused) { completion.success(); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Pause); spec.setMessage(msg); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.pausing); FlowChain chain = getPauseVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("pause-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map Data) { self = changeVmStateInDb(VmInstanceStateEvent.paused); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } }).start(); } protected void handle(final APIPauseVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { pauseVm(msg, chain); } @Override public String getName() { return String.format("pause-vm-%s", msg.getVmInstanceUuid()); } }); } protected void resumeVm(final APIResumeVmInstanceMsg msg, final SyncTaskChain taskChain) { resumeVm(msg, new Completion(taskChain) { @Override public void success() { APIResumeVmInstanceEvent evt = new APIResumeVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIResumeVmInstanceEvent evt = new APIResumeVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.RESUME_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void resumeVm(final Message msg, Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Resume); spec.setMessage(msg); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.resuming); FlowChain chain = getResumeVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("resume-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map Data) { self = changeVmStateInDb(VmInstanceStateEvent.running); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } }).start(); } protected void handle(final APIResumeVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { resumeVm(msg, chain); } @Override public String getName() { return String.format("resume-vm-%s", msg.getVmInstanceUuid()); } }); } private void handle(final APIReimageVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { reimageVmInstance(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "reimage-vminstance"; } }); } private void reimageVmInstance(final APIReimageVmInstanceMsg msg, NoErrorCompletion completion) { final APIReimageVmInstanceEvent evt = new APIReimageVmInstanceEvent(msg.getId()); String rootVolumeUuid = Q.New(VmInstanceVO.class).select(VmInstanceVO_.rootVolumeUuid) .eq(VmInstanceVO_.uuid, msg.getVmInstanceUuid()) .findValue(); ReimageVmInstanceMsg rmsg = new ReimageVmInstanceMsg(); rmsg.setVmInstanceUuid(msg.getVmInstanceUuid()); rmsg.setAccountUuid(msg.getSession().getAccountUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, VmInstanceConstant.SERVICE_ID, msg.getVmInstanceUuid()); ReimageVolumeOverlayMsg omsg = new ReimageVolumeOverlayMsg(); omsg.setMessage(rmsg); omsg.setVolumeUuid(rootVolumeUuid); bus.makeTargetServiceIdByResourceUuid(omsg, VolumeConstant.SERVICE_ID, rootVolumeUuid); bus.send(omsg, new CloudBusCallBack(completion, evt) { @Override public void run(MessageReply reply) { if (reply.isSuccess()){ self = refreshVO(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); } else { evt.setError(reply.getError()); bus.publish(evt); } completion.done(); } }); } private void handle(ReimageVmInstanceMsg msg){ ReimageVmInstanceReply reply = new ReimageVmInstanceReply(); self = refreshVO(); VolumeVO rootVolume = dbf.findByUuid(self.getRootVolumeUuid(), VolumeVO.class); VolumeInventory rootVolumeInventory = VolumeInventory.valueOf(rootVolume); // check vm stopped { if (self.getState() != VmInstanceState.Stopped) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode( VmErrors.RE_IMAGE_VM_NOT_IN_STOPPED_STATE, String.format("unable to reset volume[uuid:%s] to origin image[uuid:%s]," + " the vm[uuid:%s] volume attached to is not in Stopped state, current state is %s", rootVolume.getUuid(), rootVolume.getRootImageUuid(), rootVolume.getVmInstanceUuid(), self.getState()) )); } } // check image cache to ensure image type is not ISO { SimpleQuery<ImageCacheVO> q = dbf.createQuery(ImageCacheVO.class); q.select(ImageCacheVO_.mediaType); q.add(ImageCacheVO_.imageUuid, Op.EQ, rootVolume.getRootImageUuid()); q.setLimit(1); ImageMediaType imageMediaType = q.findValue(); if (imageMediaType == null) { throw new OperationFailureException(errf.instantiateErrorCode( VmErrors.RE_IMAGE_CANNOT_FIND_IMAGE_CACHE, String.format("unable to reset volume[uuid:%s] to origin image[uuid:%s]," + " cannot find image cache.", rootVolume.getUuid(), rootVolume.getRootImageUuid()) )); } if (imageMediaType.toString().equals("ISO")) { throw new OperationFailureException(errf.instantiateErrorCode( VmErrors.RE_IMAGE_IMAGE_MEDIA_TYPE_SHOULD_NOT_BE_ISO, String.format("unable to reset volume[uuid:%s] to origin image[uuid:%s]," + " for image type is ISO", rootVolume.getUuid(), rootVolume.getRootImageUuid()) )); } } // do the re-image op FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("reset-root-volume-%s-from-image-%s", rootVolume.getUuid(), rootVolume.getRootImageUuid())); chain.then(new ShareFlow() { String newVolumeInstallPath; @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "mark-root-volume-as-snapshot-on-primary-storage"; @Override public void run(final FlowTrigger trigger, Map data) { MarkRootVolumeAsSnapshotMsg gmsg = new MarkRootVolumeAsSnapshotMsg(); rootVolumeInventory.setDescription(String.format("save snapshot for reimage vm [uuid:%s]", msg.getVmInstanceUuid())); rootVolumeInventory.setName("reimage-vm-point"); gmsg.setVolume(rootVolumeInventory); gmsg.setAccountUuid(msg.getAccountUuid()); bus.makeLocalServiceId(gmsg, VolumeSnapshotConstant.SERVICE_ID); bus.send(gmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { trigger.next(); } else { trigger.fail(reply.getError()); } } }); } }); flow(new NoRollbackFlow() { String __name__ = "reset-root-volume-from-image-on-primary-storage"; @Override public void run(final FlowTrigger trigger, Map data) { ReInitRootVolumeFromTemplateOnPrimaryStorageMsg rmsg = new ReInitRootVolumeFromTemplateOnPrimaryStorageMsg(); rmsg.setVolume(rootVolumeInventory); bus.makeTargetServiceIdByResourceUuid(rmsg, PrimaryStorageConstant.SERVICE_ID, rootVolumeInventory.getPrimaryStorageUuid()); bus.send(rmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { ReInitRootVolumeFromTemplateOnPrimaryStorageReply re = (ReInitRootVolumeFromTemplateOnPrimaryStorageReply) reply; newVolumeInstallPath = re.getNewVolumeInstallPath(); trigger.next(); } else { trigger.fail(reply.getError()); } } }); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { rootVolume.setInstallPath(newVolumeInstallPath); dbf.update(rootVolume); List<AfterReimageVmInstanceExtensionPoint> list = pluginRgty.getExtensionList( AfterReimageVmInstanceExtensionPoint.class); for (AfterReimageVmInstanceExtensionPoint ext : list) { ext.afterReimageVmInstance(rootVolumeInventory); } self = dbf.reload(self); bus.reply(msg, reply); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { logger.warn(String.format("failed to restore volume[uuid:%s] to image[uuid:%s], %s", rootVolumeInventory.getUuid(), rootVolumeInventory.getRootImageUuid(), errCode)); reply.setError(errCode); bus.reply(msg, reply); } }); } }).start(); } private void handle(OverlayMessage msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { doOverlayMessage(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "overlay-message"; } }); } private void doOverlayMessage(OverlayMessage msg, NoErrorCompletion noErrorCompletion) { bus.send(msg.getMessage(), new CloudBusCallBack(msg, noErrorCompletion) { @Override public void run(MessageReply reply) { bus.reply(msg, reply); noErrorCompletion.done(); } }); } }
package org.spine3.protobuf; import com.google.protobuf.Any; import com.google.protobuf.Message; import org.spine3.ClassName; import org.spine3.TypeName; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Utility class for reading real proto class names from properties file. * * @author Mikhail Mikhaylov * @author Alexander Yevsyukov */ @SuppressWarnings("UtilityClass") public class TypeToClassMap { private static final char CLASS_PACKAGE_DELIMITER = '.'; /** * File, containing Protobuf messages' typeUrls and their appropriate class names. * Is generated with Gradle during build process. */ private static final String PROPERTIES_FILE_NAME = "protos.properties"; private static final Map<TypeName, ClassName> namesMap = new HashMap<>(); static { Properties properties = new Properties(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream resourceStream = classLoader.getResourceAsStream(PROPERTIES_FILE_NAME); try { properties.load(resourceStream); } catch (IOException e) { //NOP } for (String key : properties.stringPropertyNames()) { final TypeName typeName = TypeName.of(key); final ClassName className = ClassName.of(properties.getProperty(key)); namesMap.put(typeName, className); } } private TypeToClassMap() { } /** * Retrieves compiled proto's java class name by proto type url * to be used to parse {@link Message} from {@link Any}. * * @param protoType {@link Any} type url * @return Java class name */ public static ClassName get(TypeName protoType) { if (!namesMap.containsKey(protoType)) { final ClassName className = searchAsSubclass(protoType); namesMap.put(protoType, className); } final ClassName result = namesMap.get(protoType); return result; } private static ClassName searchAsSubclass(TypeName lookupTypeName) { String lookupType = lookupTypeName.value(); ClassName className = null; final StringBuilder suffix = new StringBuilder(lookupType.length()); int lastDotPosition = lookupType.lastIndexOf(CLASS_PACKAGE_DELIMITER); while (className == null && lastDotPosition != -1) { suffix.insert(0, lookupType.substring(lastDotPosition)); lookupType = lookupType.substring(0, lastDotPosition); final TypeName typeName = TypeName.of(lookupType); className = namesMap.get(typeName); lastDotPosition = lookupType.lastIndexOf(CLASS_PACKAGE_DELIMITER); } if (className == null) { throw new UnknownTypeInAnyException(lookupTypeName.value()); } className = ClassName.of(className.value() + suffix); try { Class.forName(className.value()); } catch (ClassNotFoundException e) { //noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException throw new UnknownTypeInAnyException(lookupTypeName.value()); } return className; } private static ClassName searchClassNameRecursively(String lookupType, StringBuilder currentSuffix) { final int lastDotPosition = lookupType.lastIndexOf(CLASS_PACKAGE_DELIMITER); if (lastDotPosition == -1) { return null; } String rootType = lookupType.substring(0, lastDotPosition); currentSuffix.insert(0, lookupType.substring(lastDotPosition)); final TypeName rootTypeName = TypeName.of(rootType); if (namesMap.get(rootTypeName) == null) { return searchClassNameRecursively(lookupType, currentSuffix); } return ClassName.of(rootType + currentSuffix); } }
package alluxio.client.file; import alluxio.Constants; import alluxio.annotation.PublicApi; import alluxio.client.AlluxioStorageType; import alluxio.client.BoundedStream; import alluxio.client.Seekable; import alluxio.client.block.BlockInStream; import alluxio.client.block.BufferedBlockOutStream; import alluxio.client.block.LocalBlockInStream; import alluxio.client.block.RemoteBlockInStream; import alluxio.client.block.UnderStoreBlockInStream; import alluxio.client.file.options.InStreamOptions; import alluxio.client.file.policy.FileWriteLocationPolicy; import alluxio.exception.AlluxioException; import alluxio.exception.BlockAlreadyExistsException; import alluxio.exception.PreconditionMessage; import alluxio.master.block.BlockId; import alluxio.wire.BlockInfo; import alluxio.wire.BlockLocation; import alluxio.wire.WorkerNetAddress; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import javax.annotation.concurrent.NotThreadSafe; /** * A streaming API to read a file. This API represents a file as a stream of bytes and provides a * collection of {@link #read} methods to access this stream of bytes. In addition, one can seek * into a given offset of the stream to read. * <p> * This class wraps the {@link BlockInStream} for each of the blocks in the file and abstracts the * switching between streams. The backing streams can read from Alluxio space in the local machine, * remote machines, or the under storage system. */ @PublicApi @NotThreadSafe public class FileInStream extends InputStream implements BoundedStream, Seekable { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); /** How the data should be written into Alluxio space, if at all. */ protected final AlluxioStorageType mAlluxioStorageType; /** Standard block size in bytes of the file, guaranteed for all but the last block. */ protected final long mBlockSize; /** The location policy for CACHE type of read into Alluxio. */ protected final FileWriteLocationPolicy mLocationPolicy; /** Total length of the file in bytes. */ protected final long mFileLength; /** File System context containing the {@link FileSystemMasterClient} pool. */ protected final FileSystemContext mContext; /** File information. */ protected URIStatus mStatus; /** Constant error message for block ID not cached. */ protected static final String BLOCK_ID_NOT_CACHED = "The block with ID {} could not be cached into Alluxio storage."; /** Error message for cache collision. */ private static final String BLOCK_ID_EXISTS_SO_NOT_CACHED = "The block with ID {} is already stored in the target worker, canceling the cache request."; /** If the stream is closed, this can only go from false to true. */ protected boolean mClosed; /** * Current position of the file instream. This is not always sync-ed with block instream or * cache outstream internally. */ protected long mPos; /** Include partially read blocks if Alluxio is configured to store blocks in Alluxio storage. */ private final boolean mShouldCachePartiallyReadBlock; /** Whether to cache blocks in this file into Alluxio. */ private final boolean mShouldCache; // The following 3 fields must be kept in sync. They are only updated in updateStreams together. /** Current {@link BlockInStream} backing this stream. */ protected BlockInStream mCurrentBlockInStream; /** Current {@link BufferedBlockOutStream} writing the data into Alluxio. */ protected BufferedBlockOutStream mCurrentCacheStream; /** The blockId used in the block streams. */ private long mStreamBlockId; /** * Creates a new file input stream. * * @param status the file status * @param options the client options * @return the created {@link FileInStream} instance */ public static FileInStream create(URIStatus status, InStreamOptions options) { if (status.getLength() == Constants.UNKNOWN_SIZE) { return new UnknownLengthFileInStream(status, options); } return new FileInStream(status, options); } /** * Creates a new file input stream. * * @param status the file status * @param options the client options */ protected FileInStream(URIStatus status, InStreamOptions options) { mStatus = status; mBlockSize = status.getBlockSizeBytes(); mFileLength = status.getLength(); mContext = FileSystemContext.INSTANCE; mAlluxioStorageType = options.getAlluxioStorageType(); mShouldCache = mAlluxioStorageType.isStore(); mShouldCachePartiallyReadBlock = options.isCachePartiallyReadBlock(); mClosed = false; mLocationPolicy = options.getLocationPolicy(); if (mShouldCache) { Preconditions.checkNotNull(options.getLocationPolicy(), PreconditionMessage.FILE_WRITE_LOCATION_POLICY_UNSPECIFIED); } } @Override public void close() throws IOException { if (mClosed) { return; } updateStreams(); if (mCurrentCacheStream != null && mShouldCachePartiallyReadBlock) { readCurrentBlockToPos(mFileLength); } if (mCurrentBlockInStream != null) { mCurrentBlockInStream.close(); } closeOrCancelCacheStream(); mClosed = true; } @Override public int read() throws IOException { if (!validPosition(mPos)) { return -1; } updateStreams(); Preconditions.checkState(mCurrentBlockInStream != null, "Reached EOF unexpectedly."); int data = mCurrentBlockInStream.read(); // This should not happen? if (data == -1) { // The underlying stream is done. return -1; } mPos++; if (mCurrentCacheStream != null) { try { mCurrentCacheStream.write(data); } catch (IOException e) { logCacheStreamIOException(e); closeOrCancelCacheStream(); } } return data; } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { Preconditions.checkArgument(b != null, PreconditionMessage.ERR_READ_BUFFER_NULL); Preconditions.checkArgument(off >= 0 && len >= 0 && len + off <= b.length, PreconditionMessage.ERR_BUFFER_STATE, b.length, off, len); if (len == 0) { return 0; } else if (!validPosition(mPos)) { return -1; } int currentOffset = off; int bytesLeftToRead = len; while (bytesLeftToRead > 0 && validPosition(mPos)) { updateStreams(); if (mCurrentBlockInStream == null) { // EOF is reached. break; } int bytesToRead = (int) Math.min(bytesLeftToRead, mCurrentBlockInStream.remaining()); Preconditions.checkState(bytesToRead > 0); int bytesRead = mCurrentBlockInStream.read(b, currentOffset, bytesToRead); if (bytesRead > 0) { if (mCurrentCacheStream != null) { try { mCurrentCacheStream.write(b, currentOffset, bytesRead); } catch (IOException e) { logCacheStreamIOException(e); closeOrCancelCacheStream(); } } mPos += bytesRead; bytesLeftToRead -= bytesRead; currentOffset += bytesRead; } } if (bytesLeftToRead == len && mCurrentBlockInStream.remaining() == 0) { // Nothing was read, and the underlying stream is done. return -1; } return len - bytesLeftToRead; } @Override public long remaining() { return mFileLength - mPos; } @Override public void seek(long pos) throws IOException { if (mPos == pos) { return; } Preconditions.checkArgument(pos >= 0, PreconditionMessage.ERR_SEEK_NEGATIVE, pos); // Why cannot I seek to the end of a file? Preconditions.checkArgument(validPosition(pos), PreconditionMessage.ERR_SEEK_PAST_END_OF_FILE, pos); if (!mShouldCachePartiallyReadBlock) { seekInternal(pos); } else { seekInternalWithCachingPartiallyReadBlock(pos); } } @Override public long skip(long n) throws IOException { if (n <= 0) { return 0; } /** * TODO(peis): Figure this out with Calvin or whoever wrote this. * The current implementation looks strange to me. I think it indents to skip n bytes for * caching. I think it should either be implemented the same as seek or read. */ /* long toSkip = Math.min(n, remaining()); long newPos = mPos + toSkip; long toSkipInBlock = ((newPos / mBlockSize) > mPos / mBlockSize) ? newPos % mBlockSize : toSkip; seekBlockInStream(newPos); checkAndAdvanceBlockInStream(); if (toSkipInBlock != mCurrentBlockInStream.skip(toSkipInBlock)) { throw new IOException(ExceptionMessage.INSTREAM_CANNOT_SKIP.getMessage(toSkip)); } return toSkip; */ long toSkip = Math.min(n, remaining()); closeOrCancelCacheStream(); mPos = mPos + toSkip; updateStreams(); mCurrentBlockInStream.seek(mPos % mBlockSize); return toSkip; } /** * @param pos the position to check to validity * @return true of the given pos is a valid position in the file */ protected boolean validPosition(long pos) { return pos < mFileLength; } /** * @param pos the position to check * @return the block size in bytes for the given pos, used for worker allocation */ protected long getBlockSizeAllocation(long pos) { return getBlockSize(pos); } /** * Creates and returns a {@link BlockInStream} for the UFS. * * @param blockStart the offset to start the block from * @param length the length of the block * @param path the UFS path * @return the {@link BlockInStream} for the UFS * @throws IOException if the stream cannot be created */ protected BlockInStream createUnderStoreBlockInStream(long blockStart, long length, String path) throws IOException { return new UnderStoreBlockInStream(blockStart, length, mBlockSize, path); } /** * @param pos the position to get the block size for * @return the size of the current block */ protected long getBlockSize(long pos) { // The size of the last block, 0 if it is equal to the normal block size long lastBlockSize = mFileLength % mBlockSize; // If we are not in the last block or if the last block is equal to the normal block size, // return the normal block size. Otherwise return the block size of the last block. if (mFileLength - pos > lastBlockSize) { return mBlockSize; } else { return lastBlockSize; } } /** * Check whether block instream and cache outstream should be updated. * This function is only called by {@link #updateStreams()}. * * @param currentBlockId cached result of {@link #getCurrentBlockId()} * @return true if the block stream should be updated */ protected boolean shouldUpdateStreams(long currentBlockId) { if (mCurrentBlockInStream == null || currentBlockId != mStreamBlockId) { return true; } if (mCurrentCacheStream != null) { Preconditions.checkState(mCurrentBlockInStream.remaining() == mCurrentCacheStream.remaining(), "BlockInStream and CacheStream is not sync-ed %d %d", mCurrentBlockInStream.remaining(), mCurrentCacheStream.remaining()); } return mCurrentBlockInStream.remaining() == 0; } /** * Close or cancel {@link #mCurrentCacheStream}. * * @throws IOException if the close or cancel fails */ private void closeOrCancelCacheStream() throws IOException { if (mCurrentCacheStream == null) { return; } if (mCurrentCacheStream.remaining() == 0) { mCurrentCacheStream.close(); } else { mCurrentCacheStream.cancel(); } mCurrentCacheStream = null; } /** * @return the current block id based on mPos, -1 if at the end of the file */ private long getCurrentBlockId() { if (!validPosition(mPos)) { return -1; } int index = (int) (mPos / mBlockSize); Preconditions .checkState(index < mStatus.getBlockIds().size(), PreconditionMessage.ERR_BLOCK_INDEX); return mStatus.getBlockIds().get(index); } /** * Logs IO exceptions thrown in response to the worker cache request. If the exception is not an * expected exception, a warning will be logged with the stack trace. */ private void logCacheStreamIOException(IOException e) { if (e.getCause() instanceof BlockAlreadyExistsException) { LOG.warn(BLOCK_ID_EXISTS_SO_NOT_CACHED, getCurrentBlockId()); } else { LOG.warn(BLOCK_ID_NOT_CACHED, getCurrentBlockId(), e); } } /** * Only updates {@link #mCurrentCacheStream}, {@link #mCurrentBlockInStream} and * {@link #mStreamBlockId} to be in-sync the current block (i.e. {@link #getCurrentBlockId()}). * This function can be called multiple times without side effect. It is recommended to be * invoked before every read and seek. * * @throws IOException if the next cache stream or block stream cannot be created */ private void updateStreams() throws IOException { long currentBlockId = getCurrentBlockId(); if (shouldUpdateStreams(currentBlockId)) { // The following two function handle negative currentBlockId (i.e. the end of file) // correctly. updateBlockInStream(currentBlockId); updateCacheStream(currentBlockId); mStreamBlockId = currentBlockId; } } private void updateCacheStream(long blockId) throws IOException { // We should really only close a cache stream here. This check is to verify this. Preconditions.checkState(mCurrentCacheStream == null || mCurrentCacheStream.remaining() == 0); closeOrCancelCacheStream(); Preconditions.checkState(mCurrentCacheStream == null); if (blockId < 0) { // End of file. return; } Preconditions.checkNotNull(mCurrentBlockInStream); if (!mShouldCache || mCurrentBlockInStream instanceof LocalBlockInStream) { return; } // Unlike updateBlockInStream below, we never start a block cache stream if mPos is in the // middle of a block. if (mPos % mBlockSize != 0) { return; } try { WorkerNetAddress address = mLocationPolicy.getWorkerForNextBlock( mContext.getAlluxioBlockStore().getWorkerInfoList(), getBlockSizeAllocation(mPos)); // Don't cache the block to somewhere that already has it. // TODO(andrew,peis): Filter the workers provided to the location policy to not include // workers which already contain the block. See ALLUXIO-1816. if (mCurrentBlockInStream instanceof RemoteBlockInStream) { WorkerNetAddress readAddress = ((RemoteBlockInStream) mCurrentBlockInStream).getWorkerNetAddress(); // Try to avoid an RPC. if (readAddress.equals(address)) { return; } BlockInfo blockInfo = mContext.getAlluxioBlockStore().getInfo(blockId); for (BlockLocation location : blockInfo.getLocations()) { if (address.equals(location.getWorkerAddress())) { return; } } } // If we reach here, we need to cache. mCurrentCacheStream = mContext.getAlluxioBlockStore().getOutStream(blockId, getBlockSize(mPos), address); } catch (IOException e) { logCacheStreamIOException(e); } catch (AlluxioException e) { LOG.warn(BLOCK_ID_NOT_CACHED, blockId, e); } } /** * Update {@link #mCurrentBlockInStream} to be in-sync with mPos's block. The new block * stream created with be at position 0. * This function is only called in {@link #updateStreams()}. * * @param blockId cached result of {@link #getCurrentBlockId()} * @throws IOException if the next {@link BlockInStream} cannot be obtained */ private void updateBlockInStream(long blockId) throws IOException { if (mCurrentBlockInStream != null) { mCurrentBlockInStream.close(); mCurrentBlockInStream = null; } if (blockId < 0) { // End of file. return; } try { if (mAlluxioStorageType.isPromote()) { try { mContext.getAlluxioBlockStore().promote(blockId); } catch (IOException e) { // Failed to promote LOG.warn("Promotion of block with ID {} failed.", blockId, e); } } mCurrentBlockInStream = mContext.getAlluxioBlockStore().getInStream(blockId); } catch (IOException e) { LOG.debug("Failed to get BlockInStream for block with ID {}, using UFS instead. {}", blockId, e); if (!mStatus.isPersisted()) { LOG.error("Could not obtain data for block with ID {} from Alluxio." + " The block is also not available in the under storage.", blockId); throw e; } long blockStart = BlockId.getSequenceNumber(blockId) * mBlockSize; mCurrentBlockInStream = createUnderStoreBlockInStream(blockStart, getBlockSize(blockStart), mStatus.getUfsPath()); } } /** * Seeks to a file position. Blocks are not cached unless they are fully read. This is only called * by {@link FileInStream#seek}. * * @param pos The position to seek to. It is guaranteed to be valid (pos >= 0 && pos != mPos && * pos <= mFileLength) * @throws IOException if the seek fails due to an error accessing the stream at the position */ private void seekInternal(long pos) throws IOException { closeOrCancelCacheStream(); mPos = pos; updateStreams(); mCurrentBlockInStream.seek(mPos % mBlockSize); } /** * Seeks to a file position. Blocks are cached even if they are not fully read. This is only * called by {@link FileInStream#seek}. * Invariant: if the current block is to be cached, [0, mPos) should have been cached already. * * @param pos The position to seek to. It is guaranteed to be valid (pos >= 0 && pos != mPos && * pos <= mFileLength). * @throws IOException if the seek fails due to an error accessing the stream at the position */ private void seekInternalWithCachingPartiallyReadBlock(long pos) throws IOException { // Precompute this because mPos will be updated several times in this function. boolean isInCurrentBlock = pos / mBlockSize == mPos / mBlockSize; // Make sure that mCurrentBlockInStream and mCurrentCacheStream is updated. // mPos is not updated here. updateStreams(); if (mCurrentCacheStream != null) { // Cache till pos if seeking forward within the current block. Otheriwse cache the whole // block. readCurrentBlockToPos(pos > mPos ? pos : mFileLength); // Early return if we are at pos already. This happens if we seek forward with caching // enabled for this block. if (mPos == pos) { return; } // The early return above guarantees that we won't close an incomplete cache stream. Preconditions.checkState(mCurrentCacheStream.remaining() == 0); closeOrCancelCacheStream(); } // If seeks within the current block, directly seeks to pos if we are not yet there. // If seeks outside the current block, seek to the beginning of that block first, then // cache the prefix (pos % mBlockSize) of that block. if (isInCurrentBlock) { mPos = pos; // updateStreams is necessary when pos = mFileLength. updateStreams(); mCurrentBlockInStream.seek(mPos % mBlockSize); } else { mPos = pos / mBlockSize * mBlockSize; updateStreams(); if (mCurrentCacheStream != null) { readCurrentBlockToPos(pos); } else { mPos = pos; // We are not allowed to seek to EOF, which guarantees mCurrentBlockInStream to be not null. Preconditions.checkNotNull(mCurrentBlockInStream); mCurrentBlockInStream.seek(mPos % mBlockSize); } } } /** * Reads till the file offset (mPos) equals pos or the end of the current block (whichever is * met first) if pos > mPos. Otherwise no-op. * * @param pos file offset * @throws IOException if read or cache write fails */ private void readCurrentBlockToPos(long pos) throws IOException { Preconditions.checkNotNull(mCurrentBlockInStream); Preconditions.checkNotNull(mCurrentCacheStream); long len = Math.min(pos - mPos, mCurrentBlockInStream.remaining()); if (len <= 0) { return; } byte[] buffer = new byte[Math.min(Constants.MB, (int) len)]; do { len -= read(buffer); } while (len > 0); } }
package com.ore.infinium.systems; import com.badlogic.ashley.core.*; import com.badlogic.ashley.utils.ImmutableArray; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.ore.infinium.World; import com.ore.infinium.components.*; public class PowerOverlayRenderSystem extends EntitySystem { public static int spriteCount; public boolean overlayVisible = true; // public TextureAtlas m_atlas; private World m_world; private SpriteBatch m_batch; private ComponentMapper<PlayerComponent> playerMapper = ComponentMapper.getFor(PlayerComponent.class); private ComponentMapper<SpriteComponent> spriteMapper = ComponentMapper.getFor(SpriteComponent.class); private ComponentMapper<ItemComponent> itemMapper = ComponentMapper.getFor(ItemComponent.class); private ComponentMapper<VelocityComponent> velocityMapper = ComponentMapper.getFor(VelocityComponent.class); private ComponentMapper<TagComponent> tagMapper = ComponentMapper.getFor(TagComponent.class); private ComponentMapper<PowerComponent> powerMapper = ComponentMapper.getFor(PowerComponent.class); // public Sprite outputNode = new Sprite(); private boolean m_leftClicked; private boolean m_dragInProgress; private Entity dragSourceEntity; private static final float powerNodeOffsetRatioX = 0.1f; private static final float powerNodeOffsetRatioY = 0.1f; public PowerOverlayRenderSystem(World world) { m_world = world; } public void addedToEngine(Engine engine) { m_batch = new SpriteBatch(); } public void removedFromEngine(Engine engine) { m_batch.dispose(); } //todo sufficient until we get a spatial hash or whatever private Entity entityAtPosition(Vector2 pos) { ImmutableArray<Entity> entities = m_world.engine.getEntitiesFor(Family.all(PowerComponent.class).get()); SpriteComponent spriteComponent; TagComponent tagComponent; for (int i = 0; i < entities.size(); ++i) { tagComponent = tagMapper.get(entities.get(i)); if (tagComponent != null && tagComponent.tag.equals("itemPlacementGhost")) { continue; } spriteComponent = spriteMapper.get(entities.get(i)); Rectangle rectangle = new Rectangle(spriteComponent.sprite.getX() - (spriteComponent.sprite.getWidth() * 0.5f), spriteComponent.sprite.getY() - (spriteComponent.sprite.getHeight() * 0.5f), spriteComponent.sprite.getWidth(), spriteComponent.sprite.getHeight()); if (rectangle.contains(pos)) { return entities.get(i); } } return null; } public void leftMouseClicked() { m_leftClicked = true; //fixme prolly make a threshold for dragging m_dragInProgress = true; Vector3 unprojectedMouse = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0); m_world.m_camera.unproject(unprojectedMouse); //find the entity we're dragging on dragSourceEntity = entityAtPosition(new Vector2(unprojectedMouse.x, unprojectedMouse.y)); Gdx.app.log("", "drag source" + dragSourceEntity); } public void leftMouseReleased() { m_leftClicked = false; if (m_dragInProgress) { //check if drag can be connected if (dragSourceEntity != null) { Vector3 unprojectedMouse = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0); m_world.m_camera.unproject(unprojectedMouse); Entity dropEntity = entityAtPosition(new Vector2(unprojectedMouse.x, unprojectedMouse.y)); //if the drop is invalid/empty, or they attempted to drop on the same spot they dragged from, ignore if (dropEntity == null || dropEntity == dragSourceEntity) { dragSourceEntity = null; m_dragInProgress = false; Gdx.app.log("", "drag source release, target non existent, canceling."); return; } PowerComponent powerComponent = powerMapper.get(dragSourceEntity); powerComponent.outputEntities.add(dropEntity); Gdx.app.log("", "drag source release, adding, count" + powerComponent.outputEntities.size); dragSourceEntity = null; } m_dragInProgress = false; } } public void update(float delta) { if (!overlayVisible) { return; } // m_batch.setProjectionMatrix(m_world.m_camera.combined); m_batch.setProjectionMatrix(m_world.m_camera.combined); m_batch.begin(); if (m_leftClicked) { m_batch.setColor(1, 0, 0, 0.5f); } renderEntities(delta); if (!m_leftClicked) { m_batch.setColor(1, 1, 1, 1); } m_batch.end(); //screen space rendering m_batch.setProjectionMatrix(m_world.m_client.viewport.getCamera().combined); m_batch.begin(); m_world.m_client.bitmapFont_8pt.setColor(1, 0, 0, 1); float fontY = 150; float fontX = m_world.m_client.viewport.getRightGutterX() - 220; m_batch.draw(m_world.m_atlas.findRegion("backgroundRect"), fontX - 10, fontY + 10, fontX + 100, fontY - 300); m_world.m_client.bitmapFont_8pt.draw(m_batch, "Energy overlay visible (press E)", fontX, fontY); fontY -= 15; m_world.m_client.bitmapFont_8pt.draw(m_batch, "Input: N/A Output: N/A", fontX, fontY); m_world.m_client.bitmapFont_8pt.setColor(1, 1, 1, 1); m_batch.end(); } private void renderEntities(float delta) { //todo need to exclude blocks? ImmutableArray<Entity> entities = m_world.engine.getEntitiesFor(Family.all(PowerComponent.class).get()); ItemComponent itemComponent; SpriteComponent spriteComponent; TagComponent tagComponent; PowerComponent powerComponent; if (m_dragInProgress && dragSourceEntity != null) { SpriteComponent dragSpriteComponent = spriteMapper.get(dragSourceEntity); Vector3 unprojectedMouse = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0); m_world.m_camera.unproject(unprojectedMouse); //in the middle of a drag, draw powernode from source, to mouse position renderWire(new Vector2(unprojectedMouse.x, unprojectedMouse.y), new Vector2(dragSpriteComponent.sprite.getX() + dragSpriteComponent.sprite.getWidth() * powerNodeOffsetRatioX, dragSpriteComponent.sprite.getY() + dragSpriteComponent.sprite.getHeight() * powerNodeOffsetRatioY)); } for (int i = 0; i < entities.size(); ++i) { itemComponent = itemMapper.get(entities.get(i)); assert itemComponent != null; if (itemComponent.state != ItemComponent.State.InWorldState) { continue; } tagComponent = tagMapper.get(entities.get(i)); if (tagComponent != null && tagComponent.tag.equals("itemPlacementGhost")) { continue; } spriteComponent = spriteMapper.get(entities.get(i)); //for each power node that goes outward from this sprite, draw connection lines renderPowerNode(spriteComponent); powerComponent = powerMapper.get(entities.get(i)); SpriteComponent spriteOutputNodeComponent; //go over each output of this entity, and draw a connection from this entity to the connected dest for (int j = 0; j < powerComponent.outputEntities.size; ++j) { powerComponent = powerMapper.get(entities.get(i)); spriteOutputNodeComponent = spriteMapper.get(powerComponent.outputEntities.get(j)); renderWire(new Vector2(spriteComponent.sprite.getX() + spriteComponent.sprite.getWidth() * powerNodeOffsetRatioX, spriteComponent.sprite.getY() + spriteComponent.sprite.getHeight() * powerNodeOffsetRatioY), new Vector2(spriteOutputNodeComponent.sprite.getX() + spriteOutputNodeComponent.sprite.getWidth() * powerNodeOffsetRatioX, spriteOutputNodeComponent.sprite.getY() + spriteOutputNodeComponent.sprite.getHeight() * powerNodeOffsetRatioY)); } } } private void renderWire(Vector2 source, Vector2 dest) { Vector2 diff = new Vector2(source.x - dest.x, source.y - dest.y); float rads = MathUtils.atan2(diff.y, diff.x); float degrees = rads * MathUtils.radiansToDegrees - 90; float powerLineWidth = 3.0f / World.PIXELS_PER_METER; float powerLineHeight = Vector2.dst(source.x, source.y, dest.x, dest.y); m_batch.draw(m_world.m_atlas.findRegion("power-node-line"), dest.x, dest.y, 0, 0, powerLineWidth, powerLineHeight, 1.0f, 1.0f, degrees); } private void renderPowerNode(SpriteComponent spriteComponent) { float powerNodeWidth = 20.0f / World.PIXELS_PER_METER; float powerNodeHeight = 20.0f / World.PIXELS_PER_METER; m_batch.draw(m_world.m_atlas.findRegion("power-node-circle"), spriteComponent.sprite.getX() + (spriteComponent.sprite.getWidth() * powerNodeOffsetRatioX) - (powerNodeWidth * 0.5f), spriteComponent.sprite.getY() + (spriteComponent.sprite.getHeight() * powerNodeOffsetRatioY) - (powerNodeHeight * 0.5f), powerNodeWidth, powerNodeHeight); } }
package com.twitter.elephantbird.util; import java.io.IOException; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; /** * HDFS utilities */ public final class HdfsUtils { private HdfsUtils() { } /** * Used by {@link HdfsUtils#walkPath} to 'visit' or process a * path */ public static interface PathVisitor { void visit(FileStatus fileStatus); } /** * Recursively walk a path applying visitor to each path accepted by * filter * * @param path root path to begin walking, will be visited if * it passes the filter and directory flag * @param fs FileSystem for this path * @param filter filter to determine which paths to accept * @param visitor visitor to apply to each accepted path * @throws IOException */ public static void walkPath(Path path, FileSystem fs, PathFilter filter, PathVisitor visitor) throws IOException { FileStatus fileStatus = fs.getFileStatus(path); if (filter.accept(path)) { visitor.visit(fileStatus); } if (fileStatus.isDir()) { FileStatus[] children = fs.listStatus(path); for (FileStatus childStatus : children) { walkPath(childStatus.getPath(), fs, filter, visitor); } } } /** * Recursively walk a path, adding paths that are accepted by filter to accumulator * * @param path root path to begin walking, will be added to accumulator * @param fs FileSystem for this path * @param filter filter to determine which paths to accept * @param accumulator all paths accepted will be added to accumulator * @throws IOException */ public static void collectPaths(Path path, FileSystem fs, PathFilter filter, final List<Path> accumulator) throws IOException { walkPath(path, fs, filter, new PathVisitor() { @Override public void visit(FileStatus fileStatus) { accumulator.add(fileStatus.getPath()); } }); } private static class PathSizeVisitor implements PathVisitor { private long size = 0; @Override public void visit(FileStatus fileStatus) { size += fileStatus.getLen(); } public long getSize() { return size; } } /** * Calculates the total size of all the contents of a directory that are accepted * by filter. All subdirectories will be searched recursively and paths in subdirectories * that are accepted by filter will also be counted. * * Does not include the size of directories themselves * (which are 0 in HDFS but may not be 0 on local file systems) * * To get the size of a directory without filtering, use * {@link #getDirectorySize(Path, FileSystem)} which is much more efficient. * * @param path path to recursively walk * @param fs FileSystem for this path * @param filter path filter for which paths size's to include in the total * NOTE: you do *not* need to filter out directories, this will be done for you * @return size of the directory in bytes * @throws IOException */ public static long getDirectorySize(Path path, FileSystem fs, PathFilter filter) throws IOException { PathSizeVisitor visitor = new PathSizeVisitor(); PathFilter composite = new PathFilters.CompositePathFilter( PathFilters.newExcludeDirectoriesFilter(fs.getConf()), filter); walkPath(path, fs, composite, visitor); return visitor.getSize(); } /** * Calculates the total size of all the contents of a directory, * including the contents of all of its subdirectories. * Does not include the size of directories themselves * (which are 0 in HDFS but may not be 0 on local file systems) * * @param path path to recursively walk * @param fs FileSystem for this path * @return size of the directory's contents in bytes * @throws IOException */ public static long getDirectorySize(Path path, FileSystem fs) throws IOException { ContentSummary cs = fs.getContentSummary(path); return cs.getLength(); } /** * Given a list of paths that (potentially) have glob syntax in them, * return a list of paths with all the globs expanded. * * @param pathsWithGlobs a list of paths that may or may not have glob syntax in them * @param conf job conf * @return an equivalent list of paths with no glob syntax in them * @throws IOException */ public static List<Path> expandGlobs(List<String> pathsWithGlobs, Configuration conf) throws IOException { List<Path> paths = Lists.newLinkedList(); for (String pathStr : pathsWithGlobs) { Path path = new Path(pathStr); FileSystem fs = path.getFileSystem(conf); FileStatus[] statuses = fs.globStatus(path); // some versions of hadoop return null for non-existent paths if (statuses != null) { for (FileStatus status : statuses) { paths.add(status.getPath()); } } } return paths; } }
package me.dkzwm.widget.srl; import static me.dkzwm.widget.srl.config.Constants.*; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.os.Build; import android.os.SystemClock; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.InputDevice; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.Scroller; import androidx.annotation.CallSuper; import androidx.annotation.ColorInt; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.view.GravityCompat; import androidx.core.view.NestedScrollingChild3; import androidx.core.view.NestedScrollingChildHelper; import androidx.core.view.NestedScrollingParent3; import androidx.core.view.NestedScrollingParentHelper; import androidx.core.view.ViewCompat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import me.dkzwm.widget.srl.annotation.Action; import me.dkzwm.widget.srl.annotation.Mode; import me.dkzwm.widget.srl.annotation.Orientation; import me.dkzwm.widget.srl.extra.IRefreshView; import me.dkzwm.widget.srl.indicator.DefaultIndicator; import me.dkzwm.widget.srl.indicator.IIndicator; import me.dkzwm.widget.srl.indicator.IIndicatorSetter; import me.dkzwm.widget.srl.manager.VRefreshLayoutManager; import me.dkzwm.widget.srl.manager.VScaleLayoutManager; import me.dkzwm.widget.srl.util.AppBarLayoutUtil; import me.dkzwm.widget.srl.util.ScrollCompat; import me.dkzwm.widget.srl.util.ViewCatcherUtil; /** @author dkzwm */ public class SmoothRefreshLayout extends ViewGroup implements NestedScrollingParent3, NestedScrollingChild3 { // status public static final byte SR_STATUS_INIT = 1; public static final byte SR_STATUS_PREPARE = 2; public static final byte SR_STATUS_REFRESHING = 3; public static final byte SR_STATUS_LOADING_MORE = 4; public static final byte SR_STATUS_COMPLETE = 5; // fresh view status public static final byte SR_VIEW_STATUS_INIT = 21; public static final byte SR_VIEW_STATUS_HEADER_IN_PROCESSING = 22; public static final byte SR_VIEW_STATUS_FOOTER_IN_PROCESSING = 23; protected static final Interpolator sSpringInterpolator = new Interpolator() { public float getInterpolation(float input) { --input; return input * input * input * input * input + 1.0F; } }; protected static final Interpolator sFlingInterpolator = new DecelerateInterpolator(.95f); protected static final Interpolator sSpringBackInterpolator = new DecelerateInterpolator(1.6f); protected static final byte FLAG_AUTO_REFRESH = 0x01; protected static final byte FLAG_ENABLE_NEXT_AT_ONCE = 0x01 << 2; protected static final byte FLAG_ENABLE_OVER_SCROLL = 0x01 << 3; protected static final byte FLAG_ENABLE_KEEP_REFRESH_VIEW = 0x01 << 4; protected static final byte FLAG_ENABLE_PIN_CONTENT_VIEW = 0x01 << 5; protected static final byte FLAG_ENABLE_PULL_TO_REFRESH = 0x01 << 6; protected static final int FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING = 0x01 << 7; protected static final int FLAG_ENABLE_HEADER_DRAWER_STYLE = 0x01 << 8; protected static final int FLAG_ENABLE_FOOTER_DRAWER_STYLE = 0x01 << 9; protected static final int FLAG_DISABLE_PERFORM_LOAD_MORE = 0x01 << 10; protected static final int FLAG_ENABLE_NO_MORE_DATA = 0x01 << 11; protected static final int FLAG_DISABLE_LOAD_MORE = 0x01 << 12; protected static final int FLAG_DISABLE_PERFORM_REFRESH = 0x01 << 13; protected static final int FLAG_DISABLE_REFRESH = 0x01 << 14; protected static final int FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE = 0x01 << 15; protected static final int FLAG_ENABLE_AUTO_PERFORM_REFRESH = 0x01 << 16; protected static final int FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING = 0x01 << 17; protected static final int FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE = 0x01 << 18; protected static final int FLAG_ENABLE_NO_MORE_DATA_NO_BACK = 0x01 << 19; protected static final int FLAG_ENABLE_SMOOTH_ROLLBACK_WHEN_COMPLETED = 0x01 << 20; protected static final int FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL = 0x01 << 21; protected static final int FLAG_ENABLE_COMPAT_SYNC_SCROLL = 0x01 << 22; protected static final int FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING = 0x01 << 23; protected static final int FLAG_ENABLE_OLD_TOUCH_HANDLING = 0x01 << 24; protected static final int MASK_DISABLE_PERFORM_LOAD_MORE = 0x07 << 10; protected static final int MASK_DISABLE_PERFORM_REFRESH = 0x03 << 13; public static boolean sDebug = true; private static int sId = 0; private static IRefreshViewCreator sCreator; protected final String TAG = "SmoothRefreshLayout-" + sId++; protected final int[] mParentScrollConsumed = new int[2]; protected final int[] mParentOffsetInWindow = new int[2]; private final List<View> mCachedViews = new ArrayList<>(1); protected IRefreshView<IIndicator> mHeaderView; protected IRefreshView<IIndicator> mFooterView; protected IIndicator mIndicator; protected IIndicatorSetter mIndicatorSetter; protected OnRefreshListener mRefreshListener; protected boolean mAutomaticActionUseSmoothScroll = false; protected boolean mAutomaticActionTriggered = true; protected boolean mIsSpringBackCanNotBeInterrupted = false; protected boolean mDealAnotherDirectionMove = false; protected boolean mPreventForAnotherDirection = false; protected boolean mIsInterceptTouchEventInOnceTouch = false; protected boolean mIsLastOverScrollCanNotAbort = false; protected boolean mNestedScrolling = false; protected boolean mNestedTouchScrolling = false; protected byte mStatus = SR_STATUS_INIT; protected byte mViewStatus = SR_VIEW_STATUS_INIT; protected long mLoadingStartTime = 0; protected int mAutomaticAction = ACTION_NOTIFY; protected int mLastNestedType = ViewCompat.TYPE_NON_TOUCH; protected int mDurationToCloseHeader = 350; protected int mDurationToCloseFooter = 350; protected int mDurationOfBackToHeaderHeight = 200; protected int mDurationOfBackToFooterHeight = 200; protected int mDurationOfFlingBack = 550; protected int mContentResId = View.NO_ID; protected int mStickyHeaderResId = View.NO_ID; protected int mStickyFooterResId = View.NO_ID; protected int mTouchSlop; protected int mTouchPointerId; protected int mHeaderBackgroundColor = Color.TRANSPARENT; protected int mFooterBackgroundColor = Color.TRANSPARENT; protected int mMinimumFlingVelocity; protected int mMaximumFlingVelocity; protected View mTargetView; protected View mScrollTargetView; protected View mAutoFoundScrollTargetView; protected View mStickyHeaderView; protected View mStickyFooterView; protected LayoutManager mLayoutManager; protected ScrollChecker mScrollChecker; protected VelocityTracker mVelocityTracker; protected Paint mBackgroundPaint; protected MotionEvent mLastMoveEvent; protected OnHeaderEdgeDetectCallBack mInEdgeCanMoveHeaderCallBack; protected OnFooterEdgeDetectCallBack mInEdgeCanMoveFooterCallBack; protected OnSyncScrollCallback mSyncScrollCallback; protected OnPerformAutoLoadMoreCallBack mAutoLoadMoreCallBack; protected OnPerformAutoRefreshCallBack mAutoRefreshCallBack; protected int mFlag = FLAG_DISABLE_LOAD_MORE | FLAG_ENABLE_COMPAT_SYNC_SCROLL | FLAG_ENABLE_OLD_TOUCH_HANDLING | FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING; private NestedScrollingParentHelper mNestedScrollingParentHelper; private NestedScrollingChildHelper mNestedScrollingChildHelper; private Interpolator mSpringInterpolator; private Interpolator mSpringBackInterpolator; private ArrayList<OnUIPositionChangedListener> mUIPositionChangedListeners; private ArrayList<OnStatusChangedListener> mStatusChangedListeners; private ArrayList<ILifecycleObserver> mLifecycleObservers; private DelayToDispatchNestedFling mDelayToDispatchNestedFling; private DelayToRefreshComplete mDelayToRefreshComplete; private DelayToPerformAutoRefresh mDelayToPerformAutoRefresh; private RefreshCompleteHook mHeaderRefreshCompleteHook; private RefreshCompleteHook mFooterRefreshCompleteHook; private AppBarLayoutUtil mAppBarLayoutUtil; private Matrix mCachedMatrix = new Matrix(); private boolean mIsLastRefreshSuccessful = true; private boolean mViewsZAxisNeedReset = true; private boolean mNeedFilterScrollEvent = false; private boolean mHasSendCancelEvent = false; private boolean mHasSendDownEvent = false; private float[] mCachedFloatPoint = new float[2]; private int[] mCachedIntPoint = new int[2]; private float mOffsetConsumed = 0f; private float mOffsetTotal = 0f; private int mMaxOverScrollDuration = 350; private int mMinOverScrollDuration = 100; private int mOffsetRemaining = 0; public SmoothRefreshLayout(Context context) { super(context); init(context, null, 0, 0); } public SmoothRefreshLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0, 0); } public SmoothRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, 0); } /** * Set the static refresh view creator, if the refresh view is null and the frame be needed the * refresh view,frame will use this creator to create refresh view. * * <p>nullFrame * * @param creator The static refresh view creator */ public static void setDefaultCreator(IRefreshViewCreator creator) { sCreator = creator; } @CallSuper protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { sId++; createIndicator(); if (mIndicator == null || mIndicatorSetter == null) { throw new IllegalArgumentException( "You must create a IIndicator, current indicator is null"); } ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext()); mTouchSlop = viewConfiguration.getScaledTouchSlop(); mMaximumFlingVelocity = viewConfiguration.getScaledMaximumFlingVelocity(); mMinimumFlingVelocity = viewConfiguration.getScaledMinimumFlingVelocity(); mScrollChecker = new ScrollChecker(); mSpringInterpolator = sSpringInterpolator; mSpringBackInterpolator = sSpringBackInterpolator; mNestedScrollingChildHelper = new NestedScrollingChildHelper(this); mNestedScrollingParentHelper = new NestedScrollingParentHelper(this); mDelayToPerformAutoRefresh = new DelayToPerformAutoRefresh(); TypedArray arr = context.obtainStyledAttributes( attrs, R.styleable.SmoothRefreshLayout, defStyleAttr, defStyleRes); int mode = MODE_DEFAULT; if (arr != null) { try { mContentResId = arr.getResourceId( R.styleable.SmoothRefreshLayout_sr_content, mContentResId); float resistance = arr.getFloat( R.styleable.SmoothRefreshLayout_sr_resistance, IIndicator.DEFAULT_RESISTANCE); mIndicatorSetter.setResistance(resistance); mIndicatorSetter.setResistanceOfHeader( arr.getFloat( R.styleable.SmoothRefreshLayout_sr_resistanceOfHeader, resistance)); mIndicatorSetter.setResistanceOfFooter( arr.getFloat( R.styleable.SmoothRefreshLayout_sr_resistanceOfFooter, resistance)); mDurationOfBackToHeaderHeight = arr.getInt( R.styleable.SmoothRefreshLayout_sr_backToKeepDuration, mDurationOfBackToHeaderHeight); mDurationOfBackToFooterHeight = arr.getInt( R.styleable.SmoothRefreshLayout_sr_backToKeepDuration, mDurationOfBackToFooterHeight); mDurationOfBackToHeaderHeight = arr.getInt( R.styleable.SmoothRefreshLayout_sr_backToKeepHeaderDuration, mDurationOfBackToHeaderHeight); mDurationOfBackToFooterHeight = arr.getInt( R.styleable.SmoothRefreshLayout_sr_backToKeepFooterDuration, mDurationOfBackToFooterHeight); mDurationToCloseHeader = arr.getInt( R.styleable.SmoothRefreshLayout_sr_closeDuration, mDurationToCloseHeader); mDurationToCloseFooter = arr.getInt( R.styleable.SmoothRefreshLayout_sr_closeDuration, mDurationToCloseFooter); mDurationToCloseHeader = arr.getInt( R.styleable.SmoothRefreshLayout_sr_closeHeaderDuration, mDurationToCloseHeader); mDurationToCloseFooter = arr.getInt( R.styleable.SmoothRefreshLayout_sr_closeFooterDuration, mDurationToCloseFooter); float ratio = arr.getFloat( R.styleable.SmoothRefreshLayout_sr_ratioToRefresh, IIndicator.DEFAULT_RATIO_TO_REFRESH); mIndicatorSetter.setRatioToRefresh(ratio); mIndicatorSetter.setRatioOfHeaderToRefresh( arr.getFloat( R.styleable.SmoothRefreshLayout_sr_ratioOfHeaderToRefresh, ratio)); mIndicatorSetter.setRatioOfFooterToRefresh( arr.getFloat( R.styleable.SmoothRefreshLayout_sr_ratioOfFooterToRefresh, ratio)); ratio = arr.getFloat( R.styleable.SmoothRefreshLayout_sr_ratioToKeep, IIndicator.DEFAULT_RATIO_TO_REFRESH); mIndicatorSetter.setRatioToKeepHeader(ratio); mIndicatorSetter.setRatioToKeepFooter(ratio); mIndicatorSetter.setRatioToKeepHeader( arr.getFloat(R.styleable.SmoothRefreshLayout_sr_ratioToKeepHeader, ratio)); mIndicatorSetter.setRatioToKeepFooter( arr.getFloat(R.styleable.SmoothRefreshLayout_sr_ratioToKeepFooter, ratio)); ratio = arr.getFloat( R.styleable.SmoothRefreshLayout_sr_maxMoveRatio, IIndicator.DEFAULT_MAX_MOVE_RATIO); mIndicatorSetter.setMaxMoveRatio(ratio); mIndicatorSetter.setMaxMoveRatioOfHeader( arr.getFloat( R.styleable.SmoothRefreshLayout_sr_maxMoveRatioOfHeader, ratio)); mIndicatorSetter.setMaxMoveRatioOfFooter( arr.getFloat( R.styleable.SmoothRefreshLayout_sr_maxMoveRatioOfFooter, ratio)); mStickyHeaderResId = arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_stickyHeader, NO_ID); mStickyFooterResId = arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_stickyFooter, NO_ID); mHeaderBackgroundColor = arr.getColor( R.styleable.SmoothRefreshLayout_sr_headerBackgroundColor, Color.TRANSPARENT); mFooterBackgroundColor = arr.getColor( R.styleable.SmoothRefreshLayout_sr_footerBackgroundColor, Color.TRANSPARENT); setEnableKeepRefreshView( arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableKeep, true)); setEnablePinContentView( arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enablePinContent, false)); setEnableOverScroll( arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableOverScroll, true)); setEnablePullToRefresh( arr.getBoolean( R.styleable.SmoothRefreshLayout_sr_enablePullToRefresh, false)); setDisableRefresh( !arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableRefresh, true)); setDisableLoadMore( !arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableLoadMore, false)); mode = arr.getInt(R.styleable.SmoothRefreshLayout_sr_mode, 0); setEnabled(arr.getBoolean(R.styleable.SmoothRefreshLayout_android_enabled, true)); preparePaint(); } finally { arr.recycle(); } } else { setWillNotDraw(true); setEnablePullToRefresh(true); setEnableKeepRefreshView(true); } setNestedScrollingEnabled(true); setMode(mode); } protected void createIndicator() { DefaultIndicator indicator = new DefaultIndicator(); mIndicator = indicator; mIndicatorSetter = indicator; } public final IIndicator getIndicator() { return mIndicator; } @Override @SuppressWarnings("unchecked") @CallSuper public void addView(View child, int index, ViewGroup.LayoutParams params) { if (params == null) { params = generateDefaultLayoutParams(); } else { params = generateLayoutParams(params); } if (child instanceof IRefreshView) { IRefreshView<IIndicator> view = (IRefreshView<IIndicator>) child; switch (view.getType()) { case IRefreshView.TYPE_HEADER: if (mHeaderView != null) throw new IllegalArgumentException( "Unsupported operation, HeaderView only can be add once !!"); mHeaderView = view; break; case IRefreshView.TYPE_FOOTER: if (mFooterView != null) throw new IllegalArgumentException( "Unsupported operation, FooterView only can be add once !!"); mFooterView = view; break; } } super.addView(child, index, params); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (!enabled) { reset(); } } @Override protected void onFinishInflate() { super.onFinishInflate(); checkViewsZAxisNeedReset(); } @Override protected void onDetachedFromWindow() { final List<ILifecycleObserver> observers = mLifecycleObservers; if (observers != null) { for (ILifecycleObserver observer : observers) { observer.onDetached(this); } } if (mAppBarLayoutUtil != null) { if (mInEdgeCanMoveHeaderCallBack == mAppBarLayoutUtil) { mInEdgeCanMoveHeaderCallBack = null; } if (mInEdgeCanMoveFooterCallBack == mAppBarLayoutUtil) { mInEdgeCanMoveFooterCallBack = null; } mAppBarLayoutUtil.detach(); } mAppBarLayoutUtil = null; reset(); if (mHeaderRefreshCompleteHook != null) { mHeaderRefreshCompleteHook.mLayout = null; } if (mFooterRefreshCompleteHook != null) { mFooterRefreshCompleteHook.mLayout = null; } if (mDelayToDispatchNestedFling != null) { mDelayToDispatchNestedFling.mLayout = null; } if (mDelayToRefreshComplete != null) { mDelayToRefreshComplete.mLayout = null; } mDelayToPerformAutoRefresh.mLayout = null; mLayoutManager.setLayout(null); if (mVelocityTracker != null) { mVelocityTracker.recycle(); } mVelocityTracker = null; if (sDebug) { Log.d(TAG, "onDetachedFromWindow()"); } super.onDetachedFromWindow(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (sDebug) { Log.d(TAG, "onAttachedToWindow()"); } if (mLayoutManager == null) throw new IllegalArgumentException("LayoutManager can not be null!!"); mLayoutManager.setLayout(this); final List<ILifecycleObserver> observers = mLifecycleObservers; if (observers != null) { for (ILifecycleObserver observer : observers) { observer.onAttached(this); } } View view = ViewCatcherUtil.catchAppBarLayout(this); if (view != null) { mAppBarLayoutUtil = new AppBarLayoutUtil(view); if (mInEdgeCanMoveHeaderCallBack == null) { mInEdgeCanMoveHeaderCallBack = mAppBarLayoutUtil; } if (mInEdgeCanMoveFooterCallBack == null) { mInEdgeCanMoveFooterCallBack = mAppBarLayoutUtil; } } mDelayToPerformAutoRefresh.mLayout = this; } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); if (count == 0) { return; } ensureTargetView(); int maxHeight = 0; int maxWidth = 0; int childState = 0; mCachedViews.clear(); final boolean measureMatchParentChildren = MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY || MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (mHeaderView != null && child == mHeaderView.getView()) { mLayoutManager.measureHeader(mHeaderView, widthMeasureSpec, heightMeasureSpec); } else if (mFooterView != null && child == mFooterView.getView()) { mLayoutManager.measureFooter(mFooterView, widthMeasureSpec, heightMeasureSpec); } else { measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); if (measureMatchParentChildren && (lp.width == LayoutParams.MATCH_PARENT || lp.height == LayoutParams.MATCH_PARENT)) { mCachedViews.add(child); } } maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin); maxHeight = Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin); childState = combineMeasuredStates(childState, child.getMeasuredState()); } maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingTop() + getPaddingBottom(); maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); setMeasuredDimension( resolveSizeAndState(maxWidth, widthMeasureSpec, childState), resolveSizeAndState( maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT)); count = mCachedViews.size(); if (count > 1) { for (int i = 0; i < count; i++) { final View child = mCachedViews.get(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec); child.measure(spec[0], spec[1]); } } mCachedViews.clear(); if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY || MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) { if (mHeaderView != null && mHeaderView.getView().getVisibility() != GONE) { final View child = mHeaderView.getView(); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec); mLayoutManager.measureHeader(mHeaderView, spec[0], spec[1]); } if (mFooterView != null && mFooterView.getView().getVisibility() != GONE) { final View child = mFooterView.getView(); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec); mLayoutManager.measureFooter(mFooterView, spec[0], spec[1]); } } } private int[] measureChildAgain(LayoutParams lp, int widthMeasureSpec, int heightMeasureSpec) { if (lp.width == LayoutParams.MATCH_PARENT) { final int width = Math.max( 0, getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - lp.leftMargin - lp.rightMargin); mCachedIntPoint[0] = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); } else { mCachedIntPoint[0] = getChildMeasureSpec( widthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp.width); } if (lp.height == LayoutParams.MATCH_PARENT) { final int height = Math.max( 0, getMeasuredHeight() - getPaddingTop() - getPaddingBottom() - lp.topMargin - lp.bottomMargin); mCachedIntPoint[1] = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); } else { mCachedIntPoint[1] = getChildMeasureSpec( heightMeasureSpec, getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin, lp.height); } return mCachedIntPoint; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); if (count == 0) { return; } mIndicator.checkConfig(); final int parentRight = r - l - getPaddingRight(); final int parentBottom = b - t - getPaddingBottom(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } if (mHeaderView != null && child == mHeaderView.getView()) { mLayoutManager.layoutHeaderView(mHeaderView); } else if (mTargetView != null && child == mTargetView) { mLayoutManager.layoutContentView(child); } else if (mStickyHeaderView != null && child == mStickyHeaderView) { mLayoutManager.layoutStickyHeaderView(child); } else if ((mFooterView == null || mFooterView.getView() != child) && (mStickyFooterView == null || mStickyFooterView != child)) { layoutOtherView(child, parentRight, parentBottom); } } if (mFooterView != null && mFooterView.getView().getVisibility() != GONE) { mLayoutManager.layoutFooterView(mFooterView); } if (mStickyFooterView != null && mStickyFooterView.getVisibility() != GONE) { mLayoutManager.layoutStickyFooterView(mStickyFooterView); } if (!mAutomaticActionTriggered) { removeCallbacks(mDelayToPerformAutoRefresh); postDelayed(mDelayToPerformAutoRefresh, 90); } } protected void layoutOtherView(View child, int parentRight, int parentBottom) { final int width = child.getMeasuredWidth(); final int height = child.getMeasuredHeight(); int childLeft, childTop; final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int gravity = lp.gravity; final int layoutDirection = ViewCompat.getLayoutDirection(this); final int absoluteGravity = GravityCompat.getAbsoluteGravity(gravity, layoutDirection); final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: childLeft = (int) (getPaddingLeft() + (parentRight - getPaddingLeft() - width) / 2f + lp.leftMargin - lp.rightMargin); break; case Gravity.RIGHT: childLeft = parentRight - width - lp.rightMargin; break; default: childLeft = getPaddingLeft() + lp.leftMargin; } switch (verticalGravity) { case Gravity.CENTER_VERTICAL: childTop = (int) (getPaddingTop() + (parentBottom - getPaddingTop() - height) / 2f + lp.topMargin - lp.bottomMargin); break; case Gravity.BOTTOM: childTop = parentBottom - height - lp.bottomMargin; break; default: childTop = getPaddingTop() + lp.topMargin; } child.layout(childLeft, childTop, childLeft + width, childTop + height); if (sDebug) { Log.d( TAG, String.format( "onLayout(): child: %s %s %s %s", childLeft, childTop, childLeft + width, childTop + height)); } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (!isEnabled() || mTargetView == null || ((isDisabledLoadMore() && isDisabledRefresh())) || (isEnabledPinRefreshViewWhileLoading() && ((isRefreshing() && isMovingHeader()) || (isLoadingMore() && isMovingFooter()))) || mNestedTouchScrolling) { return super.dispatchTouchEvent(ev); } return processDispatchTouchEvent(ev); } protected final boolean dispatchTouchEventSuper(MotionEvent ev) { if (!isEnabledOldTouchHandling()) { final int index = ev.findPointerIndex(mTouchPointerId); if (index < 0) { return super.dispatchTouchEvent(ev); } if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) { mOffsetConsumed = 0; mOffsetTotal = 0; mOffsetRemaining = mTouchSlop * 3; } else { if (!mIndicator.isAlreadyHere(IIndicator.START_POS) && mIndicator.getRawOffset() != 0) { if (mOffsetRemaining > 0) { mOffsetRemaining -= mTouchSlop; if (isMovingHeader()) { mOffsetTotal -= mOffsetRemaining; } else if (isMovingFooter()) { mOffsetTotal += mOffsetRemaining; } } mOffsetConsumed += mIndicator.getRawOffset() < 0 ? mIndicator.getLastPos() - mIndicator.getCurrentPos() : mIndicator.getCurrentPos() - mIndicator.getLastPos(); mOffsetTotal += mIndicator.getRawOffset(); } if (isVerticalOrientation()) { ev.offsetLocation(0, mOffsetConsumed - mOffsetTotal); } else { ev.offsetLocation(mOffsetConsumed - mOffsetTotal, 0); } } } return super.dispatchTouchEvent(ev); } @Override protected void onDraw(Canvas canvas) { if (mBackgroundPaint != null && !isEnabledPinContentView() && !mIndicator.isAlreadyHere(IIndicator.START_POS)) { if (!isDisabledRefresh() && isMovingHeader() && mHeaderBackgroundColor != Color.TRANSPARENT) { mBackgroundPaint.setColor(mHeaderBackgroundColor); drawHeaderBackground(canvas); } else if (!isDisabledLoadMore() && isMovingFooter() && mFooterBackgroundColor != Color.TRANSPARENT) { mBackgroundPaint.setColor(mFooterBackgroundColor); drawFooterBackground(canvas); } } } protected void drawHeaderBackground(Canvas canvas) { final int bottom = Math.min( getPaddingTop() + mIndicator.getCurrentPos(), getHeight() - getPaddingTop()); canvas.drawRect( getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), bottom, mBackgroundPaint); } protected void drawFooterBackground(Canvas canvas) { final int top; final int bottom; if (mTargetView != null) { final LayoutParams lp = (LayoutParams) mTargetView.getLayoutParams(); bottom = getPaddingTop() + lp.topMargin + mTargetView.getMeasuredHeight() + lp.bottomMargin; top = bottom - mIndicator.getCurrentPos(); } else { top = Math.max( getHeight() - getPaddingBottom() - mIndicator.getCurrentPos(), getPaddingTop()); bottom = getHeight() - getPaddingBottom(); } canvas.drawRect( getPaddingLeft(), top, getWidth() - getPaddingRight(), bottom, mBackgroundPaint); } public int getSupportScrollAxis() { return mLayoutManager.getOrientation() == LayoutManager.VERTICAL ? ViewCompat.SCROLL_AXIS_VERTICAL : ViewCompat.SCROLL_AXIS_HORIZONTAL; } public void addLifecycleObserver(@NonNull ILifecycleObserver observer) { if (mLifecycleObservers == null) { mLifecycleObservers = new ArrayList<>(); mLifecycleObservers.add(observer); } else if (!mLifecycleObservers.contains(observer)) { mLifecycleObservers.add(observer); } } public void removeLifecycleObserver(@NonNull ILifecycleObserver observer) { if (mLifecycleObservers != null) { mLifecycleObservers.remove(observer); } } @Nullable public View getScrollTargetView() { if (mScrollTargetView != null) { return mScrollTargetView; } else if (mAutoFoundScrollTargetView != null) { return mAutoFoundScrollTargetView; } else { return mTargetView; } } /** * Set loadMore scroll target view,For example the content view is a FrameLayout,with a listView * in it.You can call this method,set the listView as load more scroll target view. Load more * compat will try to make it smooth scrolling. * * <p><br> * SmoothRefreshLayoutCoordinatorLayout, * CoordinatorLayoutAppbarLayoutRecyclerViewRecyclerVieW * CoordinatorLayout,RecyclerViewTargetView * * @param view Target view */ public void setScrollTargetView(View view) { mScrollTargetView = view; } public void setLayoutManager(@NonNull LayoutManager layoutManager) { if (mLayoutManager != layoutManager) { if (mLayoutManager != null) { if (mLayoutManager.getOrientation() != layoutManager.getOrientation()) { reset(); requestLayout(); } } mLayoutManager = layoutManager; } } public void setMode(@Mode int mode) { if (mode == MODE_DEFAULT) { if (mLayoutManager instanceof VRefreshLayoutManager) { return; } mLayoutManager = new VRefreshLayoutManager(); } else { if (mLayoutManager instanceof VScaleLayoutManager) { return; } mLayoutManager = new VScaleLayoutManager(); } } /** * Whether to enable the synchronous scroll when load more completed. * * <p> * * @param enable enable */ public void setEnableCompatSyncScroll(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_COMPAT_SYNC_SCROLL; } else { mFlag = mFlag & ~FLAG_ENABLE_COMPAT_SYNC_SCROLL; } } /** * Set the background color of the height of the Header view. * * <p>HeaderHeader * * @param headerBackgroundColor Color */ public void setHeaderBackgroundColor(@ColorInt int headerBackgroundColor) { mHeaderBackgroundColor = headerBackgroundColor; preparePaint(); } /** * Set the background color of the height of the Footer view. * * <p>FooterFooter * * @param footerBackgroundColor Color */ public void setFooterBackgroundColor(@ColorInt int footerBackgroundColor) { mFooterBackgroundColor = footerBackgroundColor; preparePaint(); } /** * Set the custom offset calculator. * * <p> * * @param calculator Offset calculator */ public void setIndicatorOffsetCalculator(IIndicator.IOffsetCalculator calculator) { mIndicatorSetter.setOffsetCalculator(calculator); } /** * Set the listener to be notified when a refresh is triggered. * * <p> * * @param listener Listener */ public <T extends OnRefreshListener> void setOnRefreshListener(T listener) { mRefreshListener = listener; } /** * Add a listener to listen the views position change event. * * <p>UI * * @param listener Listener */ public void addOnUIPositionChangedListener(@NonNull OnUIPositionChangedListener listener) { if (mUIPositionChangedListeners == null) { mUIPositionChangedListeners = new ArrayList<>(); mUIPositionChangedListeners.add(listener); } else if (!mUIPositionChangedListeners.contains(listener)) { mUIPositionChangedListeners.add(listener); } } /** * remove the listener. * * <p>UI * * @param listener Listener */ public void removeOnUIPositionChangedListener(@NonNull OnUIPositionChangedListener listener) { if (mUIPositionChangedListeners != null) { mUIPositionChangedListeners.remove(listener); } } /** * Add a listener when status changed. * * <p> * * @param listener Listener that should be called when status changed. */ public void addOnStatusChangedListener(@NonNull OnStatusChangedListener listener) { if (mStatusChangedListeners == null) { mStatusChangedListeners = new ArrayList<>(); mStatusChangedListeners.add(listener); } else if (!mStatusChangedListeners.contains(listener)) { mStatusChangedListeners.add(listener); } } /** * remove the listener. * * <p> * * @param listener Listener */ public void removeOnStatusChangedListener(@NonNull OnStatusChangedListener listener) { if (mStatusChangedListeners != null) { mStatusChangedListeners.remove(listener); } } /** * Set a sync scrolling callback when refresh competed. * * <p>ListView * FooterListView * * @param callback a sync scrolling callback when refresh competed. */ public void setOnSyncScrollCallback(OnSyncScrollCallback callback) { mSyncScrollCallback = callback; } /** * Set a callback to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} * method. Non-null callback will return the value provided by the callback and ignore all * internal logic. * * <p>{@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} * * @param callback Callback that should be called when isChildNotYetInEdgeCannotMoveHeader() is * called. */ public void setOnHeaderEdgeDetectCallBack(OnHeaderEdgeDetectCallBack callback) { mInEdgeCanMoveHeaderCallBack = callback; } /** * Set a callback to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} * method. Non-null callback will return the value provided by the callback and ignore all * internal logic. * * <p>{@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} * * @param callback Callback that should be called when isChildNotYetInEdgeCannotMoveFooter() is * called. */ public void setOnFooterEdgeDetectCallBack(OnFooterEdgeDetectCallBack callback) { mInEdgeCanMoveFooterCallBack = callback; } /** * Set a callback to make sure you need to customize the specified trigger the auto load more * rule. * * <p> * * @param callBack Customize the specified triggered rule */ public void setOnPerformAutoLoadMoreCallBack(OnPerformAutoLoadMoreCallBack callBack) { mAutoLoadMoreCallBack = callBack; } /** * Set a callback to make sure you need to customize the specified trigger the auto refresh * rule. * * <p> * * @param callBack Customize the specified triggered rule */ public void setOnPerformAutoRefreshCallBack(OnPerformAutoRefreshCallBack callBack) { mAutoRefreshCallBack = callBack; } /** * Set a hook callback when the refresh complete event be triggered. Only can be called on * refreshing. * * <p>Hook * * @param callback Callback that should be called when refreshComplete() is called. */ public void setOnHookHeaderRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callback) { if (mHeaderRefreshCompleteHook == null) mHeaderRefreshCompleteHook = new RefreshCompleteHook(); mHeaderRefreshCompleteHook.mCallBack = callback; } /** * Set a hook callback when the refresh complete event be triggered. Only can be called on * loading more. * * <p>Hook * * @param callback Callback that should be called when refreshComplete() is called. */ public void setOnHookFooterRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callback) { if (mFooterRefreshCompleteHook == null) mFooterRefreshCompleteHook = new RefreshCompleteHook(); mFooterRefreshCompleteHook.mCallBack = callback; } /** * Whether it is refreshing state. * * <p> * * @return Refreshing */ public boolean isRefreshing() { return mStatus == SR_STATUS_REFRESHING; } /** * Whether it is loading more state. * * <p> * * @return Loading */ public boolean isLoadingMore() { return mStatus == SR_STATUS_LOADING_MORE; } /** * Whether it is refresh successful. * * <p> * * @return Is */ public boolean isRefreshSuccessful() { return mIsLastRefreshSuccessful; } /** * Perform refresh complete, to reset the state to {@link SmoothRefreshLayout#SR_STATUS_INIT} * and set the last refresh operation successfully. * * <p> */ public final void refreshComplete() { refreshComplete(true); } /** * Perform refresh complete, to reset the state to {@link SmoothRefreshLayout#SR_STATUS_INIT}. * * <p>`isSuccessful` * * @param isSuccessful Set the last refresh operation status */ public final void refreshComplete(boolean isSuccessful) { refreshComplete(isSuccessful, 0); } /** * Perform refresh complete, delay to reset the state to {@link * SmoothRefreshLayout#SR_STATUS_INIT} and set the last refresh operation successfully. * * <p>`delayDurationToChangeState` * * @param delayDurationToChangeState Delay to change the state to {@link * SmoothRefreshLayout#SR_STATUS_COMPLETE} */ public final void refreshComplete(long delayDurationToChangeState) { refreshComplete(true, delayDurationToChangeState); } /** * Perform refresh complete, delay to reset the state to {@link * SmoothRefreshLayout#SR_STATUS_INIT} and set the last refresh operation. * * <p>`isSuccessful``delayDurationToChangeState` * * @param delayDurationToChangeState Delay to change the state to {@link * SmoothRefreshLayout#SR_STATUS_INIT} * @param isSuccessful Set the last refresh operation */ public final void refreshComplete(boolean isSuccessful, long delayDurationToChangeState) { if (sDebug) { Log.d(TAG, String.format("refreshComplete(): isSuccessful: %b", isSuccessful)); } mIsLastRefreshSuccessful = isSuccessful; if (!isRefreshing() && !isLoadingMore()) { return; } if (delayDurationToChangeState <= 0) { performRefreshComplete(true, true); } else { if (isRefreshing() && mHeaderView != null) { mHeaderView.onRefreshComplete(this, isSuccessful); } else if (isLoadingMore() && mFooterView != null) { mFooterView.onRefreshComplete(this, isSuccessful); } if (mDelayToRefreshComplete == null) { mDelayToRefreshComplete = new DelayToRefreshComplete(); } mDelayToRefreshComplete.mLayout = this; mDelayToRefreshComplete.mNotifyViews = false; postDelayed(mDelayToRefreshComplete, delayDurationToChangeState); } } /** * Get the Header height, after the measurement is completed, the height will have value. * * <p>Header * * @return Height default is -1 */ public int getHeaderHeight() { return mIndicator.getHeaderHeight(); } /** * Get the Footer height, after the measurement is completed, the height will have value. * * <p>Footer * * @return Height default is -1 */ public int getFooterHeight() { return mIndicator.getFooterHeight(); } /** * Perform auto refresh at once. * * <p> */ public boolean autoRefresh() { return autoRefresh(ACTION_NOTIFY, true); } /** * If @param atOnce has been set to true. Auto perform refresh at once. * * <p>`atOnce` * * @param atOnce Auto refresh at once */ public boolean autoRefresh(boolean atOnce) { return autoRefresh(atOnce ? ACTION_AT_ONCE : ACTION_NOTIFY, true); } /** * If @param atOnce has been set to true. Auto perform refresh at once. If @param smooth has * been set to true. Auto perform refresh will using smooth scrolling. * * <p>`atOnce``smooth` * * @param atOnce Auto refresh at once * @param smoothScroll Auto refresh use smooth scrolling */ public boolean autoRefresh(boolean atOnce, boolean smoothScroll) { return autoRefresh(atOnce ? ACTION_AT_ONCE : ACTION_NOTIFY, smoothScroll); } /** * The @param action can be used to specify the action to trigger refresh. If the `action` been * set to `SR_ACTION_NOTHING`, we will not notify the refresh listener when in refreshing. If * the `action` been set to `SR_ACTION_AT_ONCE`, we will notify the refresh listener at once. If * the `action` been set to `SR_ACTION_NOTIFY`, we will notify the refresh listener when in * refreshing be later If @param smooth has been set to true. Auto perform refresh will using * smooth scrolling. * * <p>`action``smooth` * * @param action Auto refresh use action .{@link * me.dkzwm.widget.srl.config.Constants#ACTION_NOTIFY}, {@link * me.dkzwm.widget.srl.config.Constants#ACTION_AT_ONCE}, {@link * me.dkzwm.widget.srl.config.Constants#ACTION_NOTHING} * @param smoothScroll Auto refresh use smooth scrolling */ public boolean autoRefresh(@Action int action, boolean smoothScroll) { if (mStatus != SR_STATUS_INIT || isDisabledPerformRefresh()) { return false; } if (sDebug) { Log.d( TAG, String.format( "autoRefresh(): action: %d, smoothScroll: %b", action, smoothScroll)); } final byte old = mStatus; mStatus = SR_STATUS_PREPARE; notifyStatusChanged(old, mStatus); if (mHeaderView != null) { mHeaderView.onRefreshPrepare(this); } mIndicatorSetter.setMovingStatus(MOVING_HEADER); mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING; mAutomaticActionUseSmoothScroll = smoothScroll; mAutomaticAction = action; if (mIndicator.getHeaderHeight() <= 0) { mAutomaticActionTriggered = false; } else { scrollToTriggeredAutomatic(true); } return true; } /** * Perform auto load more at once. * * <p> */ public boolean autoLoadMore() { return autoLoadMore(ACTION_NOTIFY, true); } /** * If @param atOnce has been set to true. Auto perform load more at once. * * <p>`atOnce` * * @param atOnce Auto load more at once */ public boolean autoLoadMore(boolean atOnce) { return autoLoadMore(atOnce ? ACTION_AT_ONCE : ACTION_NOTIFY, true); } /** * If @param atOnce has been set to true. Auto perform load more at once. If @param smooth has * been set to true. Auto perform load more will using smooth scrolling. * * <p>`atOnce``smooth` * * @param atOnce Auto load more at once * @param smoothScroll Auto load more use smooth scrolling */ public boolean autoLoadMore(boolean atOnce, boolean smoothScroll) { return autoLoadMore(atOnce ? ACTION_AT_ONCE : ACTION_NOTIFY, smoothScroll); } /** * The @param action can be used to specify the action to trigger refresh. If the `action` been * set to `SR_ACTION_NOTHING`, we will not notify the refresh listener when in refreshing. If * the `action` been set to `SR_ACTION_AT_ONCE`, we will notify the refresh listener at once. If * the `action` been set to `SR_ACTION_NOTIFY`, we will notify the refresh listener when in * refreshing be later If @param smooth has been set to true. Auto perform load more will using * smooth scrolling. * * <p>`action``smooth` * * @param action Auto load more use action.{@link * me.dkzwm.widget.srl.config.Constants#ACTION_NOTIFY}, {@link * me.dkzwm.widget.srl.config.Constants#ACTION_AT_ONCE}, {@link * me.dkzwm.widget.srl.config.Constants#ACTION_NOTHING} * @param smoothScroll Auto load more use smooth scrolling */ public boolean autoLoadMore(@Action int action, boolean smoothScroll) { if (mStatus != SR_STATUS_INIT || isDisabledPerformLoadMore()) { return false; } if (sDebug) { Log.d( TAG, String.format( "autoLoadMore(): action: %d, smoothScroll: %b", action, smoothScroll)); } final byte old = mStatus; mStatus = SR_STATUS_PREPARE; notifyStatusChanged(old, mStatus); if (mFooterView != null) { mFooterView.onRefreshPrepare(this); } mIndicatorSetter.setMovingStatus(MOVING_FOOTER); mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING; mAutomaticActionUseSmoothScroll = smoothScroll; if (mIndicator.getFooterHeight() <= 0) { mAutomaticActionTriggered = false; } else { scrollToTriggeredAutomatic(false); } return true; } /** * Set the resistance while you are moving. * * <p> * * @param resistance Resistance */ public void setResistance(float resistance) { mIndicatorSetter.setResistance(resistance); } /** * Set the resistance while you are moving Footer. * * <p>Footer * * @param resistance Resistance */ public void setResistanceOfFooter(float resistance) { mIndicatorSetter.setResistanceOfFooter(resistance); } /** * Set the resistance while you are moving Header. * * <p>Header * * @param resistance Resistance */ public void setResistanceOfHeader(float resistance) { mIndicatorSetter.setResistanceOfHeader(resistance); } /** * Set the height ratio of the trigger refresh. * * <p> * * @param ratio Height ratio */ public void setRatioToRefresh(float ratio) { mIndicatorSetter.setRatioToRefresh(ratio); } /** * Set the Header height ratio of the trigger refresh. * * <p>Header * * @param ratio Height ratio */ public void setRatioOfHeaderToRefresh(float ratio) { mIndicatorSetter.setRatioOfHeaderToRefresh(ratio); } /** * Set the Footer height ratio of the trigger refresh. * * <p>Footer * * @param ratio Height ratio */ public void setRatioOfFooterToRefresh(float ratio) { mIndicatorSetter.setRatioOfFooterToRefresh(ratio); } /** * Set the offset of keep view in refreshing occupies the height ratio of the refresh view. * * <p>:`1f`, {@link * SmoothRefreshLayout#isEnabledKeepRefreshView} * * @param ratio Height ratio */ public void setRatioToKeep(float ratio) { mIndicatorSetter.setRatioToKeepHeader(ratio); mIndicatorSetter.setRatioToKeepFooter(ratio); } /** * Set the offset of keep Header in refreshing occupies the height ratio of the Header. * * <p>Header:`1f`, * * @param ratio Height ratio */ public void setRatioToKeepHeader(float ratio) { mIndicatorSetter.setRatioToKeepHeader(ratio); } /** * Set the offset of keep Footer in refreshing occupies the height ratio of the Footer. * * <p>Header:`1f`, * * @param ratio Height ratio */ public void setRatioToKeepFooter(float ratio) { mIndicatorSetter.setRatioToKeepFooter(ratio); } /** * Set the max duration for Cross-Boundary-Rebound(OverScroll). * * <p>:`350` * * @param duration Duration */ public void setMaxOverScrollDuration(int duration) { mMaxOverScrollDuration = duration; } /** * Set the min duration for Cross-Boundary-Rebound(OverScroll). * * <p>:`100` * * @param duration Duration */ public void setMinOverScrollDuration(int duration) { mMinOverScrollDuration = duration; } /** * Set the duration of return back to the start position. * * <p> * * @param duration Millis */ public void setDurationToClose(int duration) { mDurationToCloseHeader = duration; mDurationToCloseFooter = duration; } /** * Get the duration of Header return to the start position. * * @return mDuration */ public int getDurationToCloseHeader() { return mDurationToCloseHeader; } /** * Set the duration of Header return to the start position. * * <p>Header * * @param duration Millis */ public void setDurationToCloseHeader(int duration) { mDurationToCloseHeader = duration; } /** * Get the duration of Footer return to the start position. * * @return mDuration */ public int getDurationToCloseFooter() { return mDurationToCloseFooter; } /** * Set the duration of Footer return to the start position. * * <p>Footer * * @param duration Millis */ public void setDurationToCloseFooter(int duration) { mDurationToCloseFooter = duration; } /** * Set the duration of return to the keep refresh view position. * * <p> * * @param duration Millis */ public void setDurationOfBackToKeep(int duration) { mDurationOfBackToHeaderHeight = duration; mDurationOfBackToFooterHeight = duration; } /** * Set the duration of return to the keep refresh view position when Header moves. * * <p>Header * * @param duration Millis */ public void setDurationOfBackToKeepHeader(int duration) { this.mDurationOfBackToHeaderHeight = duration; } /** * Set the duration of return to the keep refresh view position when Footer moves. * * <p>Footer * * @param duration Millis */ public void setDurationOfBackToKeepFooter(int duration) { this.mDurationOfBackToFooterHeight = duration; } /** * Set the max can move offset occupies the height ratio of the refresh view. * * <p> * * @param ratio The max ratio of refresh view */ public void setMaxMoveRatio(float ratio) { mIndicatorSetter.setMaxMoveRatio(ratio); } /** * Set the max can move offset occupies the height ratio of the Header. * * <p>Header * * @param ratio The max ratio of Header view */ public void setMaxMoveRatioOfHeader(float ratio) { mIndicatorSetter.setMaxMoveRatioOfHeader(ratio); } /** * Set the max can move offset occupies the height ratio of the Footer. * * <p>Footer * * @param ratio The max ratio of Footer view */ public void setMaxMoveRatioOfFooter(float ratio) { mIndicatorSetter.setMaxMoveRatioOfFooter(ratio); } /** * The flag has set to autoRefresh. * * <p> * * @return Enabled */ public boolean isAutoRefresh() { return (mFlag & FLAG_AUTO_REFRESH) > 0; } /** * If enable has been set to true. The user can immediately perform next refresh. * * <p> * * @return Is enable */ public boolean isEnabledNextPtrAtOnce() { return (mFlag & FLAG_ENABLE_NEXT_AT_ONCE) > 0; } /** * If @param enable has been set to true. The user can immediately perform next refresh. * * <p> * * @param enable Enable */ public void setEnableNextPtrAtOnce(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_NEXT_AT_ONCE; } else { mFlag = mFlag & ~FLAG_ENABLE_NEXT_AT_ONCE; } } /** * The flag has set enabled overScroll. * * <p> * * @return Enabled */ public boolean isEnabledOverScroll() { return (mFlag & FLAG_ENABLE_OVER_SCROLL) > 0; } /** * If @param enable has been set to true. Will supports over scroll. * * <p> * * @param enable Enable */ public void setEnableOverScroll(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_OVER_SCROLL; } else { mFlag = mFlag & ~FLAG_ENABLE_OVER_SCROLL; } } /** * The flag has set enabled to intercept the touch event while loading. * * <p> * * @return Enabled */ public boolean isEnabledInterceptEventWhileLoading() { return (mFlag & FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING) > 0; } /** * If @param enable has been set to true. Will intercept the touch event while loading. * * <p> * * @param enable Enable */ public void setEnableInterceptEventWhileLoading(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING; } else { mFlag = mFlag & ~FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING; } } /** * The flag has been set to pull to refresh. * * <p> * * @return Enabled */ public boolean isEnabledPullToRefresh() { return (mFlag & FLAG_ENABLE_PULL_TO_REFRESH) > 0; } /** * If @param enable has been set to true. When the current pos >= refresh offsets perform * refresh. * * <p>, * * @param enable Pull to refresh */ public void setEnablePullToRefresh(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_PULL_TO_REFRESH; } else { mFlag = mFlag & ~FLAG_ENABLE_PULL_TO_REFRESH; } } /** * The flag has been set to enabled Header drawerStyle. * * <p>HeaderHeaderContent * * @return Enabled */ public boolean isEnabledHeaderDrawerStyle() { return (mFlag & FLAG_ENABLE_HEADER_DRAWER_STYLE) > 0; } /** * If @param enable has been set to true.Enable Header drawerStyle. * * <p>HeaderHeaderContent, * * @param enable enable Header drawerStyle */ public void setEnableHeaderDrawerStyle(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_HEADER_DRAWER_STYLE; } else { mFlag = mFlag & ~FLAG_ENABLE_HEADER_DRAWER_STYLE; } mViewsZAxisNeedReset = true; checkViewsZAxisNeedReset(); } /** * The flag has been set to enabled Footer drawerStyle. * * <p>FooterFooterContent * * @return Enabled */ public boolean isEnabledFooterDrawerStyle() { return (mFlag & FLAG_ENABLE_FOOTER_DRAWER_STYLE) > 0; } /** * If @param enable has been set to true.Enable Footer drawerStyle. * * <p>FooterFooterContent, * * @param enable enable Footer drawerStyle */ public void setEnableFooterDrawerStyle(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_FOOTER_DRAWER_STYLE; } else { mFlag = mFlag & ~FLAG_ENABLE_FOOTER_DRAWER_STYLE; } mViewsZAxisNeedReset = true; checkViewsZAxisNeedReset(); } /** * The flag has been set to disabled perform refresh. * * <p> * * @return Disabled */ public boolean isDisabledPerformRefresh() { return (mFlag & MASK_DISABLE_PERFORM_REFRESH) > 0; } /** * If @param disable has been set to true. Will never perform refresh. * * <p> * * @param disable Disable perform refresh */ public void setDisablePerformRefresh(boolean disable) { if (disable) { mFlag = mFlag | FLAG_DISABLE_PERFORM_REFRESH; if (isRefreshing()) reset(); } else { mFlag = mFlag & ~FLAG_DISABLE_PERFORM_REFRESH; } } /** * The flag has been set to disabled refresh. * * <p> * * @return Disabled */ public boolean isDisabledRefresh() { return (mFlag & FLAG_DISABLE_REFRESH) > 0; } /** * If @param disable has been set to true.Will disable refresh. * * <p> * * @param disable Disable refresh */ public void setDisableRefresh(boolean disable) { if (disable) { mFlag = mFlag | FLAG_DISABLE_REFRESH; reset(); } else { mFlag = mFlag & ~FLAG_DISABLE_REFRESH; } } /** * The flag has been set to disabled perform load more. * * <p> * * @return Disabled */ public boolean isDisabledPerformLoadMore() { return (mFlag & MASK_DISABLE_PERFORM_LOAD_MORE) > 0; } /** * If @param disable has been set to true.Will never perform load more. * * <p> * * @param disable Disable perform load more */ public void setDisablePerformLoadMore(boolean disable) { if (disable) { mFlag = mFlag | FLAG_DISABLE_PERFORM_LOAD_MORE; if (isLoadingMore()) reset(); } else { mFlag = mFlag & ~FLAG_DISABLE_PERFORM_LOAD_MORE; } } /** * The flag has been set to disabled load more. * * <p> * * @return Disabled */ public boolean isDisabledLoadMore() { return (mFlag & FLAG_DISABLE_LOAD_MORE) > 0; } /** * If @param disable has been set to true. Will disable load more. * * <p> * * @param disable Disable load more */ public void setDisableLoadMore(boolean disable) { if (disable) { mFlag = mFlag | FLAG_DISABLE_LOAD_MORE; reset(); } else { mFlag = mFlag & ~FLAG_DISABLE_LOAD_MORE; } } /** * The flag has been set to enabled the old touch handling logic. * * <p> * * @return Enabled */ public boolean isEnabledOldTouchHandling() { return (mFlag & FLAG_ENABLE_OLD_TOUCH_HANDLING) > 0; } /** * If @param enable has been set to true. Frame will use the old version of the touch event * handling logic. * * <p> * * * * * @param enable Enable old touch handling */ public void setEnableOldTouchHandling(boolean enable) { if (mIndicator.hasTouched()) { Log.e(TAG, "This method cannot be called during touch event handling"); return; } if (enable) { mFlag = mFlag | FLAG_ENABLE_OLD_TOUCH_HANDLING; } else { mFlag = mFlag & ~FLAG_ENABLE_OLD_TOUCH_HANDLING; } } /** * The flag has been set to disabled when horizontal move. * * <p> * * @return Disabled */ public boolean isDisabledWhenAnotherDirectionMove() { return (mFlag & FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE) > 0; } /** * Set whether to filter the horizontal moves. * * <p> * * @param disable Enable */ public void setDisableWhenAnotherDirectionMove(boolean disable) { if (disable) { mFlag = mFlag | FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE; } else { mFlag = mFlag & ~FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE; } } /** * The flag has been set to enabled load more has no more data. * * <p>Footer * * @return Enabled */ public boolean isEnabledNoMoreData() { return (mFlag & FLAG_ENABLE_NO_MORE_DATA) > 0; } /** * If @param enable has been set to true. The Footer will show no more data and will never * trigger load more. * * <p>`true` * * @param enable Enable no more data */ public void setEnableNoMoreData(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_NO_MORE_DATA; } else { mFlag = mFlag & ~FLAG_ENABLE_NO_MORE_DATA; } } /** * The flag has been set to enabled. The scroller rollback can not be interrupted when refresh * completed. * * <p> * * @return Enabled */ public boolean isEnabledSmoothRollbackWhenCompleted() { return (mFlag & FLAG_ENABLE_SMOOTH_ROLLBACK_WHEN_COMPLETED) > 0; } /** * If @param enable has been set to true. The rollback can not be interrupted when refresh * completed. * * <p> * * @param enable Enable no more data */ public void setEnableSmoothRollbackWhenCompleted(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_SMOOTH_ROLLBACK_WHEN_COMPLETED; } else { mFlag = mFlag & ~FLAG_ENABLE_SMOOTH_ROLLBACK_WHEN_COMPLETED; } } /** * The flag has been set to enabled. Load more will be disabled when the content is not full. * * <p> * * @return Disabled */ public boolean isDisabledLoadMoreWhenContentNotFull() { return (mFlag & FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL) > 0; } /** * If @param disable has been set to true.Load more will be disabled when the content is not * full. * * <p> * * @param disable Disable load more when the content is not full */ public void setDisableLoadMoreWhenContentNotFull(boolean disable) { if (disable) { mFlag = mFlag | FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL; } else { mFlag = mFlag & ~FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL; } } /** * The flag has been set to enabled when Footer has no more data to no longer need spring back. * * <p> * * @return Enabled */ public boolean isEnabledNoSpringBackWhenNoMoreData() { return (mFlag & FLAG_ENABLE_NO_MORE_DATA_NO_BACK) > 0; } /** * If @param enable has been set to true. When there is no more data will no longer spring back. * * <p>`true` * * @param enable Enable no more data */ public void setEnableNoSpringBackWhenNoMoreData(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_NO_MORE_DATA_NO_BACK; } else { mFlag = mFlag & ~FLAG_ENABLE_NO_MORE_DATA_NO_BACK; } } /** * The flag has been set to keep refresh view while loading. * * <p> * * @return Enabled */ public boolean isEnabledKeepRefreshView() { return (mFlag & FLAG_ENABLE_KEEP_REFRESH_VIEW) > 0; } /** * If @param enable has been set to true.When the current pos> = keep refresh view pos, it rolls * back to the keep refresh view pos to perform refresh and remains until the refresh completed. * * <p> * * @param enable Keep refresh view */ public void setEnableKeepRefreshView(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_KEEP_REFRESH_VIEW; } else { mFlag = mFlag & ~FLAG_ENABLE_KEEP_REFRESH_VIEW; setEnablePinRefreshViewWhileLoading(false); } } /** * The flag has been set to perform load more when the content view scrolling to bottom. * * <p> * * @return Enabled */ public boolean isEnabledAutoLoadMore() { return (mFlag & FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE) > 0; } /** * If @param enable has been set to true.When the content view scrolling to bottom, it will be * perform load more. * * <p> * * @param enable Enable */ public void setEnableAutoLoadMore(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE; } else { mFlag = mFlag & ~FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE; } } /** * The flag has been set to perform refresh when the content view scrolling to top. * * <p> * * @return Enabled */ public boolean isEnabledAutoRefresh() { return (mFlag & FLAG_ENABLE_AUTO_PERFORM_REFRESH) > 0; } /** * If @param enable has been set to true.When the content view scrolling to top, it will be * perform refresh. * * <p> * * @param enable Enable */ public void setEnableAutoRefresh(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_AUTO_PERFORM_REFRESH; } else { mFlag = mFlag & ~FLAG_ENABLE_AUTO_PERFORM_REFRESH; } } /** * The flag has been set to pinned refresh view while loading. * * <p> * * @return Enabled */ public boolean isEnabledPinRefreshViewWhileLoading() { return (mFlag & FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING) > 0; } /** * If @param enable has been set to true.The refresh view will pinned at the keep refresh * position. * * <p> {@link * SmoothRefreshLayout#setEnablePinContentView(boolean)} {@link * SmoothRefreshLayout#setEnableKeepRefreshView(boolean)}2`true` * * @param enable Pin content view */ public void setEnablePinRefreshViewWhileLoading(boolean enable) { if (enable) { if (isEnabledPinContentView() && isEnabledKeepRefreshView()) { mFlag = mFlag | FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING; } else { Log.e( TAG, "This method can only be enabled if setEnablePinContentView" + " and setEnableKeepRefreshView are set be true"); } } else { mFlag = mFlag & ~FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING; } } /** * The flag has been set to pinned content view while loading. * * <p> * * @return Enabled */ public boolean isEnabledPinContentView() { return (mFlag & FLAG_ENABLE_PIN_CONTENT_VIEW) > 0; } /** * If @param enable has been set to true. The content view will be pinned in the start pos. * * <p> * * @param enable Pin content view */ public void setEnablePinContentView(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_PIN_CONTENT_VIEW; } else { mFlag = mFlag & ~FLAG_ENABLE_PIN_CONTENT_VIEW; setEnablePinRefreshViewWhileLoading(false); } } /** * The flag has been set to perform refresh when Fling. * * <p>Fling, * * @return Enabled */ public boolean isEnabledPerformFreshWhenFling() { return (mFlag & FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING) > 0; } /** * If @param enable has been set to true. When the gesture of retracting the refresh view is * triggered and the current offset is greater than the trigger refresh offset, the fresh can be * performed without the Fling effect. * * <p>Fling * * @param enable enable perform refresh when fling */ public void setEnablePerformFreshWhenFling(boolean enable) { if (enable) { mFlag = mFlag | FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING; } else { mFlag = mFlag & ~FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING; } } @Nullable public IRefreshView<IIndicator> getFooterView() { // Use the static default creator to create the Footer view if (!isDisabledLoadMore() && mFooterView == null && sCreator != null) { final IRefreshView<IIndicator> footer = sCreator.createFooter(this); if (footer != null) { setFooterView(footer); } } return mFooterView; } /** * Set the Footer view. * * <p>Footer * * @param footer Footer view */ public void setFooterView(@NonNull IRefreshView footer) { if (footer.getType() != IRefreshView.TYPE_FOOTER) { throw new IllegalArgumentException("Wrong type, FooterView type must be TYPE_FOOTER"); } if (footer == mFooterView) { return; } if (mFooterView != null) { removeView(mFooterView.getView()); mFooterView = null; } final View view = footer.getView(); mViewsZAxisNeedReset = true; addView(view, -1, view.getLayoutParams()); } @Nullable public IRefreshView<IIndicator> getHeaderView() { // Use the static default creator to create the Header view if (!isDisabledRefresh() && mHeaderView == null && sCreator != null) { final IRefreshView<IIndicator> header = sCreator.createHeader(this); if (header != null) { setHeaderView(header); } } return mHeaderView; } /** * Set the Header view. * * <p>Header * * @param header Header view */ public void setHeaderView(@NonNull IRefreshView header) { if (header.getType() != IRefreshView.TYPE_HEADER) { throw new IllegalArgumentException("Wrong type, HeaderView type must be TYPE_HEADER"); } if (header == mHeaderView) { return; } if (mHeaderView != null) { removeView(mHeaderView.getView()); mHeaderView = null; } final View view = header.getView(); mViewsZAxisNeedReset = true; addView(view, -1, view.getLayoutParams()); } /** * Set the content view. * * <p> * * @param content Content view */ public void setContentView(View content) { if (mTargetView == content) { return; } mContentResId = View.NO_ID; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child == content) { mTargetView = content; return; } } if (mTargetView != null) { removeView(mTargetView); } ViewGroup.LayoutParams lp = content.getLayoutParams(); if (lp == null) { lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } mTargetView = content; mViewsZAxisNeedReset = true; addView(content, lp); } public void setContentResId(@IdRes int id) { if (id != mContentResId) { mContentResId = id; mTargetView = null; ensureTargetView(); } } /** * Reset scroller interpolator. * * <p>Scroller */ public void resetScrollerInterpolator() { if (mSpringInterpolator != sSpringInterpolator) { setSpringInterpolator(sSpringInterpolator); } if (mSpringBackInterpolator != sSpringBackInterpolator) { setSpringBackInterpolator(sSpringBackInterpolator); } } /** * Set the scroller default interpolator. * * <p>Scroller * * @param interpolator Scroller interpolator */ public void setSpringInterpolator(@NonNull Interpolator interpolator) { if (mSpringInterpolator != interpolator) { mSpringInterpolator = interpolator; if (mScrollChecker.isSpring()) { mScrollChecker.setInterpolator(interpolator); } } } /** * Set the scroller spring back interpolator. * * @param interpolator Scroller interpolator */ public void setSpringBackInterpolator(@NonNull Interpolator interpolator) { if (mSpringBackInterpolator != interpolator) { mSpringBackInterpolator = interpolator; if (mScrollChecker.isSpringBack() || mScrollChecker.isFlingBack()) { mScrollChecker.setInterpolator(interpolator); } } } /** * Get the ScrollChecker current mode. * * @return the mode {@link me.dkzwm.widget.srl.config.Constants#SCROLLER_MODE_NONE}, {@link * me.dkzwm.widget.srl.config.Constants#SCROLLER_MODE_PRE_FLING}, {@link * me.dkzwm.widget.srl.config.Constants#SCROLLER_MODE_FLING}, {@link * me.dkzwm.widget.srl.config.Constants#SCROLLER_MODE_CALC_FLING}, {@link * me.dkzwm.widget.srl.config.Constants#SCROLLER_MODE_FLING_BACK}, {@link * me.dkzwm.widget.srl.config.Constants#SCROLLER_MODE_SPRING}, {@link * me.dkzwm.widget.srl.config.Constants#SCROLLER_MODE_SPRING_BACK}. */ public byte getScrollMode() { return mScrollChecker.mMode; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams lp) { return lp instanceof LayoutParams; } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { if (lp instanceof LayoutParams) { return lp; } else if (lp instanceof MarginLayoutParams) { return new LayoutParams((MarginLayoutParams) lp); } else { return new LayoutParams(lp); } } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } /** * Set the pinned header view resource id * * @param resId Resource id */ public void setStickyHeaderResId(@IdRes int resId) { if (mStickyHeaderResId != resId) { mStickyHeaderResId = resId; mStickyHeaderView = null; ensureTargetView(); } } /** * Set the pinned footer view resource id * * @param resId Resource id */ public void setStickyFooterResId(@IdRes int resId) { if (mStickyFooterResId != resId) { mStickyFooterResId = resId; mStickyFooterView = null; ensureTargetView(); } } protected boolean onFling(float vx, final float vy, boolean nested) { if (sDebug) { Log.d( TAG, String.format( "onFling() velocityX: %s, velocityY: %s, nested: %s", vx, vy, nested)); } if ((isNeedInterceptTouchEvent() || isCanNotAbortOverScrolling())) { return true; } if (mPreventForAnotherDirection) { return nested && dispatchNestedPreFling(-vx, -vy); } float realVelocity = isVerticalOrientation() ? vy : vx; final boolean canNotChildScrollDown = !isNotYetInEdgeCannotMoveFooter(); final boolean canNotChildScrollUp = !isNotYetInEdgeCannotMoveHeader(); if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) { if (!isEnabledPinRefreshViewWhileLoading()) { if (Math.abs(realVelocity) > 2000) { if ((realVelocity > 0 && isMovingHeader()) || (realVelocity < 0 && isMovingFooter())) { if (isEnabledOverScroll()) { if (isDisabledLoadMoreWhenContentNotFull() && canNotChildScrollDown && canNotChildScrollUp) { return true; } boolean invert = realVelocity < 0; realVelocity = (float) Math.pow(Math.abs(realVelocity), .5f); mScrollChecker.startPreFling(invert ? -realVelocity : realVelocity); } } else { if (mScrollChecker.getFinalY(realVelocity) > mIndicator.getCurrentPos()) { if (!isEnabledPerformFreshWhenFling()) { mScrollChecker.startPreFling(realVelocity); } else if (isMovingHeader() && (isDisabledPerformRefresh() || mIndicator.getCurrentPos() < mIndicator.getOffsetToRefresh())) { mScrollChecker.startPreFling(realVelocity); } else if (isMovingFooter() && (isDisabledPerformLoadMore() || mIndicator.getCurrentPos() < mIndicator.getOffsetToLoadMore())) { mScrollChecker.startPreFling(realVelocity); } } } } return true; } if (nested) { return dispatchNestedPreFling(-vx, -vy); } else { return true; } } else { tryToResetMovingStatus(); if (isEnabledOverScroll() && (!isEnabledPinRefreshViewWhileLoading() || ((realVelocity >= 0 || !isDisabledLoadMore()) && (realVelocity <= 0 || !isDisabledRefresh())))) { if (isDisabledLoadMoreWhenContentNotFull() && realVelocity < 0 && canNotChildScrollDown && canNotChildScrollUp) { return nested && dispatchNestedPreFling(-vx, -vy); } mScrollChecker.startFling(realVelocity); if (!nested && isEnabledOldTouchHandling()) { if (mDelayToDispatchNestedFling == null) mDelayToDispatchNestedFling = new DelayToDispatchNestedFling(); mDelayToDispatchNestedFling.mLayout = this; mDelayToDispatchNestedFling.mVelocity = (int) realVelocity; ViewCompat.postOnAnimation(this, mDelayToDispatchNestedFling); invalidate(); return true; } } invalidate(); } return nested && dispatchNestedPreFling(-vx, -vy); } @Override public boolean onStartNestedScroll( @NonNull View child, @NonNull View target, int nestedScrollAxes) { return onStartNestedScroll(child, target, nestedScrollAxes, ViewCompat.TYPE_TOUCH); } @Override public boolean onStartNestedScroll( @NonNull View child, @NonNull View target, int axes, int type) { if (sDebug) { Log.d(TAG, String.format("onStartNestedScroll(): axes: %s, type: %s", axes, type)); } return isEnabled() && isNestedScrollingEnabled() && mTargetView != null && (axes & getSupportScrollAxis()) != 0; } @Override public void onNestedScrollAccepted(@NonNull View child, @NonNull View target, int axes) { onNestedScrollAccepted(child, target, axes, ViewCompat.TYPE_TOUCH); } @Override public void onNestedScrollAccepted( @NonNull View child, @NonNull View target, int axes, int type) { if (sDebug) { Log.d(TAG, String.format("onNestedScrollAccepted(): axes: %s, type: %s", axes, type)); } // Reset the counter of how much leftover scroll needs to be consumed. mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, axes, type); // Dispatch up to the nested parent startNestedScroll(axes & getSupportScrollAxis(), type); mNestedTouchScrolling = type == ViewCompat.TYPE_TOUCH; mLastNestedType = type; mNestedScrolling = true; } @Override public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed) { onNestedPreScroll(target, dx, dy, consumed, ViewCompat.TYPE_TOUCH); } @Override public void onNestedPreScroll( @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) { final boolean isVerticalOrientation = isVerticalOrientation(); if (type == ViewCompat.TYPE_TOUCH) { if (tryToFilterTouchEvent(null)) { if (isVerticalOrientation) { consumed[1] = dy; } else { consumed[0] = dx; } } else { mScrollChecker.stop(); final boolean canNotChildScrollDown = !isNotYetInEdgeCannotMoveFooter(); final boolean canNotChildScrollUp = !isNotYetInEdgeCannotMoveHeader(); final int distance = isVerticalOrientation ? dy : dx; if (distance > 0 && !isDisabledRefresh() && canNotChildScrollUp && !(isEnabledPinRefreshViewWhileLoading() && isRefreshing() && mIndicator.isOverOffsetToKeepHeaderWhileLoading())) { if (!mIndicator.isAlreadyHere(IIndicator.START_POS) && isMovingHeader()) { mIndicatorSetter.onFingerMove( mIndicator.getLastMovePoint()[0] - dx, mIndicator.getLastMovePoint()[1] - dy); moveHeaderPos(mIndicator.getOffset()); if (isVerticalOrientation) { consumed[1] = dy; } else { consumed[0] = dx; } } else { if (isVerticalOrientation) { mIndicatorSetter.onFingerMove( mIndicator.getLastMovePoint()[0] - dx, mIndicator.getLastMovePoint()[1]); } else { mIndicatorSetter.onFingerMove( mIndicator.getLastMovePoint()[0], mIndicator.getLastMovePoint()[1] - dy); } } } if (distance < 0 && !isDisabledLoadMore() && canNotChildScrollDown && !(isEnabledPinRefreshViewWhileLoading() && isLoadingMore() && mIndicator.isOverOffsetToKeepFooterWhileLoading())) { if (!mIndicator.isAlreadyHere(IIndicator.START_POS) && isMovingFooter()) { mIndicatorSetter.onFingerMove( mIndicator.getLastMovePoint()[0] - dx, mIndicator.getLastMovePoint()[1] - dy); moveFooterPos(mIndicator.getOffset()); if (isVerticalOrientation) { consumed[1] = dy; } else { consumed[0] = dx; } } else { if (isVerticalOrientation) { mIndicatorSetter.onFingerMove( mIndicator.getLastMovePoint()[0] - dx, mIndicator.getLastMovePoint()[1]); } else { mIndicatorSetter.onFingerMove( mIndicator.getLastMovePoint()[0], mIndicator.getLastMovePoint()[1] - dy); } } } if (isMovingFooter() && isFooterInProcessing() && mStatus == SR_STATUS_COMPLETE && mIndicator.hasLeftStartPosition() && !canNotChildScrollDown) { mScrollChecker.scrollTo(IIndicator.START_POS, 0); if (isVerticalOrientation) { consumed[1] = dy; } else { consumed[0] = dx; } } } tryToResetMovingStatus(); } // Now let our nested parent consume the leftovers final int[] parentConsumed = mParentScrollConsumed; parentConsumed[0] = 0; parentConsumed[1] = 0; if (dispatchNestedPreScroll( dx - consumed[0], dy - consumed[1], parentConsumed, null, type)) { consumed[0] += parentConsumed[0]; consumed[1] += parentConsumed[1]; } else if (type == ViewCompat.TYPE_NON_TOUCH) { if (!isMovingContent() && !(isEnabledPinRefreshViewWhileLoading())) { if (isVerticalOrientation) { parentConsumed[1] = dy; } else { parentConsumed[0] = dx; } consumed[0] += parentConsumed[0]; consumed[1] += parentConsumed[1]; } } if (consumed[0] != 0 || consumed[1] != 0) { onNestedScrollChanged(false); } if (sDebug) { Log.d( TAG, String.format( "onNestedPreScroll(): dx: %s, dy: %s, consumed: %s, type: %s", dx, dy, Arrays.toString(consumed), type)); } } @Override public int getNestedScrollAxes() { return mNestedScrollingParentHelper.getNestedScrollAxes(); } @Override public void onStopNestedScroll(@NonNull View target) { onStopNestedScroll(target, ViewCompat.TYPE_TOUCH); } @Override public void onStopNestedScroll(@NonNull View target, int type) { if (sDebug) { Log.d(TAG, String.format("onStopNestedScroll() type: %s", type)); } mNestedScrollingParentHelper.onStopNestedScroll(target, type); if (mLastNestedType == type) { mNestedScrolling = false; } mNestedTouchScrolling = false; mIsInterceptTouchEventInOnceTouch = isNeedInterceptTouchEvent(); mIsLastOverScrollCanNotAbort = isCanNotAbortOverScrolling(); // Dispatch up our nested parent mNestedScrollingChildHelper.stopNestedScroll(type); if (!isAutoRefresh() && type == ViewCompat.TYPE_TOUCH) { mIndicatorSetter.onFingerUp(); onFingerUp(); } onNestedScrollChanged(true); } @Override public void onNestedScroll( @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { onNestedScroll( target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, ViewCompat.TYPE_TOUCH); } @Override public void onNestedScroll( @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { mCachedIntPoint[0] = 0; mCachedIntPoint[1] = 0; onNestedScroll( target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, mCachedIntPoint); } @Override public void onNestedScroll( @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, @NonNull int[] consumed) { // Dispatch up to the nested parent first dispatchNestedScroll( dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, mParentOffsetInWindow, type, consumed); if (sDebug) { Log.d( TAG, String.format( "onNestedScroll(): dxConsumed: %s, dyConsumed: %s, dxUnconsumed: %s" + " dyUnconsumed: %s, type: %s, consumed: %s", dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, Arrays.toString(consumed))); } final boolean isVerticalOrientation = isVerticalOrientation(); if (isVerticalOrientation) { if (dyUnconsumed == 0 || consumed[1] == dyUnconsumed) { onNestedScrollChanged(false); return; } } else { if (dxUnconsumed == 0 || consumed[0] == dxUnconsumed) { onNestedScrollChanged(false); return; } } if (type == ViewCompat.TYPE_TOUCH) { if (tryToFilterTouchEvent(null)) return; final int dx = dxUnconsumed + mParentOffsetInWindow[0] - consumed[0]; final int dy = dyUnconsumed + mParentOffsetInWindow[1] - consumed[1]; final boolean canNotChildScrollDown = !isNotYetInEdgeCannotMoveFooter(); final boolean canNotChildScrollUp = !isNotYetInEdgeCannotMoveHeader(); final int distance = isVerticalOrientation ? dy : dx; if (distance < 0 && !isDisabledRefresh() && canNotChildScrollUp && !(isEnabledPinRefreshViewWhileLoading() && isRefreshing() && mIndicator.isOverOffsetToKeepHeaderWhileLoading())) { mIndicatorSetter.onFingerMove( mIndicator.getLastMovePoint()[0] - dx, mIndicator.getLastMovePoint()[1] - dy); moveHeaderPos(mIndicator.getOffset()); if (isVerticalOrientation) { consumed[1] += dy; } else { consumed[0] += dx; } } else if (distance > 0 && !isDisabledLoadMore() && canNotChildScrollDown && !(isDisabledLoadMoreWhenContentNotFull() && canNotChildScrollUp && mIndicator.isAlreadyHere(IIndicator.START_POS)) && !(isEnabledPinRefreshViewWhileLoading() && isLoadingMore() && mIndicator.isOverOffsetToKeepFooterWhileLoading())) { mIndicatorSetter.onFingerMove( mIndicator.getLastMovePoint()[0] - dx, mIndicator.getLastMovePoint()[1] - dy); moveFooterPos(mIndicator.getOffset()); if (isVerticalOrientation) { consumed[1] += dy; } else { consumed[0] += dx; } } tryToResetMovingStatus(); } if (dxConsumed != 0 || dyConsumed != 0 || consumed[0] != 0 || consumed[1] != 0) { onNestedScrollChanged(false); } } @Override public boolean isNestedScrollingEnabled() { return mNestedScrollingChildHelper.isNestedScrollingEnabled(); } @Override public void setNestedScrollingEnabled(boolean enabled) { mNestedScrollingChildHelper.setNestedScrollingEnabled(enabled); } @Override public boolean startNestedScroll(int axes) { return mNestedScrollingChildHelper.startNestedScroll(axes); } @Override public boolean startNestedScroll(int axes, int type) { return mNestedScrollingChildHelper.startNestedScroll(axes, type); } @Override public void stopNestedScroll() { stopNestedScroll(ViewCompat.TYPE_TOUCH); } @Override public void stopNestedScroll(int type) { if (sDebug) { Log.d(TAG, String.format("stopNestedScroll() type: %s", type)); } final View targetView = getScrollTargetView(); if (targetView != null) { ViewCompat.stopNestedScroll(targetView, type); } else { mNestedScrollingChildHelper.stopNestedScroll(type); } } @Override public boolean hasNestedScrollingParent() { return mNestedScrollingChildHelper.hasNestedScrollingParent(); } @Override public boolean hasNestedScrollingParent(int type) { return mNestedScrollingChildHelper.hasNestedScrollingParent(type); } @Override public boolean dispatchNestedScroll( int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { return mNestedScrollingChildHelper.dispatchNestedScroll( dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow); } @Override public boolean dispatchNestedScroll( int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, @Nullable int[] offsetInWindow, int type) { return mNestedScrollingChildHelper.dispatchNestedScroll( dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type); } @Override public void dispatchNestedScroll( int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, @Nullable int[] offsetInWindow, int type, @NonNull int[] consumed) { mNestedScrollingChildHelper.dispatchNestedScroll( dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type, consumed); } @Override public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { return mNestedScrollingChildHelper.dispatchNestedPreScroll( dx, dy, consumed, offsetInWindow); } @Override public boolean dispatchNestedPreScroll( int dx, int dy, @Nullable int[] consumed, @Nullable int[] offsetInWindow, int type) { return mNestedScrollingChildHelper.dispatchNestedPreScroll( dx, dy, consumed, offsetInWindow, type); } @Override public boolean onNestedPreFling(@NonNull View target, float velocityX, float velocityY) { return onFling(-velocityX, -velocityY, true); } @Override public boolean onNestedFling( @NonNull View target, float velocityX, float velocityY, boolean consumed) { return dispatchNestedFling(velocityX, velocityY, consumed); } @Override public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { return mNestedScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed); } @Override public boolean dispatchNestedPreFling(float velocityX, float velocityY) { return mNestedScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY); } @Override public void computeScroll() { if (mNestedScrolling || !isMovingContent()) { return; } onNestedScrollChanged(true); } @Override public boolean canScrollVertically(int direction) { if (isVerticalOrientation()) { if (direction < 0) { return super.canScrollVertically(direction) || isNotYetInEdgeCannotMoveHeader(); } else { return super.canScrollVertically(direction) || isNotYetInEdgeCannotMoveFooter(); } } return super.canScrollVertically(direction); } @Override public boolean canScrollHorizontally(int direction) { if (!isVerticalOrientation()) { if (direction < 0) { return super.canScrollHorizontally(direction) || isNotYetInEdgeCannotMoveHeader(); } else { return super.canScrollHorizontally(direction) || isNotYetInEdgeCannotMoveFooter(); } } return super.canScrollHorizontally(direction); } public void onNestedScrollChanged(boolean compute) { if (mNeedFilterScrollEvent) { mNeedFilterScrollEvent = false; return; } tryScrollToPerformAutoRefresh(); if (compute) { mScrollChecker.computeScrollOffset(); } } public boolean isVerticalOrientation() { return mLayoutManager.getOrientation() == LayoutManager.VERTICAL; } /** Check the Z-Axis relationships of the views need to be rearranged */ protected void checkViewsZAxisNeedReset() { final int count = getChildCount(); if (mViewsZAxisNeedReset && count > 0) { mCachedViews.clear(); if (mHeaderView == null && mFooterView == null) return; if (mHeaderView != null && !isEnabledHeaderDrawerStyle()) { mCachedViews.add(mHeaderView.getView()); } if (mFooterView != null && !isEnabledFooterDrawerStyle()) { mCachedViews.add(mFooterView.getView()); } for (int i = count - 1; i >= 0; i View view = getChildAt(i); if (!(view instanceof IRefreshView)) { mCachedViews.add(view); } } final int viewCount = mCachedViews.size(); if (viewCount > 0) { for (int i = viewCount - 1; i >= 0; i bringChildToFront(mCachedViews.get(i)); } } mCachedViews.clear(); } mViewsZAxisNeedReset = false; } protected void reset() { if (isRefreshing() || isLoadingMore()) { notifyUIRefreshComplete(false, true); } if (mHeaderView != null) { mHeaderView.onReset(this); } if (mFooterView != null) { mFooterView.onReset(this); } if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) { mScrollChecker.scrollTo(IIndicator.START_POS, 0); } mScrollChecker.stop(); mScrollChecker.setInterpolator(mSpringInterpolator); final byte old = mStatus; mStatus = SR_STATUS_INIT; notifyStatusChanged(old, mStatus); mAutomaticActionTriggered = true; if (mLayoutManager != null) { mLayoutManager.resetLayout( mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView); } removeCallbacks(mDelayToRefreshComplete); removeCallbacks(mDelayToDispatchNestedFling); removeCallbacks(mDelayToPerformAutoRefresh); if (sDebug) { Log.d(TAG, "reset()"); } } protected void tryToPerformAutoRefresh() { if (!mAutomaticActionTriggered) { if (sDebug) Log.d(TAG, "tryToPerformAutoRefresh()"); if (isHeaderInProcessing() && isMovingHeader()) { if (mHeaderView == null || mIndicator.getHeaderHeight() <= 0) { return; } scrollToTriggeredAutomatic(true); } else if (isFooterInProcessing() && isMovingFooter()) { if (mFooterView == null || mIndicator.getFooterHeight() <= 0) { return; } scrollToTriggeredAutomatic(false); } } } private void ensureTargetView() { boolean ensureStickyHeader = mStickyHeaderView == null && mStickyHeaderResId != NO_ID; boolean ensureStickyFooter = mStickyFooterView == null && mStickyFooterResId != NO_ID; boolean ensureTarget = mTargetView == null && mContentResId != NO_ID; final int count = getChildCount(); if (ensureStickyHeader || ensureStickyFooter || ensureTarget) { for (int i = count - 1; i >= 0; i View child = getChildAt(i); if (ensureStickyHeader && child.getId() == mStickyHeaderResId) { mStickyHeaderView = child; ensureStickyHeader = false; } else if (ensureStickyFooter && child.getId() == mStickyFooterResId) { mStickyFooterView = child; ensureStickyFooter = false; } else if (ensureTarget) { if (mContentResId == child.getId()) { mTargetView = child; View view = ensureScrollTargetView(child, true, 0, 0); if (view != null && view != child) { mAutoFoundScrollTargetView = view; } ensureTarget = false; } else if (child instanceof ViewGroup) { final View view = foundViewInViewGroupById((ViewGroup) child, mContentResId); if (view != null) { mTargetView = child; mScrollTargetView = view; ensureTarget = false; } } } else if (!ensureStickyHeader && !ensureStickyFooter) { break; } } } if (mTargetView == null) { for (int i = count - 1; i >= 0; i View child = getChildAt(i); if (child.getVisibility() == VISIBLE && !(child instanceof IRefreshView) && child != mStickyHeaderView && child != mStickyFooterView) { View view = ensureScrollTargetView(child, true, 0, 0); if (view != null) { mTargetView = child; if (view != child) { mAutoFoundScrollTargetView = view; } break; } else { mTargetView = child; break; } } } } else if (mTargetView.getParent() == null) { mTargetView = null; ensureTargetView(); mLayoutManager.offsetChild( mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView, 0); return; } mHeaderView = getHeaderView(); mFooterView = getFooterView(); } /** * Returns true if a child view contains the specified point when transformed into its * coordinate space. * * @see ViewGroup source code */ protected boolean isTransformedTouchPointInView(float x, float y, ViewGroup group, View child) { if (child.getVisibility() != VISIBLE || child.getAnimation() != null || child instanceof IRefreshView) { return false; } mCachedFloatPoint[0] = x; mCachedFloatPoint[1] = y; transformPointToViewLocal(group, mCachedFloatPoint, child); final boolean isInView = mCachedFloatPoint[0] >= 0 && mCachedFloatPoint[1] >= 0 && mCachedFloatPoint[0] < child.getWidth() && mCachedFloatPoint[1] < child.getHeight(); if (isInView) { mCachedFloatPoint[0] = mCachedFloatPoint[0] - x; mCachedFloatPoint[1] = mCachedFloatPoint[1] - y; } return isInView; } public void transformPointToViewLocal(ViewGroup group, float[] point, View child) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { group.transformPointToViewLocal(point, child); } else { // When the system version is lower than LOLLIPOP_MR1, the system source code has no // transformPointToViewLocal method. We need to be compatible with it. point[0] += group.getScrollX() - child.getLeft(); point[1] += group.getScrollY() - child.getTop(); Matrix matrix = child.getMatrix(); if (!matrix.isIdentity()) { mCachedMatrix.reset(); if (matrix.invert(mCachedMatrix)) { mCachedMatrix.mapPoints(point); } } } } protected View ensureScrollTargetView(View target, boolean noTransform, float x, float y) { if (target instanceof IRefreshView || target.getVisibility() != VISIBLE || target.getAnimation() != null) { return null; } if (isScrollingView(target)) { return target; } if (target instanceof ViewGroup) { ViewGroup group = (ViewGroup) target; final int count = group.getChildCount(); for (int i = count - 1; i >= 0; i View child = group.getChildAt(i); if (noTransform || isTransformedTouchPointInView(x, y, group, child)) { View view = ensureScrollTargetView( child, noTransform, x + mCachedFloatPoint[0], y + mCachedFloatPoint[1]); if (view != null) { return view; } } } } return null; } protected boolean isWrappedByScrollingView(ViewParent parent) { if (parent instanceof View) { if (isScrollingView((View) parent)) { return true; } return isWrappedByScrollingView(parent.getParent()); } return false; } protected boolean isScrollingView(View view) { return ScrollCompat.isScrollingView(view); } protected boolean processDispatchTouchEvent(MotionEvent ev) { final int action = ev.getAction() & MotionEvent.ACTION_MASK; if (sDebug) { Log.d(TAG, String.format("processDispatchTouchEvent(): action: %s", action)); } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final boolean oldTouchHanding = isEnabledOldTouchHandling(); switch (action) { case MotionEvent.ACTION_UP: final int pointerId = ev.getPointerId(0); mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity); float vy = mVelocityTracker.getYVelocity(pointerId); float vx = mVelocityTracker.getXVelocity(pointerId); if (Math.abs(vx) >= mMinimumFlingVelocity || Math.abs(vy) >= mMinimumFlingVelocity) { final boolean handler = onFling(vx, vy, false); final View targetView = getScrollTargetView(); if (handler && !ViewCatcherUtil.isCoordinatorLayout(mTargetView) && targetView != null && !ViewCatcherUtil.isViewPager(targetView) && targetView.getParent() instanceof View && !ViewCatcherUtil.isViewPager((View) targetView.getParent())) { ev.setAction(MotionEvent.ACTION_CANCEL); } } case MotionEvent.ACTION_CANCEL: mIndicatorSetter.onFingerUp(); mPreventForAnotherDirection = false; mDealAnotherDirectionMove = false; if (isNeedFilterTouchEvent()) { mIsInterceptTouchEventInOnceTouch = false; if (mIsLastOverScrollCanNotAbort && mIndicator.isAlreadyHere(IIndicator.START_POS)) { mScrollChecker.stop(); } mIsLastOverScrollCanNotAbort = false; } else { mIsInterceptTouchEventInOnceTouch = false; mIsLastOverScrollCanNotAbort = false; if (mIndicator.hasLeftStartPosition()) { onFingerUp(); } else { notifyFingerUp(); } } mHasSendCancelEvent = false; mVelocityTracker.clear(); break; case MotionEvent.ACTION_POINTER_UP: final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; if (ev.getPointerId(pointerIndex) == mTouchPointerId) { // Pick a new pointer to pick up the slack. final int newIndex = pointerIndex == 0 ? 1 : 0; mTouchPointerId = ev.getPointerId(newIndex); mIndicatorSetter.onFingerMove(ev.getX(newIndex), ev.getY(newIndex)); } final int count = ev.getPointerCount(); mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity); final int upIndex = ev.getActionIndex(); final int id1 = ev.getPointerId(upIndex); final float x1 = mVelocityTracker.getXVelocity(id1); final float y1 = mVelocityTracker.getYVelocity(id1); for (int i = 0; i < count; i++) { if (i == upIndex) continue; final int id2 = ev.getPointerId(i); final float x = x1 * mVelocityTracker.getXVelocity(id2); final float y = y1 * mVelocityTracker.getYVelocity(id2); final float dot = x + y; if (dot < 0) { mVelocityTracker.clear(); break; } } break; case MotionEvent.ACTION_POINTER_DOWN: mTouchPointerId = ev.getPointerId(ev.getActionIndex()); mIndicatorSetter.onFingerMove( ev.getX(ev.getActionIndex()), ev.getY(ev.getActionIndex())); break; case MotionEvent.ACTION_DOWN: mIndicatorSetter.onFingerUp(); mTouchPointerId = ev.getPointerId(0); mIndicatorSetter.onFingerDown(ev.getX(), ev.getY()); mIsInterceptTouchEventInOnceTouch = isNeedInterceptTouchEvent(); mIsLastOverScrollCanNotAbort = isCanNotAbortOverScrolling(); if (!isNeedFilterTouchEvent()) { mScrollChecker.stop(); } mHasSendDownEvent = false; mPreventForAnotherDirection = false; if (mScrollTargetView == null) { View view = ensureScrollTargetView(this, false, ev.getX(), ev.getY()); if (view != null && mTargetView != view && mAutoFoundScrollTargetView != view) { mAutoFoundScrollTargetView = view; } } else { mAutoFoundScrollTargetView = null; } removeCallbacks(mDelayToDispatchNestedFling); dispatchTouchEventSuper(ev); return true; case MotionEvent.ACTION_MOVE: final int index = ev.findPointerIndex(mTouchPointerId); if (index < 0) { Log.e( TAG, "Error processing scroll; pointer index for id " + mTouchPointerId + " not found. Did any MotionEvents get skipped?"); return super.dispatchTouchEvent(ev); } if (!mIndicator.hasTouched()) { mIndicatorSetter.onFingerDown(ev.getX(index), ev.getY(index)); } mLastMoveEvent = ev; if (tryToFilterTouchEvent(ev)) { return true; } tryToResetMovingStatus(); if (!mDealAnotherDirectionMove) { final float[] pressDownPoint = mIndicator.getFingerDownPoint(); final float offsetX = ev.getX(index) - pressDownPoint[0]; final float offsetY = ev.getY(index) - pressDownPoint[1]; tryToDealAnotherDirectionMove(offsetX, offsetY); if (mDealAnotherDirectionMove && oldTouchHanding) { mIndicatorSetter.onFingerDown( ev.getX(index) - offsetX / 10, ev.getY(index) - offsetY / 10); } final ViewParent parent = getParent(); if (!isWrappedByScrollingView(parent)) { parent.requestDisallowInterceptTouchEvent(true); } } final boolean canNotChildScrollDown = !isNotYetInEdgeCannotMoveFooter(); final boolean canNotChildScrollUp = !isNotYetInEdgeCannotMoveHeader(); if (mPreventForAnotherDirection) { if (mDealAnotherDirectionMove && isMovingHeader() && !canNotChildScrollUp) { mPreventForAnotherDirection = false; } else if (mDealAnotherDirectionMove && isMovingFooter() && !canNotChildScrollDown) { mPreventForAnotherDirection = false; } else { return super.dispatchTouchEvent(ev); } } mIndicatorSetter.onFingerMove(ev.getX(index), ev.getY(index)); final float offset = mIndicator.getOffset(); boolean movingDown = offset > 0; if (isMovingFooter() && isFooterInProcessing() && mStatus == SR_STATUS_COMPLETE && mIndicator.hasLeftStartPosition() && !canNotChildScrollDown) { mScrollChecker.scrollTo(IIndicator.START_POS, 0); if (oldTouchHanding) { return true; } return dispatchTouchEventSuper(ev); } if (!movingDown && isDisabledLoadMoreWhenContentNotFull() && mIndicator.isAlreadyHere(IIndicator.START_POS) && canNotChildScrollDown && canNotChildScrollUp) { return dispatchTouchEventSuper(ev); } boolean canMoveUp = isMovingHeader() && mIndicator.hasLeftStartPosition(); boolean canMoveDown = isMovingFooter() && mIndicator.hasLeftStartPosition(); boolean canHeaderMoveDown = canNotChildScrollUp && !isDisabledRefresh(); boolean canFooterMoveUp = canNotChildScrollDown && !isDisabledLoadMore(); if (!canMoveUp && !canMoveDown) { if ((movingDown && !canHeaderMoveDown) || (!movingDown && !canFooterMoveUp)) { if (isLoadingMore() && mIndicator.hasLeftStartPosition()) { moveFooterPos(offset); if (oldTouchHanding) { return true; } } else if (isRefreshing() && mIndicator.hasLeftStartPosition()) { moveHeaderPos(offset); if (oldTouchHanding) { return true; } } } else if (movingDown) { if (!isDisabledRefresh()) { moveHeaderPos(offset); if (oldTouchHanding) { return true; } } } else if (!isDisabledLoadMore()) { moveFooterPos(offset); if (oldTouchHanding) { return true; } } } else if (canMoveUp) { if (isDisabledRefresh()) { return dispatchTouchEventSuper(ev); } if ((!canHeaderMoveDown && movingDown)) { if (oldTouchHanding) { sendDownEvent(ev); return true; } return dispatchTouchEventSuper(ev); } moveHeaderPos(offset); if (oldTouchHanding) { return true; } } else { if (isDisabledLoadMore()) { return dispatchTouchEventSuper(ev); } if ((!canFooterMoveUp && !movingDown)) { if (oldTouchHanding) { sendDownEvent(ev); return true; } return dispatchTouchEventSuper(ev); } moveFooterPos(offset); if (oldTouchHanding) { return true; } } } return dispatchTouchEventSuper(ev); } protected void tryToDealAnotherDirectionMove(float offsetX, float offsetY) { if (isDisabledWhenAnotherDirectionMove()) { if ((Math.abs(offsetX) >= mTouchSlop && Math.abs(offsetX) > Math.abs(offsetY))) { mPreventForAnotherDirection = true; mDealAnotherDirectionMove = true; } else if (Math.abs(offsetX) < mTouchSlop && Math.abs(offsetY) < mTouchSlop) { mDealAnotherDirectionMove = false; mPreventForAnotherDirection = true; } else { mDealAnotherDirectionMove = true; mPreventForAnotherDirection = false; } } else { mPreventForAnotherDirection = Math.abs(offsetX) < mTouchSlop && Math.abs(offsetY) < mTouchSlop; if (!mPreventForAnotherDirection) { mDealAnotherDirectionMove = true; } } } protected boolean tryToFilterTouchEvent(MotionEvent ev) { if (mIsInterceptTouchEventInOnceTouch) { if ((!isAutoRefresh() && mIndicator.isAlreadyHere(IIndicator.START_POS) && !mScrollChecker.mIsScrolling) || (isAutoRefresh() && (isRefreshing() || isLoadingMore()))) { mScrollChecker.stop(); if (ev != null) { makeNewTouchDownEvent(ev); } mIsInterceptTouchEventInOnceTouch = false; } return true; } if (mIsLastOverScrollCanNotAbort) { if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !mScrollChecker.mIsScrolling) { if (ev != null) { makeNewTouchDownEvent(ev); } mIsLastOverScrollCanNotAbort = false; } return true; } if (mIsSpringBackCanNotBeInterrupted) { if (isEnabledNoMoreData() && isEnabledNoSpringBackWhenNoMoreData()) { mIsSpringBackCanNotBeInterrupted = false; return false; } if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !mScrollChecker.mIsScrolling) { if (ev != null) { makeNewTouchDownEvent(ev); } mIsSpringBackCanNotBeInterrupted = false; } return true; } return false; } private void scrollToTriggeredAutomatic(boolean isRefresh) { if (sDebug) { Log.d(TAG, "scrollToTriggeredAutomatic()"); } switch (mAutomaticAction) { case ACTION_NOTHING: if (isRefresh) { triggeredRefresh(false); } else { triggeredLoadMore(false); } break; case ACTION_NOTIFY: mFlag |= FLAG_AUTO_REFRESH; break; case ACTION_AT_ONCE: if (isRefresh) { triggeredRefresh(true); } else { triggeredLoadMore(true); } break; } int offset; if (isRefresh) { if (isEnabledKeepRefreshView()) { final int offsetToKeepHeaderWhileLoading = mIndicator.getOffsetToKeepHeaderWhileLoading(); final int offsetToRefresh = mIndicator.getOffsetToRefresh(); offset = (offsetToKeepHeaderWhileLoading >= offsetToRefresh) ? offsetToKeepHeaderWhileLoading : offsetToRefresh; } else { offset = mIndicator.getOffsetToRefresh(); } } else { if (isEnabledKeepRefreshView()) { final int offsetToKeepFooterWhileLoading = mIndicator.getOffsetToKeepFooterWhileLoading(); final int offsetToLoadMore = mIndicator.getOffsetToLoadMore(); offset = (offsetToKeepFooterWhileLoading >= offsetToLoadMore) ? offsetToKeepFooterWhileLoading : offsetToLoadMore; } else { offset = mIndicator.getOffsetToLoadMore(); } } mAutomaticActionTriggered = true; mScrollChecker.scrollTo( offset, mAutomaticActionUseSmoothScroll ? isRefresh ? mDurationToCloseHeader : mDurationToCloseFooter : 0); } protected void preparePaint() { if (mBackgroundPaint == null && (mHeaderBackgroundColor != Color.TRANSPARENT || mFooterBackgroundColor != Color.TRANSPARENT)) { mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBackgroundPaint.setStyle(Paint.Style.FILL); setWillNotDraw(false); } else { mBackgroundPaint = null; setWillNotDraw(true); } } protected boolean isNeedInterceptTouchEvent() { return (isEnabledInterceptEventWhileLoading() && (isRefreshing() || isLoadingMore())) || mAutomaticActionUseSmoothScroll; } protected boolean isNeedFilterTouchEvent() { return mIsLastOverScrollCanNotAbort || mIsSpringBackCanNotBeInterrupted || mIsInterceptTouchEventInOnceTouch; } protected boolean isCanNotAbortOverScrolling() { return ((mScrollChecker.isFling() || mScrollChecker.isFlingBack() || mScrollChecker.isPreFling()) && (((isMovingHeader() && isDisabledRefresh())) || (isMovingFooter() && isDisabledLoadMore()))); } public boolean isNotYetInEdgeCannotMoveHeader() { final View targetView = getScrollTargetView(); if (mInEdgeCanMoveHeaderCallBack != null) { return mInEdgeCanMoveHeaderCallBack.isNotYetInEdgeCannotMoveHeader( this, targetView, mFooterView); } return targetView != null && targetView.canScrollVertically(-1); } public boolean isNotYetInEdgeCannotMoveFooter() { final View targetView = getScrollTargetView(); if (mInEdgeCanMoveFooterCallBack != null) { return mInEdgeCanMoveFooterCallBack.isNotYetInEdgeCannotMoveFooter( this, targetView, mHeaderView); } return targetView != null && targetView.canScrollVertically(1); } protected void makeNewTouchDownEvent(MotionEvent ev) { if (sDebug) { Log.d(TAG, "makeNewTouchDownEvent()"); } sendCancelEvent(ev); sendDownEvent(ev); mOffsetConsumed = 0; mOffsetTotal = 0; mOffsetRemaining = mTouchSlop * 3; mIndicatorSetter.onFingerUp(); mIndicatorSetter.onFingerDown(ev.getX(), ev.getY()); } protected void sendCancelEvent(MotionEvent event) { if (mHasSendCancelEvent || (event == null && mLastMoveEvent == null)) { return; } if (sDebug) { Log.d(TAG, "sendCancelEvent()"); } final MotionEvent last = event == null ? mLastMoveEvent : event; final long now = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain( now, now, MotionEvent.ACTION_CANCEL, last.getX(), last.getY(), 0); ev.setSource(InputDevice.SOURCE_TOUCHSCREEN); mHasSendCancelEvent = true; mHasSendDownEvent = false; super.dispatchTouchEvent(ev); ev.recycle(); } protected void sendDownEvent(MotionEvent event) { if (mHasSendDownEvent || (event == null && mLastMoveEvent == null)) { return; } if (sDebug) { Log.d(TAG, "sendDownEvent()"); } final MotionEvent last = event == null ? mLastMoveEvent : event; final long now = SystemClock.uptimeMillis(); final float[] rawOffsets = mIndicator.getRawOffsets(); final MotionEvent downEv = MotionEvent.obtain( now, now, MotionEvent.ACTION_DOWN, last.getX() - rawOffsets[0], last.getY() - rawOffsets[1], 0); downEv.setSource(InputDevice.SOURCE_TOUCHSCREEN); super.dispatchTouchEvent(downEv); downEv.recycle(); final MotionEvent moveEv = MotionEvent.obtain(now, now, MotionEvent.ACTION_MOVE, last.getX(), last.getY(), 0); moveEv.setSource(InputDevice.SOURCE_TOUCHSCREEN); mHasSendCancelEvent = false; mHasSendDownEvent = true; super.dispatchTouchEvent(moveEv); moveEv.recycle(); } protected void notifyFingerUp() { if (mHeaderView != null && isHeaderInProcessing() && !isDisabledRefresh()) { mHeaderView.onFingerUp(this, mIndicator); } else if (mFooterView != null && isFooterInProcessing() && !isDisabledLoadMore()) { mFooterView.onFingerUp(this, mIndicator); } } protected void onFingerUp() { if (sDebug) { Log.d(TAG, "onFingerUp()"); } notifyFingerUp(); if (!mScrollChecker.isPreFling()) { if (isEnabledKeepRefreshView() && !(isEnabledNoMoreData() && isMovingFooter()) && mStatus != SR_STATUS_COMPLETE) { if (isHeaderInProcessing() && mHeaderView != null && !isDisabledPerformRefresh() && isMovingHeader() && mIndicator.isOverOffsetToRefresh()) { if (!mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepHeaderWhileLoading())) { mScrollChecker.scrollTo( mIndicator.getOffsetToKeepHeaderWhileLoading(), mDurationOfBackToHeaderHeight); return; } } else if (isFooterInProcessing() && mFooterView != null && !isDisabledPerformLoadMore() && isMovingFooter() && mIndicator.isOverOffsetToLoadMore()) { if (!mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepFooterWhileLoading())) { mScrollChecker.scrollTo( mIndicator.getOffsetToKeepFooterWhileLoading(), mDurationOfBackToFooterHeight); return; } } } onRelease(); } } protected void onRelease() { if (sDebug) { Log.d(TAG, "onRelease()"); } if ((isEnabledNoMoreData() && isMovingFooter() && isEnabledNoSpringBackWhenNoMoreData())) { mScrollChecker.stop(); return; } tryToPerformRefresh(); if (mStatus == SR_STATUS_COMPLETE) { notifyUIRefreshComplete(true, false); return; } else if (isEnabledKeepRefreshView()) { if (isHeaderInProcessing() && mHeaderView != null && !isDisabledPerformRefresh()) { if (isRefreshing() && isMovingHeader() && mIndicator.isAlreadyHere( mIndicator.getOffsetToKeepHeaderWhileLoading())) { return; } else if (isMovingHeader() && mIndicator.isOverOffsetToKeepHeaderWhileLoading()) { mScrollChecker.scrollTo( mIndicator.getOffsetToKeepHeaderWhileLoading(), mDurationOfBackToHeaderHeight); return; } else if (isRefreshing() && !isMovingFooter()) { return; } } else if (isFooterInProcessing() && mFooterView != null && !isDisabledPerformLoadMore()) { if (isLoadingMore() && isMovingFooter() && mIndicator.isAlreadyHere( mIndicator.getOffsetToKeepFooterWhileLoading())) { return; } else if (isMovingFooter() && mIndicator.isOverOffsetToKeepFooterWhileLoading()) { mScrollChecker.scrollTo( mIndicator.getOffsetToKeepFooterWhileLoading(), mDurationOfBackToFooterHeight); return; } else if (isLoadingMore() && !isMovingHeader()) { return; } } } tryScrollBackToTop(); } protected void tryScrollBackToTop() { // Use the current percentage duration of the current position to scroll back to the top if (mScrollChecker.isFlingBack()) { tryScrollBackToTop(mDurationOfFlingBack); } else if (isMovingHeader()) { float percent = mIndicator.getCurrentPercentOfRefreshOffset(); percent = percent > 1 || percent <= 0 ? 1 : percent; tryScrollBackToTop(Math.round(mDurationToCloseHeader * percent)); } else if (isMovingFooter()) { float percent = mIndicator.getCurrentPercentOfLoadMoreOffset(); percent = percent > 1 || percent <= 0 ? 1 : percent; tryScrollBackToTop(Math.round(mDurationToCloseFooter * percent)); } else { tryToNotifyReset(); } } protected void tryScrollBackToTop(int duration) { if (sDebug) { Log.d(TAG, String.format("tryScrollBackToTop(): duration: %s", duration)); } if (mIndicator.hasLeftStartPosition() && (!mIndicator.hasTouched() || !mIndicator.hasMoved())) { mScrollChecker.scrollTo(IIndicator.START_POS, duration); return; } if (isNeedFilterTouchEvent() && mIndicator.hasLeftStartPosition()) { mScrollChecker.scrollTo(IIndicator.START_POS, duration); return; } if (isMovingFooter() && mStatus == SR_STATUS_COMPLETE && mIndicator.hasJustBackToStartPosition()) { mScrollChecker.scrollTo(IIndicator.START_POS, duration); return; } tryToNotifyReset(); } protected void notifyUIRefreshComplete(boolean useScroll, boolean notifyViews) { mIsSpringBackCanNotBeInterrupted = isEnabledSmoothRollbackWhenCompleted(); if (notifyViews) { if (isHeaderInProcessing() && mHeaderView != null) { mHeaderView.onRefreshComplete(this, mIsLastRefreshSuccessful); } else if (isFooterInProcessing() && mFooterView != null) { mFooterView.onRefreshComplete(this, mIsLastRefreshSuccessful); } } if (useScroll) { if (mScrollChecker.isFlingBack()) { mScrollChecker.stop(); } tryScrollBackToTop(); } } protected void moveHeaderPos(float delta) { if (sDebug) { Log.d(TAG, String.format("moveHeaderPos(): delta: %s", delta)); } mNeedFilterScrollEvent = false; if (!mNestedScrolling && !mHasSendCancelEvent && isEnabledOldTouchHandling() && mIndicator.hasTouched() && !mIndicator.isAlreadyHere(IIndicator.START_POS)) sendCancelEvent(null); mIndicatorSetter.setMovingStatus(MOVING_HEADER); if (mHeaderView != null) { if (delta > 0) { final float maxHeaderDistance = mIndicator.getCanMoveTheMaxDistanceOfHeader(); final int current = mIndicator.getCurrentPos(); final boolean isFling = mScrollChecker.isFling() || mScrollChecker.isPreFling(); if (maxHeaderDistance > 0) { if (current >= maxHeaderDistance) { if ((mIndicator.hasTouched() && !mScrollChecker.mIsScrolling) || isFling) { updateAnotherDirectionPos(); return; } } else if (current + delta > maxHeaderDistance) { if ((mIndicator.hasTouched() && !mScrollChecker.mIsScrolling) || isFling) { delta = maxHeaderDistance - current; if (isFling) { mScrollChecker.mScroller.forceFinished(true); } } } } } else { // check if it is needed to compatible scroll if ((mFlag & FLAG_ENABLE_COMPAT_SYNC_SCROLL) > 0 && isNotYetInEdgeCannotMoveHeader() && !isEnabledPinContentView() && mIsLastRefreshSuccessful && (!mIndicator.hasTouched() || mNestedScrolling || isEnabledSmoothRollbackWhenCompleted()) && mStatus == SR_STATUS_COMPLETE) { if (sDebug) { Log.d( TAG, String.format( "moveHeaderPos(): compatible scroll delta: %s", delta)); } mNeedFilterScrollEvent = true; tryToCompatSyncScroll(getScrollTargetView(), delta); } } } movePos(delta); } protected void moveFooterPos(float delta) { if (sDebug) { Log.d(TAG, String.format("moveFooterPos(): delta: %s", delta)); } mNeedFilterScrollEvent = false; if (!mNestedScrolling && !mHasSendCancelEvent && isEnabledOldTouchHandling() && mIndicator.hasTouched() && !mIndicator.isAlreadyHere(IIndicator.START_POS)) sendCancelEvent(null); mIndicatorSetter.setMovingStatus(MOVING_FOOTER); if (mFooterView != null) { if (delta < 0) { final float maxFooterDistance = mIndicator.getCanMoveTheMaxDistanceOfFooter(); final int current = mIndicator.getCurrentPos(); final boolean isFling = mScrollChecker.isFling() || mScrollChecker.isPreFling(); if (maxFooterDistance > 0) { if (current >= maxFooterDistance) { if ((mIndicator.hasTouched() && !mScrollChecker.mIsScrolling) || isFling) { updateAnotherDirectionPos(); return; } } else if (current - delta > maxFooterDistance) { if ((mIndicator.hasTouched() && !mScrollChecker.mIsScrolling) || isFling) { delta = current - maxFooterDistance; if (isFling) { mScrollChecker.mScroller.forceFinished(true); } } } } } else { // check if it is needed to compatible scroll if ((mFlag & FLAG_ENABLE_COMPAT_SYNC_SCROLL) > 0 && isNotYetInEdgeCannotMoveFooter() && !isEnabledPinContentView() && mIsLastRefreshSuccessful && (!mIndicator.hasTouched() || mNestedScrolling || isEnabledSmoothRollbackWhenCompleted()) && mStatus == SR_STATUS_COMPLETE) { if (sDebug) { Log.d( TAG, String.format( "moveFooterPos(): compatible scroll delta: %s", delta)); } mNeedFilterScrollEvent = true; tryToCompatSyncScroll(getScrollTargetView(), delta); } } } movePos(-delta); } protected void tryToCompatSyncScroll(View view, float delta) { if (mSyncScrollCallback != null) { mSyncScrollCallback.onScroll(view, delta); } else { ScrollCompat.scrollCompat(view, delta); } } protected void movePos(float delta) { if (delta == 0f) { if (sDebug) { Log.d(TAG, "movePos(): delta is zero"); } mIndicatorSetter.setCurrentPos(mIndicator.getCurrentPos()); return; } int to = mIndicator.getCurrentPos() + Math.round(delta); // over top if (to < IIndicator.START_POS && mLayoutManager.isNeedFilterOverTop(delta)) { to = IIndicator.START_POS; if (sDebug) { Log.d(TAG, "movePos(): over top"); } } mIndicatorSetter.setCurrentPos(to); int change = to - mIndicator.getLastPos(); updatePos(isMovingFooter() ? -change : change); } /** * Update view's Y position * * @param change The changed value */ protected void updatePos(int change) { if (sDebug) { Log.d( TAG, String.format( "updatePos(): change: %s, current: %s last: %s", change, mIndicator.getCurrentPos(), mIndicator.getLastPos())); } final boolean isMovingHeader = isMovingHeader(); final boolean isMovingFooter = isMovingFooter(); // leave initiated position or just refresh complete if (((mIndicator.hasJustLeftStartPosition() || mViewStatus == SR_VIEW_STATUS_INIT) && mStatus == SR_STATUS_INIT) || (mStatus == SR_STATUS_COMPLETE && isEnabledNextPtrAtOnce() && ((isHeaderInProcessing() && isMovingHeader && change > 0) || (isFooterInProcessing() && isMovingFooter && change < 0)))) { final byte old = mStatus; mStatus = SR_STATUS_PREPARE; notifyStatusChanged(old, mStatus); if (isMovingHeader()) { mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING; if (mHeaderView != null) { mHeaderView.onRefreshPrepare(this); } } else if (isMovingFooter()) { mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING; if (mFooterView != null) { mFooterView.onRefreshPrepare(this); } } } tryToPerformRefreshWhenMoved(); notifyUIPositionChanged(); boolean needRequestLayout = mLayoutManager.offsetChild( mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView, change); // back to initiated position if (!(isAutoRefresh() && mStatus != SR_STATUS_COMPLETE) && mIndicator.hasJustBackToStartPosition()) { tryToNotifyReset(); if (isEnabledOldTouchHandling()) { if (mIndicator.hasTouched() && !mNestedScrolling && !mHasSendDownEvent) { sendDownEvent(null); } } } if (needRequestLayout) { requestLayout(); } else if (mBackgroundPaint != null || mIndicator.isAlreadyHere(IIndicator.START_POS)) { invalidate(); } } protected void tryToPerformRefreshWhenMoved() { // try to perform refresh if (mStatus == SR_STATUS_PREPARE && !isAutoRefresh()) { // reach fresh height while moving from top to bottom or reach load more height while // moving from bottom to top if (isHeaderInProcessing() && isMovingHeader() && !isDisabledPerformRefresh()) { if (isEnabledPullToRefresh() && mIndicator.isOverOffsetToRefresh()) { triggeredRefresh(true); } else if (isEnabledPerformFreshWhenFling() && !mIndicator.hasTouched() && !(mScrollChecker.isPreFling() || mScrollChecker.isFling()) && mIndicator.isJustReturnedOffsetToRefresh()) { triggeredRefresh(true); mScrollChecker.stop(); } } else if (isFooterInProcessing() && isMovingFooter() && !isDisabledPerformLoadMore()) { if (isEnabledPullToRefresh() && mIndicator.isOverOffsetToLoadMore()) { triggeredLoadMore(true); } else if (isEnabledPerformFreshWhenFling() && !mIndicator.hasTouched() && !(mScrollChecker.isPreFling() || mScrollChecker.isFling()) && mIndicator.isJustReturnedOffsetToLoadMore()) { triggeredLoadMore(true); mScrollChecker.stop(); } } } } /** We need to notify the X pos changed */ protected void updateAnotherDirectionPos() { if (mHeaderView != null && !isDisabledRefresh() && isMovingHeader() && mHeaderView.getView().getVisibility() == VISIBLE) { if (isHeaderInProcessing()) { mHeaderView.onRefreshPositionChanged(this, mStatus, mIndicator); } else { mHeaderView.onPureScrollPositionChanged(this, mStatus, mIndicator); } } else if (mFooterView != null && !isDisabledLoadMore() && isMovingFooter() && mFooterView.getView().getVisibility() == VISIBLE) { if (isFooterInProcessing()) { mFooterView.onRefreshPositionChanged(this, mStatus, mIndicator); } else { mFooterView.onPureScrollPositionChanged(this, mStatus, mIndicator); } } } public boolean isMovingHeader() { return mIndicator.getMovingStatus() == MOVING_HEADER; } public boolean isMovingContent() { return mIndicator.getMovingStatus() == MOVING_CONTENT; } public boolean isMovingFooter() { return mIndicator.getMovingStatus() == MOVING_FOOTER; } public boolean isHeaderInProcessing() { return mViewStatus == SR_VIEW_STATUS_HEADER_IN_PROCESSING; } public boolean isFooterInProcessing() { return mViewStatus == SR_VIEW_STATUS_FOOTER_IN_PROCESSING; } private void tryToDispatchNestedFling() { if (mScrollChecker.isPreFling() && mIndicator.isAlreadyHere(IIndicator.START_POS)) { if (sDebug) { Log.d(TAG, "tryToDispatchNestedFling()"); } final int velocity = (int) (mScrollChecker.getCurrVelocity() + 0.5f); mIndicatorSetter.setMovingStatus(MOVING_CONTENT); if (isEnabledOverScroll() && !(isDisabledLoadMoreWhenContentNotFull() && !isNotYetInEdgeCannotMoveHeader() && !isNotYetInEdgeCannotMoveFooter())) { mScrollChecker.startFling(velocity); } else { mScrollChecker.stop(); } dispatchNestedFling(velocity); postInvalidateDelayed(30); } } protected boolean tryToNotifyReset() { if ((mStatus == SR_STATUS_COMPLETE || mStatus == SR_STATUS_PREPARE) && mIndicator.isAlreadyHere(IIndicator.START_POS)) { if (sDebug) { Log.d(TAG, "tryToNotifyReset()"); } if (mHeaderView != null) { mHeaderView.onReset(this); } if (mFooterView != null) { mFooterView.onReset(this); } final byte old = mStatus; mStatus = SR_STATUS_INIT; notifyStatusChanged(old, mStatus); mViewStatus = SR_VIEW_STATUS_INIT; mAutomaticActionTriggered = true; mNeedFilterScrollEvent = false; tryToResetMovingStatus(); if (!mIndicator.hasTouched()) { mIsSpringBackCanNotBeInterrupted = false; } if (mScrollChecker.isSpringBack() || mScrollChecker.isSpring() || mScrollChecker.isFlingBack()) { mScrollChecker.stop(); } if (mLayoutManager != null) { mLayoutManager.resetLayout( mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView); } if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(false); } return true; } return false; } protected void performRefreshComplete(boolean hook, boolean notifyViews) { if (isRefreshing() && hook && mHeaderRefreshCompleteHook != null && mHeaderRefreshCompleteHook.mCallBack != null) { mHeaderRefreshCompleteHook.mLayout = this; mHeaderRefreshCompleteHook.mNotifyViews = notifyViews; mHeaderRefreshCompleteHook.doHook(); return; } if (isLoadingMore() && hook && mFooterRefreshCompleteHook != null && mFooterRefreshCompleteHook.mCallBack != null) { mFooterRefreshCompleteHook.mLayout = this; mFooterRefreshCompleteHook.mNotifyViews = notifyViews; mFooterRefreshCompleteHook.doHook(); return; } final byte old = mStatus; mStatus = SR_STATUS_COMPLETE; notifyStatusChanged(old, mStatus); notifyUIRefreshComplete( !(isMovingFooter() && isEnabledNoMoreData() && isEnabledNoSpringBackWhenNoMoreData()), notifyViews); } /** try to perform refresh or loading , if performed return true */ protected void tryToPerformRefresh() { // status not be prepare or over scrolling or moving content go to break; if (mStatus != SR_STATUS_PREPARE || isMovingContent()) { return; } if (sDebug) { Log.d(TAG, "tryToPerformRefresh()"); } final boolean isEnabledKeep = isEnabledKeepRefreshView(); if (isHeaderInProcessing() && !isDisabledPerformRefresh() && mHeaderView != null) { if ((isEnabledKeep && mIndicator.isAlreadyHere(mIndicator.getOffsetToRefresh()) || mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepHeaderWhileLoading()))) { triggeredRefresh(true); return; } } if (isFooterInProcessing() && !isDisabledPerformLoadMore() && mFooterView != null) { if ((isEnabledKeep && mIndicator.isAlreadyHere(mIndicator.getOffsetToLoadMore()) || mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepFooterWhileLoading()))) { triggeredLoadMore(true); } } } protected void tryScrollToPerformAutoRefresh() { if (isMovingContent() && (mStatus == SR_STATUS_INIT || mStatus == SR_STATUS_PREPARE)) { if ((isEnabledAutoLoadMore() && !isDisabledPerformLoadMore()) || (isEnabledAutoRefresh() && !isDisabledPerformRefresh())) { if (sDebug) { Log.d(TAG, "tryScrollToPerformAutoRefresh()"); } final View targetView = getScrollTargetView(); if (targetView != null) { if (isEnabledAutoLoadMore() && canAutoLoadMore(targetView)) { if (!isDisabledLoadMoreWhenContentNotFull() || isNotYetInEdgeCannotMoveHeader() || isNotYetInEdgeCannotMoveFooter()) { triggeredLoadMore(true); } } else if (isEnabledAutoRefresh() && canAutoRefresh(targetView)) { triggeredRefresh(true); } } } } } protected boolean canAutoLoadMore(View view) { if (mAutoLoadMoreCallBack != null) { return mAutoLoadMoreCallBack.canAutoLoadMore(this, view); } return ScrollCompat.canAutoLoadMore(view); } protected boolean canAutoRefresh(View view) { if (mAutoRefreshCallBack != null) { return mAutoRefreshCallBack.canAutoRefresh(this, view); } return ScrollCompat.canAutoRefresh(view); } protected void triggeredRefresh(boolean notify) { if (sDebug) { Log.d(TAG, "triggeredRefresh()"); } final byte old = mStatus; mStatus = SR_STATUS_REFRESHING; notifyStatusChanged(old, mStatus); mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING; mFlag &= ~(FLAG_AUTO_REFRESH | FLAG_ENABLE_NO_MORE_DATA); mIsSpringBackCanNotBeInterrupted = false; performRefresh(notify); } protected void triggeredLoadMore(boolean notify) { if (sDebug) { Log.d(TAG, "triggeredLoadMore()"); } final byte old = mStatus; mStatus = SR_STATUS_LOADING_MORE; notifyStatusChanged(old, mStatus); mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING; mFlag &= ~FLAG_AUTO_REFRESH; mIsSpringBackCanNotBeInterrupted = false; performRefresh(notify); } protected void tryToResetMovingStatus() { if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !isMovingContent()) { mIndicatorSetter.setMovingStatus(MOVING_CONTENT); notifyUIPositionChanged(); } } protected void performRefresh(boolean notify) { // loading start milliseconds since boot mLoadingStartTime = SystemClock.uptimeMillis(); if (sDebug) { Log.d(TAG, String.format("onRefreshBegin systemTime: %s", mLoadingStartTime)); } if (isRefreshing()) { if (mHeaderView != null) { mHeaderView.onRefreshBegin(this, mIndicator); } } else if (isLoadingMore()) { if (mFooterView != null) { mFooterView.onRefreshBegin(this, mIndicator); } } if (notify && mRefreshListener != null) { if (isRefreshing()) { mRefreshListener.onRefreshing(); } else { mRefreshListener.onLoadingMore(); } } } protected void dispatchNestedFling(int velocity) { if (sDebug) { Log.d(TAG, String.format("dispatchNestedFling() : velocity: %s", velocity)); } final View targetView = getScrollTargetView(); ScrollCompat.flingCompat(targetView, -velocity); } private void notifyUIPositionChanged() { final List<OnUIPositionChangedListener> listeners = mUIPositionChangedListeners; if (listeners != null) { for (OnUIPositionChangedListener listener : listeners) { listener.onChanged(mStatus, mIndicator); } } } protected void notifyStatusChanged(byte old, byte now) { final List<OnStatusChangedListener> listeners = mStatusChangedListeners; if (listeners != null) { for (OnStatusChangedListener listener : listeners) { listener.onStatusChanged(old, now); } } } private View foundViewInViewGroupById(ViewGroup group, int id) { final int size = group.getChildCount(); for (int i = 0; i < size; i++) { View view = group.getChildAt(i); if (view.getId() == id) { return view; } else if (view instanceof ViewGroup) { final View found = foundViewInViewGroupById((ViewGroup) view, id); if (found != null) { return found; } } } return null; } /** * Classes that wish to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} * method behavior should implement this interface. */ public interface OnHeaderEdgeDetectCallBack { /** * Callback that will be called when {@link * SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} method is called to allow the * implementer to override its behavior. * * @param parent SmoothRefreshLayout that this callback is overriding. * @param child The child view. * @param header The Header view. * @return Whether it is possible for the child view of parent layout to scroll up. */ boolean isNotYetInEdgeCannotMoveHeader( SmoothRefreshLayout parent, @Nullable View child, @Nullable IRefreshView header); } /** * Classes that wish to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} * method behavior should implement this interface. */ public interface OnFooterEdgeDetectCallBack { /** * Callback that will be called when {@link * SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} method is called to allow the * implementer to override its behavior. * * @param parent SmoothRefreshLayout that this callback is overriding. * @param child The child view. * @param footer The Footer view. * @return Whether it is possible for the child view of parent layout to scroll down. */ boolean isNotYetInEdgeCannotMoveFooter( SmoothRefreshLayout parent, @Nullable View child, @Nullable IRefreshView footer); } /** * Classes that wish to be notified when the swipe gesture correctly triggers a refresh should * implement this interface. */ public interface OnRefreshListener { /** Called when a refresh is triggered. */ void onRefreshing(); /** Called when a load more is triggered. */ void onLoadingMore(); } /** * Classes that wish to be notified when the views position changes should implement this * interface */ public interface OnUIPositionChangedListener { /** * UI position changed * * @param status {@link #SR_STATUS_INIT}, {@link #SR_STATUS_PREPARE}, {@link * #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE},{@link #SR_STATUS_COMPLETE}. * @param indicator @see {@link IIndicator} */ void onChanged(byte status, IIndicator indicator); } /** Classes that wish to be called when refresh completed spring back to start position */ public interface OnSyncScrollCallback { /** * Called when refresh completed spring back to start position, each move triggers a * callback once * * @param content The content view * @param delta The scroll distance in current axis */ void onScroll(View content, float delta); } public interface OnHookUIRefreshCompleteCallBack { void onHook(RefreshCompleteHook hook); } /** * Classes that wish to be called when {@link * SmoothRefreshLayout#setEnableAutoLoadMore(boolean)} has been set true and {@link * SmoothRefreshLayout#isDisabledLoadMore()} not be true and sure you need to customize the * specified trigger rule */ public interface OnPerformAutoLoadMoreCallBack { /** * Whether need trigger auto load more * * @param parent The frame * @param child the child view * @return whether need trigger */ boolean canAutoLoadMore(SmoothRefreshLayout parent, @Nullable View child); } /** * Classes that wish to be called when {@link SmoothRefreshLayout#setEnableAutoRefresh(boolean)} * has been set true and {@link SmoothRefreshLayout#isDisabledRefresh()} not be true and sure * you need to customize the specified trigger rule */ public interface OnPerformAutoRefreshCallBack { /** * Whether need trigger auto refresh * * @param parent The frame * @param child the child view * @return whether need trigger */ boolean canAutoRefresh(SmoothRefreshLayout parent, @Nullable View child); } /** Classes that wish to be notified when the status changed */ public interface OnStatusChangedListener { /** * Status changed * * @param old the old status, as follows {@link #SR_STATUS_INIT}, {@link * #SR_STATUS_PREPARE}, {@link #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE}, * {@link #SR_STATUS_COMPLETE}} * @param now the current status, as follows {@link #SR_STATUS_INIT}, {@link * #SR_STATUS_PREPARE}, {@link #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE}, * {@link #SR_STATUS_COMPLETE}} */ void onStatusChanged(byte old, byte now); } public static class LayoutParams extends MarginLayoutParams { public int gravity = Gravity.TOP | Gravity.START; @SuppressWarnings("WeakerAccess") public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); final TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.SmoothRefreshLayout_Layout); gravity = a.getInt( R.styleable.SmoothRefreshLayout_Layout_android_layout_gravity, gravity); a.recycle(); } public LayoutParams(int width, int height) { super(width, height); } @SuppressWarnings("unused") public LayoutParams(MarginLayoutParams source) { super(source); } @SuppressWarnings("WeakerAccess") public LayoutParams(ViewGroup.LayoutParams source) { super(source); } } public static class RefreshCompleteHook { private SmoothRefreshLayout mLayout; private OnHookUIRefreshCompleteCallBack mCallBack; private boolean mNotifyViews; public void onHookComplete() { if (mLayout != null) { if (sDebug) { Log.d(mLayout.TAG, "RefreshCompleteHook: onHookComplete()"); } mLayout.performRefreshComplete(false, mNotifyViews); } } private void doHook() { if (mCallBack != null) { if (sDebug) { Log.d(mLayout.TAG, "RefreshCompleteHook: doHook()"); } mCallBack.onHook(this); } } } /** Delayed completion of loading */ private static class DelayToRefreshComplete implements Runnable { private SmoothRefreshLayout mLayout; private boolean mNotifyViews; @Override public void run() { if (mLayout != null) { if (sDebug) { Log.d(mLayout.TAG, "DelayToRefreshComplete: run()"); } mLayout.performRefreshComplete(true, mNotifyViews); } } } /** Delayed to dispatch nested fling */ private static class DelayToDispatchNestedFling implements Runnable { private SmoothRefreshLayout mLayout; private int mVelocity; @Override public void run() { if (mLayout != null) { if (sDebug) { Log.d(mLayout.TAG, "DelayToDispatchNestedFling: run()"); } mLayout.dispatchNestedFling(mVelocity); } } } /** Delayed to perform auto refresh */ private static class DelayToPerformAutoRefresh implements Runnable { private SmoothRefreshLayout mLayout; @Override public void run() { if (mLayout != null) { if (sDebug) { Log.d(mLayout.TAG, "DelayToPerformAutoRefresh: run()"); } mLayout.tryToPerformAutoRefresh(); } } } public abstract static class LayoutManager { public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; protected final String TAG = getClass().getSimpleName() + "-" + SmoothRefreshLayout.sId++; protected SmoothRefreshLayout mLayout; @Orientation public abstract int getOrientation(); @CallSuper public void setLayout(SmoothRefreshLayout layout) { mLayout = layout; } public boolean isNeedFilterOverTop(float delta) { return true; } public abstract void measureHeader( @NonNull IRefreshView<IIndicator> header, int widthMeasureSpec, int heightMeasureSpec); public abstract void measureFooter( @NonNull IRefreshView<IIndicator> footer, int widthMeasureSpec, int heightMeasureSpec); public abstract void layoutHeaderView(@NonNull IRefreshView<IIndicator> header); public abstract void layoutFooterView(@NonNull IRefreshView<IIndicator> footer); public abstract void layoutContentView(@NonNull View content); public abstract void layoutStickyHeaderView(@NonNull View stickyHeader); public abstract void layoutStickyFooterView(@NonNull View stickyFooter); public abstract boolean offsetChild( @Nullable IRefreshView<IIndicator> header, @Nullable IRefreshView<IIndicator> footer, @Nullable View stickyHeader, @Nullable View stickyFooter, @Nullable View content, int change); public void resetLayout( @Nullable IRefreshView<IIndicator> header, @Nullable IRefreshView<IIndicator> footer, @Nullable View stickyHeader, @Nullable View stickyFooter, @Nullable View content) {} protected void setHeaderHeight(int height) { if (mLayout != null) { mLayout.mIndicatorSetter.setHeaderHeight(height); } } protected void setFooterHeight(int height) { if (mLayout != null) { mLayout.mIndicatorSetter.setFooterHeight(height); } } protected byte getRefreshStatus() { return mLayout == null ? SmoothRefreshLayout.SR_STATUS_INIT : mLayout.mStatus; } protected final void measureChildWithMargins( View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) child.getLayoutParams(); final int childWidthMeasureSpec = ViewGroup.getChildMeasureSpec( parentWidthMeasureSpec, mLayout.getPaddingLeft() + mLayout.getPaddingRight() + lp.leftMargin + lp.rightMargin, lp.width); final int childHeightMeasureSpec = ViewGroup.getChildMeasureSpec( parentHeightMeasureSpec, mLayout.getPaddingTop() + mLayout.getPaddingBottom() + lp.topMargin + lp.bottomMargin, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } class ScrollChecker implements Runnable { private static final float GRAVITY_EARTH = 9.80665f; private final float mPhysical; private final int mMaxDistance; Scroller[] mStaticScroller; Scroller mScroller; Scroller mCalcScroller; Interpolator mInterpolator; int mLastY; int mLastStart; int mLastTo; int mDuration; byte mMode = SCROLLER_MODE_NONE; float mVelocity; boolean mIsScrolling = false; private int[] mCachedPair; ScrollChecker() { DisplayMetrics dm = getResources().getDisplayMetrics(); mMaxDistance = (int) (dm.heightPixels / 8f); mPhysical = GRAVITY_EARTH * 39.37f * dm.density * 160f * 0.84f; mCalcScroller = new Scroller(getContext()); mInterpolator = sSpringInterpolator; mStaticScroller = new Scroller[] { new Scroller(getContext(), sSpringInterpolator), new Scroller(getContext(), sSpringBackInterpolator), new Scroller(getContext(), sFlingInterpolator) }; mScroller = mStaticScroller[0]; } @Override public void run() { if (mMode == SCROLLER_MODE_NONE || isCalcFling()) { return; } boolean finished = !mScroller.computeScrollOffset() && mScroller.getCurrY() == mLastY; int curY = mScroller.getCurrY(); int deltaY = curY - mLastY; if (sDebug) { Log.d( TAG, String.format( "ScrollChecker: run(): finished: %s, mode: %s, start: %s, " + "to: %s, curPos: %s, curY:%s, last: %s, delta: %s", finished, mMode, mLastStart, mLastTo, mIndicator.getCurrentPos(), curY, mLastY, deltaY)); } if (!finished) { mLastY = curY; if (isMovingHeader()) { moveHeaderPos(deltaY); } else if (isMovingFooter()) { if (isPreFling()) { moveFooterPos(deltaY); } else { moveFooterPos(-deltaY); } } ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this); tryToDispatchNestedFling(); } else { switch (mMode) { case SCROLLER_MODE_SPRING: case SCROLLER_MODE_FLING_BACK: case SCROLLER_MODE_SPRING_BACK: stop(); if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) { onRelease(); } break; case SCROLLER_MODE_PRE_FLING: case SCROLLER_MODE_FLING: stop(); mMode = SCROLLER_MODE_FLING_BACK; if (isEnabledPerformFreshWhenFling() || isRefreshing() || isLoadingMore() || (isEnabledAutoLoadMore() && isMovingFooter()) || (isEnabledAutoRefresh() && isMovingHeader())) { onRelease(); } else { tryScrollBackToTop(); } break; } } } boolean isPreFling() { return mMode == SCROLLER_MODE_PRE_FLING; } boolean isFling() { return mMode == SCROLLER_MODE_FLING; } boolean isFlingBack() { return mMode == SCROLLER_MODE_FLING_BACK; } boolean isSpringBack() { return mMode == SCROLLER_MODE_SPRING_BACK; } boolean isSpring() { return mMode == SCROLLER_MODE_SPRING; } boolean isCalcFling() { return mMode == SCROLLER_MODE_CALC_FLING; } float getCurrVelocity() { final int originalSymbol = mVelocity > 0 ? 1 : -1; float v = mScroller.getCurrVelocity() * originalSymbol; if (sDebug) { Log.d(TAG, String.format("ScrollChecker: getCurrVelocity(): v: %s", v)); } return v; } int getFinalY(float v) { mCalcScroller.fling( 0, 0, 0, (int) v, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE); final int y = Math.abs(mCalcScroller.getFinalY()); if (sDebug) { Log.d( TAG, String.format( "ScrollChecker: getFinalY(): v: %s, finalY: %s, " + "currentY: %s", v, y, mIndicator.getCurrentPos())); } mCalcScroller.abortAnimation(); return y; } void startPreFling(float v) { stop(); mMode = SCROLLER_MODE_PRE_FLING; setInterpolator(sFlingInterpolator); mVelocity = v; mScroller.fling( 0, 0, 0, (int) v, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE); if (sDebug) { Log.d(TAG, String.format("ScrollChecker: startPreFling(): v: %s", v)); } ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this); } void startFling(float v) { stop(); mMode = SCROLLER_MODE_CALC_FLING; setInterpolator(sFlingInterpolator); mVelocity = v; mScroller.fling( 0, 0, 0, (int) v, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE); if (sDebug) { Log.d(TAG, String.format("ScrollChecker: startFling(): v: %s", v)); } } void scrollTo(int to, int duration) { final int curPos = mIndicator.getCurrentPos(); if (to > curPos) { stop(); setInterpolator(mSpringInterpolator); mMode = SCROLLER_MODE_SPRING; } else if (to < curPos) { if (!mScrollChecker.isFlingBack()) { stop(); mMode = SCROLLER_MODE_SPRING_BACK; } setInterpolator(mSpringBackInterpolator); } else { mMode = SCROLLER_MODE_NONE; return; } mLastStart = curPos; mLastTo = to; if (sDebug) { Log.d( TAG, String.format( "ScrollChecker: scrollTo(): to:%s, duration:%s", to, duration)); } int distance = mLastTo - mLastStart; mLastY = 0; mDuration = duration; mIsScrolling = true; mScroller.startScroll(0, 0, 0, distance, duration); removeCallbacks(this); if (duration <= 0) { run(); } else { ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this); } } void computeScrollOffset() { if (mScroller.computeScrollOffset()) { if (sDebug) { Log.d(TAG, "ScrollChecker: computeScrollOffset()"); } if (isCalcFling()) { mLastY = mScroller.getCurrY(); if (mVelocity > 0 && mIndicator.isAlreadyHere(IIndicator.START_POS) && !isNotYetInEdgeCannotMoveHeader()) { final float velocity = Math.abs(getCurrVelocity()); stop(); mIndicatorSetter.setMovingStatus(MOVING_HEADER); final int[] result = computeScroll(velocity); if (getHeaderHeight() > 0 && isEnabledAutoRefresh()) { startBounce( Math.min(result[0] * 2, getHeaderHeight()), Math.min( Math.max(result[1] / 2 * 5, mMinOverScrollDuration), mMaxOverScrollDuration)); } else { startBounce(result[0], result[1]); } return; } else if (mVelocity < 0 && mIndicator.isAlreadyHere(IIndicator.START_POS) && !isNotYetInEdgeCannotMoveFooter()) { final float velocity = Math.abs(getCurrVelocity()); stop(); mIndicatorSetter.setMovingStatus(MOVING_FOOTER); final int[] result = computeScroll(velocity); if (getFooterHeight() > 0 && (isEnabledNoMoreData() || isEnabledAutoLoadMore())) { startBounce( Math.min(result[0] * 2, getFooterHeight()), Math.min( Math.max(result[1] / 2 * 5, mMinOverScrollDuration), mMaxOverScrollDuration)); } else { startBounce(result[0], result[1]); } return; } } invalidate(); } } int[] computeScroll(float velocity) { // Multiply by a given empirical value velocity = velocity * .535f; if (mCachedPair == null) mCachedPair = new int[2]; float deceleration = (float) Math.log( Math.abs(velocity / 4.5f) / (ViewConfiguration.getScrollFriction() * mPhysical)); float ratio = (float) ((Math.exp(-Math.log10(velocity) / 1.2d)) * 2f); mCachedPair[0] = Math.max( Math.min( (int) ((ViewConfiguration.getScrollFriction() * mPhysical * Math.exp(deceleration)) * ratio), mMaxDistance), mTouchSlop); mCachedPair[1] = Math.min( Math.max((int) (1000f * ratio), mMinOverScrollDuration), mMaxOverScrollDuration); return mCachedPair; } void startBounce(int to, int duration) { mMode = SCROLLER_MODE_FLING; setInterpolator(sSpringInterpolator); mLastStart = mIndicator.getCurrentPos(); mLastTo = to; if (sDebug) { Log.d( TAG, String.format( "ScrollChecker: startBounce(): to:%s, duration:%s", to, duration)); } int distance = mLastTo - mLastStart; mLastY = 0; mDuration = duration; mIsScrolling = true; mScroller.startScroll(0, 0, 0, distance, duration); removeCallbacks(this); ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this); } void setInterpolator(Interpolator interpolator) { if (mInterpolator == interpolator) { return; } if (sDebug) { Log.d( TAG, String.format( "ScrollChecker: updateInterpolator(): interpolator: %s", interpolator == null ? "null" : interpolator.getClass().getSimpleName())); } mInterpolator = interpolator; if (!mScroller.isFinished()) { switch (mMode) { case SCROLLER_MODE_SPRING: case SCROLLER_MODE_FLING_BACK: case SCROLLER_MODE_SPRING_BACK: mLastStart = mIndicator.getCurrentPos(); int distance = mLastTo - mLastStart; int passed = mScroller.timePassed(); mScroller = makeOrGetScroller(interpolator); mScroller.startScroll(0, 0, 0, distance, mDuration - passed); removeCallbacks(this); ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this); break; case SCROLLER_MODE_PRE_FLING: case SCROLLER_MODE_CALC_FLING: final float currentVelocity = getCurrVelocity(); mScroller = makeOrGetScroller(interpolator); if (isCalcFling()) { startFling(currentVelocity); } else { startPreFling(currentVelocity); } break; default: mScroller = makeOrGetScroller(interpolator); break; } } else { mScroller = makeOrGetScroller(interpolator); } } void stop() { if (mMode != SCROLLER_MODE_NONE) { if (sDebug) { Log.d(TAG, "ScrollChecker: stop()"); } if (mNestedScrolling && isCalcFling()) { mMode = SCROLLER_MODE_NONE; stopNestedScroll(ViewCompat.TYPE_NON_TOUCH); } else { mMode = SCROLLER_MODE_NONE; } mAutomaticActionUseSmoothScroll = false; mIsScrolling = false; mScroller.forceFinished(true); mDuration = 0; mLastY = 0; mLastTo = -1; mLastStart = 0; removeCallbacks(this); } } private Scroller makeOrGetScroller(Interpolator interpolator) { if (interpolator == sSpringInterpolator) { return mStaticScroller[0]; } else if (interpolator == sSpringBackInterpolator) { return mStaticScroller[1]; } else if (interpolator == sFlingInterpolator) { return mStaticScroller[2]; } else { return new Scroller(getContext(), interpolator); } } } }
package org.infinispan.protostream; import static com.google.gson.stream.JsonToken.END_DOCUMENT; import static org.infinispan.protostream.WrappedMessage.WRAPPED_BOOL; import static org.infinispan.protostream.WrappedMessage.WRAPPED_BYTES; import static org.infinispan.protostream.WrappedMessage.WRAPPED_DESCRIPTOR_FULL_NAME; import static org.infinispan.protostream.WrappedMessage.WRAPPED_DESCRIPTOR_ID; import static org.infinispan.protostream.WrappedMessage.WRAPPED_DOUBLE; import static org.infinispan.protostream.WrappedMessage.WRAPPED_ENUM; import static org.infinispan.protostream.WrappedMessage.WRAPPED_FIXED32; import static org.infinispan.protostream.WrappedMessage.WRAPPED_FIXED64; import static org.infinispan.protostream.WrappedMessage.WRAPPED_FLOAT; import static org.infinispan.protostream.WrappedMessage.WRAPPED_INT32; import static org.infinispan.protostream.WrappedMessage.WRAPPED_INT64; import static org.infinispan.protostream.WrappedMessage.WRAPPED_MESSAGE; import static org.infinispan.protostream.WrappedMessage.WRAPPED_SFIXED32; import static org.infinispan.protostream.WrappedMessage.WRAPPED_SFIXED64; import static org.infinispan.protostream.WrappedMessage.WRAPPED_SINT32; import static org.infinispan.protostream.WrappedMessage.WRAPPED_SINT64; import static org.infinispan.protostream.WrappedMessage.WRAPPED_STRING; import static org.infinispan.protostream.WrappedMessage.WRAPPED_UINT32; import static org.infinispan.protostream.WrappedMessage.WRAPPED_UINT64; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.nio.ByteBuffer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Base64; import java.util.Date; import java.util.GregorianCalendar; import java.util.Set; import java.util.TimeZone; import java.util.stream.Collectors; import org.infinispan.protostream.config.Configuration; import org.infinispan.protostream.descriptors.AnnotatedDescriptor; import org.infinispan.protostream.descriptors.Descriptor; import org.infinispan.protostream.descriptors.EnumDescriptor; import org.infinispan.protostream.descriptors.EnumValueDescriptor; import org.infinispan.protostream.descriptors.FieldDescriptor; import org.infinispan.protostream.descriptors.GenericDescriptor; import org.infinispan.protostream.descriptors.Label; import org.infinispan.protostream.descriptors.Type; import org.infinispan.protostream.impl.BaseMarshallerDelegate; import org.infinispan.protostream.impl.ByteArrayOutputStreamEx; import org.infinispan.protostream.impl.RawProtoStreamReaderImpl; import org.infinispan.protostream.impl.RawProtoStreamWriterImpl; import org.infinispan.protostream.impl.SerializationContextImpl; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.MalformedJsonException; /** * This is the entry point to the ProtoStream library. This class provides methods to write and read Java objects * to/from a Protobuf encoded data stream. * * @author anistor@redhat.com * @since 1.0 */ public final class ProtobufUtil { private static final int BUFFER_SIZE = 512; // Z-normalized RFC 3339 format private static final String RFC_3339_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; private static final Gson GSON = new Gson(); /** * Classpath location of the message-wrapping.proto resource file. */ private static final String WRAPPING_DEFINITIONS_RES = "/org/infinispan/protostream/message-wrapping.proto"; private static final String JSON_TYPE_FIELD = "_type"; private static final String JSON_VALUE_FIELD = "_value"; private ProtobufUtil() { } public static SerializationContext newSerializationContext() { return newSerializationContext(Configuration.builder().build()); } public static SerializationContext newSerializationContext(Configuration configuration) { SerializationContextImpl serializationContext = new SerializationContextImpl(configuration); try { serializationContext.registerProtoFiles(FileDescriptorSource.fromResources(WRAPPING_DEFINITIONS_RES)); } catch (IOException | DescriptorParserException e) { throw new RuntimeException("Failed to initialize serialization context", e); } serializationContext.registerMarshaller(new WrappedMessage.Marshaller()); return serializationContext; } private static <A> void writeTo(ImmutableSerializationContext ctx, RawProtoStreamWriter out, A t) throws IOException { if (t == null) { throw new IllegalArgumentException("Object to marshall cannot be null"); } BaseMarshallerDelegate marshallerDelegate = ((SerializationContextImpl) ctx).getMarshallerDelegate(t.getClass()); marshallerDelegate.marshall(null, t, null, out); out.flush(); } public static void writeTo(ImmutableSerializationContext ctx, OutputStream out, Object t) throws IOException { writeTo(ctx, RawProtoStreamWriterImpl.newInstance(out), t); } public static byte[] toByteArray(ImmutableSerializationContext ctx, Object t) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); writeTo(ctx, baos, t); return baos.toByteArray(); } public static ByteBuffer toByteBuffer(ImmutableSerializationContext ctx, Object t) throws IOException { ByteArrayOutputStreamEx baos = new ByteArrayOutputStreamEx(BUFFER_SIZE); writeTo(ctx, baos, t); return baos.getByteBuffer(); } private static <A> A readFrom(ImmutableSerializationContext ctx, RawProtoStreamReader in, Class<A> clazz) throws IOException { BaseMarshallerDelegate<A> marshallerDelegate = ((SerializationContextImpl) ctx).getMarshallerDelegate(clazz); return marshallerDelegate.unmarshall(null, null, in); } public static <A> A readFrom(ImmutableSerializationContext ctx, InputStream in, Class<A> clazz) throws IOException { return readFrom(ctx, RawProtoStreamReaderImpl.newInstance(in), clazz); } public static <A> A fromByteArray(ImmutableSerializationContext ctx, byte[] bytes, Class<A> clazz) throws IOException { return readFrom(ctx, RawProtoStreamReaderImpl.newInstance(bytes), clazz); } //todo [anistor] what happens with remaining unconsumed trailing bytes after offset+length, here and in general? signal an error, a warning, or ignore? public static <A> A fromByteArray(ImmutableSerializationContext ctx, byte[] bytes, int offset, int length, Class<A> clazz) throws IOException { return readFrom(ctx, RawProtoStreamReaderImpl.newInstance(bytes, offset, length), clazz); } public static <A> A fromByteBuffer(ImmutableSerializationContext ctx, ByteBuffer byteBuffer, Class<A> clazz) throws IOException { return readFrom(ctx, RawProtoStreamReaderImpl.newInstance(byteBuffer), clazz); } /** * Parses a top-level message that was wrapped according to the org.infinispan.protostream.WrappedMessage proto * definition. * * @param ctx the serialization context * @param bytes the array of bytes to parse * @return the unwrapped object * @throws IOException in case parsing fails */ public static <A> A fromWrappedByteArray(ImmutableSerializationContext ctx, byte[] bytes) throws IOException { return fromWrappedByteArray(ctx, bytes, 0, bytes.length); } public static <A> A fromWrappedByteArray(ImmutableSerializationContext ctx, byte[] bytes, int offset, int length) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes, offset, length); return WrappedMessage.readMessage(ctx, RawProtoStreamReaderImpl.newInstance(bais)); } public static <A> A fromWrappedByteBuffer(ImmutableSerializationContext ctx, ByteBuffer byteBuffer) throws IOException { return WrappedMessage.readMessage(ctx, RawProtoStreamReaderImpl.newInstance(byteBuffer)); } //todo [anistor] should make it possible to plug in a custom wrapping strategy instead of the default one public static byte[] toWrappedByteArray(ImmutableSerializationContext ctx, Object t) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); WrappedMessage.writeMessage(ctx, RawProtoStreamWriterImpl.newInstance(baos), t); return baos.toByteArray(); } public static ByteBuffer toWrappedByteBuffer(ImmutableSerializationContext ctx, Object t) throws IOException { ByteArrayOutputStreamEx baos = new ByteArrayOutputStreamEx(BUFFER_SIZE); WrappedMessage.writeMessage(ctx, RawProtoStreamWriterImpl.newInstance(baos), t); return baos.getByteBuffer(); } private static final class JsonNestingLevel { boolean isFirstField = true; FieldDescriptor repeatedFieldDescriptor; int indent; JsonNestingLevel previous; JsonNestingLevel(JsonNestingLevel previous) { this.previous = previous; this.indent = previous != null ? previous.indent + 1 : 0; } } public static String toCanonicalJSON(ImmutableSerializationContext ctx, byte[] bytes) throws IOException { return toCanonicalJSON(ctx, bytes, true); } public static byte[] fromCanonicalJSON(ImmutableSerializationContext ctx, Reader reader) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); RawProtoStreamWriter writer = RawProtoStreamWriterImpl.newInstance(baos); JsonReader jsonReader = new JsonReader(reader); jsonReader.setLenient(false); try { JsonToken token = jsonReader.peek(); while (jsonReader.hasNext() && !token.equals(END_DOCUMENT)) { token = jsonReader.peek(); switch (token) { case BEGIN_OBJECT: processJsonDocument(ctx, jsonReader, writer); break; case NULL: jsonReader.nextNull(); break; case END_DOCUMENT: break; default: throw new IllegalStateException("Invalid top level object! Found token: " + token); } } writer.flush(); return baos.toByteArray(); } catch (MalformedJsonException e) { throw new IllegalStateException("Invalid JSON", e); } finally { baos.close(); reader.close(); } } private static void writeEnumField(JsonReader reader, RawProtoStreamWriter writer, FieldDescriptor fd) throws IOException { String value = reader.nextString(); EnumDescriptor enumDescriptor = fd.getEnumType(); EnumValueDescriptor valueDescriptor = enumDescriptor.findValueByName(value); if (valueDescriptor == null) { throw new IllegalStateException("Invalid enum value '" + value + "'"); } int choice = valueDescriptor.getNumber(); writer.writeEnum(fd.getNumber(), choice); } private static void writeField(JsonReader reader, RawProtoStreamWriter writer, Type fieldType, int fieldId) throws IOException { switch (fieldType) { case DOUBLE: writer.writeDouble(fieldId, reader.nextDouble()); break; case FLOAT: writer.writeFloat(fieldId, Float.valueOf(reader.nextString())); break; case INT64: writer.writeInt64(fieldId, reader.nextLong()); break; case UINT64: writer.writeUInt64(fieldId, reader.nextLong()); break; case FIXED64: writer.writeFixed64(fieldId, reader.nextLong()); break; case SFIXED64: writer.writeSFixed64(fieldId, reader.nextLong()); break; case SINT64: writer.writeSInt64(fieldId, reader.nextLong()); break; case INT32: writer.writeInt32(fieldId, reader.nextInt()); break; case FIXED32: writer.writeFixed32(fieldId, reader.nextInt()); break; case UINT32: writer.writeUInt32(fieldId, reader.nextInt()); break; case SFIXED32: writer.writeSFixed32(fieldId, reader.nextInt()); break; case SINT32: writer.writeSInt32(fieldId, reader.nextInt()); break; case BOOL: writer.writeBool(fieldId, reader.nextBoolean()); break; case STRING: writer.writeString(fieldId, reader.nextString()); break; case BYTES: byte[] decoded = Base64.getDecoder().decode(reader.nextString()); writer.writeBytes(fieldId, decoded); break; default: throw new IllegalArgumentException("The Protobuf declared field type is not compatible with the written type : " + fieldType); } } private static void expectField(String expected, String value) { if (value == null || !value.equals(expected)) { throw new IllegalStateException("The document should contain a top level field '" + expected + "'"); } } private static void expectField(FieldDescriptor descriptor, String fieldName) { if (descriptor == null) throw new IllegalStateException("The field '" + fieldName + "' was not found in the Protobuf schema"); } private static void processJsonDocument(ImmutableSerializationContext ctx, JsonReader reader, RawProtoStreamWriter writer) throws IOException { reader.beginObject(); String currentField; String topLevelType; JsonToken token = reader.peek(); while (reader.hasNext() && !(token == END_DOCUMENT)) { token = reader.peek(); switch (token) { case NAME: currentField = reader.nextName(); expectField(JSON_TYPE_FIELD, currentField); break; case STRING: topLevelType = reader.nextString(); Type fieldType = getFieldType(ctx, topLevelType); switch (fieldType) { case ENUM: processEnum(reader, writer, (EnumDescriptor) ctx.getDescriptorByName(topLevelType)); break; case MESSAGE: processObject(ctx, reader, writer, topLevelType, null, true); break; default: processPrimitive(reader, writer, fieldType); break; } } } } private static void processEnum(JsonReader reader, RawProtoStreamWriter writer, EnumDescriptor enumDescriptor) throws IOException { while (reader.hasNext()) { JsonToken token = reader.peek(); switch (token) { case NAME: String fieldName = reader.nextName(); expectField(JSON_VALUE_FIELD, fieldName); break; case STRING: String read = reader.nextString(); EnumValueDescriptor valueByName = enumDescriptor.findValueByName(read); if (valueByName == null) { throw new IllegalStateException("Invalid enum value '" + read + "'"); } int choice = valueByName.getNumber(); Integer typeId = enumDescriptor.getTypeId(); writer.writeInt32(WRAPPED_DESCRIPTOR_ID, typeId); writer.writeEnum(WRAPPED_ENUM, choice); break; case NULL: reader.nextNull(); throw new IllegalStateException("Invalid enum value 'null'"); case BOOLEAN: boolean bool = reader.nextBoolean(); throw new IllegalStateException("Invalid enum value '" + bool + "'"); case NUMBER: long number = reader.nextLong(); throw new IllegalStateException("Invalid enum value '" + number + "'"); default: throw new IllegalStateException("Unexpected token :" + token); } } } private static void processObject(ImmutableSerializationContext ctx, JsonReader reader, RawProtoStreamWriter writer, String type, Integer typeId, boolean topLevel) throws IOException { GenericDescriptor descriptorByName = ctx.getDescriptorByName(type); Descriptor messageDescriptor = (Descriptor) descriptorByName; Set<String> requiredFields = messageDescriptor.getFields().stream() .filter(FieldDescriptor::isRequired).map(FieldDescriptor::getName).collect(Collectors.toSet()); ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); RawProtoStreamWriter objectWriter = RawProtoStreamWriterImpl.newInstance(baos); String currentField = null; while (reader.hasNext()) { JsonToken token = reader.peek(); switch (token) { case BEGIN_ARRAY: processArray(ctx, type, currentField, reader, objectWriter); break; case BEGIN_OBJECT: reader.beginObject(); FieldDescriptor descriptor = ((Descriptor) descriptorByName).findFieldByName(currentField); Descriptor messageType = descriptor.getMessageType(); if (messageType == null) { throw new IllegalStateException("Field '" + currentField + "' is not an object"); } processObject(ctx, reader, objectWriter, messageType.getFullName(), descriptor.getNumber(), false); requiredFields.remove(descriptor.getName()); break; case NAME: currentField = reader.nextName(); break; case STRING: case NUMBER: case BOOLEAN: FieldDescriptor fieldByName = ((Descriptor) descriptorByName).findFieldByName(currentField); expectField(fieldByName, currentField); if (fieldByName.getType() == Type.ENUM) { writeEnumField(reader, objectWriter, fieldByName); } else { writeField(reader, objectWriter, fieldByName.getType(), fieldByName.getNumber()); } requiredFields.remove(fieldByName.getName()); break; case NULL: reader.nextNull(); break; } } if (!requiredFields.isEmpty()) { String missing = requiredFields.iterator().next(); throw new IllegalStateException("Required field '" + missing + "' missing"); } if (topLevel) { Integer tlt = descriptorByName.getTypeId(); if (tlt == null) { writer.writeString(WRAPPED_DESCRIPTOR_FULL_NAME, type); } else { writer.writeInt32(WRAPPED_DESCRIPTOR_ID, tlt); } objectWriter.flush(); writer.writeBytes(WRAPPED_MESSAGE, baos.toByteArray()); } else { objectWriter.flush(); writer.writeBytes(typeId, baos.toByteArray()); } writer.flush(); reader.endObject(); } private static void processPrimitive(JsonReader reader, RawProtoStreamWriter writer, Type fieldType) throws IOException { while (reader.hasNext()) { JsonToken token = reader.peek(); switch (token) { case NAME: String fieldName = reader.nextName(); expectField(JSON_VALUE_FIELD, fieldName); break; case STRING: case NUMBER: case BOOLEAN: writeField(reader, writer, fieldType, getPrimitiveFieldId(fieldType)); break; case NULL: reader.nextNull(); break; default: throw new IllegalStateException("Unexpected token :" + token); } } } private static int getPrimitiveFieldId(Type primitiveType) { switch (primitiveType) { case DOUBLE: return WRAPPED_DOUBLE; case FLOAT: return WRAPPED_FLOAT; case INT32: return WRAPPED_INT32; case INT64: return WRAPPED_INT64; case FIXED32: return WRAPPED_FIXED32; case FIXED64: return WRAPPED_FIXED64; case BOOL: return WRAPPED_BOOL; case STRING: return WRAPPED_STRING; case BYTES: return WRAPPED_BYTES; case UINT32: return WRAPPED_UINT32; case UINT64: return WRAPPED_UINT64; case SFIXED32: return WRAPPED_SFIXED32; case SFIXED64: return WRAPPED_SFIXED64; case SINT32: return WRAPPED_SINT32; case SINT64: return WRAPPED_SINT64; default: throw new IllegalStateException("Unknown field type " + primitiveType); } } private static Type getFieldType(ImmutableSerializationContext ctx, String fullTypeName) { switch (fullTypeName) { case "double": return Type.DOUBLE; case "float": return Type.FLOAT; case "int32": return Type.INT32; case "int64": return Type.INT64; case "fixed32": return Type.FIXED32; case "fixed64": return Type.FIXED64; case "bool": return Type.BOOL; case "string": return Type.STRING; case "bytes": return Type.BYTES; case "uint32": return Type.UINT32; case "uint64": return Type.UINT64; case "sfixed32": return Type.SFIXED32; case "sfixed64": return Type.SFIXED64; case "sint32": return Type.SINT32; case "sint64": return Type.SINT64; default: GenericDescriptor descriptorByName = ctx.getDescriptorByName(fullTypeName); if (descriptorByName instanceof EnumDescriptor) { return Type.ENUM; } return Type.MESSAGE; } } private static void processArray(ImmutableSerializationContext ctx, String type, String field, JsonReader reader, RawProtoStreamWriter writer) throws IOException { reader.beginArray(); while (reader.hasNext()) { JsonToken token = reader.peek(); switch (token) { case BEGIN_ARRAY: processArray(ctx, type, field, reader, writer); case BEGIN_OBJECT: reader.beginObject(); Descriptor d = (Descriptor) ctx.getDescriptorByName(type); FieldDescriptor fieldByName = d.findFieldByName(field); int number = fieldByName.getNumber(); processObject(ctx, reader, writer, fieldByName.getMessageType().getFullName(), number, false); break; case STRING: case NUMBER: case BOOLEAN: Descriptor de = (Descriptor) ctx.getDescriptorByName(type); FieldDescriptor fd = de.findFieldByName(field); Type fieldType = fd.getType(); if (!fd.isRepeated()) { throw new IllegalStateException("Field '" + fd.getName() + "' is not an array"); } if (fieldType == Type.ENUM) { writeEnumField(reader, writer, fd); } else { writeField(reader, writer, fieldType, fd.getNumber()); } break; } } reader.endArray(); } public static String toCanonicalJSON(ImmutableSerializationContext ctx, byte[] bytes, boolean prettyPrint) throws IOException { StringBuilder jsonOut = new StringBuilder(); toCanonicalJSON(ctx, bytes, jsonOut, prettyPrint ? 0 : -1); return jsonOut.toString(); } private static void toCanonicalJSON(ImmutableSerializationContext ctx, byte[] bytes, StringBuilder jsonOut, int initNestingLevel) throws IOException { if (bytes.length == 0) { // only null values get to be encoded to an empty byte array jsonOut.append("null"); return; } Descriptor wrapperDescriptor = ctx.getMessageDescriptor(WrappedMessage.PROTOBUF_TYPE_NAME); boolean prettyPrint = initNestingLevel >= 0; TagHandler messageHandler = new TagHandler() { private JsonNestingLevel nestingLevel; /** * Have we written the "_type" field? */ private boolean missingType = true; private void indent() { jsonOut.append('\n'); for (int k = initNestingLevel + nestingLevel.indent; k > 0; k jsonOut.append(" "); } } @Override public void onStart(GenericDescriptor descriptor) { nestingLevel = new JsonNestingLevel(null); if (prettyPrint) { indent(); nestingLevel.indent++; } jsonOut.append('{'); writeType(descriptor); } private void writeType(AnnotatedDescriptor descriptor) { if (descriptor != null && nestingLevel.previous == null && nestingLevel.isFirstField) { missingType = false; nestingLevel.isFirstField = false; if (prettyPrint) { indent(); } jsonOut.append('\"').append("_type").append('\"').append(':'); if (prettyPrint) { jsonOut.append(' '); } String type; if (descriptor instanceof FieldDescriptor) { type = FieldDescriptor.class.cast(descriptor).getTypeName(); } else { type = descriptor.getFullName(); } jsonOut.append('\"').append(type).append('\"'); } } private String escape(String tagValue) { return GSON.toJson(tagValue); } @Override public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object tagValue) { if (fieldDescriptor == null) { // unknown field, ignore return; } if (missingType) { writeType(fieldDescriptor); } startSlot(fieldDescriptor); switch (fieldDescriptor.getType()) { case STRING: jsonOut.append(escape((String) tagValue)); break; case INT64: case SINT64: case UINT64: case FIXED64: jsonOut.append('\"').append(tagValue).append('\"'); break; case FLOAT: Float f = (Float) tagValue; if (f.isInfinite() || f.isNaN()) { jsonOut.append('\"').append(f).append('\"'); } else { jsonOut.append(f); } break; case DOUBLE: Double d = (Double) tagValue; if (d.isInfinite() || d.isNaN()) { jsonOut.append('\"').append(d).append('\"'); } else { jsonOut.append(d); } break; case ENUM: EnumValueDescriptor enumValue = fieldDescriptor.getEnumType().findValueByNumber((Integer) tagValue); jsonOut.append('\"').append(enumValue.getName()).append('\"'); break; case BYTES: String base64encoded = Base64.getEncoder().encodeToString((byte[]) tagValue); jsonOut.append('\"').append(base64encoded).append('\"'); break; default: if (tagValue instanceof Date) { jsonOut.append('\"').append(formatDate((Date) tagValue)).append('\"'); } else if (fieldNumber == WRAPPED_ENUM) { jsonOut.append('\"').append(tagValue).append('\"'); } else { jsonOut.append(tagValue); } } } @Override public void onStartNested(int fieldNumber, FieldDescriptor fieldDescriptor) { if (fieldDescriptor == null) { // unknown field, ignore return; } startSlot(fieldDescriptor); nestingLevel = new JsonNestingLevel(nestingLevel); if (prettyPrint) { indent(); nestingLevel.indent++; } jsonOut.append('{'); } @Override public void onEndNested(int fieldNumber, FieldDescriptor fieldDescriptor) { if (nestingLevel.repeatedFieldDescriptor != null) { endArraySlot(); } if (prettyPrint) { nestingLevel.indent indent(); } jsonOut.append('}'); nestingLevel = nestingLevel.previous; } @Override public void onEnd() { if (nestingLevel.repeatedFieldDescriptor != null) { endArraySlot(); } if (prettyPrint) { nestingLevel.indent indent(); } jsonOut.append('}'); nestingLevel = null; if (prettyPrint) { jsonOut.append('\n'); } } private void startSlot(FieldDescriptor fieldDescriptor) { if (nestingLevel.repeatedFieldDescriptor != null && nestingLevel.repeatedFieldDescriptor != fieldDescriptor) { endArraySlot(); } if (nestingLevel.isFirstField) { nestingLevel.isFirstField = false; } else { jsonOut.append(','); } if (!fieldDescriptor.isRepeated() || nestingLevel.repeatedFieldDescriptor == null) { if (prettyPrint) { indent(); } if (fieldDescriptor.getLabel() == Label.ONE_OF) { jsonOut.append('"').append(JSON_VALUE_FIELD).append("\":"); } else { jsonOut.append('"').append(fieldDescriptor.getName()).append("\":"); } } if (prettyPrint) { jsonOut.append(' '); } if (fieldDescriptor.isRepeated() && nestingLevel.repeatedFieldDescriptor == null) { nestingLevel.repeatedFieldDescriptor = fieldDescriptor; jsonOut.append('['); } } private void endArraySlot() { if (prettyPrint && nestingLevel.repeatedFieldDescriptor.getType() == Type.MESSAGE) { indent(); } nestingLevel.repeatedFieldDescriptor = null; jsonOut.append(']'); } }; TagHandler wrapperHandler = new TagHandler() { private Integer typeId; private String typeName; private byte[] wrappedMessage; private Integer wrappedEnum; private GenericDescriptor getDescriptor() { return typeId != null ? ctx.getDescriptorByTypeId(typeId) : ctx.getDescriptorByName(typeName); } @Override public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object tagValue) { if (fieldDescriptor == null) { // ignore unknown fields return; } switch (fieldNumber) { case WRAPPED_DESCRIPTOR_ID: typeId = (Integer) tagValue; break; case WRAPPED_DESCRIPTOR_FULL_NAME: typeName = (String) tagValue; break; case WRAPPED_MESSAGE: wrappedMessage = (byte[]) tagValue; break; case WRAPPED_ENUM: wrappedEnum = (Integer) tagValue; break; case WrappedMessage.WRAPPED_DOUBLE: case WrappedMessage.WRAPPED_FLOAT: case WrappedMessage.WRAPPED_INT64: case WrappedMessage.WRAPPED_UINT64: case WrappedMessage.WRAPPED_INT32: case WrappedMessage.WRAPPED_FIXED64: case WrappedMessage.WRAPPED_FIXED32: case WrappedMessage.WRAPPED_BOOL: case WrappedMessage.WRAPPED_STRING: case WrappedMessage.WRAPPED_BYTES: case WrappedMessage.WRAPPED_UINT32: case WrappedMessage.WRAPPED_SFIXED32: case WrappedMessage.WRAPPED_SFIXED64: case WrappedMessage.WRAPPED_SINT32: case WrappedMessage.WRAPPED_SINT64: messageHandler.onStart(null); messageHandler.onTag(fieldNumber, fieldDescriptor, tagValue); messageHandler.onEnd(); break; } } @Override public void onEnd() { if (wrappedEnum != null) { EnumDescriptor enumDescriptor = (EnumDescriptor) getDescriptor(); String enumConstantName = enumDescriptor.findValueByNumber(wrappedEnum).getName(); FieldDescriptor fd = wrapperDescriptor.findFieldByNumber(WRAPPED_ENUM); messageHandler.onStart(enumDescriptor); messageHandler.onTag(WRAPPED_ENUM, fd, enumConstantName); messageHandler.onEnd(); } else if (wrappedMessage != null) { try { Descriptor messageDescriptor = (Descriptor) getDescriptor(); ProtobufParser.INSTANCE.parse(messageHandler, messageDescriptor, wrappedMessage); } catch (IOException e) { throw new RuntimeException(e); } } } }; ProtobufParser.INSTANCE.parse(wrapperHandler, wrapperDescriptor, bytes); } private static String formatDate(Date tagValue) { return timestampFormat.get().format(tagValue); } private static final ThreadLocal<DateFormat> timestampFormat = ThreadLocal.withInitial(() -> { // Z-normalized RFC 3339 format SimpleDateFormat sdf = new SimpleDateFormat(RFC_3339_DATE_FORMAT); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.setGregorianChange(new Date(Long.MIN_VALUE)); sdf.setCalendar(calendar); return sdf; }); }
package game.entity.block.breakable; import engine.music.Music; import engine.save.DataTag; import game.World; import game.entity.block.Block; import game.entity.living.player.Player; import game.item.ItemStack; import game.item.tool.ItemTool; import game.item.tool.ItemTool.EnumTools; import java.awt.Color; import java.awt.Graphics2D; public class BlockBreakable extends Block{ private int health; private boolean jiggle; /**the tool that can be used to destroy this block*/ private EnumTools effectiveTool; int tracker = 0; public BlockBreakable(World world, String uin) { super(world, uin); } public BlockBreakable(World world, String uin, EnumTools toolEffectiveness) { this(world, uin); setEffectiveTool(toolEffectiveness); } public BlockBreakable setEffectiveTool(EnumTools tool){ effectiveTool = tool; return this; } public EnumTools getEffectiveTool(){ return effectiveTool; } private int defaultHealth; public BlockBreakable setHealth(int i){ health = i; defaultHealth = i; return this; } public void resetHealth(){ health = defaultHealth; } public int getHealth(){ return health; } @Override public void draw(Graphics2D g) { setMapPosition(); if(jiggle){ tracker ++; if(tracker < 2) xmap +=4; else if(tracker < 4) xmap-=4; else { jiggle = false; tracker = 0; } } if (facingRight) g.drawImage(getAnimation().getImage(), (int) ((xScreen + xmap) - (width / 2)), (int) ((yScreen + ymap) - (height / 2)), null); else g.drawImage(getAnimation().getImage(), (int) (((xScreen + xmap) - (width / 2)) + width), (int) ((yScreen + ymap) - (height / 2)), -width, height, null); if (getWorld().showBoundingBoxes) { g.setColor(Color.WHITE); g.draw(getRectangle()); } } @Override public void onEntityHit(Player player) { int wepDmg = 0; ItemStack weaponStack = player.invArmor.getWeapon(); ItemTool tool = null; if(weaponStack != null && weaponStack.getItem() instanceof ItemTool) tool = ((ItemTool)weaponStack.getItem()); if(tool != null) wepDmg = tool.getEffectiveDamage(weaponStack); if(tool == null){ if(!needsToolToMine()){ hit(); health -= player.getAttackDamage(); } }else{ // if(needsToolToMine()){//if this block needs a tool, break only when tool is held if(effectiveTool == tool.getEffectiveness()){ hit(); health -=wepDmg; } //now only exclusive tools will work // else // if(effectiveTool == tool.getEffectiveness())//if the block doesnt need a tool, a bonus for wielding the right tool will kick in // health -= wepDmg; // else{ // health -= wepDmg/2;//if bonus tool is not yield, use half of the current weapons dmg as bonus } if(health <= 0) mine(player); } @Override public void onEntityHit(float damage) { hit(); health -= damage; if(health <= 0) remove = true; } private void hit(){ jiggle = true; switch (getType()) { case ROCK: Music.play("hit_rock_" + (rand.nextInt(4)+1)); break; case WOOD: Music.play("hit_wood_" + (rand.nextInt(5)+1)); break; default: break; } } protected void mine(Player p){ if(getDrop() != null){ if(p.getInventory().setStackInNextAvailableSlot(getDrop())){ remove = true; if(p.invArmor.getWeapon() != null){ p.invArmor.getWeapon().damageStack(1); } }else { remove = false; health = defaultHealth; } }else{ health = defaultHealth; } } @Override public void writeToSave(DataTag data) { super.writeToSave(data); data.writeInt("punchHealth", health); } @Override public void readFromSave(DataTag data) { super.readFromSave(data); health = data.readInt("punchHealth"); } public boolean needsToolToMine(){ return false; } public World getWorld(){ return (World)world; } }
package com.gokuai.base; import com.gokuai.base.utils.Util; import com.google.gson.Gson; import java.util.ArrayList; import java.util.HashMap; public abstract class HttpEngine extends SignAbility { private final static String LOG_TAG = "HttpEngine"; protected String mClientSecret; protected String mClientId; public HttpEngine(String clientId, String clientSecret) { mClientId = clientId; mClientSecret = clientSecret; } public static final int ERRORID_NETDISCONNECT = 1; /** * * * @author Administrator */ public interface DataListener { void onReceivedData(int apiId, Object object, int errorId); } /** * API,SSO * * @param params * @return */ public String generateSign(HashMap<String, String> params) { return generateSign(params, mClientSecret); } /** * @param params * @param ignoreKeys * @return */ protected String generateSign(HashMap<String, String> params, ArrayList<String> ignoreKeys) { return generateSign(params, mClientSecret, ignoreKeys); } public class RequestHelper { RequestMethod method; HashMap<String, String> params; HashMap<String, String> headParams; String url; boolean checkAuth; String postType = NetConfig.POST_DEFAULT_FORM_TYPE; IAsyncTarget target; ArrayList<String> ignoreKeys; public RequestHelper setMethod(RequestMethod method) { this.method = method; return this; } public RequestHelper setParams(HashMap<String, String> params) { this.params = params; return this; } public RequestHelper setHeadParams(HashMap<String, String> headParams) { this.headParams = headParams; return this; } public RequestHelper setCheckAuth(boolean checkAuth) { this.checkAuth = checkAuth; return this; } public RequestHelper setPostType(String postType) { this.postType = postType; return this; } public RequestHelper setUrl(String url) { this.url = url; return this; } public RequestHelper setIgnoreKeys(ArrayList<String> ignoreKeys) { this.ignoreKeys = ignoreKeys; return this; } public RequestHelper setTarget(IAsyncTarget target) { this.target = target; return this; } /** * * * @return */ public String executeSync() { checkNecessaryParams(url, method); if (!isNetworkAvailableEx()) { ReturnResult returnResult = new ReturnResult("", ERRORID_NETDISCONNECT); return new Gson().toJson(returnResult); } if (checkAuth) { if (HttpEngine.this instanceof IAuthRequest) { return ((IAuthRequest) HttpEngine.this).sendRequestWithAuth(url, method, params, headParams, ignoreKeys, postType); } else { LogPrint.error(LOG_TAG, "You need implement IAuthRequest before set checkAuth=true"); } } return NetConnection.sendRequest(url, method, params, headParams, postType); } /** * * * @return */ public IAsyncTarget executeAsync(DataListener listener, int apiId, RequestHelperCallBack callBack) { checkNecessaryParams(url, method); if (target != null) { return target.execute(listener, this, callBack, apiId); } return new DefaultAsyncTarget().execute(listener, this, callBack, apiId); } /** * * * @return */ public IAsyncTarget executeAsync(DataListener listener, int apiId) { return executeAsync(listener, apiId, null); } private void checkNecessaryParams(String url, RequestMethod method) { if (Util.isEmpty(url)) { throw new IllegalArgumentException("url must not be null"); } if (method == null) { throw new IllegalArgumentException("method must not be null"); } } } public interface RequestHelperCallBack { Object getReturnData(String returnString); } /** * @return */ protected boolean isNetworkAvailableEx() { return true; } }
package com.androidsx.rateme; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.LightingColorFilter; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.androidsx.libraryrateme.R; public class DialogRateMe extends DialogFragment { private static final String TAG = DialogRateMe.class.getSimpleName(); private static final String MARKET_CONSTANT = "market://details?id="; private static final String GOOGLE_PLAY_CONSTANT = "http://play.google.com/store/apps/details?id="; //Identify TitleDivider private String RESOURCE_NAME = "titleDivider"; private String DEFAULT_TYPE_RESOURCE = "id"; private String DEFAULT_PACKAGE = "android"; //Views private View mView; private View tView; private View confirDialogView; private Button close; private RatingBar ratingBar; private LayerDrawable stars; private Button rateMe; private Button noThanks; private Button share; //configuration private final String appPackageName; private final boolean goToMail; private final String email; private final boolean showShareButton; private final int titleTextColor; private final int titleBackgroundColor; private final int dialogColor; private final int lineDividerColor; private final int textColor; private final int logoResId; private final int rateButtonBackgroundColor; private final int rateButtonTextColor; private final int rateButtonPressedBackgroundColor; private final int defaultStarsSelected; private final int iconColor; private final boolean changeIconTitleColor; private final boolean showOKButtonByDefault; private DialogRateMe(Builder builder) { this.appPackageName = builder.appPackageName; this.goToMail = builder.goToMail; this.email = builder.email; this.showShareButton = builder.showShareButton; this.titleTextColor = builder.titleTextColor; this.titleBackgroundColor = builder.titleBackgroundColor; this.dialogColor = builder.dialogColor; this.lineDividerColor = builder.lineDividerColor; this.textColor = builder.textColor; this.logoResId = builder.logoResId; this.rateButtonBackgroundColor = builder.rateButtonBackgroundColor; this.rateButtonTextColor = builder.rateButtonTextColor; this.rateButtonPressedBackgroundColor = builder.rateButtonPressedBackgroundColor; this.defaultStarsSelected = builder.defaultStarsSelected; this.iconColor = builder.iconColor; this.changeIconTitleColor = builder.changeIconColor; this.showOKButtonByDefault = builder.showOKButtonByDefault; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { initializeUiFields(); Log.d(TAG, "initialize correctly all the components"); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); if(changeIconTitleColor){ setIconsColor(iconColor); } stars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP); if(showOKButtonByDefault) { ratingBar.setRating((float) defaultStarsSelected); } ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if (rating >= 4.0) { rateMe.setVisibility(View.VISIBLE); noThanks.setVisibility(View.GONE); } else { noThanks.setVisibility(View.VISIBLE); rateMe.setVisibility(View.GONE); } } }); ratingBar.setRating((float) defaultStarsSelected); configureButtons(); close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); RateMeDialogTimer.clearSharedPreferences(getActivity()); Log.d(TAG, "clear preferences"); } }); share.setVisibility(showShareButton ? View.VISIBLE : View.GONE); share.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(shareApp(appPackageName)); Log.d(TAG, "share App"); } }); return builder.setView(mView).setCustomTitle(tView).setCancelable(false).create(); } @Override public void onStart() { super.onStart(); final int titleDividerId = getResources().getIdentifier(RESOURCE_NAME,DEFAULT_TYPE_RESOURCE , DEFAULT_PACKAGE); final View titleDivider = getDialog().findViewById(titleDividerId); if (titleDivider != null) { titleDivider.setBackgroundColor(lineDividerColor); } } private void initializeUiFields() { //Main Dialog GradientDrawable rateMeButton = (GradientDrawable) getResources().getDrawable(R.drawable.customshape); GradientDrawable rateMeButtonItemSelected = (GradientDrawable) getResources().getDrawable(R.drawable.itemselected); rateMeButton.setColor(rateButtonBackgroundColor); rateMeButtonItemSelected.setColor(rateButtonPressedBackgroundColor); mView = getActivity().getLayoutInflater().inflate(R.layout.library, null); tView = getActivity().getLayoutInflater().inflate(R.layout.title, null); close = (Button) tView.findViewById(R.id.buttonClose); share = (Button) tView.findViewById(R.id.buttonShare); rateMe = (Button) mView.findViewById(R.id.buttonRateMe); noThanks = (Button) mView.findViewById(R.id.buttonThanks); ratingBar = (RatingBar) mView.findViewById(R.id.ratingBar); stars = (LayerDrawable) ratingBar.getProgressDrawable(); mView.setBackgroundColor(dialogColor); tView.setBackgroundColor(titleBackgroundColor); ((TextView) tView.findViewById(R.id.title)).setTextColor(titleTextColor); ((ImageView) mView.findViewById(R.id.picture)).setImageResource(logoResId); ((TextView) mView.findViewById(R.id.phraseCenter)).setTextColor(textColor); rateMe.setTextColor(rateButtonTextColor); noThanks.setTextColor(rateButtonTextColor); //Confirmation Dialog confirDialogView = getActivity().getLayoutInflater().inflate(R.layout.confirmationtitledialog, null); confirDialogView.setBackgroundColor(dialogColor); ((TextView) confirDialogView.findViewById(R.id.confirmDialogTitle)).setTextColor(textColor); ((ImageView) confirDialogView.findViewById(R.id.iconConfirmDialog)).setImageResource(logoResId); } private void configureButtons() { rateMe.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { rateApp(); Log.d(TAG, "go to Google Play Store for Rate-Me"); RateMeDialogTimer.setOptOut(getActivity(), true); } }); noThanks.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (goToMail) { confirmGoToMailDialog(getArguments()).show(); Log.d(TAG, "got to Mail for explain what is the problem"); }else{ dismiss(); } } }); } private void rateApp() { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_CONSTANT + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_CONSTANT + appPackageName))); } } private void goToMail() { final String subject = getResources().getString(R.string.subject_email); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("plain/text"); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { email }); intent.putExtra(Intent.EXTRA_SUBJECT, subject); try { startActivity(Intent.createChooser(intent, "")); } catch (android.content.ActivityNotFoundException ex) { rateApp(); } } private Dialog confirmGoToMailDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setCustomTitle(confirDialogView).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { goToMail(); dismiss(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dismiss(); } }); return builder.create(); } private Intent shareApp(String appPackageName) { Intent shareApp = new Intent(); shareApp.setAction(Intent.ACTION_SEND); try { shareApp.putExtra(Intent.EXTRA_TEXT, MARKET_CONSTANT + appPackageName); } catch (android.content.ActivityNotFoundException anfe) { shareApp.putExtra(Intent.EXTRA_TEXT, GOOGLE_PLAY_CONSTANT + appPackageName); } shareApp.setType("text/plain"); return shareApp; } private void setIconsColor(int buttonColor){ Drawable iconClose = getResources().getDrawable( R.drawable.ic_action_cancel ); Drawable iconShare = getResources().getDrawable( R.drawable.ic_action_share ); ColorFilter filter = new LightingColorFilter( buttonColor, buttonColor); iconClose.setColorFilter(filter); iconShare.setColorFilter(filter); } public static class Builder { private String appPackageName; private boolean goToMail; private String email; private boolean showShareButton; private int titleTextColor = Color.WHITE; private int titleBackgroundColor = Color.BLACK; private int dialogColor = Color.WHITE; private int lineDividerColor = Color.GRAY; private int textColor = Color.WHITE; private int logoResId = R.drawable.icono; private int rateButtonBackgroundColor = Color.BLACK; private int rateButtonTextColor = Color.WHITE; private int rateButtonPressedBackgroundColor = Color.GRAY; private int defaultStarsSelected = 0; private int iconColor = Color.WHITE; private boolean changeIconColor; private boolean showOKButtonByDefault = false; public Builder(Context ctx) { this.appPackageName = ctx.getApplicationContext().getPackageName(); } public Builder setEmail(String email) { this.email = email; return this; } public Builder setShowShareButton(boolean showShareButton) { this.showShareButton = showShareButton; return this; } public Builder setGoToMail(boolean goToMail) { this.goToMail = goToMail; return this; } public Builder setTitleColor(int titleTextColor) { this.titleTextColor = titleTextColor; return this; } public Builder setTitleBackgroundColor(int titleBackgroundColor) { this.titleBackgroundColor = titleBackgroundColor; return this; } public Builder setDialogColor(int dialogColor) { this.dialogColor = dialogColor; return this; } public Builder setLineDividerColor(int lineDividerColor) { this.lineDividerColor = lineDividerColor; return this; } public Builder setLogoResourceId(int logoResId) { this.logoResId = logoResId; return this; } public Builder setTextColor(int textColor) { this.textColor = textColor; return this; } public Builder setRateButtonBackgroundColor(int rateButtonBackgroundColor) { this.rateButtonBackgroundColor = rateButtonBackgroundColor; return this; } public Builder setRateButtonTextColor(int rateButtonTextColor) { this.rateButtonTextColor = rateButtonTextColor; return this; } public Builder setRateButtonPressedBackgroundColor( int rateButtonPressedBackgroundColor) { this.rateButtonPressedBackgroundColor = rateButtonPressedBackgroundColor; return this; } public Builder setDefaultStartSelected( int numStars) { this.defaultStarsSelected = numStars; return this; } public Builder setIconColor(int iconColor) { this.iconColor = iconColor; return this; } public Builder setChangeIconColor (boolean changeIconColor) { this.changeIconColor = changeIconColor; return this; } public Builder setShowOKButtonByDefault( boolean visible) { this.showOKButtonByDefault = visible; return this; } public DialogRateMe build() { return new DialogRateMe(this); } } }
package com.jediterm.terminal.model; import com.google.common.collect.Lists; import com.jediterm.terminal.StyledTextConsumer; import com.jediterm.terminal.TextStyle; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Holds styled characters lines */ public class LinesBuffer { private static final Logger LOG = Logger.getLogger(LinesBuffer.class); private static final int BUFFER_MAX_LINES = 1000; private ArrayList<TerminalLine> myLines = Lists.newArrayList(); public LinesBuffer() { } public synchronized String getLines() { final StringBuilder sb = new StringBuilder(); boolean first = true; for (TerminalLine line : myLines) { if (!first) { sb.append("\n"); } sb.append(line.getText()); first = false; } return sb.toString(); } public synchronized void addNewLine(@NotNull TextStyle style, @NotNull CharBuffer characters) { addNewLine(new TerminalLine.TextEntry(style, characters)); } private synchronized void addNewLine(@NotNull TerminalLine.TextEntry entry) { addLine(new TerminalLine(entry)); } private synchronized void addLine(@NotNull TerminalLine line) { if (myLines.size() >= BUFFER_MAX_LINES) { removeTopLines(1); } myLines.add(line); } public synchronized int getLineCount() { return myLines.size(); } public synchronized void removeTopLines(int count) { myLines = Lists.newArrayList(myLines.subList(count, myLines.size())); } public String getLineText(int row) { TerminalLine line = getLine(row); return line.getText(); } public synchronized void insertLines(int y, int count, int lastLine) { LinesBuffer tail = new LinesBuffer(); if (lastLine < getLineCount() - 1) { moveBottomLinesTo(getLineCount() - lastLine - 1, tail); } LinesBuffer head = new LinesBuffer(); if (y > 0) { moveTopLinesTo(y, head); } for (int i = 0; i < count; i++) { head.addNewLine(TextStyle.EMPTY, CharBuffer.EMPTY); } head.moveBottomLinesTo(head.getLineCount(), this); removeBottomLines(count); tail.moveTopLinesTo(tail.getLineCount(), this); } public synchronized LinesBuffer deleteLines(int y, int count, int lastLine) { LinesBuffer tail = new LinesBuffer(); if (lastLine < getLineCount() - 1) { moveBottomLinesTo(getLineCount() - lastLine - 1, tail); } LinesBuffer head = new LinesBuffer(); if (y > 0) { moveTopLinesTo(y, head); } int toRemove = Math.min(count, getLineCount()); LinesBuffer removed = new LinesBuffer(); moveTopLinesTo(toRemove, removed); head.moveBottomLinesTo(head.getLineCount(), this); for (int i = 0; i < toRemove; i++) { addNewLine(TextStyle.EMPTY, CharBuffer.EMPTY); } tail.moveTopLinesTo(tail.getLineCount(), this); return removed; } public synchronized void writeString(int x, int y, String str, @NotNull TextStyle style) { TerminalLine line = getLine(y); line.writeString(x, str, style); } public synchronized void clearLines(int startRow, int endRow) { for (int i = startRow; i <= endRow; i++) { if (i < myLines.size()) { TerminalLine line = myLines.get(i); line.clear(); } else { break; } } } public synchronized void clearAll() { myLines.clear(); } public synchronized void deleteCharacters(int x, int y, int count) { TerminalLine line = getLine(y); line.deleteCharacters(x, count); } public synchronized void insertBlankCharacters(final int x, final int y, final int count, final int maxLen) { TerminalLine line = getLine(y); line.insertBlankCharacters(x, count, maxLen); } public synchronized void clearArea(int leftX, int topY, int rightX, int bottomY, @NotNull TextStyle style) { for (int y = topY; y < bottomY; y++) { TerminalLine line = getLine(y); line.clearArea(leftX, rightX, style); } } interface TextEntryProcessor { /** * @return true to remove entry */ void process(int x, int y, @NotNull TerminalLine.TextEntry entry); } public synchronized void processLines(final int yStart, final int yCount, @NotNull final StyledTextConsumer consumer, final int startRow) { iterateLines(yStart, yCount, new TextEntryProcessor() { @Override public void process(int x, int y, @NotNull TerminalLine.TextEntry entry) { consumer.consume(x, y, entry.getStyle(), entry.getText(), startRow); } }); } public synchronized void processLines(final int yStart, final int yCount, @NotNull final StyledTextConsumer consumer) { processLines(yStart, yCount, consumer, -getLineCount()); } public synchronized void iterateLines(final int firstLine, final int count, @NotNull TextEntryProcessor processor) { for (int y = firstLine; y<Math.min(firstLine+count, myLines.size()); y++) { TerminalLine line = myLines.get(y); line.process(y, processor); } } public synchronized void moveTopLinesTo(int count, final @NotNull LinesBuffer buffer) { count = Math.min(count, getLineCount()); buffer.addLines(myLines.subList(0, count)); removeTopLines(count); } public synchronized void addLines(@NotNull List<TerminalLine> lines) { int count = myLines.size() + lines.size(); if (count >= BUFFER_MAX_LINES) { removeTopLines(count - BUFFER_MAX_LINES); } myLines.addAll(lines); } @NotNull public synchronized TerminalLine getLine(int row) { if (row >= getLineCount()) { for (int i = getLineCount(); i <= row; i++) { addLine(TerminalLine.createEmpty()); } } return myLines.get(row); } public synchronized void moveBottomLinesTo(int count, final @NotNull LinesBuffer buffer) { count = Math.min(count, getLineCount()); buffer.addLinesFirst(myLines.subList(getLineCount() - count, getLineCount())); removeBottomLines(count); } private synchronized void addLinesFirst(@NotNull List<TerminalLine> lines) { List<TerminalLine> list = Lists.newArrayList(lines); list.addAll(myLines); myLines = Lists.newArrayList(list); } private synchronized void removeBottomLines(int count) { myLines = Lists.newArrayList(myLines.subList(0, getLineCount() - count)); } }
package org.xtreemfs.mrc.utils; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.xtreemfs.common.ReplicaUpdatePolicies; import org.xtreemfs.common.uuids.ServiceUUID; import org.xtreemfs.common.uuids.UnknownUUIDException; import org.xtreemfs.common.xloc.ReplicationFlags; import org.xtreemfs.foundation.json.JSONException; import org.xtreemfs.foundation.json.JSONParser; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno; import org.xtreemfs.foundation.util.OutputUtils; import org.xtreemfs.mrc.MRCConfig; import org.xtreemfs.mrc.MRCException; import org.xtreemfs.mrc.UserException; import org.xtreemfs.mrc.ac.FileAccessManager; import org.xtreemfs.mrc.database.AtomicDBUpdate; import org.xtreemfs.mrc.database.DatabaseException; import org.xtreemfs.mrc.database.DatabaseResultSet; import org.xtreemfs.mrc.database.StorageManager; import org.xtreemfs.mrc.database.VolumeInfo; import org.xtreemfs.mrc.database.VolumeManager; import org.xtreemfs.mrc.metadata.FileMetadata; import org.xtreemfs.mrc.metadata.ReplicationPolicy; import org.xtreemfs.mrc.metadata.StripingPolicy; import org.xtreemfs.mrc.metadata.XAttr; import org.xtreemfs.mrc.metadata.XLoc; import org.xtreemfs.mrc.metadata.XLocList; import org.xtreemfs.mrc.osdselection.OSDStatusManager; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.Service; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceDataMap; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceSet; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.KeyValuePair; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.VivaldiCoordinates; public class MRCHelper { public static class GlobalFileIdResolver { final String volumeId; final long localFileId; public GlobalFileIdResolver(String globalFileId) throws UserException { try { int i = globalFileId.indexOf(':'); volumeId = globalFileId.substring(0, i); localFileId = Long.parseLong(globalFileId.substring(i + 1)); } catch (Exception exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid global file ID: " + globalFileId + "; expected pattern: <volume_ID>:<local_file_ID>"); } } public String getVolumeId() { return volumeId; } public long getLocalFileId() { return localFileId; } } public static final String POLICY_ATTR_PREFIX = "policies"; public static final String VOL_ATTR_PREFIX = "volattr"; public static final String XTREEMFS_POLICY_ATTR_PREFIX = "xtreemfs." + POLICY_ATTR_PREFIX + "."; public enum SysAttrs { locations, file_id, object_type, url, owner, group, default_sp, ac_policy_id, rsel_policy, osel_policy, usable_osds, free_space, used_space, num_files, num_dirs, snapshots, snapshots_enabled, snapshot_time, acl, read_only, mark_replica_complete, set_repl_update_policy, default_rp } public enum FileType { nexists, dir, file } public static Service createDSVolumeInfo(VolumeInfo vol, OSDStatusManager osdMan, StorageManager sMan, String mrcUUID) { String free = String.valueOf(osdMan.getFreeSpace(vol.getId())); String volSize = null; try { volSize = String.valueOf(sMan.getVolumeInfo().getVolumeSize()); } catch (DatabaseException e) { Logging.logMessage(Logging.LEVEL_WARN, Category.storage, null, "could not retrieve volume size from database for volume '%s': %s", new Object[] { vol.getName(), e.toString() }); } ServiceDataMap.Builder dmap = buildServiceDataMap("mrc", mrcUUID, "free", free, "used", volSize); try { DatabaseResultSet<XAttr> attrIt = sMan.getXAttrs(1, StorageManager.SYSTEM_UID); while (attrIt.hasNext()) { XAttr attr = attrIt.next(); if (attr.getKey().startsWith("xtreemfs.volattr.")) { byte[] value = attr.getValue(); dmap.addData(KeyValuePair.newBuilder() .setKey("attr." + attr.getKey().substring("xtreemfs.volattr.".length())) .setValue(value == null ? null : new String(value))); } } attrIt.destroy(); } catch (DatabaseException e) { Logging.logMessage(Logging.LEVEL_ERROR, Category.storage, null, OutputUtils.stackTraceToString(e), new Object[0]); } Service sreg = Service.newBuilder().setType(ServiceType.SERVICE_TYPE_VOLUME).setUuid(vol.getId()).setVersion(0) .setName(vol.getName()).setData(dmap).setLastUpdatedS(0).build(); return sreg; } public static int updateFileTimes(long parentId, FileMetadata file, boolean setATime, boolean setCTime, boolean setMTime, StorageManager sMan, int currentTime, AtomicDBUpdate update) throws DatabaseException { if (parentId == -1) return -1; if (setATime) file.setAtime(currentTime); if (setCTime) file.setCtime(currentTime); if (setMTime) file.setMtime(currentTime); sMan.setMetadata(file, FileMetadata.FC_METADATA, update); return currentTime; } public static XLoc createReplica(StripingPolicy stripingPolicy, StorageManager sMan, OSDStatusManager osdMan, VolumeInfo volume, long parentDirId, String path, InetAddress clientAddress, VivaldiCoordinates clientCoordinates, XLocList currentXLoc, int replFlags) throws DatabaseException, UserException, MRCException { // if no striping policy is provided, try to retrieve it from the parent // directory if (stripingPolicy == null) stripingPolicy = sMan.getDefaultStripingPolicy(parentDirId); // if the parent directory has no default policy, take the one // associated with the volume if (stripingPolicy == null) stripingPolicy = sMan.getDefaultStripingPolicy(1); if (stripingPolicy == null) throw new UserException(POSIXErrno.POSIX_ERROR_EIO, "could not open file " + path + ": no default striping policy available"); // determine the set of OSDs to be assigned to the replica ServiceSet.Builder usableOSDs = osdMan.getUsableOSDs(volume.getId(), clientAddress, clientCoordinates, currentXLoc, stripingPolicy.getWidth()); if (usableOSDs == null || usableOSDs.getServicesCount() == 0) { Logging.logMessage(Logging.LEVEL_WARN, Category.all, (Object) null, "no suitable OSDs available for file %s", path); throw new UserException(POSIXErrno.POSIX_ERROR_EIO, "could not assign OSDs to file " + path + ": no feasible OSDs available"); } // determine the actual striping width; if not enough OSDs are // available, the width will be limited to the amount of available OSDs int width = Math.min(stripingPolicy.getWidth(), usableOSDs.getServicesCount()); // convert the set of OSDs to a string array of OSD UUIDs List<Service> osdServices = usableOSDs.getServicesList(); String[] osds = new String[width]; for (int i = 0; i < width; i++) osds[i] = osdServices.get(i).getUuid(); if (width != stripingPolicy.getWidth()) stripingPolicy = sMan.createStripingPolicy(stripingPolicy.getPattern(), stripingPolicy.getStripeSize(), width); return sMan.createXLoc(stripingPolicy, osds, replFlags); } /** * Checks whether the given replica (i.e. list of OSDs) can be added to the * given X-Locations list without compromising consistency. * * @param xLocList * the X-Locations list * @param newOSDs * the list of new OSDs to add * @return <tt>true</tt>, if adding the OSD list is possible, <tt>false</tt> * , otherwise */ public static boolean isAddable(XLocList xLocList, List<String> newOSDs) { if (xLocList != null) for (int i = 0; i < xLocList.getReplicaCount(); i++) { XLoc replica = xLocList.getReplica(i); for (int j = 0; j < replica.getOSDCount(); j++) for (String newOsd : newOSDs) if (replica.getOSD(j).equals(newOsd)) return false; } return true; } /** * Checks whether all service UUIDs from the list can be resolved, i.e. * refer to valid services. * * @param newOSDs * the list of OSDs * @return <tt>true</tt>, if all OSDs are resolvable, <tt>false</tt>, * otherwise */ public static boolean isResolvable(List<String> newOSDs) { if (newOSDs != null) for (String osd : newOSDs) { try { new ServiceUUID(osd).getAddress(); } catch (Exception exc) { return false; } } return true; } /** * Checks whether the given X-Locations list is consistent. It is regarded * as consistent if no OSD in any replica occurs more than once. * * @param xLocList * the X-Locations list to check for consistency * @return <tt>true</tt>, if the list is consistent, <tt>false</tt>, * otherwise */ public static boolean isConsistent(XLocList xLocList) { Set<String> tmp = new HashSet<String>(); if (xLocList != null) { for (int i = 0; i < xLocList.getReplicaCount(); i++) { XLoc replica = xLocList.getReplica(i); for (int j = 0; j < replica.getOSDCount(); j++) { String osd = replica.getOSD(j); if (!tmp.contains(osd)) tmp.add(osd); else return false; } } } return true; } public static String getSysAttrValue(MRCConfig config, StorageManager sMan, OSDStatusManager osdMan, FileAccessManager faMan, String path, FileMetadata file, String keyString) throws DatabaseException, UserException, JSONException { if (keyString.startsWith(POLICY_ATTR_PREFIX + ".")) return getPolicyValue(sMan, keyString); if (keyString.startsWith(VOL_ATTR_PREFIX + ".")) return getVolAttrValue(sMan, keyString); SysAttrs key = null; try { key = SysAttrs.valueOf(keyString); } catch (IllegalArgumentException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "unknown system attribute '" + keyString + "'"); } if (key != null) { switch (key) { case locations: if (file.isDirectory()) { return ""; } else { XLocList xLocList = file.getXLocList(); try { return xLocList == null ? "" : Converter.xLocListToJSON(xLocList, osdMan); } catch (UnknownUUIDException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EIO, "cannot retrieve '" + SysAttrs.locations.name() + "' attribute value: " + exc); } } case file_id: return sMan.getVolumeInfo().getId() + ":" + file.getId(); case object_type: String ref = sMan.getSoftlinkTarget(file.getId()); return ref != null ? "3" : file.isDirectory() ? "2" : "1"; case url: { InetSocketAddress addr = config.getDirectoryService(); final String hostname = (config.getHostName().length() > 0) ? config.getHostName() : addr.getAddress() .getCanonicalHostName(); return config.getURLScheme() + "://" + hostname + ":" + addr.getPort() + "/" + path; } case owner: return file.getOwnerId(); case group: return file.getOwningGroupId(); case default_sp: if (!file.isDirectory()) return ""; StripingPolicy sp = sMan.getDefaultStripingPolicy(file.getId()); if (sp == null) return ""; return Converter.stripingPolicyToJSONString(sp); case ac_policy_id: return file.getId() == 1 ? sMan.getVolumeInfo().getAcPolicyId() + "" : ""; case osel_policy: return file.getId() == 1 ? Converter.shortArrayToString(sMan.getVolumeInfo().getOsdPolicy()) : ""; case rsel_policy: return file.getId() == 1 ? Converter.shortArrayToString(sMan.getVolumeInfo().getReplicaPolicy()) : ""; case read_only: if (file.isDirectory()) return ""; return String.valueOf(file.isReadOnly()); case usable_osds: { // only return a value for the volume root if (file.getId() != 1) return ""; try { ServiceSet.Builder srvs = osdMan.getUsableOSDs(sMan.getVolumeInfo().getId()); Map<String, String> osds = new HashMap<String, String>(); for (Service srv : srvs.getServicesList()) { ServiceUUID uuid = new ServiceUUID(srv.getUuid()); osds.put(uuid.toString(), uuid.getAddressString()); } return JSONParser.writeJSON(osds); } catch (UnknownUUIDException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EIO, "cannot retrieve '" + SysAttrs.usable_osds.name() + "' attribute value: " + exc); } } case free_space: return file.getId() == 1 ? String.valueOf(osdMan.getFreeSpace(sMan.getVolumeInfo().getId())) : ""; case used_space: return file.getId() == 1 ? String.valueOf(sMan.getVolumeInfo().getVolumeSize()) : ""; case num_files: return file.getId() == 1 ? String.valueOf(sMan.getVolumeInfo().getNumFiles()) : ""; case num_dirs: return file.getId() == 1 ? String.valueOf(sMan.getVolumeInfo().getNumDirs()) : ""; case snapshots: { if (file.getId() != 1 || sMan.getVolumeInfo().isSnapVolume()) return ""; String[] snaps = sMan.getAllSnapshots(); Arrays.sort(snaps); List<String> snapshots = new ArrayList<String>(snaps.length); for (String snap : snaps) { if (snap.equals(".dump")) continue; snapshots.add(snap); } return JSONParser.writeJSON(snapshots); } case snapshots_enabled: return file.getId() == 1 && !sMan.getVolumeInfo().isSnapVolume() ? String.valueOf(sMan.getVolumeInfo() .isSnapshotsEnabled()) : ""; case snapshot_time: return file.getId() == 1 && sMan.getVolumeInfo().isSnapVolume() ? Long.toString(sMan.getVolumeInfo() .getCreationTime()) : ""; case acl: Map<String, Object> acl; try { acl = faMan.getACLEntries(sMan, file); } catch (MRCException e) { Logging.logError(Logging.LEVEL_ERROR, null, e); throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL); } if (acl != null) { Map<String, Object> map = new HashMap<String, Object>(); for (Entry<String, Object> entry : acl.entrySet()) map.put(entry.getKey(), "" + entry.getValue()); return JSONParser.writeJSON(map); } case default_rp: if (!file.isDirectory()) return ""; ReplicationPolicy rp = sMan.getDefaultReplicationPolicy(file.getId()); if (rp == null) return ""; return Converter.replicationPolicyToJSONString(rp); } } return ""; } public static void setSysAttrValue(StorageManager sMan, VolumeManager vMan, FileAccessManager faMan, long parentId, FileMetadata file, String keyString, String value, AtomicDBUpdate update) throws UserException, DatabaseException { // handle policy-specific values if (keyString.startsWith(POLICY_ATTR_PREFIX.toString() + ".")) { setPolicyValue(sMan, keyString, value, update); return; } SysAttrs key = null; try { key = SysAttrs.valueOf(keyString); } catch (IllegalArgumentException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "unknown system attribute '" + keyString + "'"); } switch (key) { case default_sp: if (!file.isDirectory()) throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "default striping policies can only be set on volumes and directories"); try { org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.StripingPolicy sp = null; sp = Converter.jsonStringToStripingPolicy(value); if (file.getId() == 1 && sp == null) throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "cannot remove the volume's default striping policy"); // check if striping + rw replication would be set ReplicationPolicy replPolicy = sMan.getDefaultReplicationPolicy(file.getId()); if (sp != null && sp.getWidth() > 1 && replPolicy != null && (replPolicy.getName().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE) || replPolicy .getName().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ))) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "Striping of rw-replicated Files is not supported yet."); } sMan.setDefaultStripingPolicy(file.getId(), sp, update); } catch (JSONException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default striping policy: " + value); } catch (ClassCastException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default striping policy: " + value); } catch (NullPointerException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default striping policy: " + value); } catch (IllegalArgumentException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default striping policy: " + value); } break; case osel_policy: if (file.getId() != 1) throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "OSD selection policies can only be set on volumes"); try { short[] newPol = Converter.stringToShortArray(value); sMan.getVolumeInfo().setOsdPolicy(newPol, update); } catch (NumberFormatException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid OSD selection policy: " + value); } break; case rsel_policy: if (file.getId() != 1) throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "replica selection policies can only be set and configured on volumes"); try { short[] newPol = Converter.stringToShortArray(value); sMan.getVolumeInfo().setReplicaPolicy(newPol, update); } catch (NumberFormatException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid replica selection policy: " + value); } break; case read_only: // TODO: unify w/ 'set_repl_update_policy' if (file.isDirectory()) throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "only files can be made read-only"); boolean readOnly = Boolean.valueOf(value); if (!readOnly && file.getXLocList() != null && file.getXLocList().getReplicaCount() > 1) throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "read-only flag cannot be removed from files with multiple replicas"); // set the update policy string in the X-Locations list to 'read // only replication' and mark the first replica as 'full' if (file.getXLocList() != null) { XLocList xLoc = file.getXLocList(); XLoc[] replicas = new XLoc[xLoc.getReplicaCount()]; for (int i = 0; i < replicas.length; i++) replicas[i] = xLoc.getReplica(i); replicas[0].setReplicationFlags(ReplicationFlags.setFullReplica(ReplicationFlags .setReplicaIsComplete(replicas[0].getReplicationFlags()))); XLocList newXLoc = sMan.createXLocList(replicas, readOnly ? ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY : ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE, xLoc.getVersion() + 1); file.setXLocList(newXLoc); sMan.setMetadata(file, FileMetadata.RC_METADATA, update); } // set the read-only flag file.setReadOnly(readOnly); sMan.setMetadata(file, FileMetadata.RC_METADATA, update); break; case snapshots: if (!file.isDirectory()) throw new UserException(POSIXErrno.POSIX_ERROR_ENOTDIR, "snapshots of single files are not allowed so far"); // value format: "c|cr|d| name" // TODO: restrict to admin users int index = value.indexOf(" "); String command = null; String name = null; try { command = value.substring(0, index); name = value.substring(index + 1); } catch (Exception exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "malformed snapshot configuration"); } // create snapshot if (command.charAt(0) == 'c') vMan.createSnapshot(sMan.getVolumeInfo().getId(), name, parentId, file, command.equals("cr")); // delete snapshot else if (command.equals("d")) vMan.deleteSnapshot(sMan.getVolumeInfo().getId(), file, name); else throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid snapshot command: " + value); break; case snapshots_enabled: if (file.getId() != 1) throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "snapshots can only be enabled or disabled on volumes"); boolean enable = Boolean.parseBoolean(value); sMan.getVolumeInfo().setAllowSnaps(enable, update); break; case mark_replica_complete: if (file.isDirectory()) throw new UserException(POSIXErrno.POSIX_ERROR_EISDIR, "file required"); XLocList xlocs = file.getXLocList(); XLoc[] xlocArray = new XLoc[xlocs.getReplicaCount()]; Iterator<XLoc> it = xlocs.iterator(); for (int i = 0; it.hasNext(); i++) { XLoc xloc = it.next(); if (value.equals(xloc.getOSD(0))) xloc.setReplicationFlags(ReplicationFlags.setReplicaIsComplete(xloc.getReplicationFlags())); xlocArray[i] = xloc; } XLocList newXLocList = sMan.createXLocList(xlocArray, xlocs.getReplUpdatePolicy(), xlocs.getVersion()); file.setXLocList(newXLocList); sMan.setMetadata(file, FileMetadata.RC_METADATA, update); break; case acl: // parse the modification command index = value.indexOf(" "); try { command = value.substring(0, index); String params = value.substring(index + 1); // modify an ACL entry if (command.equals("m")) { int index2 = params.lastIndexOf(':'); String entity = params.substring(0, index2); String rights = params.substring(index2 + 1); Map<String, Object> entries = new HashMap<String, Object>(); entries.put(entity, rights); faMan.updateACLEntries(sMan, file, parentId, entries, update); } // remove an ACL entry else if (command.equals("x")) { List<Object> entries = new ArrayList<Object>(1); entries.add(params); faMan.removeACLEntries(sMan, file, parentId, entries, update); } else throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid ACL modification command: " + command); } catch (MRCException e) { Logging.logError(Logging.LEVEL_ERROR, null, e); throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL); } catch (Exception exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "malformed ACL modification request"); } break; case set_repl_update_policy: if (file.isDirectory()) throw new UserException(POSIXErrno.POSIX_ERROR_EISDIR, "file required"); xlocs = file.getXLocList(); xlocArray = new XLoc[xlocs.getReplicaCount()]; it = xlocs.iterator(); for (int i = 0; it.hasNext(); i++) xlocArray[i] = it.next(); String replUpdatePolicy = xlocs.getReplUpdatePolicy(); // Check allowed policies. if (!ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ.equals(value) && !ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE.equals(value) && !ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE.equals(value) && !ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(value)) throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "Invalid replica update policy: " + value); // WaRa was renamed to WaR1. if (ReplicaUpdatePolicies.REPL_UPDATE_PC_WARA.equals(value)) { throw new UserException( POSIXErrno.POSIX_ERROR_EINVAL, "Do no longer use the policy WaRa. Instead you're probably looking for the WaR1 policy (write all replicas, read from one)." + value); } if (ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(replUpdatePolicy) && xlocArray.length > 1) throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "changing replica update policies of read-only-replicated files is not allowed"); if (ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE.equals(value)) { // if there are more than one replica, report an error if (xlocs.getReplicaCount() > 1) throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "number of replicas has to be reduced to 1 before replica update policy can be set to " + ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE + " (current replica count = " + xlocs.getReplicaCount() + ")"); } // Do not allow to switch between read-only and read/write replication // as there are currently no mechanisms in place to guarantee that the replicas are synchronized. if ((ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(replUpdatePolicy) && (ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ.equals(value) || ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE.equals(value))) || (ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(value) && (ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ.equals(replUpdatePolicy) || ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE.equals(replUpdatePolicy)))) { throw new UserException( POSIXErrno.POSIX_ERROR_EINVAL, "Currently, it is not possible to change from a read-only to a read/write replication policy or vise versa."); } // Update replication policy in new xloc list. newXLocList = sMan.createXLocList(xlocArray, value, xlocs.getVersion() + 1); // mark the first replica in the list as 'complete' (only relevant // for read-only replication) if (ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(value)) { newXLocList.getReplica(0).setReplicationFlags( ReplicationFlags.setFullReplica(ReplicationFlags.setReplicaIsComplete(newXLocList.getReplica(0) .getReplicationFlags()))); file.setReadOnly(true); } // check if striping + rw replication would be set StripingPolicy stripingPolicy = file.getXLocList().getReplica(0).getStripingPolicy(); if (stripingPolicy.getWidth() > 1 && (value.equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE) || value .equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ))) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "RW-replication of striped files is not supported yet."); } // Remove read only state of file if readonly policy gets reverted. if (ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(replUpdatePolicy) && ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE.equals(value)) { file.setReadOnly(false); } // Write back updated file data. file.setXLocList(newXLocList); sMan.setMetadata(file, FileMetadata.RC_METADATA, update); break; case default_rp: if (!file.isDirectory()) throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "default replication policies can only be set on volumes and directories"); try { ReplicationPolicy rp = null; rp = Converter.jsonStringToReplicationPolicy(value); if (rp.getFactor() == 1 && !ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE.equals(rp.getName())) { throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "a default replication policy requires a replication factor >= 2"); } // check if rw replication + striping would be set if (sMan.getDefaultStripingPolicy(file.getId()).getWidth() > 1 && (rp.getName().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE) || rp.getName().equals( ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ))) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "RW-replication of striped files is not supported yet."); } sMan.setDefaultReplicationPolicy(file.getId(), rp, update); } catch (JSONException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default replication policy: " + value); } catch (ClassCastException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default replication policy: " + value); } catch (NullPointerException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default replication policy: " + value); } catch (IllegalArgumentException exc) { throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default replication policy: " + value); } break; default: throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "system attribute '" + keyString + "' is immutable"); } } public static List<String> getSpecialAttrNames(StorageManager sMan, String namePrefix) throws DatabaseException { final String prefix = "xtreemfs." + namePrefix; final List<String> result = new LinkedList<String>(); DatabaseResultSet<XAttr> it = sMan.getXAttrs(1, StorageManager.SYSTEM_UID); while (it.hasNext()) { XAttr attr = it.next(); if (attr.getKey().startsWith(prefix)) result.add(attr.getKey()); } it.destroy(); return result; } public static ServiceDataMap.Builder buildServiceDataMap(String... kvPairs) { assert (kvPairs.length % 2 == 0); ServiceDataMap.Builder builder = ServiceDataMap.newBuilder(); for (int i = 0; i < kvPairs.length; i += 2) { KeyValuePair.Builder kvp = KeyValuePair.newBuilder(); kvp.setKey(kvPairs[i]); kvp.setValue(kvPairs[i + 1]); builder.addData(kvp); } return builder; } private static String getPolicyValue(StorageManager sMan, String keyString) throws DatabaseException { byte[] value = sMan.getXAttr(1, StorageManager.SYSTEM_UID, "xtreemfs." + keyString); return value == null ? null : new String(value); } private static String getVolAttrValue(StorageManager sMan, String keyString) throws DatabaseException { byte[] value = sMan.getXAttr(1, StorageManager.SYSTEM_UID, "xtreemfs." + keyString); return value == null ? null : new String(value); } private static void setPolicyValue(StorageManager sMan, String keyString, String value, AtomicDBUpdate update) throws DatabaseException, UserException { // remove "policies." String checkString = keyString.substring(POLICY_ATTR_PREFIX.length()+1); int index = checkString.indexOf('.'); if (index <= 0) { // remove trailing "." if (keyString.startsWith(".")) { keyString = keyString.substring(1); } throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "'"+keyString+"="+value+" :' " + "XtreemFS no longer supports global policy attributes. " + "It is necessary to specify a policy e.g., '1000."+keyString+"="+value+"'"); } // set the value in the database byte[] bytes = value.getBytes(); sMan.setXAttr(1, StorageManager.SYSTEM_UID, "xtreemfs." + keyString, bytes == null || bytes.length == 0 ? null : bytes, update); } }
package org.jboss.jgettext; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; /** * Message implementation * * @author Steve Ebersole */ public class Message { private String domain; private String msgctxt; private String msgid; private String msgidPlural; private String msgstr; private List<String> msgstrPlural = new ArrayList<String>(); private String prevMsgctx; private String prevMsgid; private String prevMsgidPlural; private Collection<String> comments = new ArrayList<String>(); private Collection<String> extractedComments = new ArrayList<String>(); private SortedSet<Occurence> occurences = new TreeSet<Occurence>( new OccurenceComparator() ); private Collection<String> formats = new ArrayList<String>(); private boolean fuzzy; private boolean obsolete; private Boolean allowWrap; public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getMsgctxt() { return msgctxt; } public void setMsgctxt(String msgctxt) { this.msgctxt = msgctxt; } public String getPrevMsgctx() { return prevMsgctx; } public void setPrevMsgctx(String prevMsgctx) { this.prevMsgctx = prevMsgctx; } public String getMsgid() { return msgid; } public void setMsgid(String msgid) { this.msgid = msgid; } public String getPrevMsgid() { return prevMsgid; } public void setPrevMsgid(String prevMsgid) { this.prevMsgid = prevMsgid; } public String getMsgidPlural() { return msgidPlural; } public void setMsgidPlural(String msgidPlural) { this.msgidPlural = msgidPlural; } public String getPrevMsgidPlural() { return prevMsgidPlural; } public void setPrevMsgidPlural(String prevMsgidPlural) { this.prevMsgidPlural = prevMsgidPlural; } public String getMsgstr() { return msgstr; } public void setMsgstr(String msgstr) { this.msgstr = msgstr; } public void addMsgstrPlural(String msgstr, int position) { if ( msgstrPlural == null ) { msgstrPlural = new ArrayList<String>(); } msgstrPlural.add( position, msgstr ); } public void markFuzzy() { this.fuzzy = true; } public boolean isFuzzy() { return fuzzy; } public void markObsolete() { this.obsolete = true; } public boolean isObsolete() { return obsolete; } public Boolean getAllowWrap() { return allowWrap; } public void setAllowWrap(Boolean allowWrap) { this.allowWrap = allowWrap; } public void addComment(String comment) { comments.add( comment ); } public void addExtractedComment(String comment) { extractedComments.add( comment ); } public Occurence addOccurence(String file, int line) { Occurence o = new Occurence( file, line ); addOccurence( o ); return o; } public void addOccurence(Occurence occurence) { occurences.add( occurence ); } public void addFormat(String format) { formats.add( format ); } public boolean isHeader() { return msgctxt == null && "".equals( msgid ); } public List<String> getMsgstrPlural() { return msgstrPlural; } public SortedSet<Occurence> getOccurences() { return occurences; } public Collection<String> getComments() { return comments; } public Collection<String> getExtractedComments() { return extractedComments; } public Collection<String> getFormats() { return formats; } /** * Returns a string representation of the Message, in a format * suitable for inclusion in debug messages. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Message(msgctxt \"").append(msgctxt). append("\", msgid \"").append(getMsgid()). append("\", msgstr \"").append(getMsgstr()); if(!getComments().isEmpty()) sb.append("\", transComments \"").append(getComments()); if(!getExtractedComments().isEmpty()) sb.append("\", extComments \"").append(getExtractedComments()); if(!getFormats().isEmpty()) sb.append("\", flags \"").append(getFormats()); if(!getOccurences().isEmpty()) sb.append("\", references \"").append(getOccurences()); // TODO should include fuzzy, obsolete, plurals, domain, prevMsg sb.append("\")"); return sb.toString(); } private static class OccurenceComparator implements Comparator<Occurence> { public int compare(Occurence o1, Occurence o2) { int sub = o1.getFileName().compareTo( o2.getFileName() ); if ( sub != 0 ) { return sub; } if ( o1.getLine() == o2.getLine() ) { return 0; } else if ( o1.getLine() < o2.getLine() ) { return -1; } else { return 1; } } } }
package org.jmock.core; import java.util.List; import junit.framework.AssertionFailedError; import org.jmock.core.constraint.IsAnything; import org.jmock.core.matcher.ArgumentsMatcher; import org.jmock.core.matcher.MethodNameMatcher; import org.jmock.core.matcher.NoArgumentsMatcher; import org.jmock.core.stub.CustomStub; import org.jmock.core.stub.ReturnStub; public abstract class AbstractDynamicMock implements DynamicMock { private InvocationDispatcher invocationDispatcher; private Class mockedType; private String name; private DynamicMockError failure = null; public AbstractDynamicMock( Class mockedType, String name ) { this(mockedType, name, new LIFOInvocationDispatcher()); } public AbstractDynamicMock( Class mockedType, String name, InvocationDispatcher invocationDispatcher ) { this.mockedType = mockedType; this.name = name; this.invocationDispatcher = invocationDispatcher; setupDefaultBehaviour(); } public Class getMockedType() { return mockedType; } protected Object mockInvocation( Invocation invocation ) throws Throwable { if (failure != null) throw failure; try { return invocationDispatcher.dispatch(invocation); } catch (AssertionFailedError failure) { this.failure = new DynamicMockError(this, invocation, invocationDispatcher, failure.getMessage()); this.failure.fillInStackTrace(); throw this.failure; } } public void verify() { forgetFailure(); try { invocationDispatcher.verify(); } catch (AssertionFailedError ex) { throw new AssertionFailedError( "mock object " + name + ": " + ex.getMessage()); } } public String toString() { return this.name; } public String getMockName() { return this.name; } public void setDefaultStub( Stub newDefaultStub ) { invocationDispatcher.setDefaultStub(newDefaultStub); } public void addInvokable( Invokable invokable ) { invocationDispatcher.add(invokable); } public void reset() { //TODO write tests for this invocationDispatcher.clear(); forgetFailure(); setupDefaultBehaviour(); } public static String mockNameFromClass( Class c ) { return "mock" + Formatting.classShortName(c); } private void setupDefaultBehaviour() { addInvokable(hiddenInvocationMocker("toString", NoArgumentsMatcher.INSTANCE, new ReturnStub(name))); addInvokable(hiddenInvocationMocker("equals", new ArgumentsMatcher(new Constraint[]{new IsAnything()}), new IsSameAsProxyStub())); addInvokable(hiddenInvocationMocker("hashCode", NoArgumentsMatcher.INSTANCE, new HashCodeStub())); } private void forgetFailure() { failure = null; } private static final InvocationMocker.Describer NO_DESCRIPTION = new InvocationMocker.Describer() { public boolean hasDescription() { return false; } public void describeTo( StringBuffer buffer, List matchers, Stub stub, String name ) { } }; private InvocationMocker hiddenInvocationMocker( String methodName, InvocationMatcher arguments, Stub stub ) { InvocationMocker invocationMocker = new InvocationMocker(NO_DESCRIPTION); invocationMocker.addMatcher(new MethodNameMatcher(methodName)); invocationMocker.addMatcher(arguments); invocationMocker.setStub(stub); return invocationMocker; } private class IsSameAsProxyStub extends CustomStub { private IsSameAsProxyStub() { super("returns whether equal to proxy"); } public Object invoke( Invocation invocation ) throws Throwable { return new Boolean(invocation.parameterValues.get(0) == proxy()); } } private class HashCodeStub extends CustomStub { private HashCodeStub() { super("returns hashCode for proxy"); } public Object invoke( Invocation invocation ) throws Throwable { return new Integer(AbstractDynamicMock.this.hashCode()); } } }
package org.jtrim.image; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Transparency; import java.awt.image.*; import org.jtrim.cache.MemoryHeavyObject; import org.jtrim.collections.ArraysEx; /** * Defines an image which was retrieved from an external source. Apart from the * image itself, the {@code ImageData} contains the meta data information of * the image and an exception associated with the image retrieval. * <P> * Although it is possible to mutate the properties of an {@code ImageData} * instance, the intended use of {@code ImageData} is to use it as an * effectively immutable object. That is, its properties should not be modified * (e.g.: The pixels of the {@code BufferedImage} should not be modified). * <P> * This class implements the {@link MemoryHeavyObject} interface and * approximates the size of an {@code ImageData} instance by the approximate * size of the underlying {@code BufferedImage}. * <P> * Note that this class also provides several useful static helper methods, * to create {@code BufferedImage} instance better handled by the Java and * methods to calculate the approximate size of a {@code BufferedImage}. * * <h3>Thread safety</h3> * Methods of this class can be safely accessed by multiple threads. Although * individual properties are not immutable, they should treated so. Users of * this class can assume that the properties of {@code ImageData} are not * modified and can be safely accessed by multiple concurrent threads as well. * * <h4>Synchronization transparency</h4> * The methods of this class are <I>synchronization transparent</I>. * * @author Kelemen Attila */ public final class ImageData implements MemoryHeavyObject { private static final double BITS_IN_BYTE = 8.0; private static final double ALLOWED_SIZE_DIFFERENCE_FOR_GROWTH = 0.75; private final BufferedImage image; private final long approxSize; private final ImageMetaData metaData; private final ImageReceiveException exception; private static double getStoredPixelSizeInBits(ColorModel cm, SampleModel sm) { int dataType = sm.getDataType(); int dataTypeSize = DataBuffer.getDataTypeSize(dataType); if (sm instanceof ComponentSampleModel) { sm.getNumDataElements(); return sm.getNumDataElements() * dataTypeSize; } else if (sm instanceof SinglePixelPackedSampleModel) { return dataTypeSize; } else if (sm instanceof MultiPixelPackedSampleModel) { int pixelSize = cm.getPixelSize(); // pixelSize must not be larger than dataTypeSize // according to the documentation. int pixelPerData = dataTypeSize / pixelSize; return (double)dataTypeSize / (double)pixelPerData; } else { // Though it may not be true, this is out best guess. return cm.getPixelSize(); } } private static double getStoredPixelSizeInBits(ColorModel cm) { try { return getStoredPixelSizeInBits(cm, cm.createCompatibleSampleModel(1, 1)); } catch (UnsupportedOperationException ex) { return cm.getPixelSize(); } } /** * Returns the average size in bytes of a single pixel in the given * {@code ColorModel}. The returned value might not be an integer because * some {@code ColorModel} encodes pixels in a fraction of a byte (or just * not in a multiple of eight bits). * <P> * Note that for some obscure {@code ColorModel} this method may return an * incorrect value but tries to return a good approximate in this cases as * well. * * @param cm the {@code ColorModel} of which pixel size in bytes is to be * returned. This argument cannot be {@code null}. * @return the average size in bytes of a single pixel in the given * {@code ColorModel}. This method always return a value greater than or * equal to zero. A return value is zero is usually only theoretical since * there is no such practical color model. * * @throws NullPointerException thrown if the specified color model is * {@code null} */ public static double getStoredPixelSize(ColorModel cm) { return getStoredPixelSizeInBits(cm) / 8.0; } /** * Returns the approximate memory in bytes the specified * {@code BufferedImage} retains. The size is approximate by the size of all * the pixels in the {@code BufferedImage}. * * @param image the {@code BufferedImage} whose size is to be approximated. * This argument can be {@code null}, in which case zero is returned. * @return the approximate memory in bytes the specified * {@code BufferedImage} retains. This method always returns a value * greater than or equal to zero. */ public static long getApproxSize(BufferedImage image) { if (image != null) { double bitsPerPixel = getStoredPixelSizeInBits( image.getColorModel(), image.getSampleModel()); long pixelCount = (long)image.getWidth() * (long)image.getHeight(); return (long)((1.0 / BITS_IN_BYTE) * bitsPerPixel * (double)pixelCount); } else { return 0; } } /** * Returns the type of the {@code BufferedImage} which most closely * approximates the specified {@code ColorModel}. * <P> * The returned integer can be used as an image type for a * {@code BufferedImage}. That is, this integer can be specified for the * {@code BufferedImage} at construction time and will be returned by the * {@code BufferedImage.getType()} method. Note however, that this method * may return {@code BufferedImage.TYPE_CUSTOM} for which the constructor * of {@code BufferedImage} will throw an exception but any other return * value will be accepted by {@code BufferedImage}. * * @param colorModel the {@code ColorModel} which is to be approximated with * a {@code BufferedImage} image type. This argument cannot be * {@code null}. * @return the {@code BufferedImage} image type which most closely * approximates the specified {@code ColorModel}. */ public static int getCompatibleBufferType(ColorModel colorModel) { WritableRaster raster = colorModel.createCompatibleWritableRaster(1, 1); BufferedImage image = new BufferedImage(colorModel, raster, false, null); return image.getType(); } /** * Creates a returns a new {@code BufferedImage} which is compatible with * the specified {@code BufferedImage} with the given dimensions. The * returned {@code BufferedImage} will have the same {@code ColorModel} as * the one specified. The returned {@code BufferedImage} is compatible in * the sense that its pixels can be copied using simple array copies and * does not require any other transformations. * * @param image the image to which a compatible {@code BufferedImage} is to * be returned. This argument can be {@code null}, in which case * {@code null} is returned. * @param width the width of the returned {@code BufferedImage}. This * argument must be greater than zero. * @param height the height of the returned {@code BufferedImage}. This * argument must be greater than zero. * @return a new {@code BufferedImage} which is compatible with the * specified {@code BufferedImage} with the given dimensions. This method * returns {@code null} only if the specified image was also {@code null}. */ public static BufferedImage createCompatibleBuffer(BufferedImage image, int width, int height) { if (image == null) return null; ColorModel cm = image.getColorModel(); WritableRaster wr; wr = cm.createCompatibleWritableRaster(width, height); return new BufferedImage(cm, wr, cm.isAlphaPremultiplied(), null); } /** * Returns a new {@code BufferedImage} which is the copy of the specified * image. That is, returns an image which when modified does not affect the * specified image. The returned and the specified {@code BufferedImage} * have the same color model, dimensions and are otherwise compatible. * * @param image the image which is to be copied. This argument can be * {@code null}, in which case {@code null} is returned. * @return a new {@code BufferedImage} which is the copy of the specified * image. This method returns {@code null} only if the specified image was * also {@code null}. */ public static BufferedImage cloneImage(BufferedImage image) { if (image == null) { return null; } BufferedImage result; result = createCompatibleBuffer(image, image.getWidth(), image.getHeight()); Graphics2D g = result.createGraphics(); g.drawImage(image, null, 0, 0); g.dispose(); return result; } /** * Returns a new image which have the same pixels as the specified image but * is likely to be accelerated by the currently present graphics card (if * there is any). * <P> * This methods differs from {@link #createAcceleratedBuffer(BufferedImage) createAcceleratedBuffer} * by always returning a new image which is independent from the argument. * That is, modifications of the returned image have no effect on the * image passed as an argument. * * @param image the base image to which an image is to be returned which * is more likely to be accelerated by the currently present graphics * card. If this method cannot do better, it will return a copy of this * image. This argument can be {@code null}, in which case {@code null} * is returned. * @return the image having the same pixels as the specified image but * is likely to be accelerated by the currently present graphics card. * This method returns {@code null} only if the specified image was also * {@code null}. Modifying the returned image has no effect on the image * passed in the argument. * * @see #createAcceleratedBuffer(BufferedImage) * @see #createNewOptimizedBuffer(BufferedImage) */ public static BufferedImage createNewAcceleratedBuffer(BufferedImage image) { BufferedImage result = createAcceleratedBuffer(image); return result == image ? cloneImage(image) : result; } /** * Returns an image which have the same pixels as the specified image but * is likely to be accelerated by the currently present graphics card (if * there is any). * <P> * This method uses several undefined heuristics to determine the required * image type and may also return an image which requires somewhat more * memory to be stored. * <P> * This method may return the same {@code BufferedImage} image as the one * specified in the argument. If this is undesired, use the * {@link #createNewAcceleratedBuffer(BufferedImage) createNewAcceleratedBuffer} * method instead. * * @param image the base image to which an image is to be returned which * is more likely to be accelerated by the currently present graphics * card. This method may return this image if it cannot do better. This * argument can be {@code null}, in which case {@code null} is returned. * @return the image having the same pixels as the specified image but * is likely to be accelerated by the currently present graphics card. * This method returns {@code null} only if the specified image was also * {@code null}. * * @see #createNewAcceleratedBuffer(BufferedImage) */ public static BufferedImage createAcceleratedBuffer(BufferedImage image) { if (image == null) return null; int width = image.getWidth(); int height = image.getHeight(); GraphicsConfiguration config = GraphicsEnvironment .getLocalGraphicsEnvironment() .getDefaultScreenDevice() .getDefaultConfiguration(); BufferedImage result; try { ColorModel srcColorModel = image.getColorModel(); if (srcColorModel.getTransparency() != Transparency.OPAQUE && !config.isTranslucencyCapable()) { return image; } // Note: For some reason it seems that translucent images // are faster. // Maybe because this way the renderer don't have to // ignore the alpha byte? int transparency = java.awt.Transparency.TRANSLUCENT; ColorModel destColorModel = config.getColorModel(transparency); if (srcColorModel.equals(destColorModel)) { return image; } double srcSize = getStoredPixelSizeInBits(srcColorModel, image.getSampleModel()); double destSize = getStoredPixelSizeInBits(destColorModel); // We should allow a limit growth in size because // TYPE_3BYTE_BGR images are *very* slow. // So this check allows TYPE_3BYTE_BGR to be converted // to TYPE_INT_RGB or TYPE_INT_ARGB or TYPE_INT_ARGB_PRE. if (srcSize < ALLOWED_SIZE_DIFFERENCE_FOR_GROWTH * destSize) { return image; } int srcMaxSize = ArraysEx.findMax(srcColorModel.getComponentSize()); int destMaxSize = ArraysEx.findMax(destColorModel.getComponentSize()); // In this case we would surely lose some precision // so to be safe we will return the same image. if (destMaxSize < srcMaxSize) { return image; } // The most likely cause is that the source image is a grayscale // image and the destination is an RGB buffer. In this case // we want to avoid converting the image. if (srcColorModel.getNumColorComponents() != destColorModel.getNumColorComponents()) { return image; } result = config.createCompatibleImage(width, height, transparency); } catch (IllegalArgumentException|NullPointerException ex) { // This exception may only happen if getComponentSize() returns // an empty array or createCompatibleImage cannot create an image // with the given transparency. These cases should not happen // in my oppinion. // NullPointerException: // May happen if getComponentSize() returns null but I do not // think that a well behaved implementation of ColorModel can // return null. result = null; } if (result == null) { return image; } Graphics2D g = result.createGraphics(); g.drawImage(image, null, 0, 0); g.dispose(); return result; } /** * Returns a new image which have the same pixels as the specified image but * is likely to be more efficiently handled than the one specified. * <P> * This methods differs from {@link #createOptimizedBuffer(BufferedImage) createOptimizedBuffer} * by always returning a new image which is independent from the argument. * That is, modifications of the returned image have no effect on the * image passed as an argument. * * @param image the base image to which an image is to be returned which * is likely to be more efficiently handled in general. If this method * cannot do better, it will return a copy of this image. This argument * can be {@code null}, in which case {@code null} is returned. * @return the image which have the same pixels as the specified image but * is likely to be more efficiently handled than the one specified. * This method returns {@code null} only if the specified image was also * {@code null}. * * @see #createNewAcceleratedBuffer(BufferedImage) * @see #createOptimizedBuffer(BufferedImage) */ public static BufferedImage createNewOptimizedBuffer(BufferedImage image) { BufferedImage result = createOptimizedBuffer(image); return result == image ? cloneImage(image) : result; } /** * Returns an image which have the same pixels as the specified image but * is likely to be more efficiently handled than the one specified. * <P> * Unlike {@link #createAcceleratedBuffer(BufferedImage) createAcceleratedBuffer}, * this method does not consider graphic card acceleration. That is, this is * a general purpose method and only employs heuristics for converting the * image which are very likely to increase performance in general or at * least does not downgrade performance. This method may also return an * image which requires somewhat more memory to be stored. * <P> * This method may return the same {@code BufferedImage} image as the one * specified in the argument. If this is undesired, use the * {@link #createNewOptimizedBuffer(BufferedImage) createNewOptimizedBuffer} * method instead. * * @param image the base image to which an image is to be returned which * is likely to be more efficiently handled in general. This method may * return this image if it cannot do better. This argument can be * {@code null}, in which case {@code null} is returned. * @return the image which have the same pixels as the specified image but * is likely to be more efficiently handled than the one specified. * This method returns {@code null} only if the specified image was also * {@code null}. * * @see #createAcceleratedBuffer(BufferedImage) * @see #createNewOptimizedBuffer(BufferedImage) */ public static BufferedImage createOptimizedBuffer( BufferedImage image) { if (image == null) return null; int width = image.getWidth(); int height = image.getHeight(); int newType; switch (image.getType()) { case BufferedImage.TYPE_4BYTE_ABGR_PRE: { newType = BufferedImage.TYPE_INT_ARGB_PRE; break; } case BufferedImage.TYPE_4BYTE_ABGR: { newType = BufferedImage.TYPE_INT_ARGB; break; } case BufferedImage.TYPE_3BYTE_BGR: { newType = BufferedImage.TYPE_INT_RGB; break; } default: newType = image.getType(); break; } if (image.getType() != newType) { BufferedImage result; result = new BufferedImage(width, height, newType); Graphics2D g = result.createGraphics(); g.drawImage(image, null, 0, 0); g.dispose(); return result; } else { return image; } } public ImageData(BufferedImage image, ImageMetaData metaData, ImageReceiveException exception) { if (image != null && metaData != null) { if (image.getWidth() != metaData.getWidth() || image.getHeight() != metaData.getHeight()) { throw new IllegalArgumentException("The dimensions specified " + "by the meta data and the image are inconsistent."); } } this.image = image; this.approxSize = getApproxSize(image); this.metaData = metaData; this.exception = exception; } /** * Returns the exception describing the failure of the image retrieval. This * method returns the same exception as specified at construction time. * <P> * Note that even in case of failure, a partial or incomplete image might * still be available. * * @return the exception describing the failure of the image retrieval. This * method may return {@code null}, if {@code null} was specified at * construction time. */ public ImageReceiveException getException() { return exception; } /** * Returns the retrieved image. The image might be incomplete or partial * if not completely available or in case of some failure. * * @return the retrieved image. This method may return {@code null}, if * {@code null} was specified at construction time. */ public BufferedImage getImage() { return image; } /** * Returns the meta data information of the image. In case both the meta * data and the image are specified, they define the same dimensions. That * is, both {@code getMetaData().getWidth() == getImage().getWidth()} and * {@code getMetaData().getHeight() == getImage().getHeight()} holds. * * @return the meta data information of the image. This method may return * {@code null}, if {@code null} was specified at construction time. */ public ImageMetaData getMetaData() { return metaData; } /** * Returns the width of the image or -1 if it is unknown. * <P> * If the meta data is available, the width is retrieved from the meta data, * if not and the image is available, it is retrieved from the image. * * @return the width of the image or -1 if it is unknown */ public int getWidth() { return metaData != null ? metaData.getWidth() : (image != null ? image.getWidth() : -1); } /** * Returns the height of the image or -1 if it is unknown. * <P> * If the meta data is available, the height is retrieved from the meta * data, if not and the image is available, it is retrieved from the image. * * @return the height of the image or -1 if it is unknown */ public int getHeight() { return metaData != null ? metaData.getHeight() : (image != null ? image.getHeight() : -1); } /** * Returns the approximate size of memory in bytes, the image of this * {@code ImageData} retains. That is, this method returns the same value as * the {@code ImageData.getApproxSize(getImage())} invocation. * * @return the approximate size of memory in bytes, the image of this * {@code ImageData} retains. This method always returns a value greater * than or equal to zero. */ @Override public long getApproxMemorySize() { return approxSize; } }
package com.tpcstld.twozerogame; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.View; import java.util.ArrayList; public class MainView extends View { //Intenal Constants static final int BASE_ANIMATION_TIME = 100000000; private static final float MERGING_ACCELERATION = (float) -0.5; private static final float INITIAL_VELOCITY = (1 - MERGING_ACCELERATION) / 4; public final int numCellTypes = 21; private final BitmapDrawable[] bitmapCell = new BitmapDrawable[numCellTypes]; public final MainGame game; //Internal variables private final Paint paint = new Paint(); public boolean hasSaveState = false; public boolean continueButtonEnabled = false; public int startingX; public int startingY; public int endingX; public int endingY; //Icon variables public int sYIcons; public int sXNewGame; public int sXUndo; public int iconSize; //Misc boolean refreshLastTime = true; //Timing private long lastFPSTime = System.nanoTime(); //Text private float titleTextSize; private float bodyTextSize; private float headerTextSize; private float instructionsTextSize; private float gameOverTextSize; //Layout variables private int cellSize = 0; private float textSize = 0; private float cellTextSize = 0; private int gridWidth = 0; private int textPaddingSize; private int iconPaddingSize; //Assets private Drawable backgroundRectangle; private Drawable lightUpRectangle; private Drawable fadeRectangle; private Bitmap background = null; private BitmapDrawable loseGameOverlay; private BitmapDrawable winGameContinueOverlay; private BitmapDrawable winGameFinalOverlay; //Text variables private int sYAll; private int titleStartYAll; private int bodyStartYAll; private int eYAll; private int titleWidthHighScore; private int titleWidthScore; public MainView(Context context) { super(context); Resources resources = context.getResources(); //Loading resources game = new MainGame(context, this); try { //Getting assets backgroundRectangle = resources.getDrawable(R.drawable.background_rectangle); lightUpRectangle = resources.getDrawable(R.drawable.light_up_rectangle); fadeRectangle = resources.getDrawable(R.drawable.fade_rectangle); this.setBackgroundColor(resources.getColor(R.color.background)); Typeface font = Typeface.createFromAsset(resources.getAssets(), "ClearSans-Bold.ttf"); paint.setTypeface(font); paint.setAntiAlias(true); } catch (Exception e) { System.out.println("Error getting assets?"); } setOnTouchListener(new InputListener(this)); game.newGame(); } private static int log2(int n) { if (n <= 0) throw new IllegalArgumentException(); return 31 - Integer.numberOfLeadingZeros(n); } @Override public void onDraw(Canvas canvas) { //Reset the transparency of the screen canvas.drawBitmap(background, 0, 0, paint); drawScoreText(canvas); if (!game.isActive() && !game.aGrid.isAnimationActive()) { drawNewGameButton(canvas, true); } drawCells(canvas); if (!game.isActive()) { drawEndGameState(canvas); } if (!game.canContinue()) { drawEndlessText(canvas); } //Refresh the screen if there is still an animation running if (game.aGrid.isAnimationActive()) { invalidate(startingX, startingY, endingX, endingY); tick(); //Refresh one last time on game end. } else if (!game.isActive() && refreshLastTime) { invalidate(); refreshLastTime = false; } } @Override protected void onSizeChanged(int width, int height, int oldw, int oldh) { super.onSizeChanged(width, height, oldw, oldh); getLayout(width, height); createBitmapCells(); createBackgroundBitmap(width, height); createOverlays(); } private void drawDrawable(Canvas canvas, Drawable draw, int startingX, int startingY, int endingX, int endingY) { draw.setBounds(startingX, startingY, endingX, endingY); draw.draw(canvas); } private void drawCellText(Canvas canvas, int value) { int textShiftY = centerText(); if (value >= 8) { paint.setColor(getResources().getColor(R.color.text_white)); } else { paint.setColor(getResources().getColor(R.color.text_black)); } canvas.drawText("" + value, cellSize / 2, cellSize / 2 - textShiftY, paint); } private void drawScoreText(Canvas canvas) { //Drawing the score text: Ver 2 paint.setTextSize(bodyTextSize); paint.setTextAlign(Paint.Align.CENTER); int bodyWidthHighScore = (int) (paint.measureText("" + game.highScore)); int bodyWidthScore = (int) (paint.measureText("" + game.score)); int textWidthHighScore = Math.max(titleWidthHighScore, bodyWidthHighScore) + textPaddingSize * 2; int textWidthScore = Math.max(titleWidthScore, bodyWidthScore) + textPaddingSize * 2; int textMiddleHighScore = textWidthHighScore / 2; int textMiddleScore = textWidthScore / 2; int eXHighScore = endingX; int sXHighScore = eXHighScore - textWidthHighScore; int eXScore = sXHighScore - textPaddingSize; int sXScore = eXScore - textWidthScore; //Outputting high-scores box backgroundRectangle.setBounds(sXHighScore, sYAll, eXHighScore, eYAll); backgroundRectangle.draw(canvas); paint.setTextSize(titleTextSize); paint.setColor(getResources().getColor(R.color.text_brown)); canvas.drawText(getResources().getString(R.string.high_score), sXHighScore + textMiddleHighScore, titleStartYAll, paint); paint.setTextSize(bodyTextSize); paint.setColor(getResources().getColor(R.color.text_white)); canvas.drawText(String.valueOf(game.highScore), sXHighScore + textMiddleHighScore, bodyStartYAll, paint); //Outputting scores box backgroundRectangle.setBounds(sXScore, sYAll, eXScore, eYAll); backgroundRectangle.draw(canvas); paint.setTextSize(titleTextSize); paint.setColor(getResources().getColor(R.color.text_brown)); canvas.drawText(getResources().getString(R.string.score), sXScore + textMiddleScore, titleStartYAll, paint); paint.setTextSize(bodyTextSize); paint.setColor(getResources().getColor(R.color.text_white)); canvas.drawText(String.valueOf(game.score), sXScore + textMiddleScore, bodyStartYAll, paint); } private void drawNewGameButton(Canvas canvas, boolean lightUp) { if (lightUp) { drawDrawable(canvas, lightUpRectangle, sXNewGame, sYIcons, sXNewGame + iconSize, sYIcons + iconSize ); } else { drawDrawable(canvas, backgroundRectangle, sXNewGame, sYIcons, sXNewGame + iconSize, sYIcons + iconSize ); } drawDrawable(canvas, getResources().getDrawable(R.drawable.ic_action_refresh), sXNewGame + iconPaddingSize, sYIcons + iconPaddingSize, sXNewGame + iconSize - iconPaddingSize, sYIcons + iconSize - iconPaddingSize ); } private void drawUndoButton(Canvas canvas) { drawDrawable(canvas, backgroundRectangle, sXUndo, sYIcons, sXUndo + iconSize, sYIcons + iconSize ); drawDrawable(canvas, getResources().getDrawable(R.drawable.ic_action_undo), sXUndo + iconPaddingSize, sYIcons + iconPaddingSize, sXUndo + iconSize - iconPaddingSize, sYIcons + iconSize - iconPaddingSize ); } private void drawHeader(Canvas canvas) { //Drawing the header paint.setTextSize(headerTextSize); paint.setColor(getResources().getColor(R.color.text_black)); paint.setTextAlign(Paint.Align.LEFT); int textShiftY = centerText() * 2; int headerStartY = sYAll - textShiftY; canvas.drawText(getResources().getString(R.string.header), startingX, headerStartY, paint); } private void drawInstructions(Canvas canvas) { //Drawing the instructions paint.setTextSize(instructionsTextSize); paint.setTextAlign(Paint.Align.LEFT); int textShiftY = centerText() * 2; canvas.drawText(getResources().getString(R.string.instructions), startingX, endingY - textShiftY + textPaddingSize, paint); } private void drawBackground(Canvas canvas) { drawDrawable(canvas, backgroundRectangle, startingX, startingY, endingX, endingY); } //Renders the set of 16 background squares. private void drawBackgroundGrid(Canvas canvas) { Resources resources = getResources(); Drawable backgroundCell = resources.getDrawable(R.drawable.cell_rectangle); // Outputting the game grid for (int xx = 0; xx < game.numSquaresX; xx++) { for (int yy = 0; yy < game.numSquaresY; yy++) { int sX = startingX + gridWidth + (cellSize + gridWidth) * xx; int eX = sX + cellSize; int sY = startingY + gridWidth + (cellSize + gridWidth) * yy; int eY = sY + cellSize; drawDrawable(canvas, backgroundCell, sX, sY, eX, eY); } } } private void drawCells(Canvas canvas) { paint.setTextSize(textSize); paint.setTextAlign(Paint.Align.CENTER); // Outputting the individual cells for (int xx = 0; xx < game.numSquaresX; xx++) { for (int yy = 0; yy < game.numSquaresY; yy++) { int sX = startingX + gridWidth + (cellSize + gridWidth) * xx; int eX = sX + cellSize; int sY = startingY + gridWidth + (cellSize + gridWidth) * yy; int eY = sY + cellSize; Tile currentTile = game.grid.getCellContent(xx, yy); if (currentTile != null) { //Get and represent the value of the tile int value = currentTile.getValue(); int index = log2(value); //Check for any active animations ArrayList<AnimationCell> aArray = game.aGrid.getAnimationCell(xx, yy); boolean animated = false; for (int i = aArray.size() - 1; i >= 0; i AnimationCell aCell = aArray.get(i); //If this animation is not active, skip it if (aCell.getAnimationType() == MainGame.SPAWN_ANIMATION) { animated = true; } if (!aCell.isActive()) { continue; } if (aCell.getAnimationType() == MainGame.SPAWN_ANIMATION) { // Spawning animation double percentDone = aCell.getPercentageDone(); float textScaleSize = (float) (percentDone); paint.setTextSize(textSize * textScaleSize); float cellScaleSize = cellSize / 2 * (1 - textScaleSize); bitmapCell[index].setBounds((int) (sX + cellScaleSize), (int) (sY + cellScaleSize), (int) (eX - cellScaleSize), (int) (eY - cellScaleSize)); bitmapCell[index].draw(canvas); } else if (aCell.getAnimationType() == MainGame.MERGE_ANIMATION) { // Merging Animation double percentDone = aCell.getPercentageDone(); float textScaleSize = (float) (1 + INITIAL_VELOCITY * percentDone + MERGING_ACCELERATION * percentDone * percentDone / 2); paint.setTextSize(textSize * textScaleSize); float cellScaleSize = cellSize / 2 * (1 - textScaleSize); bitmapCell[index].setBounds((int) (sX + cellScaleSize), (int) (sY + cellScaleSize), (int) (eX - cellScaleSize), (int) (eY - cellScaleSize)); bitmapCell[index].draw(canvas); } else if (aCell.getAnimationType() == MainGame.MOVE_ANIMATION) { // Moving animation double percentDone = aCell.getPercentageDone(); int tempIndex = index; if (aArray.size() >= 2) { tempIndex = tempIndex - 1; } int previousX = aCell.extras[0]; int previousY = aCell.extras[1]; int currentX = currentTile.getX(); int currentY = currentTile.getY(); int dX = (int) ((currentX - previousX) * (cellSize + gridWidth) * (percentDone - 1) * 1.0); int dY = (int) ((currentY - previousY) * (cellSize + gridWidth) * (percentDone - 1) * 1.0); bitmapCell[tempIndex].setBounds(sX + dX, sY + dY, eX + dX, eY + dY); bitmapCell[tempIndex].draw(canvas); } animated = true; } //No active animations? Just draw the cell if (!animated) { bitmapCell[index].setBounds(sX, sY, eX, eY); bitmapCell[index].draw(canvas); } } } } } private void drawEndGameState(Canvas canvas) { double alphaChange = 1; continueButtonEnabled = false; for (AnimationCell animation : game.aGrid.globalAnimation) { if (animation.getAnimationType() == MainGame.FADE_GLOBAL_ANIMATION) { alphaChange = animation.getPercentageDone(); } } BitmapDrawable displayOverlay = null; if (game.gameWon()) { if (game.canContinue()) { continueButtonEnabled = true; displayOverlay = winGameContinueOverlay; } else { displayOverlay = winGameFinalOverlay; } } else if (game.gameLost()) { displayOverlay = loseGameOverlay; } if (displayOverlay != null) { displayOverlay.setBounds(startingX, startingY, endingX, endingY); displayOverlay.setAlpha((int) (255 * alphaChange)); displayOverlay.draw(canvas); } } private void drawEndlessText(Canvas canvas) { paint.setTextAlign(Paint.Align.LEFT); paint.setTextSize(bodyTextSize); paint.setColor(getResources().getColor(R.color.text_black)); canvas.drawText(getResources().getString(R.string.endless), startingX, sYIcons - centerText() * 2, paint); } private void createEndGameStates(Canvas canvas, boolean win, boolean showButton) { int width = endingX - startingX; int length = endingY - startingY; int middleX = width / 2; int middleY = length / 2; if (win) { lightUpRectangle.setAlpha(127); drawDrawable(canvas, lightUpRectangle, 0, 0, width, length); lightUpRectangle.setAlpha(255); paint.setColor(getResources().getColor(R.color.text_white)); paint.setAlpha(255); paint.setTextSize(gameOverTextSize); paint.setTextAlign(Paint.Align.CENTER); int textBottom = middleY - centerText(); canvas.drawText(getResources().getString(R.string.you_win), middleX, textBottom, paint); paint.setTextSize(bodyTextSize); String text = showButton ? getResources().getString(R.string.go_on) : getResources().getString(R.string.for_now); canvas.drawText(text, middleX, textBottom + textPaddingSize * 2 - centerText() * 2, paint); } else { fadeRectangle.setAlpha(127); drawDrawable(canvas, fadeRectangle, 0, 0, width, length); fadeRectangle.setAlpha(255); paint.setColor(getResources().getColor(R.color.text_black)); paint.setAlpha(255); paint.setTextSize(gameOverTextSize); paint.setTextAlign(Paint.Align.CENTER); canvas.drawText(getResources().getString(R.string.game_over), middleX, middleY - centerText(), paint); } } private void createBackgroundBitmap(int width, int height) { background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(background); drawHeader(canvas); drawNewGameButton(canvas, false); drawUndoButton(canvas); drawBackground(canvas); drawBackgroundGrid(canvas); drawInstructions(canvas); } private void createBitmapCells() { Resources resources = getResources(); int[] cellRectangleIds = getCellRectangleIds(); paint.setTextAlign(Paint.Align.CENTER); for (int xx = 1; xx < bitmapCell.length; xx++) { int value = (int) Math.pow(2, xx); paint.setTextSize(cellTextSize); float tempTextSize = cellTextSize * cellSize * 0.9f / Math.max(cellSize * 0.9f, paint.measureText(String.valueOf(value))); paint.setTextSize(tempTextSize); Bitmap bitmap = Bitmap.createBitmap(cellSize, cellSize, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawDrawable(canvas, resources.getDrawable(cellRectangleIds[xx]), 0, 0, cellSize, cellSize); drawCellText(canvas, value); bitmapCell[xx] = new BitmapDrawable(resources, bitmap); } } private int[] getCellRectangleIds() { int[] cellRectangleIds = new int[numCellTypes]; cellRectangleIds[0] = R.drawable.cell_rectangle; cellRectangleIds[1] = R.drawable.cell_rectangle_2; cellRectangleIds[2] = R.drawable.cell_rectangle_4; cellRectangleIds[3] = R.drawable.cell_rectangle_8; cellRectangleIds[4] = R.drawable.cell_rectangle_16; cellRectangleIds[5] = R.drawable.cell_rectangle_32; cellRectangleIds[6] = R.drawable.cell_rectangle_64; cellRectangleIds[7] = R.drawable.cell_rectangle_128; cellRectangleIds[8] = R.drawable.cell_rectangle_256; cellRectangleIds[9] = R.drawable.cell_rectangle_512; cellRectangleIds[10] = R.drawable.cell_rectangle_1024; cellRectangleIds[11] = R.drawable.cell_rectangle_2048; for (int xx = 12; xx < cellRectangleIds.length; xx++) { cellRectangleIds[xx] = R.drawable.cell_rectangle_4096; } return cellRectangleIds; } private void createOverlays() { Resources resources = getResources(); //Initalize overlays Bitmap bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); createEndGameStates(canvas, true, true); winGameContinueOverlay = new BitmapDrawable(resources, bitmap); bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); createEndGameStates(canvas, true, false); winGameFinalOverlay = new BitmapDrawable(resources, bitmap); bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); createEndGameStates(canvas, false, false); loseGameOverlay = new BitmapDrawable(resources, bitmap); } private void tick() { long currentTime = System.nanoTime(); game.aGrid.tickAll(currentTime - lastFPSTime); lastFPSTime = currentTime; } public void resyncTime() { lastFPSTime = System.nanoTime(); } private void getLayout(int width, int height) { cellSize = Math.min(width / (game.numSquaresX + 1), height / (game.numSquaresY + 3)); gridWidth = cellSize / 7; int screenMiddleX = width / 2; int screenMiddleY = height / 2; int boardMiddleY = screenMiddleY + cellSize / 2; iconSize = cellSize / 2; paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(cellSize); textSize = cellSize * cellSize / Math.max(cellSize, paint.measureText("0000")); cellTextSize = textSize; titleTextSize = textSize / 3; bodyTextSize = (int) (textSize / 1.5); instructionsTextSize = (int) (textSize / 1.5); headerTextSize = textSize * 2; gameOverTextSize = textSize * 2; textPaddingSize = (int) (textSize / 3); iconPaddingSize = (int) (textSize / 5); //Grid Dimensions double halfNumSquaresX = game.numSquaresX / 2d; double halfNumSquaresY = game.numSquaresY / 2d; startingX = (int) (screenMiddleX - (cellSize + gridWidth) * halfNumSquaresX - gridWidth / 2); endingX = (int) (screenMiddleX + (cellSize + gridWidth) * halfNumSquaresX + gridWidth / 2); startingY = (int) (boardMiddleY - (cellSize + gridWidth) * halfNumSquaresY - gridWidth / 2); endingY = (int) (boardMiddleY + (cellSize + gridWidth) * halfNumSquaresY + gridWidth / 2); paint.setTextSize(titleTextSize); int textShiftYAll = centerText(); //static variables sYAll = (int) (startingY - cellSize * 1.5); titleStartYAll = (int) (sYAll + textPaddingSize + titleTextSize / 2 - textShiftYAll); bodyStartYAll = (int) (titleStartYAll + textPaddingSize + titleTextSize / 2 + bodyTextSize / 2); titleWidthHighScore = (int) (paint.measureText(getResources().getString(R.string.high_score))); titleWidthScore = (int) (paint.measureText(getResources().getString(R.string.score))); paint.setTextSize(bodyTextSize); textShiftYAll = centerText(); eYAll = (int) (bodyStartYAll + textShiftYAll + bodyTextSize / 2 + textPaddingSize); sYIcons = (startingY + eYAll) / 2 - iconSize / 2; sXNewGame = (endingX - iconSize); sXUndo = sXNewGame - iconSize * 3 / 2 - iconPaddingSize; resyncTime(); } private int centerText() { return (int) ((paint.descent() + paint.ascent()) / 2); } }
package com.exedio.cope.pattern; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import com.exedio.cope.AttributeValue; import com.exedio.cope.Item; import com.exedio.cope.LengthViolationException; import com.exedio.cope.NotNullViolationException; import com.exedio.cope.ObjectAttribute; import com.exedio.cope.Pattern; import com.exedio.cope.ReadOnlyViolationException; import com.exedio.cope.UniqueViolationException; public final class Vector extends Pattern { private final ObjectAttribute[] sources; public Vector(final ObjectAttribute[] sources) { this.sources = sources; } public Vector(final ObjectAttribute template, final int length) { this(template2Sources(template, length)); } private static final ObjectAttribute[] template2Sources(final ObjectAttribute template, final int length) { final ObjectAttribute[] result = new ObjectAttribute[length]; for(int i = 0; i<length; i++) result[i] = template.copyAsTemplate(); return result; } public void initialize() { final String name = getName(); for(int i = 0; i<sources.length; i++) { final ObjectAttribute source = sources[i]; if(!source.isInitialized()) initialize(source, name+(i+1/*TODO: make this '1' customizable*/)); } } public final List getSources() { return Collections.unmodifiableList(Arrays.asList(sources)); } public List get(final Item item) { final ArrayList result = new ArrayList(sources.length); for(int i = 0; i<sources.length; i++) { final Object value = item.get(sources[i]); if(value!=null) result.add(value); } return result; } public void set(final Item item, final Collection values) throws UniqueViolationException, NotNullViolationException, LengthViolationException, ReadOnlyViolationException, ClassCastException { int i = 0; final AttributeValue[] attributeValues = new AttributeValue[sources.length]; for(Iterator it = values.iterator(); it.hasNext(); i++) attributeValues[i] = new AttributeValue(sources[i], it.next()); for(; i<sources.length; i++) attributeValues[i] = new AttributeValue(sources[i], null); item.set(attributeValues); } // TODO equal // TODO notEqual // TODO contains }
package com.sun.star.lib.uno.protocols.urp; import com.sun.star.lib.uno.environments.remote.ThreadId; import com.sun.star.lib.uno.typedesc.TypeDescription; import com.sun.star.uno.Any; import com.sun.star.uno.Enum; import com.sun.star.uno.IBridge; import com.sun.star.uno.IFieldDescription; import com.sun.star.uno.Type; import com.sun.star.uno.TypeClass; import com.sun.star.uno.XInterface; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; final class Unmarshal { public Unmarshal(IBridge bridge, int cacheSize) { this.bridge = bridge; objectIdCache = new String[cacheSize]; threadIdCache = new ThreadId[cacheSize]; typeCache = new TypeDescription[cacheSize]; reset(new byte[0]); } public int read8Bit() { try { return input.readUnsignedByte(); } catch (IOException e) { throw new RuntimeException(e.toString()); } } public int read16Bit() { try { return input.readUnsignedShort(); } catch (IOException e) { throw new RuntimeException(e.toString()); } } public String readObjectId() { String id = readStringValue(); int index = read16Bit(); if (index == 0xFFFF) { if (id.length() == 0) { id = null; } } else { if (id.length() == 0) { id = objectIdCache[index]; } else { objectIdCache[index] = id; } } return id; } public Object readInterface(Type type) { String id = readObjectId(); return id == null ? null : bridge.mapInterfaceFrom(id, type); } public ThreadId readThreadId() { int len = readCompressedNumber(); byte[] data = null; ThreadId id = null; if (len != 0) { data = new byte[len]; readBytes(data); id = new ThreadId(data); } int index = read16Bit(); if (index != 0xFFFF) { if (len == 0) { id = threadIdCache[index]; } else { threadIdCache[index] = id; } } return id; } public TypeDescription readType() { int b = read8Bit(); TypeClass typeClass = TypeClass.fromInt(b & 0x7F); if (TypeDescription.isTypeClassSimple(typeClass)) { return TypeDescription.getTypeDescription(typeClass); } else { int index = read16Bit(); TypeDescription type = null; if ((b & 0x80) != 0) { try { type = TypeDescription.getTypeDescription( readStringValue()); } catch (ClassNotFoundException e) { throw new RuntimeException(e.toString()); } } if (index != 0xFFFF) { if ((b & 0x80) == 0) { type = typeCache[index]; } else { typeCache[index] = type; } } return type; } } public Object readValue(TypeDescription type) { switch (type.getTypeClass().getValue()) { case TypeClass.VOID_value: return null; case TypeClass.BOOLEAN_value: return readBooleanValue(); case TypeClass.BYTE_value: return readByteValue(); case TypeClass.SHORT_value: case TypeClass.UNSIGNED_SHORT_value: return readShortValue(); case TypeClass.LONG_value: case TypeClass.UNSIGNED_LONG_value: return readLongValue(); case TypeClass.HYPER_value: case TypeClass.UNSIGNED_HYPER_value: return readHyperValue(); case TypeClass.FLOAT_value: return readFloatValue(); case TypeClass.DOUBLE_value: return readDoubleValue(); case TypeClass.CHAR_value: return readCharValue(); case TypeClass.STRING_value: return readStringValue(); case TypeClass.TYPE_value: return readTypeValue(); case TypeClass.ANY_value: return readAnyValue(); case TypeClass.SEQUENCE_value: return readSequenceValue(type); case TypeClass.ENUM_value: return readEnumValue(type); case TypeClass.STRUCT_value: return readStructValue(type); case TypeClass.EXCEPTION_value: return readExceptionValue(type); case TypeClass.INTERFACE_value: return readInterfaceValue(type); default: throw new IllegalArgumentException("Bad type descriptor " + type); } } public boolean hasMore() { try { return input.available() > 0; } catch (IOException e) { throw new RuntimeException(e.toString()); } } public void reset(byte[] data) { input = new DataInputStream(new ByteArrayInputStream(data)); } private Boolean readBooleanValue() { try { return input.readBoolean() ? Boolean.TRUE : Boolean.FALSE; } catch (IOException e) { throw new RuntimeException(e.toString()); } } private Byte readByteValue() { try { return new Byte(input.readByte()); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private Short readShortValue() { try { return new Short(input.readShort()); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private Integer readLongValue() { try { return new Integer(input.readInt()); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private Long readHyperValue() { try { return new Long(input.readLong()); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private Float readFloatValue() { try { return new Float(input.readFloat()); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private Double readDoubleValue() { try { return new Double(input.readDouble()); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private Character readCharValue() { try { return new Character(input.readChar()); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private String readStringValue() { int len = readCompressedNumber(); byte[] data = new byte[len]; readBytes(data); try { return new String(data, "UTF8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString()); } } private Type readTypeValue() { return new Type(readType()); } private Object readAnyValue() { TypeDescription type = readType(); switch (type.getTypeClass().getValue()) { case TypeClass.VOID_value: return Any.VOID; case TypeClass.BOOLEAN_value: return readBooleanValue(); case TypeClass.BYTE_value: return readByteValue(); case TypeClass.SHORT_value: return readShortValue(); case TypeClass.UNSIGNED_SHORT_value: return new Any(Type.UNSIGNED_SHORT, readShortValue()); case TypeClass.LONG_value: return readLongValue(); case TypeClass.UNSIGNED_LONG_value: return new Any(Type.UNSIGNED_LONG, readLongValue()); case TypeClass.HYPER_value: return readHyperValue(); case TypeClass.UNSIGNED_HYPER_value: return new Any(Type.UNSIGNED_HYPER, readHyperValue()); case TypeClass.FLOAT_value: return readFloatValue(); case TypeClass.DOUBLE_value: return readDoubleValue(); case TypeClass.CHAR_value: return readCharValue(); case TypeClass.STRING_value: return readStringValue(); case TypeClass.TYPE_value: return readTypeValue(); case TypeClass.SEQUENCE_value: { Object value = readSequenceValue(type); TypeDescription ctype = (TypeDescription) type.getComponentType(); while (ctype.getTypeClass() == TypeClass.SEQUENCE) { ctype = (TypeDescription) ctype.getComponentType(); } switch (ctype.getTypeClass().getValue()) { case TypeClass.UNSIGNED_SHORT_value: case TypeClass.UNSIGNED_LONG_value: case TypeClass.UNSIGNED_HYPER_value: return new Any(new Type(type), value); case TypeClass.STRUCT_value: if (ctype.hasTypeArguments()) { return new Any(new Type(type), value); } default: return value; } } case TypeClass.ENUM_value: return readEnumValue(type); case TypeClass.STRUCT_value: { Object value = readStructValue(type); return type.hasTypeArguments() ? new Any(new Type(type), value) : value; } case TypeClass.EXCEPTION_value: return readExceptionValue(type); case TypeClass.INTERFACE_value: { Object value = readInterfaceValue(type); return type.getZClass() == XInterface.class ? value : new Any(new Type(type), value); } default: throw new RuntimeException( "Reading ANY with bad type " + type.getTypeClass()); } } private Object readSequenceValue(TypeDescription type) { int len = readCompressedNumber(); TypeDescription ctype = (TypeDescription) type.getComponentType(); if (ctype.getTypeClass() == TypeClass.BYTE) { byte[] data = new byte[len]; readBytes(data); return data; } else { Object value = Array.newInstance( ctype.getTypeClass() == TypeClass.ANY ? Object.class : ctype.getZClass(), len); for (int i = 0; i < len; ++i) { Array.set(value, i, readValue(ctype)); } return value; } } private Enum readEnumValue(TypeDescription type) { try { return (Enum) type.getZClass().getMethod( "fromInt", new Class[] { int.class }). invoke(null, new Object[] { readLongValue() }); } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } catch (InvocationTargetException e) { throw new RuntimeException(e.toString()); } catch (NoSuchMethodException e) { throw new RuntimeException(e.toString()); } } private Object readStructValue(TypeDescription type) { Object value; try { value = type.getZClass().newInstance(); } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } catch (InstantiationException e) { throw new RuntimeException(e.toString()); } readFields(type, value); return value; } private Exception readExceptionValue(TypeDescription type) { Exception value; try { value = (Exception) type.getZClass().getConstructor(new Class[] { String.class }). newInstance(new Object[] { readStringValue() }); } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } catch (InstantiationException e) { throw new RuntimeException(e.toString()); } catch (InvocationTargetException e) { throw new RuntimeException(e.toString()); } catch (NoSuchMethodException e) { throw new RuntimeException(e.toString()); } readFields(type, value); return value; } private Object readInterfaceValue(TypeDescription type) { return readInterface(new Type(type)); } private int readCompressedNumber() { int number = read8Bit(); try { return number < 0xFF ? number : input.readInt(); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private void readBytes(byte[] data) { try { input.readFully(data); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private void readFields(TypeDescription type, Object value) { IFieldDescription[] fields = type.getFieldDescriptions(); for (int i = 0; i < fields.length; ++i) { try { fields[i].getField().set( value, readValue( (TypeDescription) fields[i].getTypeDescription())); } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } } } private final IBridge bridge; private final String[] objectIdCache; private final ThreadId[] threadIdCache; private final TypeDescription[] typeCache; private DataInputStream input; }
package jvstm.cps; import jvstm.VBox; import jvstm.Transaction; import jvstm.TopLevelTransaction; import jvstm.util.Cons; import java.lang.reflect.Method; import java.util.Set; import java.util.Iterator; public class ConsistentTopLevelTransaction extends TopLevelTransaction implements ConsistentTransaction { private Cons newObjects = Cons.empty(); public ConsistentTopLevelTransaction(int number) { super(number); } public void registerNewObject(Object obj) { newObjects = newObjects.cons(obj); } public void registerNewObjects(Cons objs) { newObjects = objs.reverseInto(newObjects); } public Transaction makeNestedTransaction() { return new ConsistentNestedTransaction(this); } protected void tryCommit() { if (isWriteTransaction()) { checkConsistencyPredicates(); } super.tryCommit(); } protected void checkConsistencyPredicates() { // recheck all consistency predicates that may have changed Iterator<DependenceRecord> depRecIter = getDependenceRecordsToRecheck(); while (depRecIter.hasNext()) { recheckDependenceRecord(depRecIter.next()); } // check consistency predicates for all new objects for (Object obj : newObjects) { checkConsistencyPredicates(obj); } } protected void recheckDependenceRecord(DependenceRecord dependence) { Set<Depended> newDepended = checkOnePredicate(dependence.getDependent(), dependence.getPredicate()); Iterator<Depended> oldDeps = dependence.getDepended(); while (oldDeps.hasNext()) { Depended dep = oldDeps.next(); if (! newDepended.remove(dep)) { // if we didn't find the dep in the newDepended, it's // because it is no longer a depended, so remove the dependence oldDeps.remove(); dep.removeDependence(dependence); } } // the elements remaining in the set newDepended are new and // should be added to the dependence record // likewise, the dependence record should be added to those depended for (Depended dep : newDepended) { dep.addDependence(dependence); dependence.addDepended(dep); } } protected void checkConsistencyPredicates(Object obj) { for (Method predicate : ConsistencyPredicateSystem.getPredicatesFor(obj)) { Set<Depended> depended = checkOnePredicate(obj, predicate); if (! depended.isEmpty()) { DependenceRecord dependence = makeDependenceRecord(obj, predicate, depended); for (Depended dep : depended) { dep.addDependence(dependence); } } } } protected Set<Depended> checkOnePredicate(Object obj, Method predicate) { ConsistencyCheckTransaction tx = makeConsistencyCheckTransaction(obj); tx.start(); boolean finished = false; Class<? extends ConsistencyException> excClass = predicate.getAnnotation(ConsistencyPredicate.class).value(); try { if (! ((Boolean)predicate.invoke(obj)).booleanValue()) { ConsistencyException exc = excClass.newInstance(); exc.init(obj, predicate); throw exc; } Transaction.commit(); finished = true; return tx.getDepended(); } catch (Throwable t) { ConsistencyException exc; try { exc = excClass.newInstance(); } catch (Throwable t2) { throw new Error(t2); } exc.init(obj, predicate); exc.initCause(t); throw exc; } finally { if (! finished) { Transaction.abort(); } } } protected ConsistencyCheckTransaction makeConsistencyCheckTransaction(Object obj) { return new DefaultConsistencyCheckTransaction(this); } protected DependenceRecord makeDependenceRecord(Object dependent, Method predicate, Set<Depended> depended) { return new DefaultDependenceRecord(dependent, predicate, depended); } protected Iterator<DependenceRecord> getDependenceRecordsToRecheck() { Cons<Iterator<DependenceRecord>> iteratorsList = Cons.empty(); for (VBox box : boxesWritten.keySet()) { Depended dep = DependedVBoxes.getDependedForBoxIfExists(box); if (dep != null) { iteratorsList = iteratorsList.cons(dep.getDependenceRecords().iterator()); } } return new ChainedIterator<DependenceRecord>(iteratorsList.iterator()); } }
package org.traccar.protocol; import static org.junit.Assert.assertNull; import org.junit.Test; import static org.traccar.helper.DecoderVerifier.verify; public class Gps103ProtocolDecoderTest extends ProtocolDecoderTest { @Test public void testDecode() throws Exception { Gps103ProtocolDecoder decoder = new Gps103ProtocolDecoder(null); // Log on request assertNull(decoder.decode(null, null, null, "##,imei:359586015829802,A")); // Heartbeat package assertNull(decoder.decode(null, null, null, "359586015829802")); // No GPS signal assertNull(decoder.decode(null, null, null, "imei:359586015829802,tracker,000000000,13554900601,L,;")); verify(decoder.decode(null, null, null, "imei:869039001186913,tracker,1308282156,0,F,215630.000,A,5602.11015,N,9246.30767,E,1.4,,175.9,")); verify(decoder.decode(null, null, null, "imei:359710040656622,tracker,13/02/27 23:40,,F,125952.000,A,3450.9430,S,13828.6753,E,0.00,0")); verify(decoder.decode(null, null, null, "imei:359710040565419,tracker,13/05/25 14:23,,F,062209.000,A,0626.0411,N,10149.3904,E,0.00,0")); verify(decoder.decode(null, null, null, "imei:353451047570260,tracker,1302110948,,F,144807.000,A,0805.6615,S,07859.9763,W,0.00,,")); verify(decoder.decode(null, null, null, "imei:359587016817564,tracker,1301251602,,F,080251.000,A,3223.5832,N,11058.9449,W,0.03,")); verify(decoder.decode(null, null, null, "imei:359587016817564,tracker,1301251602,,F,080251.000,A,3223.5832,N,11058.9449,W,,")); verify(decoder.decode(null, null, null, "imei:012497000208821,tracker,1301080525,,F,212511.000,A,2228.5279,S,06855.6328,W,18.62,268.98,")); verify(decoder.decode(null, null, null, "imei:012497000208821,tracker,1301072224,,F,142411.077,A,2227.0739,S,06855.2912,,0,0,")); verify(decoder.decode(null, null, null, "imei:012497000431811,tracker,1210260609,,F,220925.000,A,0845.5500,N,07024.7673,W,0.00,,")); verify(decoder.decode(null, null, null, "imei:100000000000000,help me,1004171910,,F,010203.000,A,0102.0003,N,00102.0003,E,1.02,")); verify(decoder.decode(null, null, null, "imei:353451040164707,tracker,1105182344,+36304665439,F,214418.000,A,4804.2222,N,01916.7593,E,0.37,")); verify(decoder.decode(null, null, null, "imei:353451042861763,tracker,1106132241,,F,144114.000,A,2301.9052,S,04909.3676,W,0.13,")); verify(decoder.decode(null, null, null, "imei:359587010124900,tracker,0809231929,13554900601,F,112909.397,A,2234.4669,N,11354.3287,E,0.11,321.53,")); verify(decoder.decode(null, null, null, "imei:353451049926460,tracker,1208042043,123456 99008026,F,124336.000,A,3509.8668,N,03322.7636,E,0.00,,")); // SOS alarm verify(decoder.decode(null, null, null, "imei:359586015829802,help me,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); // Low battery alarm verify(decoder.decode(null, null, null, "imei:359586015829802,low battery,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); // Geo-fence alarm verify(decoder.decode(null, null, null, "imei:359586015829802,stockade,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); // Move alarm verify(decoder.decode(null, null, null, "imei:359586015829802,move,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); // Over speed alarm verify(decoder.decode(null, null, null, "imei:359586015829802,speed,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); verify(decoder.decode(null, null, null, "imei:863070010423167,tracker,1211051840,,F,104000.000,A,2220.6483,N,11407.6377,,0,0,")); verify(decoder.decode(null, null, null, "imei:863070010423167,tracker,1211051951,63360926,F,115123.000,A,2220.6322,N,11407.5313,E,0.00,,")); verify(decoder.decode(null, null, null, "imei:863070010423167,tracker,1211060621,,F,062152.000,A,2220.6914,N,11407.5506,E,15.85,347.84,")); verify(decoder.decode(null, null, null, "imei:863070012698733,tracker,1303092334,,F,193427.000,A,5139.0369,N,03907.2791,E,0.00,,")); verify(decoder.decode(null, null, null, "imei:869039001186913,tracker,130925065533,0,F,065533.000,A,5604.11015,N,9232.12238,E,0.0,,329.0,")); verify(decoder.decode(null, null, null, "imei:359710041641581,acc alarm,1402231159,,F,065907.000,A,2456.2591,N,06708.8335,E,7.53,76.10,,1,0,0.03%,,")); verify(decoder.decode(null, null, null, "imei:359710041641581,acc alarm,1402231159,,F,065907.000,A,2456.2591,N,06708.8335,E,7.53,76.10,,1,0,0.03%,,")); verify(decoder.decode(null, null, null, "imei:313009071131684,tracker,1403211928,,F,112817.000,A,0610.1133,N,00116.5840,E,0.00,,,0,0,0.0,0.0,")); verify(decoder.decode(null, null, null, "imei:866989771979791,tracker,140527055653,,F,215653.00,A,5050.33113,N,00336.98783,E,0.066,0")); verify(decoder.decode(null, null, null, "imei:353552045375005,tracker,150401165832,61.0,F,31.0,A,1050.73696,N,10636.49489,E,8.0,,22.0,")); verify(decoder.decode(null, null, null, "imei:353552045403597,tracker,150420050648,53.0,F,0.0,A,N,5306.64155,E,00700.77848,0.0,,1.0,;")); verify(decoder.decode(null, null, null, "imei:353552045403597,tracker,150420051153,53.0,F,0.0,A,5306.64155,N,00700.77848,E,0.0,,1.0,;")); verify(decoder.decode(null, null, null, "imei:359710047424644,tracker,150506224036,,F,154037.000,A,0335.2785,N,09841.1543,E,3.03,337.54,,0,0,45.16%,,;")); } }
package hudson.model; import com.gargoylesoftware.htmlunit.ElementNotFoundException; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.security.GlobalMatrixAuthorizationStrategy; import hudson.tasks.Shell; import hudson.scm.NullSCM; import hudson.Launcher; import hudson.FilePath; import hudson.Functions; import hudson.Util; import hudson.tasks.ArtifactArchiver; import hudson.util.StreamTaskListener; import hudson.util.OneShotEvent; import java.io.IOException; import org.jvnet.hudson.test.HudsonTestCase; import org.jvnet.hudson.test.Bug; import org.jvnet.hudson.test.recipes.PresetData; import org.jvnet.hudson.test.recipes.PresetData.DataSet; import java.io.File; import java.util.concurrent.Future; import org.apache.commons.io.FileUtils; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.ArrayList; /** * @author Kohsuke Kawaguchi */ public class AbstractProjectTest extends HudsonTestCase { public void testConfigRoundtrip() throws Exception { FreeStyleProject project = createFreeStyleProject(); Label l = jenkins.getLabel("foo && bar"); project.setAssignedLabel(l); configRoundtrip((Item)project); assertEquals(l,project.getAssignedLabel()); } /** * Tests the workspace deletion. */ public void testWipeWorkspace() throws Exception { FreeStyleProject project = createFreeStyleProject(); project.getBuildersList().add(new Shell("echo hello")); FreeStyleBuild b = project.scheduleBuild2(0).get(); assertTrue("Workspace should exist by now", b.getWorkspace().exists()); // emulate the user behavior WebClient webClient = new WebClient(); HtmlPage page = webClient.getPage(project); page = (HtmlPage)page.getFirstAnchorByText("Workspace").click(); page = (HtmlPage)page.getFirstAnchorByText("Wipe Out Workspace").click(); page = (HtmlPage)((HtmlForm)page.getElementById("confirmation")).submit(null); assertFalse("Workspace should be gone by now", b.getWorkspace().exists()); } /** * Makes sure that the workspace deletion is protected. */ @PresetData(DataSet.NO_ANONYMOUS_READACCESS) public void testWipeWorkspaceProtected() throws Exception { FreeStyleProject project = createFreeStyleProject(); project.getBuildersList().add(new Shell("echo hello")); FreeStyleBuild b = project.scheduleBuild2(0).get(); assertTrue("Workspace should exist by now",b.getWorkspace().exists()); // make sure that the action link is protected try { new WebClient().getPage(project,"doWipeOutWorkspace"); fail("Should have failed"); } catch (FailingHttpStatusCodeException e) { assertEquals(e.getStatusCode(),403); } } /** * Makes sure that the workspace deletion link is not provided * when the user doesn't have an access. */ @PresetData(DataSet.ANONYMOUS_READONLY) public void testWipeWorkspaceProtected2() throws Exception { ((GlobalMatrixAuthorizationStrategy) jenkins.getAuthorizationStrategy()).add(AbstractProject.WORKSPACE,"anonymous"); // make sure that the deletion is protected in the same way testWipeWorkspaceProtected(); // there shouldn't be any "wipe out workspace" link for anonymous user WebClient webClient = new WebClient(); HtmlPage page = webClient.getPage(jenkins.getItem("test0")); page = (HtmlPage)page.getFirstAnchorByText("Workspace").click(); try { page.getFirstAnchorByText("Wipe Out Workspace"); fail("shouldn't find a link"); } catch (ElementNotFoundException e) { } } /** * Tests the &lt;optionalBlock @field> round trip behavior by using {@link AbstractProject#concurrentBuild} */ public void testOptionalBlockDataBindingRoundtrip() throws Exception { FreeStyleProject p = createFreeStyleProject(); for( boolean b : new boolean[]{true,false}) { p.setConcurrentBuild(b); submit(new WebClient().getPage(p,"configure").getFormByName("config")); assertEquals(b,p.isConcurrentBuild()); } } /** * Tests round trip configuration of the blockBuildWhenUpstreamBuilding field */ @Bug(4423) public void testConfiguringBlockBuildWhenUpstreamBuildingRoundtrip() throws Exception { FreeStyleProject p = createFreeStyleProject(); p.blockBuildWhenUpstreamBuilding = false; HtmlForm form = new WebClient().getPage(p, "configure").getFormByName("config"); HtmlInput input = form.getInputByName("blockBuildWhenUpstreamBuilding"); assertFalse("blockBuildWhenUpstreamBuilding check box is checked.", input.isChecked()); input.setChecked(true); submit(form); assertTrue("blockBuildWhenUpstreamBuilding was not updated from configuration form", p.blockBuildWhenUpstreamBuilding); form = new WebClient().getPage(p, "configure").getFormByName("config"); input = form.getInputByName("blockBuildWhenUpstreamBuilding"); assertTrue("blockBuildWhenUpstreamBuilding check box is not checked.", input.isChecked()); } /** * Unless the concurrent build option is enabled, polling and build should be mutually exclusive * to avoid allocating unnecessary workspaces. */ @Bug(4202) public void testPollingAndBuildExclusion() throws Exception { final OneShotEvent sync = new OneShotEvent(); final FreeStyleProject p = createFreeStyleProject(); FreeStyleBuild b1 = buildAndAssertSuccess(p); p.setScm(new NullSCM() { @Override public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) { try { sync.block(); } catch (InterruptedException e) { e.printStackTrace(); } return true; } /** * Don't write 'this', so that subtypes can be implemented as anonymous class. */ private Object writeReplace() { return new Object(); } @Override public boolean requiresWorkspaceForPolling() { return true; } }); Thread t = new Thread() { @Override public void run() { p.pollSCMChanges(StreamTaskListener.fromStdout()); } }; try { t.start(); Future<FreeStyleBuild> f = p.scheduleBuild2(0); // add a bit of delay to make sure that the blockage is happening Thread.sleep(3000); // release the polling sync.signal(); FreeStyleBuild b2 = assertBuildStatusSuccess(f); // they should have used the same workspace. assertEquals(b1.getWorkspace(), b2.getWorkspace()); } finally { t.interrupt(); } } @Bug(1986) public void testBuildSymlinks() throws Exception { // If we're on Windows, don't bother doing this. if (Functions.isWindows()) return; FreeStyleProject job = createFreeStyleProject(); job.getBuildersList().add(new Shell("echo \"Build #$BUILD_NUMBER\"\n")); FreeStyleBuild build = job.scheduleBuild2(0, new Cause.UserCause()).get(); File lastSuccessful = new File(job.getRootDir(), "lastSuccessful"), lastStable = new File(job.getRootDir(), "lastStable"); // First build creates links assertSymlinkForBuild(lastSuccessful, 1); assertSymlinkForBuild(lastStable, 1); FreeStyleBuild build2 = job.scheduleBuild2(0, new Cause.UserCause()).get(); // Another build updates links assertSymlinkForBuild(lastSuccessful, 2); assertSymlinkForBuild(lastStable, 2); // Delete latest build should update links build2.delete(); assertSymlinkForBuild(lastSuccessful, 1); assertSymlinkForBuild(lastStable, 1); // Delete all builds should remove links build.delete(); assertFalse("lastSuccessful link should be removed", lastSuccessful.exists()); assertFalse("lastStable link should be removed", lastStable.exists()); } private static void assertSymlinkForBuild(File file, int buildNumber) throws IOException, InterruptedException { assertTrue("should exist and point to something that exists", file.exists()); assertTrue("should be symlink", Util.isSymlink(file)); String s = FileUtils.readFileToString(new File(file, "log")); assertTrue("link should point to build #" + buildNumber + ", but link was: " + Util.resolveSymlink(file, TaskListener.NULL) + "\nand log was:\n" + s, s.contains("Build #" + buildNumber + "\n")); } @Bug(2543) public void testSymlinkForPostBuildFailure() throws Exception { // If we're on Windows, don't bother doing this. if (Functions.isWindows()) return; // Links should be updated after post-build actions when final build result is known FreeStyleProject job = createFreeStyleProject(); job.getBuildersList().add(new Shell("echo \"Build #$BUILD_NUMBER\"\n")); FreeStyleBuild build = job.scheduleBuild2(0, new Cause.UserCause()).get(); assertEquals(Result.SUCCESS, build.getResult()); File lastSuccessful = new File(job.getRootDir(), "lastSuccessful"), lastStable = new File(job.getRootDir(), "lastStable"); // First build creates links assertSymlinkForBuild(lastSuccessful, 1); assertSymlinkForBuild(lastStable, 1); // Archive artifacts that don't exist to create failure in post-build action job.getPublishersList().add(new ArtifactArchiver("*.foo", "", false)); build = job.scheduleBuild2(0, new Cause.UserCause()).get(); assertEquals(Result.FAILURE, build.getResult()); // Links should not be updated since build failed assertSymlinkForBuild(lastSuccessful, 1); assertSymlinkForBuild(lastStable, 1); } // Force garbage collection of ref's referent. Taken from NetBeans code. public static void forceGc(final Reference<?> ref) { ArrayList<byte[]> alloc = new ArrayList<byte[]>(); int size = 100000; System.out.print("forcing garbage collection..."); for (int i = 0; i < 50; i++) { if (ref.get() == null) { System.out.println("succeeded"); return; } try { System.gc(); System.runFinalization(); } catch (OutOfMemoryError error) { } try { alloc.add(new byte[size]); size = (int)(((double)size) * 1.3); } catch (OutOfMemoryError error) { size = size / 2; } try { if (i % 3 == 0) { Thread.sleep(321); } } catch (InterruptedException t) { // ignore } } System.out.println("failed"); } @Bug(15156) public void testGetBuildAfterGc() throws Exception { FreeStyleProject job = createFreeStyleProject(); job.scheduleBuild2(0, new Cause.UserCause()).get(); // If this fails to garbage-collect, the test run will not have any value, but it will // at least not fail. forceGc(new WeakReference(job.getLastBuild())); assertTrue(job.getLastBuild() != null); } }
package hotchemi.android.rate; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.os.Build; final class Utils { private Utils() { } static boolean underHoneyComb() { return Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; } static boolean isLollipop() { return Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1; } static int getDialogTheme() { return isLollipop() ? R.style.CustomLollipopDialogStyle : 0; } @SuppressLint("NewApi") static AlertDialog.Builder getDialogBuilder(Context context) { if (underHoneyComb()) { return new AlertDialog.Builder(context); } else { return new AlertDialog.Builder(context, getDialogTheme()); } } }
package com.mesmotronic.plugins; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.graphics.Point; import android.os.Build; import android.view.View; import android.view.Window; import android.view.WindowManager; public class FullScreenPlugin extends CordovaPlugin { public static final String ACTION_IS_SUPPORTED = "isSupported"; public static final String ACTION_IS_IMMERSIVE_MODE_SUPPORTED = "isImmersiveModeSupported"; public static final String ACTION_IMMERSIVE_WIDTH = "immersiveWidth"; public static final String ACTION_IMMERSIVE_HEIGHT = "immersiveHeight"; public static final String ACTION_LEAN_MODE = "leanMode"; public static final String ACTION_SHOW_SYSTEM_UI = "showSystemUI"; public static final String ACTION_SHOW_UNDER_STATUS_BAR = "showUnderStatusBar"; public static final String ACTION_SHOW_UNDER_SYSTEM_UI = "showUnderSystemUI"; public static final String ACTION_IMMERSIVE_MODE = "immersiveMode"; private CallbackContext context; private Activity activity; private Window window; private View decorView; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { context = callbackContext; activity = cordova.getActivity(); window = activity.getWindow(); decorView = window.getDecorView(); if (ACTION_IS_SUPPORTED.equals(action)) return isSupported(); else if (ACTION_IS_IMMERSIVE_MODE_SUPPORTED.equals(action)) return isImmersiveModeSupported(); else if (ACTION_IMMERSIVE_WIDTH.equals(action)) return immersiveWidth(); else if (ACTION_IMMERSIVE_HEIGHT.equals(action)) return immersiveHeight(); else if (ACTION_LEAN_MODE.equals(action)) return leanMode(); else if (ACTION_SHOW_SYSTEM_UI.equals(action)) return showSystemUI(); else if (ACTION_SHOW_UNDER_STATUS_BAR.equals(action)) return showUnderStatusBar(); else if (ACTION_SHOW_UNDER_SYSTEM_UI.equals(action)) return showUnderSystemUI(); else if (ACTION_IMMERSIVE_MODE.equals(action)) return immersiveMode(); return false; } protected void resetWindow() { decorView.setOnFocusChangeListener(null); decorView.setOnSystemUiVisibilityChangeListener(null); window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } /** * Are any of the features of this plugin supported? */ protected boolean isSupported() { boolean supported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; PluginResult res = new PluginResult(PluginResult.Status.OK, supported); context.sendPluginResult(res); return true; } /** * Is immersive mode supported? */ protected boolean isImmersiveModeSupported() { boolean supported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; PluginResult res = new PluginResult(PluginResult.Status.OK, supported); context.sendPluginResult(res); return true; } /** * The width of the screen in immersive mode */ protected boolean immersiveWidth() { activity.runOnUiThread(new Runnable() { @Override public void run() { try { Point outSize = new Point(); decorView.getDisplay().getRealSize(outSize); PluginResult res = new PluginResult(PluginResult.Status.OK, outSize.x); context.sendPluginResult(res); } catch (Exception e) { context.error(e.getMessage()); } } }); return true; } /** * The height of the screen in immersive mode */ protected boolean immersiveHeight() { activity.runOnUiThread(new Runnable() { @Override public void run() { try { Point outSize = new Point(); decorView.getDisplay().getRealSize(outSize); PluginResult res = new PluginResult(PluginResult.Status.OK, outSize.y); context.sendPluginResult(res); } catch (Exception e) { context.error(e.getMessage()); } } }); return true; } /** * Hide system UI until user interacts */ protected boolean leanMode() { if (!isSupported()) { context.error("Not supported"); return false; } activity.runOnUiThread(new Runnable() { @Override public void run() { try { resetWindow(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; decorView.setOnSystemUiVisibilityChangeListener(null); decorView.setSystemUiVisibility(uiOptions); context.success(); } catch (Exception e) { context.error(e.getMessage()); } } }); return true; } /** * Show system UI */ protected boolean showSystemUI() { if (!isSupported()) { context.error("Not supported"); return false; } activity.runOnUiThread(new Runnable() { @Override public void run() { try { resetWindow(); // Remove translucent theme from bars window.clearFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS ); // Update system UI decorView.setOnSystemUiVisibilityChangeListener(null); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); PluginResult res = new PluginResult(PluginResult.Status.OK, true); context.sendPluginResult(res); context.success(); } catch (Exception e) { context.error(e.getMessage()); } } }); return true; } /** * Extend your app underneath the status bar (Android 4.4+ only) */ protected boolean showUnderStatusBar() { if (!isImmersiveModeSupported()) { context.error("Not supported"); return false; } activity.runOnUiThread(new Runnable() { @Override public void run() { try { resetWindow(); // Make the status bar translucent window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // Extend view underneath status bar int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); context.success(); } catch (Exception e) { context.error(e.getMessage()); } } }); return true; } /** * Extend your app underneath the system UI (Android 4.4+ only) */ protected boolean showUnderSystemUI() { if (!isImmersiveModeSupported()) { context.error("Not supported"); return false; } activity.runOnUiThread(new Runnable() { @Override public void run() { try { resetWindow(); // Make the status and nav bars translucent window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // Extend view underneath status and nav bars int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; decorView.setSystemUiVisibility(uiOptions); context.success(); } catch (Exception e) { context.error(e.getMessage()); } } }); return true; } /** * Hide system UI and switch to immersive mode (Android 4.4+ only) */ protected boolean immersiveMode() { if (!isImmersiveModeSupported()) { context.error("Not supported"); return false; } activity.runOnUiThread(new Runnable() { @Override public void run() { try { resetWindow(); final int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); decorView.setSystemUiVisibility(uiOptions); decorView.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { decorView.setSystemUiVisibility(uiOptions); } } }); decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { decorView.setSystemUiVisibility(uiOptions); } }); context.success(); } catch (Exception e) { context.error(e.getMessage()); } } }); return true; } }
package ch.ethz.inf.vs.californium.dtls; import java.util.logging.Logger; import ch.ethz.inf.vs.californium.util.DatagramReader; import ch.ethz.inf.vs.californium.util.DatagramWriter; public abstract class HandshakeMessage implements DTLSMessage { // Logging ///////////////////////////////////////////////////////// protected static final Logger LOG = Logger.getLogger(HandshakeMessage.class.getName()); // CoAP-specific constants ///////////////////////////////////////// private static final int MESSAGE_TYPE_BITS = 8; private static final int MESSAGE_LENGTH_BITS = 24; private static final int MESSAGE_SEQ_BITS = 16; private static final int FRAGMENT_OFFSET_BITS = 24; private static final int FRAGMENT_LENGTH_BITS = 24; // Members ////////////////////////////////////////////////////////// private int messageSeq; /** * The number of bytes contained in previous fragments. */ private int fragmentOffset; /** * The length of this fragment. An unfragmented message is a degenerate case * with fragment_offset=0 and fragment_length=length. */ private int fragmentLength; // Constructors ///////////////////////////////////////////////////// public HandshakeMessage() { this.messageSeq = 0; // TODO fragmentation this.fragmentOffset = 0; this.fragmentLength = 0; } // Methods //////////////////////////////////////////////////////// /** * Returns the type of the handshake message. See {@link HandshakeType}. * * @return the {@link HandshakeType}. */ public abstract HandshakeType getMessageType(); /** * Must be implemented by each subclass. The length is given in bytes and * only includes the length of the subclass' specific fields (not the * handshake message header). * * @return the length of the message <strong>in bytes</strong>. */ public abstract int getMessageLength(); @Override public int getLength() { // fixed: message type (1 byte) + message length (3 bytes) + message seq // (2 bytes) + fragment offset (3 bytes) + fragment length (3 bytes) = // 12 bytes return 12 + getMessageLength(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\tHandshake Protocol\n"); sb.append("\tType: " + getMessageType().toString() + "\n"); sb.append("\tMessage Sequence: " + messageSeq + " \n"); sb.append("\tFragment Offset: " + fragmentOffset + "\n"); sb.append("\tFragment Length: " + fragmentLength + "\n"); sb.append("\tLength: " + getMessageLength() + "\n"); return sb.toString(); } // Serialization ////////////////////////////////////////////////// /** * Returns the raw binary representation of the handshake header. The * subclasses are responsible for the specific rest of the fragment. * * @return the byte representation of the handshake message. */ public byte[] toByteArray() { // create datagram writer to encode message data DatagramWriter writer = new DatagramWriter(); // write fixed-size handshake message header writer.write(getMessageType().getCode(), MESSAGE_TYPE_BITS); writer.write(getMessageLength(), MESSAGE_LENGTH_BITS); writer.write(messageSeq, MESSAGE_SEQ_BITS); writer.write(fragmentOffset, FRAGMENT_OFFSET_BITS); writer.write(fragmentLength, FRAGMENT_LENGTH_BITS); return writer.toByteArray(); } public static HandshakeMessage fromByteArray(byte[] byteArray) { DatagramReader reader = new DatagramReader(byteArray); HandshakeType type = HandshakeType.getTypeByCode(reader.read(MESSAGE_TYPE_BITS)); int length = reader.read(MESSAGE_LENGTH_BITS); int messageSeq = reader.read(MESSAGE_SEQ_BITS); int fragmentOffset = reader.read(FRAGMENT_OFFSET_BITS); int fragmentLength = reader.read(FRAGMENT_LENGTH_BITS); HandshakeMessage body = null; byte[] bytesLeft = reader.readBytes(length); switch (type) { case HELLO_REQUEST: body = new HelloRequest(); break; case CLIENT_HELLO: body = ClientHello.fromByteArray(bytesLeft); break; case SERVER_HELLO: body = ServerHello.fromByteArray(bytesLeft); break; case HELLO_VERIFY_REQUEST: body = HelloVerifyRequest.fromByteArray(bytesLeft); break; case CERTIFICATE: body = CertificateMessage.fromByteArray(bytesLeft); break; case SERVER_KEY_EXCHANGE: // TODO make this variable body = ECDHServerKeyExchange.fromByteArray(bytesLeft); break; case CERTIFICATE_REQUEST: body = CertificateRequest.fromByteArray(bytesLeft); break; case SERVER_HELLO_DONE: body = new ServerHelloDone(); break; case CERTIFICATE_VERIFY: body = CertificateVerify.fromByteArray(bytesLeft); break; case CLIENT_KEY_EXCHANGE: // TODO make this variable body = ECDHClientKeyExchange.fromByteArray(bytesLeft); break; case FINISHED: body = Finished.fromByteArray(bytesLeft); break; default: break; } body.setFragmentLength(fragmentLength); body.setFragmentOffset(fragmentOffset); body.setMessageSeq(messageSeq); return body; } // Getters and Setters //////////////////////////////////////////// public int getMessageSeq() { return messageSeq; } public void incrementMessageSeq() { messageSeq++; } public int getFragmentOffset() { return fragmentOffset; } public int getFragmentLength() { return fragmentLength; } public void setFragmentLength(int length) { this.fragmentLength = length; } public void setMessageSeq(int messageSeq) { this.messageSeq = messageSeq; } public void setFragmentOffset(int fragmentOffset) { this.fragmentOffset = fragmentOffset; } }
package com.airbnb.lottie; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.util.Log; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; /** * Helper to run asynchronous tasks with a result. * Results can be obtained with {@link #addListener(LottieListener)}. * Failures can be obtained with {@link #addFailureListener(LottieListener)}. * * A task will produce a single result or a single failure. */ public class LottieTask<T> { /** * Set this to change the executor that LottieTasks are run on. This will be the executor that composition parsing and url * fetching happens on. * * You may change this to run deserialization synchronously for testing. */ @SuppressWarnings("WeakerAccess") public static Executor EXECUTOR = Executors.newCachedThreadPool(); @Nullable private Thread taskObserver; /* Preserve add order. */ private final Set<LottieListener<T>> successListeners = new LinkedHashSet<>(1); private final Set<LottieListener<Throwable>> failureListeners = new LinkedHashSet<>(1); private final Handler handler = new Handler(Looper.getMainLooper()); private final FutureTask<LottieResult<T>> task; @Nullable private volatile LottieResult<T> result = null; @RestrictTo(RestrictTo.Scope.LIBRARY) public LottieTask(Callable<LottieResult<T>> runnable) { this(runnable, false); } /** * runNow is only used for testing. */ @RestrictTo(RestrictTo.Scope.LIBRARY) LottieTask(Callable<LottieResult<T>> runnable, boolean runNow) { task = new FutureTask<>(runnable); if (runNow) { try { setResult(runnable.call()); } catch (Throwable e) { setResult(new LottieResult<T>(e)); } } else { EXECUTOR.execute(task); startTaskObserverIfNeeded(); } } private void setResult(@Nullable LottieResult<T> result) { if (this.result != null) { throw new IllegalStateException("A task may only be set once."); } this.result = result; notifyListeners(); } /** * Add a task listener. If the task has completed, the listener will be called synchronously. * @return the task for call chaining. */ public synchronized LottieTask<T> addListener(LottieListener<T> listener) { if (result != null && result.getValue() != null) { listener.onResult(result.getValue()); } successListeners.add(listener); startTaskObserverIfNeeded(); return this; } /** * Remove a given task listener. The task will continue to execute so you can re-add * a listener if neccesary. * @return the task for call chaining. */ public synchronized LottieTask<T> removeListener(LottieListener<T> listener) { successListeners.remove(listener); stopTaskObserverIfNeeded(); return this; } /** * Add a task failure listener. This will only be called in the even that an exception * occurs. If an exception has already occurred, the listener will be called immediately. * @return the task for call chaining. */ public synchronized LottieTask<T> addFailureListener(LottieListener<Throwable> listener) { if (result != null && result.getException() != null) { listener.onResult(result.getException()); } failureListeners.add(listener); startTaskObserverIfNeeded(); return this; } /** * Remove a given task failure listener. The task will continue to execute so you can re-add * a listener if neccesary. * @return the task for call chaining. */ public synchronized LottieTask<T> removeFailureListener(LottieListener<Throwable> listener) { failureListeners.remove(listener); stopTaskObserverIfNeeded(); return this; } private void notifyListeners() { // Listeners should be called on the main thread. handler.post(new Runnable() { @Override public void run() { if (result == null || task.isCancelled()) { return; } // Local reference in case it gets set on a background thread. LottieResult<T> result = LottieTask.this.result; if (result.getValue() != null) { notifySuccessListeners(result.getValue()); } else { notifyFailureListeners(result.getException()); } } }); } private void notifySuccessListeners(T value) { // Allows listeners to remove themselves in onResult. // Otherwise we risk ConcurrentModificationException. List<LottieListener<T>> listenersCopy = new ArrayList<>(successListeners); for (LottieListener<T> l : listenersCopy) { l.onResult(value); } } private void notifyFailureListeners(Throwable e) { // Allows listeners to remove themselves in onResult. // Otherwise we risk ConcurrentModificationException. List<LottieListener<Throwable>> listenersCopy = new ArrayList<>(failureListeners); if (listenersCopy.isEmpty()) { Log.w(L.TAG, "Lottie encountered an error but no failure listener was added.", e); return; } for (LottieListener<Throwable> l : listenersCopy) { l.onResult(e); } } /** * We monitor the task with an observer thread to determine when it is done and should notify * the appropriate listeners. */ private synchronized void startTaskObserverIfNeeded() { if (taskObserverAlive() || result != null) { return; } taskObserver = new Thread("LottieTaskObserver") { private boolean taskComplete = false; @Override public void run() { while (true) { if (isInterrupted() || taskComplete) { return; } if (task.isDone()) { try { setResult(task.get()); } catch (InterruptedException | ExecutionException e) { setResult(new LottieResult<T>(e)); } taskComplete = true; stopTaskObserverIfNeeded(); } } } }; taskObserver.start(); L.debug("Starting TaskObserver thread"); } /** * We can stop observing the task if there are no more listeners or if the task is complete. */ private synchronized void stopTaskObserverIfNeeded() { if (!taskObserverAlive()) { return; } if (successListeners.isEmpty() || result != null) { taskObserver.interrupt(); taskObserver = null; L.debug("Stopping TaskObserver thread"); } } private boolean taskObserverAlive() { return taskObserver != null && taskObserver.isAlive(); } }
package ch.unizh.ini.jaer.projects.minliu; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import com.jogamp.opengl.util.awt.TextRenderer; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import eu.seebetter.ini.chips.davis.imu.IMUSample; import java.awt.Color; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.filter.Steadicam; import net.sf.jaer.graphics.FrameAnnotater; /** * Uses patch matching to measureTT local optical flow. <b>Not</b> gradient * based, but rather matches local features backwards in time. * * @author Tobi and Min, Jan 2016 */ @Description("Computes optical flow with vector direction using binary block matching") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements Observer, FrameAnnotater { private int[][][] histograms = null; private int numSlices = 3; private int sx, sy; private int tMinus2SliceIdx = 0, tMinus1SliceIdx = 1, currentSliceIdx = 2; private int[][] currentSlice = null, tMinus1Slice = null, tMinus2Slice = null; private ArrayList<Integer[]>[][] spikeTrains = null; // Spike trains for one block private ArrayList<int[][]>[] histogramsAL = null; private ArrayList<int[][]> currentAL = null, previousAL = null, previousMinus1AL = null; // One is for current, the second is for previous, the third is for the one before previous one private BitSet[] histogramsBitSet = null; private BitSet currentSli = null, tMinus1Sli = null, tMinus2Sli = null; private final SADResult tmpSadResult = new SADResult(0, 0, 0); private int patchDimension = getInt("patchDimension", 9); private boolean displayOutputVectors = getBoolean("displayOutputVectors", true); private int eventPatchDimension = getInt("eventPatchDimension", 3); private int forwardEventNum = getInt("forwardEventNum", 10); private float cost = getFloat("cost", 0.001f); private float confidenceThreshold = getFloat("confidenceThreshold", 0f); private float validPixOccupancy = getFloat("validPixOccupancy", 0.01f); // threshold for valid pixel percent for one block private float weightDistance = getFloat("weightDistance", 0.9f); // confidence value consists of the distance and the dispersion, this value set the distance value private int thresholdTime = getInt("thresholdTime", 1000000); private int[][] lastFireIndex = null; // Events are numbered in time order for every block. This variable is for storing the last event index fired on all blocks. private int[][] eventSeqStartTs = null; private boolean preProcessEnable = false; private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps) private int skipCounter = 0; // results histogram for each packet private int[][] resultHistogram = null; public enum PatchCompareMethod { JaccardDistance, HammingDistance, SAD, EventSqeDistance }; private PatchCompareMethod patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.HammingDistance.toString())); private int sliceDurationUs = getInt("sliceDurationUs", 100000); private int sliceEventCount = getInt("sliceEventCount", 1000); private boolean rewindFlg = false; // The flag to indicate the rewind event. private FilterChain filterChain; private Steadicam cameraMotion; // calibration private boolean calibrating = false; // used to flag calibration state private int calibrationSampleCount = 0; private int NUM_CALIBRATION_SAMPLES_DEFAULT = 800; // 400 samples /sec protected int numCalibrationSamples = getInt("numCalibrationSamples", NUM_CALIBRATION_SAMPLES_DEFAULT); TextRenderer imuTextRenderer = null; private boolean showGrid = getBoolean("showGrid", true); private boolean displayResultHistogram = getBoolean("displayResultHistogram", true); public enum SliceMethod { ConstantDuration, ConstantEventNumber, AdaptationDuration }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.ConstantDuration.toString())); private int eventCounter = 0; private int sliceLastTs = 0; public PatchMatchFlow(AEChip chip) { super(chip); filterChain = new FilterChain(chip); cameraMotion = new Steadicam(chip); cameraMotion.setFilterEnabled(true); cameraMotion.setDisableRotation(true); cameraMotion.setDisableTranslation(true); // filterChain.add(cameraMotion); setEnclosedFilterChain(filterChain); String patchTT = "Block matching"; String eventSqeMatching = "Event squence matching"; String preProcess = "Denoise"; String metricConfid = "Confidence of current metric"; chip.addObserver(this); // to allocate memory once chip size is known setPropertyTooltip(preProcess, "preProcessEnable", "enable this to denoise before data processing"); setPropertyTooltip(preProcess, "forwardEventNum", "Number of events have fired on the current block since last processing"); setPropertyTooltip(metricConfid, "confidenceThreshold", "<html>Confidence threshold for rejecting unresonable value; Range from 0 to 1. <p>Higher value means it is harder to accept the event. <br>Set to 0 to accept all results."); setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated."); setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0."); setPropertyTooltip(patchTT, "patchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches"); setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval"); setPropertyTooltip(patchTT, "sliceMethod", "set method for determining time slice duration for block matching"); setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)"); setPropertyTooltip(eventSqeMatching, "cost", "The cost to translation one event to the other position"); setPropertyTooltip(eventSqeMatching, "thresholdTime", "The threshold value of interval time between the first event and the last event"); setPropertyTooltip(eventSqeMatching, "sliceEventCount", "number of collected events in each bitmap"); setPropertyTooltip(eventSqeMatching, "eventPatchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(dispTT, "displayOutputVectors", "display the output motion vectors or not"); setPropertyTooltip(dispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance"); } @Override synchronized public EventPacket filterPacket(EventPacket in) { setupFilter(in); checkArrays(); if (resultHistogram == null || resultHistogram.length != 2 * searchDistance + 1) { int dim = 2 * searchDistance + 1; // e.g. search distance 1, dim=3, 3x3 possibilties (including zero motion) resultHistogram = new int[dim][dim]; } else { for (int[] h : resultHistogram) { Arrays.fill(h, 0); } } ApsDvsEventPacket in2 = (ApsDvsEventPacket) in; Iterator itr = in2.fullIterator(); // Wfffsfe also need IMU data, so here we use the full iterator. while (itr.hasNext()) { Object ein = itr.next(); if (ein == null) { log.warning("null event passed in, returning input packet"); return in; } if (!extractEventInfo(ein)) { continue; } ApsDvsEvent apsDvsEvent = (ApsDvsEvent) ein; if (apsDvsEvent.isImuSample()) { IMUSample s = apsDvsEvent.getImuSample(); continue; } if (apsDvsEvent.isApsData()) { continue; } // inItr = in.inputIterator; if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { imuFlowEstimator.calculateImuFlow((ApsDvsEvent) inItr.next()); setGroundTruth(); } if (xyFilter()) { continue; } countIn++; // compute flow SADResult result = null; int blockLocX = x / eventPatchDimension; int blockLocY = y / eventPatchDimension; // Build the spike trains of every block, every block is consist of 3*3 pixels. if (spikeTrains[blockLocX][blockLocY] == null) { spikeTrains[blockLocX][blockLocY] = new ArrayList(); } int spikeBlokcLength = spikeTrains[blockLocX][blockLocY].size(); int previousTsInterval = 0; if (spikeBlokcLength == 0) { previousTsInterval = ts; } else { previousTsInterval = ts - spikeTrains[blockLocX][blockLocY].get(spikeBlokcLength - 1)[0]; } if (preProcessEnable || patchCompareMethod == PatchCompareMethod.EventSqeDistance) { spikeTrains[blockLocX][blockLocY].add(new Integer[]{ts, type}); } switch (patchCompareMethod) { case HammingDistance: maybeRotateSlices(); if (!accumulateEvent()) { break; } if (preProcessEnable) { // There are enough events fire on the specific block now. if ((spikeTrains[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY]) >= forwardEventNum) { lastFireIndex[blockLocX][blockLocY] = spikeTrains[blockLocX][blockLocY].size() - 1; result = minHammingDistance(x, y, tMinus2Sli, tMinus1Sli); result.dx = (result.dx / sliceDurationUs) * 1000000; result.dy = (result.dy / sliceDurationUs) * 1000000; } } else { result = minHammingDistance(x, y, tMinus2Sli, tMinus1Sli); result.dx = (result.dx / sliceDurationUs) * 1000000; // hack, convert to pix/second result.dy = (result.dy / sliceDurationUs) * 1000000; } break; case SAD: maybeRotateSlices(); if (!accumulateEvent()) { break; } if (preProcessEnable) { // There're enough events fire on the specific block now if ((spikeTrains[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY]) >= forwardEventNum) { lastFireIndex[blockLocX][blockLocY] = spikeTrains[blockLocX][blockLocY].size() - 1; result = minSad(x, y, tMinus2Sli, tMinus1Sli); result.dx = (result.dx / sliceDurationUs) * 1000000; result.dy = (result.dy / sliceDurationUs) * 1000000; } } else { result = minSad(x, y, tMinus2Sli, tMinus1Sli); result.dx = (result.dx / sliceDurationUs) * 1000000; result.dy = (result.dy / sliceDurationUs) * 1000000; } break; case JaccardDistance: maybeRotateSlices(); if (!accumulateEvent()) { break; } if (preProcessEnable) { // There're enough events fire on the specific block now if ((spikeTrains[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY]) >= forwardEventNum) { lastFireIndex[blockLocX][blockLocY] = spikeTrains[blockLocX][blockLocY].size() - 1; result = minJaccardDistance(x, y, tMinus2Sli, tMinus1Sli); result.dx = (result.dx / sliceDurationUs) * 1000000; result.dy = (result.dy / sliceDurationUs) * 1000000; } } else { result = minJaccardDistance(x, y, tMinus2Sli, tMinus1Sli); result.dx = (result.dx / sliceDurationUs) * 1000000; result.dy = (result.dy / sliceDurationUs) * 1000000; } break; case EventSqeDistance: if (previousTsInterval < 0) { spikeTrains[blockLocX][blockLocY].remove(spikeTrains[blockLocX][blockLocY].size() - 1); continue; } if (previousTsInterval >= thresholdTime) { float maxDt = 0; float[][] dataPoint = new float[9][2]; if ((blockLocX >= 1) && (blockLocY >= 1) && (blockLocX <= 238) && (blockLocY <= 178)) { for (int ii = -1; ii < 2; ii++) { for (int jj = -1; jj < 2; jj++) { float dt = ts - eventSeqStartTs[blockLocX + ii][blockLocY + jj]; // Remove the seq1 itself if ((0 == ii) && (0 == jj)) { // continue; dt = 0; } dataPoint[((ii + 1) * 3) + (jj + 1)][0] = dt; if (dt > maxDt) { } } } } // result = minVicPurDistance(blockLocX, blockLocY); eventSeqStartTs[blockLocX][blockLocY] = ts; boolean allZeroFlg = true; for (int mm = 0; mm < 9; mm++) { for (int nn = 0; nn < 1; nn++) { if (dataPoint[mm][nn] != 0) { allZeroFlg = false; } } } if (allZeroFlg) { continue; } KMeans cluster = new KMeans(); cluster.setData(dataPoint); int[] initialValue = new int[3]; initialValue[0] = 0; initialValue[1] = 4; initialValue[2] = 8; cluster.setInitialByUser(initialValue); cluster.cluster(); ArrayList<ArrayList<Integer>> kmeansResult = cluster.getResult(); float[][] classData = cluster.getClassData(); int firstClusterIdx = -1, secondClusterIdx = -1, thirdClusterIdx = -1; for (int i = 0; i < 3; i++) { if (kmeansResult.get(i).contains(0)) { firstClusterIdx = i; } if (kmeansResult.get(i).contains(4)) { secondClusterIdx = i; } if (kmeansResult.get(i).contains(8)) { thirdClusterIdx = i; } } if ((kmeansResult.get(firstClusterIdx).size() == 3) && (kmeansResult.get(firstClusterIdx).size() == 3) && (kmeansResult.get(firstClusterIdx).size() == 3) && kmeansResult.get(firstClusterIdx).contains(1) && kmeansResult.get(firstClusterIdx).contains(2)) { result.dx = (-1 / (classData[secondClusterIdx][0] - classData[firstClusterIdx][0])) * 1000000 * 0.2f * eventPatchDimension;; result.dy = 0; } if ((kmeansResult.get(firstClusterIdx).size() == 3) && (kmeansResult.get(firstClusterIdx).size() == 3) && (kmeansResult.get(firstClusterIdx).size() == 3) && kmeansResult.get(thirdClusterIdx).contains(2) && kmeansResult.get(thirdClusterIdx).contains(5)) { result.dy = (-1 / (classData[thirdClusterIdx][0] - classData[secondClusterIdx][0])) * 1000000 * 0.2f * eventPatchDimension;; result.dx = 0; } } break; } if (result == null) { continue; // maybe some property change caused this } vx = result.dx; vy = result.dy; v = (float) Math.sqrt((vx * vx) + (vy * vy)); // reject values that are unreasonable if (isNotSufficientlyAccurate(result)) { continue; } if (resultHistogram != null) { resultHistogram[result.xidx][result.yidx]++; } processGoodEvent(); } if (rewindFlg) { rewindFlg = false; sliceLastTs = 0; final int sx = chip.getSizeX(), sy = chip.getSizeY(); for (int i = 0; i < sx; i++) { for (int j = 0; j < sy; j++) { if (spikeTrains != null && spikeTrains[i][j] != null) { spikeTrains[i][j] = null; } if (lastFireIndex != null) { lastFireIndex[i][j] = 0; } eventSeqStartTs[i][j] = 0; } } } motionFlowStatistics.updatePacket(countIn, countOut); return isShowRawInputEnabled() ? in : dirPacket; } @Override public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); if (displayResultHistogram && resultHistogram != null) { GL2 gl = drawable.getGL().getGL2(); // draw histogram as shaded in 2d hist above color wheel // normalize hist int max = 0; for (int[] h : resultHistogram) { for (int v : h) { if (v > max) { max = v; } } } if (max == 0) { return; } final float maxRecip = 1f / max; int dim = resultHistogram.length; float s = 8; // chip pixels/bin gl.glPushMatrix(); gl.glTranslatef(-dim*s, .65f * chip.getSizeY(), 0); gl.glScalef(s, s, 1); gl.glColor3f(0,0,1); gl.glLineWidth(2f); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(0,0); gl.glVertex2f(dim,0); gl.glVertex2f(dim,dim); gl.glVertex2f(0,dim); gl.glEnd(); for (int x = 0; x < dim; x++) { for (int y = 0; y < dim; y++) { float g = maxRecip * resultHistogram[x][y]; gl.glColor3f(g, g, g); gl.glBegin(GL2.GL_QUADS); gl.glVertex2f(x, y); gl.glVertex2f(x + 1, y); gl.glVertex2f(x + 1, y + 1); gl.glVertex2f(x, y + 1); gl.glEnd(); } } gl.glPopMatrix(); } } @Override public synchronized void resetFilter() { super.resetFilter(); eventCounter = 0; lastTs = Integer.MIN_VALUE; if ((histograms == null) || (histograms.length != subSizeX) || (histograms[0].length != subSizeY)) { if ((numSlices == 0) && (subSizeX == 0) && (subSizeX == 0)) { return; } histograms = new int[numSlices][subSizeX][subSizeY]; } for (int[][] a : histograms) { for (int[] b : a) { Arrays.fill(b, 0); } } if (histogramsBitSet == null) { histogramsBitSet = new BitSet[numSlices]; } for (int ii = 0; ii < numSlices; ii++) { histogramsBitSet[ii] = new BitSet(subSizeX * subSizeY); } // Initialize 3 ArrayList's histogram, every pixel has three patches: current, previous and previous-1 if (histogramsAL == null) { histogramsAL = new ArrayList[3]; } if ((spikeTrains == null) & (subSizeX != 0) & (subSizeY != 0)) { spikeTrains = new ArrayList[subSizeX][subSizeY]; } if (patchDimension != 0) { int colPatchCnt = subSizeX / patchDimension; int rowPatchCnt = subSizeY / patchDimension; for (int ii = 0; ii < numSlices; ii++) { histogramsAL[ii] = new ArrayList(); for (int jj = 0; jj < (colPatchCnt * rowPatchCnt); jj++) { int[][] patch = new int[patchDimension][patchDimension]; histogramsAL[ii].add(patch); } } } tMinus2SliceIdx = 0; tMinus1SliceIdx = 1; currentSliceIdx = 2; assignSliceReferences(); sliceLastTs = 0; rewindFlg = true; } @Override public void update(Observable o, Object arg) { if (!isFilterEnabled()) { return; } super.update(o, arg); if ((o instanceof AEChip) && (chip.getNumPixels() > 0)) { resetFilter(); } } /** * uses the current event to maybe rotate the slices */ private void maybeRotateSlices() { int dt = ts - sliceLastTs; switch (sliceMethod) { case ConstantDuration: if (rewindFlg) { return; } if ((dt < sliceDurationUs) || (dt < 0)) { return; } break; case ConstantEventNumber: if (eventCounter++ < sliceEventCount) { return; } case AdaptationDuration: log.warning("The adaptation method is not supported yet."); return; } /* The index cycle is " current idx -> t1 idx -> t2 idx -> current idx". Change the index, the change should like this: next t2 = previous t1 = histogram(previous t2 idx + 1); next t1 = previous current = histogram(previous t1 idx + 1); */ currentSliceIdx = (currentSliceIdx + 1) % numSlices; tMinus1SliceIdx = (tMinus1SliceIdx + 1) % numSlices; tMinus2SliceIdx = (tMinus2SliceIdx + 1) % numSlices; sliceEventCount = 0; sliceLastTs = ts; assignSliceReferences(); } private int updateAdaptDuration() { return 1000; } private void assignSliceReferences() { currentSlice = histograms[currentSliceIdx]; tMinus1Slice = histograms[tMinus1SliceIdx]; tMinus2Slice = histograms[tMinus2SliceIdx]; currentSli = histogramsBitSet[currentSliceIdx]; tMinus1Sli = histogramsBitSet[tMinus1SliceIdx]; tMinus2Sli = histogramsBitSet[tMinus2SliceIdx]; currentSli.clear(); } /** * Accumulates the current event to the current slice * * @return true if subsequent processing should done, false if it should be * skipped for efficiency */ private boolean accumulateEvent() { currentSlice[x][y] += e.getPolaritySignum(); currentSli.set((x + 1) + (y * subSizeX)); // All evnets wheather 0 or 1 will be set in the BitSet Slice. if (skipProcessingEventsCount == 0) { return true; } if (skipCounter++ < skipProcessingEventsCount) { return false; } skipCounter = 0; return true; } private void clearSlice(int idx) { for (int[] a : histograms[idx]) { Arrays.fill(a, 0); } } /** * Computes hamming eight around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { float minSum = Integer.MAX_VALUE, sum = 0; // if ((x >= 128) && (x <= 130) && (y >= 189) && (y <= 191)) { // For debugging // int tmp = 0; for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { sum = hammingDistance(x, y, dx, dy, prevSlice, curSlice); if (sum <= minSum) { minSum = sum; tmpSadResult.dx = dx; tmpSadResult.dy = dy; tmpSadResult.sadValue = minSum; } } } tmpSadResult.xidx = (int) tmpSadResult.dx + searchDistance; tmpSadResult.yidx = (int) tmpSadResult.dy + searchDistance; // what a hack.... return tmpSadResult; } /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param x coordinate x in subSampled space * @param y coordinate y in subSampled space * @param dx * @param dy * @param prevSlice * @param curSlice * @return Hamming Distance value */ private float hammingDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { float retVal = 0, hd = 0; int blockRadius = patchDimension / 2; float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { return 1; } for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice if (currSlicePol != prevSlicePol) { hd += 1; } if (currSlicePol == true) { validPixNumCurrSli += 1; } if (prevSlicePol == true) { validPixNumPrevSli += 1; } } } // TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE // Calculate the metric confidence value float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. retVal = 1; } else { /* retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block. Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. */ retVal = ((hd * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); } return retVal; } /** * Computes hamming weight around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { float minSum = Integer.MAX_VALUE, sum = 0; SADResult sadResult = new SADResult(0, 0, 0); for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice); if (sum <= minSum) { minSum = sum; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSum; } } } return sadResult; } /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSlice * @param curSlice * @return SAD value */ private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { float retVal = 0; float M01 = 0, M10 = 0, M11 = 0; int blockRadius = patchDimension / 2; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { return 1; } for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { M11 += 1; } if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) { M01 += 1; } if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { M10 += 1; } } } if (0 == (M01 + M10 + M11)) { retVal = 0; } else { retVal = M11 / (M01 + M10 + M11); } retVal = 1 - retVal; return retVal; } private SADResult minVicPurDistance(int blockX, int blockY) { ArrayList<Integer[]> seq1 = new ArrayList(1); SADResult sadResult = new SADResult(0, 0, 0); int size = spikeTrains[blockX][blockY].size(); int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0]; for (int i = size - forwardEventNum; i < size; i++) { seq1.add(spikeTrains[blockX][blockY].get(i)); } // if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) { // return sadResult; double minium = Integer.MAX_VALUE; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { // Remove the seq1 itself if ((0 == i) && (0 == j)) { continue; } ArrayList<Integer[]> seq2 = new ArrayList(1); if ((blockX >= 2) && (blockY >= 2)) { ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j]; if (tmpSpikes != null) { for (int index = 0; index < tmpSpikes.size(); index++) { if (tmpSpikes.get(index)[0] >= lastTs) { seq2.add(tmpSpikes.get(index)); } } double dis = vicPurDistance(seq1, seq2); if (dis < minium) { minium = dis; sadResult.dx = -i; sadResult.dy = -j; } } } } } lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1; if ((sadResult.dx != 1) || (sadResult.dy != 0)) { // sadResult = new SADResult(0, 0, 0); } return sadResult; } private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) { int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0; Iterator itr1 = seq1.iterator(); Iterator itr2 = seq2.iterator(); int length1 = seq1.size(); int length2 = seq2.size(); double[][] distanceMatrix = new double[length1 + 1][length2 + 1]; for (int h = 0; h <= length1; h++) { for (int k = 0; k <= length2; k++) { if (h == 0) { distanceMatrix[h][k] = k; continue; } if (k == 0) { distanceMatrix[h][k] = h; continue; } double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1); double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0]; double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0]; distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2))); } } while (itr1.hasNext()) { Integer[] ii = (Integer[]) itr1.next(); if (ii[1] == 1) { sum1Plus += 1; } else { sum1Minus += 1; } } while (itr2.hasNext()) { Integer[] ii = (Integer[]) itr2.next(); if (ii[1] == 1) { sum2Plus += 1; } else { sum2Minus += 1; } } // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus); return distanceMatrix[length1][length2]; } /** * Computes min SAD shift around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) { // for now just do exhaustive search over all shifts up to +/-searchDistance SADResult sadResult = new SADResult(0, 0, 0); float minSad = 1; for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { float sad = sad(x, y, dx, dy, prevSlice, curSlice); if (sad <= minSad) { minSad = sad; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSad; } } } return sadResult; } /** * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate x in subSampled space * @param y coordinate y in subSampled space * @param dx block shift of x * @param dy block shift of y * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { int blockRadius = patchDimension / 2; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { return 1; } float sad = 0, retVal = 0; float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice int d = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0); if (currSlicePol == true) { validPixNumCurrSli += 1; } if (prevSlicePol == true) { validPixNumPrevSli += 1; } if (d <= 0) { d = -d; } sad += d; } } // Calculate the metric confidence value float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. retVal = 1; } else { /* retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block. Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. */ retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); } return retVal; } private class SADResult { float dx, dy; float sadValue; int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW public SADResult(float dx, float dy, float sadValue) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } @Override public String toString() { return String.format("dx,dy=%d,%5 SAD=%d", dx, dy, sadValue); } } /** * @return the patchDimension */ public int getPatchDimension() { return patchDimension; } /** * @param patchDimension the patchDimension to set */ public void setPatchDimension(int patchDimension) { this.patchDimension = patchDimension; putInt("patchDimension", patchDimension); } public int getEventPatchDimension() { return eventPatchDimension; } public void setEventPatchDimension(int eventPatchDimension) { this.eventPatchDimension = eventPatchDimension; putInt("eventPatchDimension", eventPatchDimension); } public int getForwardEventNum() { return forwardEventNum; } public void setForwardEventNum(int forwardEventNum) { this.forwardEventNum = forwardEventNum; putInt("forwardEventNum", forwardEventNum); } public float getCost() { return cost; } public void setCost(float cost) { this.cost = cost; putFloat("cost", cost); } public int getThresholdTime() { return thresholdTime; } public void setThresholdTime(int thresholdTime) { this.thresholdTime = thresholdTime; putInt("thresholdTime", thresholdTime); } /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ public void setSliceMethod(SliceMethod sliceMethod) { this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); } public PatchCompareMethod getPatchCompareMethod() { return patchCompareMethod; } public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) { this.patchCompareMethod = patchCompareMethod; putString("patchCompareMethod", patchCompareMethod.toString()); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { this.sliceDurationUs = sliceDurationUs; putInt("sliceDurationUs", sliceDurationUs); } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); } public boolean isDisplayOutputVectors() { return displayOutputVectors; } public void setDisplayOutputVectors(boolean displayOutputVectors) { this.displayOutputVectors = displayOutputVectors; putBoolean("displayOutputVectors", displayOutputVectors); } public boolean isPreProcessEnable() { return preProcessEnable; } public void setPreProcessEnable(boolean preProcessEnable) { this.preProcessEnable = preProcessEnable; putBoolean("preProcessEnable", preProcessEnable); } public float getConfidenceThreshold() { return confidenceThreshold; } public void setConfidenceThreshold(float confidenceThreshold) { if(confidenceThreshold<0) confidenceThreshold=0; else if(confidenceThreshold>1)confidenceThreshold=1; this.confidenceThreshold = confidenceThreshold; putFloat("confidenceThreshold", confidenceThreshold); } public float getValidPixOccupancy() { return validPixOccupancy; } public void setValidPixOccupancy(float validPixOccupancy) { if(validPixOccupancy<0) validPixOccupancy=0; else if(validPixOccupancy>1)validPixOccupancy=1; this.validPixOccupancy = validPixOccupancy; putFloat("validPixOccupancy", validPixOccupancy); } public float getWeightDistance() { return weightDistance; } public void setWeightDistance(float weightDistance) { if(weightDistance<0)weightDistance=0; else if(weightDistance>1)weightDistance=1; this.weightDistance = weightDistance; putFloat("weightDistance", weightDistance); } private void checkArrays() { if (lastFireIndex == null) { lastFireIndex = new int[chip.getSizeX()][chip.getSizeY()]; } if (eventSeqStartTs == null) { eventSeqStartTs = new int[chip.getSizeX()][chip.getSizeY()]; } } /** * * @param distResult * @return the confidence of the result. True means it's not good and should * be rejected, false means we should accept it. */ public synchronized boolean isNotSufficientlyAccurate(SADResult distResult) { boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true // additional test, normalized blaock distance must be small enough // distance has max value 1 if (distResult.sadValue >= (1-confidenceThreshold)) { retVal = true; } return retVal; } /** * @return the skipProcessingEventsCount */ public int getSkipProcessingEventsCount() { return skipProcessingEventsCount; } /** * @param skipProcessingEventsCount the skipProcessingEventsCount to set */ public void setSkipProcessingEventsCount(int skipProcessingEventsCount) { if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } if (skipProcessingEventsCount > 100) { skipProcessingEventsCount = 100; } this.skipProcessingEventsCount = skipProcessingEventsCount; putInt("skipProcessingEventsCount", skipProcessingEventsCount); } /** * @return the displayResultHistogram */ public boolean isDisplayResultHistogram() { return displayResultHistogram; } /** * @param displayResultHistogram the displayResultHistogram to set */ public void setDisplayResultHistogram(boolean displayResultHistogram) { this.displayResultHistogram = displayResultHistogram; putBoolean("displayResultHistogram",displayResultHistogram); } }
package ch.unizh.ini.jaer.projects.minliu; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import java.util.Arrays; import java.util.Observable; import java.util.Observer; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.EventPacket; /** * Uses patch matching to measure local optical flow. <b>Not</b> gradient based, * but rather matches local features backwards in time. * * @author Tobi, Jan 2016 */ @Description("Computes true flow events with speed and vector direction using binary feature patch matching.") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements Observer { // These const values are for the fast implementation of the hamming weight calculation private final long m1 = 0x5555555555555555L; //binary: 0101... private final long m2 = 0x3333333333333333L; //binary: 00110011.. private final long m4 = 0x0f0f0f0f0f0f0f0fL; //binary: 4 zeros, 4 ones ... private final long m8 = 0x00ff00ff00ff00ffL; //binary: 8 zeros, 8 ones ... private final long m16 = 0x0000ffff0000ffffL; //binary: 16 zeros, 16 ones ... private final long m32 = 0x00000000ffffffffL; //binary: 32 zeros, 32 ones private final long hff = 0xffffffffffffffffL; //binary: all ones private final long h01 = 0x0101010101010101L; //the sum of 256 to the power of 0,1,2,3... private int[][][] histograms = null; private int numSlices = 3; private int sx, sy; private int currentSliceIdx = 0, tMinus1SliceIdx = 1, tMinus2SliceIdx = 2; private int[][] currentSlice = null, tMinus1Slice = null, tMinus2Slice = null; private int patchDimension = getInt("patchDimension", 8); private int sliceDurationUs = getInt("sliceDurationUs", 1000); private int sliceEventCount = getInt("sliceEventCount", 1000); private String patchTT = "Patch matching"; public enum SliceMethod { ConstantDuration, ConstantEventNumber }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.ConstantDuration.toString())); private int eventCounter = 0; private int sliceLastTs = Integer.MIN_VALUE; public PatchMatchFlow(AEChip chip) { super(chip); chip.addObserver(this); // to allocate memory once chip size is known setPropertyTooltip(patchTT, "patchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "timesliceDurationUs", "duration of patches in us"); setPropertyTooltip(patchTT, "sliceEventNumber", "number of collected events in each bitmap"); } @Override public EventPacket filterPacket(EventPacket in) { for (Object ein : in) { extractEventInfo(ein); if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { imuFlowEstimator.calculateImuFlow((ApsDvsEvent) inItr.next()); setGroundTruth(); } if (isInvalidAddress(searchDistance)) { continue; } if (xyFilter()) { continue; } countIn++; // compute flow maybeRotateSlices(); accumulateEvent(); SADResult sadResult=minSad(x, y, tMinus2Slice, tMinus1Slice); // reject values that are unreasonable if (accuracyTests()) { continue; } writeOutputEvent(); if (measureAccuracy) { motionFlowStatistics.update(vx, vy, v, vxGT, vyGT, vGT); } } motionFlowStatistics.updatePacket(countIn, countOut); return isShowRawInputEnabled() ? in : dirPacket; } @Override public synchronized void resetFilter() { super.resetFilter(); eventCounter = 0; lastTs = Integer.MIN_VALUE; if (histograms == null || histograms.length != subSizeX || histograms[0].length != subSizeY) { histograms = new int[numSlices][subSizeX][subSizeY]; } for (int[][] a : histograms) { for (int[] b : a) { Arrays.fill(b, 0); } } currentSliceIdx = 0; tMinus1SliceIdx = 1; tMinus2SliceIdx = 2; assignSliceReferences(); } private void assignSliceReferences() { currentSlice = histograms[currentSliceIdx]; tMinus1Slice = histograms[tMinus1SliceIdx]; tMinus2Slice = histograms[tMinus2SliceIdx]; } @Override public void update(Observable o, Object arg) { super.update(o, arg); if (!isFilterEnabled()) { return; } if (o instanceof AEChip && chip.getNumPixels() > 0) { resetFilter(); } } /** * uses the current event to maybe rotate the slices */ private void maybeRotateSlices() { switch (sliceMethod) { case ConstantDuration: int dt = ts - sliceLastTs; if (dt < sliceDurationUs && dt < 0) { return; } break; case ConstantEventNumber: if (eventCounter++ < sliceEventCount) { return; } } currentSliceIdx = (currentSliceIdx + 1) % numSlices; tMinus1SliceIdx = (tMinus1SliceIdx + 1) % numSlices; tMinus2SliceIdx = (tMinus2SliceIdx + 1) % numSlices; sliceEventCount = 0; sliceLastTs = ts; assignSliceReferences(); } /** * Accumulates the current event to the current slice */ private void accumulateEvent() { currentSlice[x][y] += e.getPolaritySignum(); } private void clearSlice(int idx) { for (int[] a : histograms[idx]) { Arrays.fill(a, 0); } } /** * Computes min SAD shift around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minSad(int x, int y, int[][] prevSlice, int[][] curSlice) { // for now just do exhaustive search over all shifts up to +/-searchDistance SADResult sadResult = new SADResult(0, 0, 0); int minSad = Integer.MAX_VALUE, minDx = 0, minDy = 0; for (int dx = -searchDistance; dx < searchDistance; dx++) { for (int dy = -searchDistance; dy < searchDistance; dy++) { int sad = sad(x, y, dx, dy, prevSlice, curSlice); if (sad <= minSad) { minSad = sad; sadResult.dx = dx; sadResult.dy = dy; } } } return sadResult; } /** * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param dx * @param dy * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private int sad(int x, int y, int dx, int dy, int[][] prevSlice, int[][] curSlice) { if (x < searchDistance || x > subSizeX - searchDistance || y < searchDistance || y > subSizeY - searchDistance) { return 0; } int sad = 0; for (int xx = x - searchDistance; xx < x + searchDistance; x++) { for (int yy = y - searchDistance; yy < y + searchDistance; y++) { int d = prevSlice[xx + dx][yy + dy] - curSlice[xx][yy]; if (d < 0) { d = -d; } sad += d; } } return sad; } //This uses fewer arithmetic operations than any other known //implementation on machines with fast multiplication. //It uses 12 arithmetic operations, one of which is a multiply. public long popcount_3(long x) { x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits return (x * h01)>>56; //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ... } private class SADResult { float dx, dy; float sadValue; public SADResult(float dx, float dy, float sadValue) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } @Override public String toString() { return String.format("dx,dy=%d,%5 SAD=%d",dx,dy,sadValue); } } /** * @return the patchDimension */ public int getPatchDimension() { return patchDimension; } /** * @param patchDimension the patchDimension to set */ public void setPatchDimension(int patchDimension) { this.patchDimension = patchDimension; putInt("patchDimension", patchDimension); } /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ public void setSliceMethod(SliceMethod sliceMethod) { this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { this.sliceDurationUs = sliceDurationUs; putInt("sliceDurationUs", sliceDurationUs); } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); } }
package cgeo.geocaching.connector.gc; import cgeo.geocaching.Geocache; import cgeo.geocaching.ICache; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.cgData; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.connector.AbstractConnector; import cgeo.geocaching.connector.ILoggingManager; import cgeo.geocaching.connector.capability.ILogin; import cgeo.geocaching.connector.capability.ISearchByCenter; import cgeo.geocaching.connector.capability.ISearchByGeocode; import cgeo.geocaching.connector.capability.ISearchByViewPort; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.settings.SettingsActivity; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.Log; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.content.Context; import android.os.Handler; import java.util.regex.Pattern; public class GCConnector extends AbstractConnector implements ISearchByGeocode, ISearchByCenter, ISearchByViewPort, ILogin { private static final String CACHE_URL_SHORT = "http://coord.info/"; // Double slash is used to force open in browser private static final String CACHE_URL_LONG = "http: /** * Pocket queries downloaded from the website use a numeric prefix. The pocket query creator Android app adds a * verbatim "pocketquery" prefix. */ private static final Pattern GPX_ZIP_FILE_PATTERN = Pattern.compile("((\\d{7,})|(pocketquery))" + "(_.+)?" + "\\.zip", Pattern.CASE_INSENSITIVE); /** * Pattern for GC codes */ private final static Pattern PATTERN_GC_CODE = Pattern.compile("GC[0-9A-Z]+", Pattern.CASE_INSENSITIVE); private GCConnector() { // singleton } /** * initialization on demand holder pattern */ private static class Holder { private static final GCConnector INSTANCE = new GCConnector(); } public static GCConnector getInstance() { return Holder.INSTANCE; } @Override public boolean canHandle(String geocode) { if (geocode == null) { return false; } return GCConnector.PATTERN_GC_CODE.matcher(geocode).matches(); } @Override public String getLongCacheUrl(Geocache cache) { return CACHE_URL_LONG + cache.getGeocode(); } @Override public String getCacheUrl(Geocache cache) { return CACHE_URL_SHORT + cache.getGeocode(); } @Override public boolean supportsPersonalNote() { return Settings.isPremiumMember(); } @Override public boolean supportsOwnCoordinates() { return true; } @Override public boolean supportsWatchList() { return true; } @Override public boolean supportsLogging() { return true; } @Override public boolean supportsLogImages() { return true; } @Override public ILoggingManager getLoggingManager(Activity activity, Geocache cache) { return new GCLoggingManager(activity, cache); } @Override public boolean canLog(Geocache cache) { return StringUtils.isNotBlank(cache.getCacheId()); } @Override public String getName() { return "geocaching.com"; } @Override public String getHost() { return "www.geocaching.com"; } @Override public boolean supportsUserActions() { return true; } @Override public SearchResult searchByGeocode(final String geocode, final String guid, final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_loadpage); final String page = GCParser.requestHtmlPage(geocode, guid, "y", String.valueOf(GCConstants.NUMBER_OF_LOGS)); if (StringUtils.isEmpty(page)) { final SearchResult search = new SearchResult(); if (cgData.isThere(geocode, guid, true, false)) { if (StringUtils.isBlank(geocode) && StringUtils.isNotBlank(guid)) { Log.i("Loading old cache from cache."); search.addGeocode(cgData.getGeocodeForGuid(guid)); } else { search.addGeocode(geocode); } search.setError(StatusCode.NO_ERROR); return search; } Log.e("GCConnector.searchByGeocode: No data from server"); search.setError(StatusCode.COMMUNICATION_ERROR); return search; } final SearchResult searchResult = GCParser.parseCache(page, handler); if (searchResult == null || CollectionUtils.isEmpty(searchResult.getGeocodes())) { Log.w("GCConnector.searchByGeocode: No cache parsed"); return searchResult; } // do not filter when searching for one specific cache return searchResult; } @Override public SearchResult searchByViewport(Viewport viewport, String[] tokens) { return GCMap.searchByViewport(viewport, tokens); } @Override public boolean isZippedGPXFile(final String fileName) { return GPX_ZIP_FILE_PATTERN.matcher(fileName).matches(); } @Override public boolean isReliableLatLon(boolean cacheHasReliableLatLon) { return cacheHasReliableLatLon; } @Override public boolean isOwner(final ICache cache) { return StringUtils.equalsIgnoreCase(cache.getOwnerUserId(), Settings.getUsername()); } @Override public boolean addToWatchlist(Geocache cache) { final boolean added = GCParser.addToWatchlist(cache); if (added) { cgData.saveChangedCache(cache); } return added; } @Override public boolean removeFromWatchlist(Geocache cache) { final boolean removed = GCParser.removeFromWatchlist(cache); if (removed) { cgData.saveChangedCache(cache); } return removed; } /** * Add a cache to the favorites list. * * This must not be called from the UI thread. * * @param cache the cache to add * @return <code>true</code> if the cache was sucessfully added, <code>false</code> otherwise */ public static boolean addToFavorites(Geocache cache) { final boolean added = GCParser.addToFavorites(cache); if (added) { cgData.saveChangedCache(cache); } return added; } /** * Remove a cache from the favorites list. * * This must not be called from the UI thread. * * @param cache the cache to add * @return <code>true</code> if the cache was sucessfully added, <code>false</code> otherwise */ public static boolean removeFromFavorites(Geocache cache) { final boolean removed = GCParser.removeFromFavorites(cache); if (removed) { cgData.saveChangedCache(cache); } return removed; } @Override public boolean uploadModifiedCoordinates(Geocache cache, Geopoint wpt) { final boolean uploaded = GCParser.uploadModifiedCoordinates(cache, wpt); if (uploaded) { cgData.saveChangedCache(cache); } return uploaded; } @Override public boolean deleteModifiedCoordinates(Geocache cache) { final boolean deleted = GCParser.deleteModifiedCoordinates(cache); if (deleted) { cgData.saveChangedCache(cache); } return deleted; } @Override public boolean uploadPersonalNote(Geocache cache) { final boolean uploaded = GCParser.uploadPersonalNote(cache); if (uploaded) { cgData.saveChangedCache(cache); } return uploaded; } @Override public SearchResult searchByCenter(Geopoint center) { // TODO make search by coordinate use this method. currently it is just a marker that this connector supports search by center return null; } @Override public boolean supportsFavoritePoints() { return true; } @Override protected String getCacheUrlPrefix() { return CACHE_URL_SHORT; } @Override public boolean isActivated() { return Settings.isGCConnectorActive(); } @Override public int getCacheMapMarkerId(boolean disabled) { if (disabled) { return R.drawable.marker_disabled; } return R.drawable.marker; } @Override public boolean login(Handler handler, Context fromActivity) { // login final StatusCode status = Login.login(); if (status == StatusCode.NO_ERROR) { cgeoapplication.getInstance().checkLogin = false; Login.detectGcCustomDate(); } if (cgeoapplication.getInstance().showLoginToast && handler != null) { handler.sendMessage(handler.obtainMessage(0, status)); cgeoapplication.getInstance().showLoginToast = false; // invoke settings activity to insert login details if (status == StatusCode.NO_LOGIN_INFO_STORED && fromActivity != null) { SettingsActivity.jumpToServicesPage(fromActivity); } } return status == StatusCode.NO_ERROR; } @Override public String getUserName() { return Login.getActualUserName(); } @Override public int getCachesFound() { return Login.getActualCachesFound(); } @Override public String getLoginStatusString() { return Login.getActualStatus(); } @Override public boolean isLoggedIn() { return Login.isActualLoginStatus(); } }
package ch.unizh.ini.jaer.projects.minliu; import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.util.logging.Level; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GL2ES3; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.util.awt.TextRenderer; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.MotionFlowStatistics; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.MotionFlowStatistics.GlobalMotion; import com.jogamp.opengl.GLException; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEInputStream; import net.sf.jaer.eventprocessing.TimeLimiter; import net.sf.jaer.graphics.AEViewer; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.graphics.ImageDisplay; import net.sf.jaer.graphics.ImageDisplay.Legend; import net.sf.jaer.util.DrawGL; import net.sf.jaer.util.EngineeringFormat; import net.sf.jaer.util.TobiLogger; import net.sf.jaer.util.filter.LowpassFilter; import org.apache.commons.lang3.ArrayUtils; /** * Uses adaptive block matching optical flow (ABMOF) to measureTT local optical * flow. <b>Not</b> gradient based, but rather matches local features backwards * in time. * * @author Tobi and Min, Jan 2016 */ @Description("<html>EDFLOW: Computes optical flow with vector direction using SFAST keypoint/corner detection and adaptive time slice block matching (ABMOF) as published in<br>" + "Liu, M., and Delbruck, T. (2018). <a href=\"http://bmvc2018.org/contents/papers/0280.pdf\">Adaptive Time-Slice Block-Matching Optical Flow Algorithm for Dynamic Vision Sensors</a>.<br> in BMVC 2018 (Nescatle upon Tyne)") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements FrameAnnotater { /* LDSP is Large Diamond Search Pattern, and SDSP mens Small Diamond Search Pattern. LDSP has 9 points and SDSP consists of 5 points. */ private static final int LDSP[][] = {{0, -2}, {-1, -1}, {1, -1}, {-2, 0}, {0, 0}, {2, 0}, {-1, 1}, {1, 1}, {0, 2}}; private static final int SDSP[][] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}}; // private int[][][] histograms = null; private int numSlices = 3; //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d volatile private int numScales = getInt("numScales", 3); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d private String scalesToCompute = getString("scalesToCompute", ""); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d private Integer[] scalesToComputeArray = null; // holds array of scales to actually compute, for debugging private int[] scaleResultCounts = new int[numScales]; // holds counts at each scale for min SAD results /** * The computed average possible match distance from 0 motion */ protected float avgPossibleMatchDistance; private static final int MIN_SLICE_EVENT_COUNT_FULL_FRAME = 1000; private static final int MAX_SLICE_EVENT_COUNT_FULL_FRAME = 1000000; // private int sx, sy; private int currentSliceIdx = 0; // the slice we are currently filling with events /** * time slice 2d histograms of (maybe signed) event counts slices = new * byte[numSlices][numScales][subSizeX][subSizeY] [slice][scale][x][y] */ private byte[][][][] slices = null; private float[] sliceSummedSADValues = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration private int[] sliceSummedSADCounts = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration private int[] sliceStartTimeUs; // holds the time interval between reference slice and this slice private int[] sliceEndTimeUs; // holds the time interval between reference slice and this slice private byte[][][] currentSlice; private SADResult lastGoodSadResult = new SADResult(0, 0, 0, 0); // used for consistency check public static final int BLOCK_DIMENSION_DEFAULT = 7; private int blockDimension = getInt("blockDimension", BLOCK_DIMENSION_DEFAULT); // This is the block dimension of the coarse scale. // private float cost = getFloat("cost", 0.001f); public static final float MAX_ALLOWABLE_SAD_DISTANCE_DEFAULT = .5f; private float maxAllowedSadDistance = getFloat("maxAllowedSadDistance", MAX_ALLOWABLE_SAD_DISTANCE_DEFAULT); public static final float VALID_PIXEL_OCCUPANCY_DEFAULT = 0.01f; private float validPixOccupancy = getFloat("validPixOccupancy", VALID_PIXEL_OCCUPANCY_DEFAULT); // threshold for valid pixel percent for one block private float weightDistance = getFloat("weightDistance", 0.95f); // confidence value consists of the distance and the dispersion, this value set the distance value private static final int MAX_SKIP_COUNT = 1000; private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps) private int skipCounter = 0; private boolean adaptiveEventSkipping = getBoolean("adaptiveEventSkipping", true); private float skipChangeFactor = (float) Math.sqrt(2); // by what factor to change the skip count if too slow or too fast private boolean outputSearchErrorInfo = false; // make user choose this slow down every time private boolean adaptiveSliceDuration = getBoolean("adaptiveSliceDuration", true); private boolean adaptiveSliceDurationLogging = false; // for debugging and analyzing control of slice event number/duration private TobiLogger adaptiveSliceDurationLogger = null; private int adaptiveSliceDurationPacketCount = 0; private boolean useSubsampling = getBoolean("useSubsampling", false); private int adaptiveSliceDurationMinVectorsToControl = getInt("adaptiveSliceDurationMinVectorsToControl", 10); private boolean showBlockMatches = getBoolean("showBlockMatches", false); // Display the bitmaps private boolean showSlices = false; // Display the bitmaps private int showSlicesScale = 0; // Display the bitmaps private float adapativeSliceDurationProportionalErrorGain = getFloat("adapativeSliceDurationProportionalErrorGain", 0.05f); // factor by which an error signal on match distance changes slice duration private boolean adapativeSliceDurationUseProportionalControl = getBoolean("adapativeSliceDurationUseProportionalControl", false); private int processingTimeLimitMs = getInt("processingTimeLimitMs", 100); // time limit for processing packet in ms to process OF events (events still accumulate). Overrides the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events. public static final int SLICE_MAX_VALUE_DEFAULT = 15; private int sliceMaxValue = getInt("sliceMaxValue", SLICE_MAX_VALUE_DEFAULT); private boolean rectifyPolarties = getBoolean("rectifyPolarties", false); private int sliceDurationMinLimitUS = getInt("sliceDurationMinLimitUS", 100); private int sliceDurationMaxLimitUS = getInt("sliceDurationMaxLimitUS", 300000); private boolean outlierRejectionEnabled = getBoolean("outlierRejectionEnabled", false); private float outlierRejectionThresholdSigma = getFloat("outlierRejectionThresholdSigma", 2f); protected int outlierRejectionWindowSize = getInt("outlierRejectionWindowSize", 300); private MotionFlowStatistics outlierRejectionMotionFlowStatistics; private TimeLimiter timeLimiter = new TimeLimiter(); // private instance used to accumulate events to slices even if packet has timed out // results histogram for each packet // private int ANGLE_HISTOGRAM_COUNT = 16; // private int[] resultAngleHistogram = new int[ANGLE_HISTOGRAM_COUNT + 1]; private int[][] resultHistogram = null; // private int resultAngleHistogramCount = 0, resultAngleHistogramMax = 0; private int resultHistogramCount; private volatile float avgMatchDistance = 0; // stores average match distance for rendering it private float histStdDev = 0, lastHistStdDev = 0; private float FSCnt = 0, DSCorrectCnt = 0; float DSAverageNum = 0, DSAveError[] = {0, 0}; // Evaluate DS cost average number and the error. // private float lastErrSign = Math.signum(1); // private final String outputFilename; private int sliceDeltaT; // The time difference between two slices used for velocity caluction. For constantDuration, this one is equal to the duration. For constantEventNumber, this value will change. private boolean enableImuTimesliceLogging = false; private TobiLogger imuTimesliceLogger = null; private volatile boolean resetOFHistogramFlag; // signals to reset the OF histogram after it is rendered private float cornerThr = getFloat("cornerThr", 0.2f); private boolean saveSliceGrayImage = false; private PrintWriter dvsWriter = null; private EngineeringFormat engFmt; private TextRenderer textRenderer = null; // These variables are only used by HW_ABMOF. // HW_ABMOF send slice rotation flag so we need to indicate the real rotation timestamp // HW_ABMOF is only supported for davis346Zynq private int curretnRotatTs_HW = 0, tMinus1RotateTs_HW = 0, tMinus2RotateTs_HW = 0; private float deltaTsMs_HW = 0; private boolean HWABMOFEnabled = false; public enum CornerCircleSelection { InnerCircle, OuterCircle, OR, AND } private CornerCircleSelection cornerCircleSelection = CornerCircleSelection.valueOf(getString("cornerCircleSelection", CornerCircleSelection.OuterCircle.name())); // Tobi change to Outer which is the condition used for experimental results in paper protected static String DEFAULT_FILENAME = "jAER.txt"; protected String lastFileName = getString("lastFileName", DEFAULT_FILENAME); public enum PatchCompareMethod { /*JaccardDistance,*/ /*HammingDistance*/ SAD/*, EventSqeDistance*/ }; private PatchCompareMethod patchCompareMethod = null; public enum SearchMethod { FullSearch, DiamondSearch, CrossDiamondSearch }; private SearchMethod searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.DiamondSearch.toString())); private int sliceDurationUs = getInt("sliceDurationUs", 20000); public static final int SLICE_EVENT_COUNT_DEFAULT = 700; private int sliceEventCount = getInt("sliceEventCount", SLICE_EVENT_COUNT_DEFAULT); private boolean rewindFlg = false; // The flag to indicate the rewind event. private boolean displayResultHistogram = getBoolean("displayResultHistogram", true); public enum SliceMethod { ConstantDuration, ConstantEventNumber, AreaEventNumber, ConstantIntegratedFlow }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.AreaEventNumber.toString())); // counting events into subsampled areas, when count exceeds the threshold in any area, the slices are rotated public static final int AREA_EVENT_NUMBER_SUBSAMPLING_DEFAULT = 5; private int areaEventNumberSubsampling = getInt("areaEventNumberSubsampling", AREA_EVENT_NUMBER_SUBSAMPLING_DEFAULT); private int[][] areaCounts = null; private int numAreas = 1; private boolean areaCountExceeded = false; // nongreedy flow evaluation // the entire scene is subdivided into regions, and a bitmap of these regions distributed flow computation more fairly // by only servicing a region when sufficient fraction of other regions have been serviced first private boolean nonGreedyFlowComputingEnabled = getBoolean("nonGreedyFlowComputingEnabled", false); private boolean[][] nonGreedyRegions = null; private int nonGreedyRegionsNumberOfRegions, nonGreedyRegionsCount; /** * This fraction of the regions must be serviced for computing flow before * we reset the nonGreedyRegions map */ private float nonGreedyFractionToBeServiced = getFloat("nonGreedyFractionToBeServiced", .5f); // Print scale count's statics private boolean printScaleCntStatEnabled = getBoolean("printScaleCntStatEnabled", false); // timers and flags for showing filter properties temporarily private final int SHOW_STUFF_DURATION_MS = 4000; private volatile TimerTask stopShowingStuffTask = null; private boolean showBlockSizeAndSearchAreaTemporarily = false; private volatile boolean showAreaCountAreasTemporarily = false; private int eventCounter = 0; private int sliceLastTs = Integer.MAX_VALUE; private JFrame blockMatchingFrame[] = new JFrame[numScales]; private JFrame blockMatchingFrameTarget[] = new JFrame[numScales]; private ImageDisplay blockMatchingImageDisplay[] = new ImageDisplay[numScales]; private ImageDisplay blockMatchingImageDisplayTarget[] = new ImageDisplay[numScales]; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities private Legend blockMatchingDisplayLegend[] = new Legend[numScales]; private Legend blockMatchingDisplayLegendTarget[] = new Legend[numScales]; private static final String LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH = "G: search area\nR: ref block area\nB: best match"; private JFrame sliceBitMapFrame = null; private ImageDisplay sliceBitmapImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities private Legend sliceBitmapImageDisplayLegend; private static final String LEGEND_SLICES = "R: Slice t-d\nG: Slice t-2d"; private JFrame timeStampBlockFrame = null; private ImageDisplay timeStampBlockImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities private Legend timeStampBlockImageDisplayLegend; private static final String TIME_STAMP_BLOCK_LEGEND_SLICES = "R: Inner Circle\nB: Outer Circle\nG: Current event"; private static final int circle1[][] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; private static final int circle2[][] = {{0, 2}, {1, 2}, {2, 1}, {2, 0}, {2, -1}, {1, -2}, {0, -2}, {-1, -2}, {-2, -1}, {-2, 0}, {-2, 1}, {-1, 2}}; private static final int circle3[][] = {{0, 3}, {1, 3}, {2, 2}, {3, 1}, {3, 0}, {3, -1}, {2, -2}, {1, -3}, {0, -3}, {-1, -3}, {-2, -2}, {-3, -1}, {-3, 0}, {-3, 1}, {-2, 2}, {-1, 3}}; private static final int circle4[][] = {{0, 4}, {1, 4}, {2, 3}, {3, 2}, {4, 1}, {4, 0}, {4, -1}, {3, -2}, {2, -3}, {1, -4}, {0, -4}, {-1, -4}, {-2, -3}, {-3, -2}, {-4, -1}, {-4, 0}, {-4, 1}, {-3, 2}, {-2, 3}, {-1, 4}}; int innerCircle[][] = circle1; int innerCircleSize = innerCircle.length; int xInnerOffset[] = new int[innerCircleSize]; int yInnerOffset[] = new int[innerCircleSize]; int innerTsValue[] = new int[innerCircleSize]; int outerCircle[][] = circle2; int outerCircleSize = outerCircle.length; int yOuterOffset[] = new int[outerCircleSize]; int xOuterOffset[] = new int[outerCircleSize]; int outerTsValue[] = new int[outerCircleSize]; private HWCornerPointRenderer keypointFilter = null; /** * A PropertyChangeEvent with this value is fired when the slices has been * rotated. The oldValue is t-2d slice. The newValue is the t-d slice. */ public static final String EVENT_NEW_SLICES = "eventNewSlices"; TobiLogger sadValueLogger = new TobiLogger("sadvalues", "sadvalue,scale"); // TODO debug private boolean calcOFonCornersEnabled = getBoolean("calcOFonCornersEnabled", true); protected boolean useEFASTnotSFAST = getBoolean("useEFASTnotSFAST", false); private final ApsFrameExtractor apsFrameExtractor; // Corner events array; only used for rendering. private boolean showCorners = getBoolean("showCorners", true); protected int cornerSize = getInt("cornerSize", 2); private ArrayList<BasicEvent> cornerEvents = new ArrayList(1000); public PatchMatchFlow(AEChip chip) { super(chip); this.engFmt = new EngineeringFormat(); getEnclosedFilterChain().clear(); // getEnclosedFilterChain().add(new SpatioTemporalCorrelationFilter(chip)); keypointFilter = new HWCornerPointRenderer(chip); apsFrameExtractor = new ApsFrameExtractor(chip); apsFrameExtractor.setShowAPSFrameDisplay(false); getEnclosedFilterChain().add(apsFrameExtractor); // getEnclosedFilterChain().add(keypointFilter); // use for EFAST setSliceDurationUs(getSliceDurationUs()); // 40ms is good for the start of the slice duration adatative since 4ms is too fast and 500ms is too slow. setDefaultScalesToCompute(); // // Save the result to the file // Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss"); // // Instantiate a Date object // Date date = new Date(); // Log file for the OF distribution's statistics // outputFilename = "PMF_HistStdDev" + formatter.format(date) + ".txt"; // String eventSqeMatching = "Event squence matching"; // String preProcess = "Denoise"; try { patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.SAD.toString())); } catch (IllegalArgumentException e) { patchCompareMethod = PatchCompareMethod.SAD; } String hwTip = "0b: Hardware EDFLOW"; setPropertyTooltip(hwTip, "HWABMOFEnabled", "Select to show output of hardware EDFLOW camera"); String cornerTip = "0c: Corners/Keypoints"; setPropertyTooltip(cornerTip, "showCorners", "Select to show corners (as red overlay)"); setPropertyTooltip(cornerTip, "cornerThr", "Threshold difference for SFAST detection as fraction of maximum event count value; increase for fewer corners"); setPropertyTooltip(cornerTip, "calcOFonCornersEnabled", "Calculate OF based on corners or not"); setPropertyTooltip(cornerTip, "cornerCircleSelection", "Determines SFAST circles used for detecting the corner/keypoint"); setPropertyTooltip(cornerTip, "useEFASTnotSFAST", "Use EFAST corner detector, not SFAST which is default"); setPropertyTooltip(cornerTip, "cornerSize", "Dimension WxH of the drawn detector corners in chip pixels"); String patchTT = "0a: Block matching"; // move ppsScale to main top GUI since we use it a lot setPropertyTooltip(patchTT, "ppsScale", "<html>When <i>ppsScaleDisplayRelativeOFLength=false</i>, then this is <br>scale of screen pixels per px/s flow to draw local motion vectors; <br>global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE + "<p>" + "When <i>ppsScaleDisplayRelativeOFLength=true</i>, then local motion vectors are scaled by average speed of flow"); setPropertyTooltip(patchTT, "blockDimension", "Linear dimenion of patches to match on coarse scale, in pixels. Median and fine scale block sizes are scaled up approx by powers of 2."); setPropertyTooltip(patchTT, "searchDistance", "Search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches; SAD=sum of absolute differences, HammingDistance is same as SAD for binary bitmaps"); setPropertyTooltip(patchTT, "searchMethod", "method to search patches"); setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval, when ConstantDuration method is used"); setPropertyTooltip(patchTT, "sliceEventCount", "number of events collected to fill a slice, when ConstantEventNumber method is used"); setPropertyTooltip(patchTT, "sliceMethod", "<html>Method for determining time slice duration for block matching<ul>" + "<li>ConstantDuration: slices are fixed time duration" + "<li>ConstantEventNumber: slices are fixed event number" + "<li>AreaEventNumber: slices are fixed event number in any subsampled area defined by areaEventNumberSubsampling" + "<li>ConstantIntegratedFlow: slices are rotated when average speeds times delta time exceeds half the search distance"); setPropertyTooltip(patchTT, "areaEventNumberSubsampling", "<html>how to subsample total area to count events per unit subsampling blocks for AreaEventNumber method. <p>For example, if areaEventNumberSubsampling=5, <br> then events falling into 32x32 blocks of pixels are counted <br>to determine when they exceed sliceEventCount to make new slice"); setPropertyTooltip(patchTT, "adapativeSliceDurationProportionalErrorGain", "gain for proporportional change of duration or slice event number. typically 0.05f for bang-bang, and 0.5f for proportional control"); setPropertyTooltip(patchTT, "adapativeSliceDurationUseProportionalControl", "If true, then use proportional error control. If false, use bang-bang control with sign of match distance error"); setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)"); setPropertyTooltip(patchTT, "adaptiveEventSkipping", "enables adaptive event skipping depending on free time left in AEViewer animation loop"); setPropertyTooltip(patchTT, "adaptiveSliceDuration", "<html>Enables adaptive slice duration using feedback control, <br> based on average match search distance compared with total search distance. <p>If the match distance is too small, increaes duration or event count, and if too far, decreases duration or event count.<p>If using <i>AreaEventNumber</i> slice rotation method, don't increase count if actual duration is already longer than <i>sliceDurationUs</i>"); setPropertyTooltip(patchTT, "nonGreedyFlowComputingEnabled", "<html>Enables fairer distribution of computing flow by areas; an area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use <i>processingTimeLimitMs</i> to ensure minimum frame rate"); setPropertyTooltip(patchTT, "nonGreedyFractionToBeServiced", "An area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use the timeLimiter to ensure minimum frame rate"); setPropertyTooltip(patchTT, "useSubsampling", "<html>Enables using both full and subsampled block matching; <p>when using adaptiveSliceDuration, enables adaptive slice duration using feedback controlusing difference between full and subsampled resolution slice matching"); setPropertyTooltip(patchTT, "adaptiveSliceDurationMinVectorsToControl", "<html>Min flow vectors computed in packet to control slice duration, increase to reject control during idle periods"); setPropertyTooltip(patchTT, "processingTimeLimitMs", "<html>time limit for processing packet in ms to process OF events (events still accumulate). <br> Set to 0 to disable. <p>Alternative to the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events"); setPropertyTooltip(patchTT, "outputSearchErrorInfo", "enables displaying the search method error information"); setPropertyTooltip(patchTT, "outlierMotionFilteringEnabled", "(Currently has no effect) discards first optical flow event that points in opposite direction as previous one (dot product is negative)"); setPropertyTooltip(patchTT, "numSlices", "<html>Number of bitmaps to use. <p>At least 3: 1 to collect on, and two more to match on. <br>If >3, then best match is found between last slice reference block and all previous slices."); setPropertyTooltip(patchTT, "numScales", "<html>Number of scales to search over for minimum SAD value; 1 for single full resolution scale, 2 for full + 2x2 subsampling, etc."); setPropertyTooltip(patchTT, "sliceMaxValue", "<html> the maximum value used to represent each pixel in the time slice:<br>1 for binary or signed binary slice, (in conjunction with rectifyEventPolarities==true), etc, <br>up to 127 by these byte values"); setPropertyTooltip(patchTT, "rectifyPolarties", "<html> whether to rectify ON and OFF polarities to unsigned counts; true ignores polarity for block matching, false uses polarity with sliceNumBits>1"); setPropertyTooltip(patchTT, "scalesToCompute", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc"); setPropertyTooltip(patchTT, "defaults", "Sets reasonable defaults"); setPropertyTooltip(patchTT, "enableImuTimesliceLogging", "Logs IMU and rate gyro"); setPropertyTooltip(patchTT, "startRecordingForEDFLOW", "Start to record events and its OF result to a file which can be converted to a .bin file for EDFLOW."); setPropertyTooltip(patchTT, "stopRecordingForEDFLOW", "Stop to record events and its OF result to a file which can be converted to a .bin file for EDFLOW."); setPropertyTooltip(patchTT, "sliceDurationMinLimitUS", "The minimum value (us) of slice duration."); setPropertyTooltip(patchTT, "sliceDurationMaxLimitUS", "The maximum value (us) of slice duration."); setPropertyTooltip(patchTT, "outlierRejectionEnabled", "Enable outlier flow vector rejection"); setPropertyTooltip(patchTT, "outlierRejectionThresholdSigma", "Flow vectors that are larger than this many sigma from global flow variation are discarded"); setPropertyTooltip(patchTT, "outlierRejectionWindowSize", "Window in events for measurement of average flow for outlier rejection"); String metricConfid = "0ab: Density checks"; setPropertyTooltip(metricConfid, "maxAllowedSadDistance", "<html>SAD distance threshold for rejecting unresonable block matching result; <br> events with SAD distance larger than this value are rejected. <p>Lower value means it is harder to accept the event. <p> Distance is sum of absolute differences for this best match normalized by number of pixels in reference area."); setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated."); setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0."); String patchDispTT = "0b: Block matching display"; setPropertyTooltip(patchDispTT, "showSlices", "enables displaying the entire bitmaps slices (the current slices)"); setPropertyTooltip(patchDispTT, "showSlicesScale", "sets which scale of the slices to display"); setPropertyTooltip(patchDispTT, "showBlockMatches", "enables displaying the individual block matches"); setPropertyTooltip(patchDispTT, "displayOutputVectors", "display the output motion vectors or not"); setPropertyTooltip(patchDispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance"); setPropertyTooltip(patchDispTT, "printScaleCntStatEnabled", "enables printing the statics of scale counts"); getSupport().addPropertyChangeListener(AEViewer.EVENT_TIMESTAMPS_RESET, this); getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this); getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this); getSupport().addPropertyChangeListener(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, this); computeAveragePossibleMatchDistance(); numInputTypes = 2; // allocate timestamp map } // TODO debug public void doStartLogSadValues() { sadValueLogger.setEnabled(true); } // TODO debug public void doStopLogSadValues() { sadValueLogger.setEnabled(false); } @Override synchronized public EventPacket filterPacket(EventPacket in) { setupFilter(in); checkArrays(); if (processingTimeLimitMs > 0) { timeLimiter.setTimeLimitMs(processingTimeLimitMs); timeLimiter.restart(); } else { timeLimiter.setEnabled(false); } int minDistScale = 0; // following awkward block needed to deal with DVS/DAVIS and IMU/APS events // block STARTS Iterator i = null; if (in instanceof ApsDvsEventPacket) { i = ((ApsDvsEventPacket) in).fullIterator(); } else { i = ((EventPacket) in).inputIterator(); } cornerEvents.clear(); nSkipped = 0; nProcessed = 0; while (i.hasNext()) { Object o = i.next(); if (o == null) { log.warning("null event passed in, returning input packet"); return in; } if ((o instanceof ApsDvsEvent) && ((ApsDvsEvent) o).isApsData()) { continue; } PolarityEvent ein = (PolarityEvent) o; if (!extractEventInfo(o)) { continue; } if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { if (imuFlowEstimator.calculateImuFlow(o)) { continue; } } // block ENDS if (xyFilter()) { continue; } if (isInvalidTimestamp()) { continue; } countIn++; // compute flow SADResult result = null; if (HWABMOFEnabled) // Only use it when there is hardware supported. Hardware is davis346Zynq { SADResult sliceResult = new SADResult(); int data = ein.address & 0x7ff; // The OF result from the hardware has following procotol: // If the data is 0x7ff, it indicates that this result is an invalid result // if the data is 0x7fe, then it means slice rotated on this event, // in this case, only rotation information is included. // Other cases are valid OF data. // The valid OF data is represented in a compressed data format. // It is calculated by OF_x * (2 * maxSearchDistanceRadius + 1) + OF_y. // Therefore, simple decompress is required. if ((data & 0x7ff) == 0x7ff) { continue; } else if ((data & 0x7ff) == 0x7fe) { tMinus2RotateTs_HW = tMinus1RotateTs_HW; tMinus1RotateTs_HW = curretnRotatTs_HW; curretnRotatTs_HW = ts; deltaTsMs_HW = (float) (tMinus1RotateTs_HW - tMinus2RotateTs_HW) / (float) 1000.0; continue; } else { final int searchDistanceHW = 3; // hardcoded on hardware. final int maxSearchDistanceRadius = (4 + 2 + 1) * searchDistanceHW; int OF_x = (data / (2 * maxSearchDistanceRadius + 1)) - maxSearchDistanceRadius; int OF_y = (data % (2 * maxSearchDistanceRadius + 1)) - maxSearchDistanceRadius; sliceResult.dx = -OF_x; sliceResult.dy = OF_y; sliceResult.vx = (float) (1e3 * sliceResult.dx / deltaTsMs_HW); sliceResult.vy = (float) (1e3 * sliceResult.dy / deltaTsMs_HW); result = sliceResult; vx = result.vx; vy = result.vy; v = (float) Math.sqrt((vx * vx) + (vy * vy)); cornerEvents.add(e); } } else { float[] sadVals = new float[numScales]; // TODO debug int[] dxInitVals = new int[numScales]; int[] dyInitVals = new int[numScales]; int rotateFlg = 0; switch (patchCompareMethod) { case SAD: boolean rotated = maybeRotateSlices(); if (rotated) { rotateFlg = 1; adaptSliceDuration(); setResetOFHistogramFlag(); resetOFHistogram(); nCountPerSlicePacket = 0; // Reset counter for next slice packet. } nCountPerSlicePacket++; // if (ein.x >= subSizeX || ein.y > subSizeY) { // log.warning("event out of range"); // continue; if (!accumulateEvent(ein)) { // maybe skip events here if (dvsWriter != null) { dvsWriter.println(String.format("%d %d %d %d %d %d %d %d %d", ein.timestamp, ein.x, ein.y, ein.polarity == PolarityEvent.Polarity.Off ? 0 : 1, 0x7, 0x7, 0, rotateFlg, 0)); } break; } SADResult sliceResult = new SADResult(); minDistScale = 0; boolean OFRetValidFlag = true; // Sorts scalesToComputeArray[] in descending order Arrays.sort(scalesToComputeArray, Collections.reverseOrder()); minDistScale = 0; for (int scale : scalesToComputeArray) { if (scale >= numScales) { // log.warning("scale " + scale + " is out of range of " + numScales + "; fix scalesToCompute for example by clearing it"); // break; } int dx_init = ((result != null) && !isNotSufficientlyAccurate(sliceResult)) ? (sliceResult.dx >> scale) : 0; int dy_init = ((result != null) && !isNotSufficientlyAccurate(sliceResult)) ? (sliceResult.dy >> scale) : 0; // dx_init = 0; // dy_init = 0; // The reason why we inverse dx_init, dy_init i is the offset is pointing from previous slice to current slice. // The dx_init, dy_init are from the corse scale's result, and it is used as the finer scale's initial guess. sliceResult = minSADDistance(ein.x, ein.y, -dx_init, -dy_init, slices[sliceIndex(1)], slices[sliceIndex(2)], scale); // from ref slice to past slice k+1, using scale 0,1,.... // sliceSummedSADValues[sliceIndex(scale + 2)] += sliceResult.sadValue; // accumulate SAD for this past slice // sliceSummedSADCounts[sliceIndex(scale + 2)]++; // accumulate SAD count for this past slice // sliceSummedSADValues should end up filling 2 values for 4 slices sadVals[scale] = sliceResult.sadValue; // TODO debug dxInitVals[scale] = dx_init; dyInitVals[scale] = dy_init; if (sliceResult.sadValue >= this.maxAllowedSadDistance) { OFRetValidFlag = false; break; } else { if ((result == null) || (sliceResult.sadValue < result.sadValue)) { result = sliceResult; // result holds the overall min sad result minDistScale = scale; } } // result=sliceResult; // TODO tobi: override the absolute minimum to always use the finest scale result, which has been guided by coarser scales } result = sliceResult; float dt = (sliceDeltaTimeUs(2) * 1e-6f); if (result != null) { result.vx = result.dx / dt; // hack, convert to pix/second result.vy = result.dy / dt; // TODO clean up, make time for each slice, since could be different when const num events } if (dvsWriter != null) { dvsWriter.println(String.format("%d %d %d %d %d %d %d %d %d", ein.timestamp, ein.x, ein.y, ein.polarity == PolarityEvent.Polarity.Off ? 0 : 1, result.dx, result.dy, OFRetValidFlag ? 1 : 0, rotateFlg, 1)); } break; // case JaccardDistance: // maybeRotateSlices(); // if (!accumulateEvent(in)) { // break; // result = minJaccardDistance(x, y, bitmaps[sliceIndex(2)], bitmaps[sliceIndex(1)]); // float dtj=(sliceDeltaTimeUs(2) * 1e-6f); // result.dx = result.dx / dtj; // result.dy = result.dy / dtj; // break; } if (result == null || result.sadValue == Float.MAX_VALUE) { continue; // maybe some property change caused this } // reject values that are unreasonable if (isNotSufficientlyAccurate(result)) { continue; } scaleResultCounts[minDistScale]++; vx = result.vx; vy = result.vy; v = (float) Math.sqrt((vx * vx) + (vy * vy)); // TODO debug StringBuilder sadValsString = new StringBuilder(); for (int k = 0; k < sadVals.length - 1; k++) { sadValsString.append(String.format("%f,", sadVals[k])); } sadValsString.append(String.format("%f", sadVals[sadVals.length - 1])); // very awkward to prevent trailing , if (sadValueLogger.isEnabled()) { // TODO debug sadValueLogger.log(sadValsString.toString()); } if (showBlockMatches) { // TODO danger, drawing outside AWT thread final SADResult thisResult = result; final PolarityEvent thisEvent = ein; final byte[][][][] thisSlices = slices; // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { drawMatching(thisResult, thisEvent, thisSlices, sadVals, dxInitVals, dyInitVals); // ein.x >> result.scale, ein.y >> result.scale, (int) result.dx >> result.scale, (int) result.dy >> result.scale, slices[sliceIndex(1)][result.scale], slices[sliceIndex(2)][result.scale], result.scale); drawTimeStampBlock(thisEvent); } } if (isOutlierFlowVector(result)) { countOutliers++; continue; } // if (result.dx != 0 || result.dy != 0) { // final int bin = (int) Math.round(ANGLE_HISTOGRAM_COUNT * (Math.atan2(result.dy, result.dx) + Math.PI) / (2 * Math.PI)); // int v = ++resultAngleHistogram[bin]; // resultAngleHistogramCount++; // if (v > resultAngleHistogramMax) { // resultAngleHistogramMax = v; processGoodEvent(); if (resultHistogram != null) { resultHistogram[result.dx + computeMaxSearchDistance()][result.dy + computeMaxSearchDistance()]++; resultHistogramCount++; } lastGoodSadResult.set(result); } motionFlowStatistics.updatePacket(countIn, countOut, ts); outlierRejectionMotionFlowStatistics.updatePacket(countIn, countOut, ts); // float fracOutliers = (float) countOutliers / countIn; // System.out.println(String.format("Fraction of outliers: %.1f%%", 100 * fracOutliers)); adaptEventSkipping(); if (rewindFlg) { rewindFlg = false; for (byte[][][] b : slices) { clearSlice(b); } currentSliceIdx = 0; // start by filling slice 0 currentSlice = slices[currentSliceIdx]; sliceLastTs = Integer.MAX_VALUE; } return isDisplayRawInput() ? in : dirPacket; } public void doDefaults() { setSearchMethod(SearchMethod.DiamondSearch); setBlockDimension(BLOCK_DIMENSION_DEFAULT); setNumScales(3); setSearchDistance(3); setAdaptiveEventSkipping(false); setSkipProcessingEventsCount(0); setProcessingTimeLimitMs(5000); setDisplayVectorsEnabled(true); setPpsScaleDisplayRelativeOFLength(false); setDisplayGlobalMotion(true); setRectifyPolarties(true); // rectify to better handle cases of steadicam where pan/tilt flips event polarities setPpsScale(.1f); setSliceMaxValue(SLICE_MAX_VALUE_DEFAULT); setValidPixOccupancy(VALID_PIXEL_OCCUPANCY_DEFAULT); // at least this fraction of pixels from each block must both have nonzero values setMaxAllowedSadDistance(MAX_ALLOWABLE_SAD_DISTANCE_DEFAULT); setSliceMethod(SliceMethod.AreaEventNumber); setAdaptiveSliceDuration(true); setSliceEventCount(SLICE_EVENT_COUNT_DEFAULT); // compute nearest power of two over block dimension // int ss = (int) (Math.log(blockDimension - 1) / Math.log(2)) + 1; setAreaEventNumberSubsampling(AREA_EVENT_NUMBER_SUBSAMPLING_DEFAULT); // set to paper value // // set event count so that count=block area * sliceMaxValue/4; // // i.e. set count to roll over when slice pixels from most subsampled scale are half full if they are half stimulated // final int eventCount = (((blockDimension * blockDimension) * sliceMaxValue) / 2) >> (numScales - 1); // setSliceEventCount(eventCount); setSliceDurationMinLimitUS(1000); setSliceDurationMaxLimitUS(300000); setSliceDurationUs(50000); // set a bit smaller max duration in us to avoid instability where count gets too high with sparse input setShowCorners(true); setCalcOFonCornersEnabled(true); // Enable corner detector setCornerCircleSelection(CornerCircleSelection.OuterCircle); setCornerThr(0.2f); } private void adaptSliceDuration() { // measure last hist to get control signal on slice duration // measures avg match distance. weights the average so that long distances with more pixels in hist are not overcounted, simply // by having more pixels. if (rewindFlg) { return; // don't adapt during rewind or delay before playing again } float radiusSum = 0; int countSum = 0; // int maxRadius = (int) Math.ceil(Math.sqrt(2 * searchDistance * searchDistance)); // int countSum = 0; final int totSD = computeMaxSearchDistance(); for (int xx = -totSD; xx <= totSD; xx++) { for (int yy = -totSD; yy <= totSD; yy++) { int count = resultHistogram[xx + totSD][yy + totSD]; if (count > 0) { final float radius = (float) Math.sqrt((xx * xx) + (yy * yy)); countSum += count; radiusSum += radius * count; } } } if (countSum > 0) { avgMatchDistance = radiusSum / (countSum); // compute average match distance from reference block } if (adaptiveSliceDuration && (countSum > adaptiveSliceDurationMinVectorsToControl)) { // if (resultHistogramCount > 0) { // following stats not currently used // double[] rstHist1D = new double[resultHistogram.length * resultHistogram.length]; // int index = 0; //// int rstHistMax = 0; // for (int[] resultHistogram1 : resultHistogram) { // for (int element : resultHistogram1) { // rstHist1D[index++] = element; // Statistics histStats = new Statistics(rstHist1D); // // double histMax = Collections.max(Arrays.asList(ArrayUtils.toObject(rstHist1D))); // double histMax = histStats.getMax(); // for (int m = 0; m < rstHist1D.length; m++) { // rstHist1D[m] = rstHist1D[m] / histMax; // lastHistStdDev = histStdDev; // histStdDev = (float) histStats.getStdDev(); // try (FileWriter outFile = new FileWriter(outputFilename,true)) { // outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + histStdDev + "\r\n")); // outFile.close(); // } catch (IOException ex) { // Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); // } catch (Exception e) { // log.warning("Caught " + e + ". See following stack trace."); // e.printStackTrace(); // float histMean = (float) histStats.getMean(); // compute error signal. // If err<0 it means the average match distance is larger than target avg match distance, so we need to reduce slice duration // If err>0, it means the avg match distance is too short, so increse time slice final float err = avgMatchDistance / (avgPossibleMatchDistance); // use target that is smaller than average possible to bound excursions to large slices better // final float err = avgPossibleMatchDistance / 2 - avgMatchDistance; // use target that is smaller than average possible to bound excursions to large slices better // final float err = ((searchDistance << (numScales - 1)) / 2) - avgMatchDistance; // final float lastErr = searchDistance / 2 - lastHistStdDev; // final double err = histMean - 1/ (rstHist1D.length * rstHist1D.length); float errSign = Math.signum(err - 1); // float avgSad2 = sliceSummedSADValues[sliceIndex(4)] / sliceSummedSADCounts[sliceIndex(4)]; // float avgSad3 = sliceSummedSADValues[sliceIndex(3)] / sliceSummedSADCounts[sliceIndex(3)]; // float errSign = avgSad2 <= avgSad3 ? 1 : -1; // if(Math.abs(err) > Math.abs(lastErr)) { // errSign = -errSign; // if(histStdDev >= 0.14) { // if(lastHistStdDev > histStdDev) { // errSign = -lastErrSign; // } else { // errSign = lastErrSign; // errSign = 1; // } else { // errSign = (float) Math.signum(err); // lastErrSign = errSign; // problem with following is that if sliceDurationUs gets really big, then of course the avgMatchDistance becomes small because // of the biased-towards-zero search policy that selects the closest match switch (sliceMethod) { case ConstantDuration: if (adapativeSliceDurationUseProportionalControl) { // proportional setSliceDurationUs(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceDurationUs)); } else { // bang bang int durChange = (int) (-errSign * adapativeSliceDurationProportionalErrorGain * sliceDurationUs); setSliceDurationUs(sliceDurationUs + durChange); } break; case ConstantEventNumber: case AreaEventNumber: if (adapativeSliceDurationUseProportionalControl) { // proportional setSliceEventCount(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceEventCount)); } else { if (errSign < 0) { // match distance too short, increase duration // match too short, increase count setSliceEventCount(Math.round(sliceEventCount * (1 + adapativeSliceDurationProportionalErrorGain))); } else if (errSign > 0) { // match too long, decrease duration setSliceEventCount(Math.round(sliceEventCount * (1 - adapativeSliceDurationProportionalErrorGain))); } } break; case ConstantIntegratedFlow: setSliceEventCount(eventCounter); } if (adaptiveSliceDurationLogger != null && adaptiveSliceDurationLogger.isEnabled()) { if (!isDisplayGlobalMotion()) { setDisplayGlobalMotion(true); } adaptiveSliceDurationLogger.log(String.format("%f\t%d\t%d\t%f\t%f\t%f\t%d\t%d", e.timestamp * 1e-6f, adaptiveSliceDurationPacketCount++, nCountPerSlicePacket, avgMatchDistance, err, motionFlowStatistics.getGlobalMotion().getGlobalSpeed().getMean(), sliceDeltaT, sliceEventCount)); } } } private void setResetOFHistogramFlag() { resetOFHistogramFlag = true; } private void clearResetOFHistogramFlag() { resetOFHistogramFlag = false; } private void resetOFHistogram() { if (!resetOFHistogramFlag || resultHistogram == null) { return; } for (int[] h : resultHistogram) { Arrays.fill(h, 0); } resultHistogramCount = 0; // Arrays.fill(resultAngleHistogram, 0); // resultAngleHistogramCount = 0; // resultAngleHistogramMax = Integer.MIN_VALUE; // Print statics of scale count, only for debuuging. if (printScaleCntStatEnabled) { float sumScaleCounts = 0; for (int scale : scalesToComputeArray) { sumScaleCounts += scaleResultCounts[scale]; } for (int scale : scalesToComputeArray) { System.out.println("Scale " + scale + " count percentage is: " + scaleResultCounts[scale] / sumScaleCounts); } } Arrays.fill(scaleResultCounts, 0); clearResetOFHistogramFlag(); } @Override synchronized public void annotate(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); // first draw corners if (showCorners) { gl.glLineWidth(getMotionVectorLineWidthPixels()); gl.glColor4f(.5f, 0, 0, 0.5f); for (BasicEvent e : cornerEvents) { gl.glPushMatrix(); DrawGL.drawCross(gl, e.x, e.y, getCornerSize(), 0); gl.glPopMatrix(); } } super.annotate(drawable); try { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glBlendEquation(GL.GL_FUNC_ADD); } catch (GLException e) { e.printStackTrace(); } // then on top, draw the motion vectors if (displayResultHistogram && (resultHistogram != null)) { // draw histogram as shaded in 2d hist above color wheel // normalize hist int rhDim = resultHistogram.length; // this.computeMaxSearchDistance(); gl.glPushMatrix(); final float scale = 30f / rhDim; // size same as the color wheel gl.glTranslatef(-35, .65f * chip.getSizeY(), 0); // center above color wheel gl.glScalef(scale, scale, 1); gl.glColor3f(0, 0, 1); gl.glLineWidth(2f); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(0, 0); gl.glVertex2f(rhDim, 0); gl.glVertex2f(rhDim, rhDim); gl.glVertex2f(0, rhDim); gl.glEnd(); if (textRenderer == null) { textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 64)); } int max = 0; for (int[] h : resultHistogram) { for (int vv : h) { if (vv > max) { max = vv; } } } if (max == 0) { gl.glTranslatef(0, rhDim / 2, 0); // translate to UL corner of histogram textRenderer.begin3DRendering(); textRenderer.draw3D("No data", 0, 0, 0, .07f); textRenderer.end3DRendering(); gl.glPopMatrix(); } else { final float maxRecip = 2f / max; gl.glPushMatrix(); // draw hist values for (int xx = 0; xx < rhDim; xx++) { for (int yy = 0; yy < rhDim; yy++) { float g = maxRecip * resultHistogram[xx][yy]; gl.glColor3f(g, g, g); gl.glBegin(GL2ES3.GL_QUADS); gl.glVertex2f(xx, yy); gl.glVertex2f(xx + 1, yy); gl.glVertex2f(xx + 1, yy + 1); gl.glVertex2f(xx, yy + 1); gl.glEnd(); } } final int tsd = computeMaxSearchDistance(); if (avgMatchDistance > 0) { gl.glPushMatrix(); gl.glColor4f(1f, 0, 0, .5f); gl.glLineWidth(5f); DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgMatchDistance, 16); gl.glPopMatrix(); } if (avgPossibleMatchDistance > 0) { gl.glPushMatrix(); gl.glColor4f(0, 1f, 0, .5f); gl.glLineWidth(5f); DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgPossibleMatchDistance, 16); // draw circle at target match distance gl.glPopMatrix(); } // a bunch of cryptic crap to draw a string the same width as the histogram... gl.glPopMatrix(); gl.glPopMatrix(); // back to original chip coordinates gl.glPushMatrix(); textRenderer.begin3DRendering(); String s = String.format("dt=%.1f ms", 1e-3f * sliceDeltaT); // final float sc = TextRendererScale.draw3dScale(textRenderer, s, chip.getCanvas().getScale(), chip.getWidth(), .1f); // determine width of string in pixels and scale accordingly FontRenderContext frc = textRenderer.getFontRenderContext(); Rectangle2D r = textRenderer.getBounds(s); // bounds in java2d coordinates, downwards more positive Rectangle2D rt = frc.getTransform().createTransformedShape(r).getBounds2D(); // get bounds in textrenderer coordinates // float ps = chip.getCanvas().getScale(); float w = (float) rt.getWidth(); // width of text in textrenderer, i.e. histogram cell coordinates (1 unit = 1 histogram cell) float sc = subSizeX / w / 6; // scale to histogram width gl.glTranslatef(0, .65f * subSizeY, 0); // translate to UL corner of histogram textRenderer.draw3D(s, 0, 0, 0, sc); String s2 = String.format("Skip: %d", skipProcessingEventsCount); textRenderer.draw3D(s2, 0, (float) (rt.getHeight()) * sc, 0, sc); String s3 = String.format("Slice events: %d", sliceEventCount); textRenderer.draw3D(s3, 0, 2 * (float) (rt.getHeight()) * sc, 0, sc); StringBuilder sb = new StringBuilder("Scale counts: "); for (int c : scaleResultCounts) { sb.append(String.format("%d ", c)); } textRenderer.draw3D(sb.toString(), 0, (float) (3 * rt.getHeight()) * sc, 0, sc); if (timeLimiter.isTimedOut()) { String s4 = String.format("Timed out: skipped %,d events", nSkipped); textRenderer.draw3D(s4, 0, 4 * (float) (rt.getHeight()) * sc, 0, sc); } if (outlierRejectionEnabled) { String s5 = String.format("Outliers: %%%.0f", 100 * (float) countOutliers / countIn); textRenderer.draw3D(s5, 0, 5 * (float) (rt.getHeight()) * sc, 0, sc); } textRenderer.end3DRendering(); gl.glPopMatrix(); // back to original chip coordinates // log.info(String.format("processed %.1f%% (%d/%d)", 100 * (float) nProcessed / (nSkipped + nProcessed), nProcessed, (nProcessed + nSkipped))); // // draw histogram of angles around center of image // if (resultAngleHistogramCount > 0) { // gl.glPushMatrix(); // gl.glTranslatef(subSizeX / 2, subSizeY / 2, 0); // gl.glLineWidth(getMotionVectorLineWidthPixels()); // gl.glColor3f(1, 1, 1); // gl.glBegin(GL.GL_LINES); // for (int i = 0; i < ANGLE_HISTOGRAM_COUNT; i++) { // float l = ((float) resultAngleHistogram[i] / resultAngleHistogramMax) * chip.getMinSize() / 2; // bin 0 is angle -PI // double angle = ((2 * Math.PI * i) / ANGLE_HISTOGRAM_COUNT) - Math.PI; // float dx = (float) Math.cos(angle) * l, dy = (float) Math.sin(angle) * l; // gl.glVertex2f(0, 0); // gl.glVertex2f(dx, dy); // gl.glEnd(); // gl.glPopMatrix(); } } if (sliceMethod == SliceMethod.AreaEventNumber && showAreaCountAreasTemporarily) { int d = 1 << areaEventNumberSubsampling; gl.glLineWidth(2f); gl.glColor3f(1, 1, 1); gl.glBegin(GL.GL_LINES); for (int x = 0; x <= subSizeX; x += d) { gl.glVertex2f(x, 0); gl.glVertex2f(x, subSizeY); } for (int y = 0; y <= subSizeY; y += d) { gl.glVertex2f(0, y); gl.glVertex2f(subSizeX, y); } gl.glEnd(); } if (sliceMethod == SliceMethod.ConstantIntegratedFlow && showAreaCountAreasTemporarily) { // TODO fill in what to draw } if (showBlockSizeAndSearchAreaTemporarily) { gl.glLineWidth(2f); gl.glColor3f(1, 0, 0); // show block size final int xx = subSizeX / 2, yy = subSizeY / 2, d = blockDimension / 2; gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(xx - d, yy - d); gl.glVertex2f(xx + d, yy - d); gl.glVertex2f(xx + d, yy + d); gl.glVertex2f(xx - d, yy + d); gl.glEnd(); // show search area gl.glColor3f(0, 1, 0); final int sd = d + (searchDistance << (numScales - 1)); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(xx - sd, yy - sd); gl.glVertex2f(xx + sd, yy - sd); gl.glVertex2f(xx + sd, yy + sd); gl.glVertex2f(xx - sd, yy + sd); gl.glEnd(); } } @Override public void initFilter() { super.initFilter(); checkForEASTCornerDetectorEnclosedFilter(); outlierRejectionMotionFlowStatistics = new MotionFlowStatistics(this.getClass().getSimpleName(), subSizeX, subSizeY, outlierRejectionWindowSize); outlierRejectionMotionFlowStatistics.setMeasureGlobalMotion(true); } @Override public synchronized void resetFilter() { setSubSampleShift(0); // filter breaks with super's bit shift subsampling super.resetFilter(); eventCounter = 0; // lastTs = Integer.MIN_VALUE; checkArrays(); if (slices == null) { return; // on reset maybe chip is not set yet } for (byte[][][] b : slices) { clearSlice(b); } // currentSliceIdx = 0; // start by filling slice 0 // currentSlice = slices[currentSliceIdx]; // sliceLastTs = Integer.MAX_VALUE; rewindFlg = true; if (adaptiveEventSkippingUpdateCounterLPFilter != null) { adaptiveEventSkippingUpdateCounterLPFilter.reset(); } clearAreaCounts(); clearNonGreedyRegions(); // setSliceEventCount(getInt("sliceEventCount", SLICE_EVENT_COUNT_DEFAULT)); } private LowpassFilter speedFilter = new LowpassFilter(); /** * uses the current event to maybe rotate the slices * * @return true if slices were rotated */ private boolean maybeRotateSlices() { int dt = ts - sliceLastTs; if (dt < 0) { // handle timestamp wrapping // System.out.println("rotated slices at "); // System.out.println("rotated slices with dt= "+dt); rotateSlices(); eventCounter = 0; sliceDeltaT = dt; sliceLastTs = ts; return true; } switch (sliceMethod) { case ConstantDuration: if ((dt < sliceDurationUs)) { return false; } break; case ConstantEventNumber: if (eventCounter < sliceEventCount) { return false; } break; case AreaEventNumber: // If dt is too small, we should rotate it later until it has enough accumulation time. if (!areaCountExceeded && dt < getSliceDurationMaxLimitUS() || (dt < getSliceDurationMinLimitUS())) { return false; } break; case ConstantIntegratedFlow: speedFilter.setTauMs(sliceDeltaTimeUs(2) >> 10); final float meanGlobalSpeed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed; if (!Float.isNaN(meanGlobalSpeed)) { speedFilter.filter(meanGlobalSpeed, ts); } final float filteredMeanGlobalSpeed = speedFilter.getValue(); final float totalMovement = filteredMeanGlobalSpeed * dt * 1e-6f; if (Float.isNaN(meanGlobalSpeed)) { // we need to rotate slices somwhow even if there is no motion computed yet if (eventCounter < sliceEventCount) { return false; } if ((dt < sliceDurationUs)) { return false; } break; } if (totalMovement < searchDistance / 2 && dt < sliceDurationUs) { return false; } break; } rotateSlices(); /* Slices have been rotated */ getSupport().firePropertyChange(PatchMatchFlow.EVENT_NEW_SLICES, slices[sliceIndex(1)], slices[sliceIndex(2)]); return true; } void saveAPSImage() { byte[] grayImageBuffer = new byte[sizex * sizey]; for (int y = 0; y < sizey; y++) { for (int x = 0; x < sizex; x++) { final int idx = x + (sizey - y - 1) * chip.getSizeX(); float bufferValue = apsFrameExtractor.getRawFrame()[idx]; grayImageBuffer[x + y * chip.getSizeX()] = (byte) (int) (bufferValue * 0.5f); } } final BufferedImage theImage = new BufferedImage(chip.getSizeX(), chip.getSizeY(), BufferedImage.TYPE_BYTE_GRAY); theImage.getRaster().setDataElements(0, 0, sizex, sizey, grayImageBuffer); final Date d = new Date(); final String PNG = "png"; final String fn = "ApsFrame-" + sliceEndTimeUs[sliceIndex(1)] + "." + PNG; // if user is playing a file, use folder that file lives in String userDir = Paths.get(".").toAbsolutePath().normalize().toString(); File APSFrmaeDir = new File(userDir + File.separator + "APSFrames" + File.separator + getChip().getAeInputStream().getFile().getName()); if (!APSFrmaeDir.exists()) { APSFrmaeDir.mkdirs(); } File outputfile = new File(APSFrmaeDir + File.separator + fn); try { ImageIO.write(theImage, "png", outputfile); } catch (IOException ex) { Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); } } /** * Rotates slices by incrementing the slice pointer with rollover back to * zero, and sets currentSliceIdx and currentBitmap. Clears the new * currentBitmap. Thus the slice pointer increments. 0,1,2,0,1,2 * */ private void rotateSlices() { if (e != null) { sliceEndTimeUs[currentSliceIdx] = e.timestamp; } /*Thus if 0 is current index for current filling slice, then sliceIndex returns 1,2 for pointer =1,2. * Then if NUM_SLICES=3, after rotateSlices(), currentSliceIdx=NUM_SLICES-1=2, and sliceIndex(0)=2, sliceIndex(1)=0, sliceIndex(2)=1. */ sliceSummedSADValues[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation sliceSummedSADCounts[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation currentSliceIdx if (currentSliceIdx < 0) { currentSliceIdx = numSlices - 1; } currentSlice = slices[currentSliceIdx]; //sliceStartTimeUs[currentSliceIdx] = ts; // current event timestamp; set on first event to slice clearSlice(currentSlice); clearAreaCounts(); eventCounter = 0; sliceDeltaT = ts - sliceLastTs; sliceLastTs = ts; if (imuTimesliceLogger != null && imuTimesliceLogger.isEnabled()) { imuTimesliceLogger.log(String.format("%d %d %.3f", ts, sliceDeltaT, imuFlowEstimator.getPanRateDps())); } saveSliceGrayImage = true; // if(e.timestamp == 213686212) // saveAPSImage(); // saveSliceGrayImage = true; if (isShowSlices() && !rewindFlg) { // TODO danger, drawing outside AWT thread final byte[][][][] thisSlices = slices; // log.info("making runnable to draw slices in EDT"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // will grab this instance. if called from AWT via e.g. slider, then can deadlock if we also invokeAndWait to draw something in ViewLoop drawSlices(thisSlices); } }); } } /** * Returns index to slice given pointer, with zero as current filling slice * pointer. * * * @param pointer how many slices in the past to index for. I.e.. 0 for * current slice (one being currently filled), 1 for next oldest, 2 for * oldest (when using NUM_SLICES=3). * @return index into bitmaps[] */ private int sliceIndex(int pointer) { return (currentSliceIdx + pointer) % numSlices; } /** * returns slice delta time in us from reference slice * * @param pointer how many slices in the past to index for. I.e.. 0 for * current slice (one being currently filled), 1 for next oldest, 2 for * oldest (when using NUM_SLICES=3). Only meaningful for pointer>=2, * currently exactly only pointer==2 since we are using only 3 slices. * * Modified to compute the delta time using the average of start and end * timestamps of each slices, i.e. the slice time "midpoint" where midpoint * is defined by average of first and last timestamp. * */ protected int sliceDeltaTimeUs(int pointer) { // System.out.println("dt(" + pointer + ")=" + (sliceStartTimeUs[sliceIndex(1)] - sliceStartTimeUs[sliceIndex(pointer)])); int idxOlder = sliceIndex(pointer), idxYounger = sliceIndex(1); int tOlder = (sliceStartTimeUs[idxOlder] + sliceEndTimeUs[idxOlder]) / 2; int tYounger = (sliceStartTimeUs[idxYounger] + sliceEndTimeUs[idxYounger]) / 2; int dt = tYounger - tOlder; return dt; } private int nSkipped = 0, nProcessed = 0, nCountPerSlicePacket = 0; /** * Accumulates the current event to the current slice * * @return true if subsequent processing should done, false if it should be * skipped for efficiency */ synchronized private boolean accumulateEvent(PolarityEvent e) { if (eventCounter++ == 0) { sliceStartTimeUs[currentSliceIdx] = e.timestamp; // current event timestamp } for (int s = 0; s < numScales; s++) { final int xx = e.x >> s; final int yy = e.y >> s; // if (xx >= currentSlice[legendString].length || yy > currentSlice[legendString][xx].length) { // log.warning("event out of range"); // return false; int cv = currentSlice[s][xx][yy]; cv += rectifyPolarties ? 1 : (e.polarity == PolarityEvent.Polarity.On ? 1 : -1); // cv = cv << (numScales - 1 - legendString); if (cv > sliceMaxValue) { cv = sliceMaxValue; } else if (cv < -sliceMaxValue) { cv = -sliceMaxValue; } currentSlice[s][xx][yy] = (byte) cv; } if (sliceMethod == SliceMethod.AreaEventNumber) { if (areaCounts == null) { clearAreaCounts(); } int c = ++areaCounts[e.x >> areaEventNumberSubsampling][e.y >> areaEventNumberSubsampling]; if (c >= sliceEventCount) { areaCountExceeded = true; // int count=0, sum=0, sum2=0; // StringBuilder sb=new StringBuilder("Area counts:\n"); // for(int[] i:areaCounts){ // for(int j:i){ // count++; // sum+=j; // sum2+=j*j; // sb.append(String.format("%6d ",j)); // sb.append("\n"); // float m=(float)sum/count; // float legendString=(float)Math.sqrt((float)sum2/count-m*m); // sb.append(String.format("mean=%.1f, std=%.1f",m,legendString)); // log.info("area count stats "+sb.toString()); } } // detect if keypoint here boolean isEASTCorner = (useEFASTnotSFAST && ((e.getAddress() & 1) == 1)); // supported only HWCornerPointRender or HW EFAST is used boolean isBFASTCorner = PatchFastDetectorisFeature(e); boolean isCorner = (useEFASTnotSFAST && isEASTCorner) || (!useEFASTnotSFAST && isBFASTCorner); if (calcOFonCornersEnabled && !isCorner) { return false; } else { cornerEvents.add(e); } // now finally compute flow if (timeLimiter.isTimedOut()) { nSkipped++; return false; } if (nonGreedyFlowComputingEnabled) { // only process the event for flow if most of the other regions have already been processed int xx = e.x >> areaEventNumberSubsampling, yy = e.y >> areaEventNumberSubsampling; boolean didArea = nonGreedyRegions[xx][yy]; if (!didArea) { nonGreedyRegions[xx][yy] = true; nonGreedyRegionsCount++; if (nonGreedyRegionsCount >= (int) (nonGreedyFractionToBeServiced * nonGreedyRegionsNumberOfRegions)) { clearNonGreedyRegions(); } nProcessed++; return true; // skip counter is ignored } else { nSkipped++; return false; } } if (skipProcessingEventsCount == 0) { nProcessed++; return true; } if (skipCounter++ < skipProcessingEventsCount) { nSkipped++; return false; } nProcessed++; skipCounter = 0; return true; } // private void clearSlice(int idx) { // for (int[] a : histograms[idx]) { // Arrays.fill(a, 0); private float sumArray[][] = null; /** * Computes block matching image difference best match around point x,y * using blockDimension and searchDistance and scale * * @param x coordinate in subsampled space * @param y * @param dx_init initial offset * @param dy_init * @param prevSlice the slice over which we search for best match * @param curSlice the slice from which we get the reference block * @param subSampleBy the scale to compute this SAD on, 0 for full * resolution, 1 for 2x2 subsampled block bitmap, etc * @return SADResult that provides the shift and SAD value */ // private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { private SADResult minSADDistance(int x, int y, int dx_init, int dy_init, byte[][][] curSlice, byte[][][] prevSlice, int subSampleBy) { SADResult result = new SADResult(); float minSum = Float.MAX_VALUE, sum; float FSDx = 0, FSDy = 0, DSDx = 0, DSDy = 0; // This is for testing the DS search accuracy. final int searchRange = (2 * searchDistance) + 1; // The maximum search distance in this subSampleBy slice if ((sumArray == null) || (sumArray.length != searchRange)) { sumArray = new float[searchRange][searchRange]; } else { for (float[] row : sumArray) { Arrays.fill(row, Float.MAX_VALUE); } } if (outputSearchErrorInfo) { searchMethod = SearchMethod.FullSearch; } else { searchMethod = getSearchMethod(); } final int xsub = (x >> subSampleBy) + dx_init; final int ysub = (y >> subSampleBy) + dy_init; final int r = ((blockDimension) / 2) << (numScales - 1 - subSampleBy); int w = subSizeX >> subSampleBy, h = subSizeY >> subSampleBy; // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception. // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle if (xsub - r - searchDistance < 0 || xsub + r + searchDistance >= 1 * w || ysub - r - searchDistance < 0 || ysub + r + searchDistance >= 1 * h) { result.sadValue = Float.MAX_VALUE; // return very large distance for this match so it is not selected result.scale = subSampleBy; return result; } switch (searchMethod) { case DiamondSearch: // SD = small diamond, LD=large diamond SP=search process /* The center of the LDSP or SDSP could change in the iteration process, so we need to use a variable to represent it. In the first interation, it's the Zero Motion Potion (ZMP). */ int xCenter = x, yCenter = y; /* x offset of center point relative to ZMP, y offset of center point to ZMP. x offset of center pointin positive number to ZMP, y offset of center point in positive number to ZMP. */ int dx, dy, xidx, yidx; // x and y best match offsets in pixels, indices of these in 2d hist int minPointIdx = 0; // Store the minimum point index. boolean SDSPFlg = false; // If this flag is set true, then it means LDSP search is finished and SDSP search could start. /* If one block has been already calculated, the computedFlg will be set so we don't to do the calculation again. */ boolean computedFlg[][] = new boolean[searchRange][searchRange]; for (boolean[] row : computedFlg) { Arrays.fill(row, false); } if (searchDistance == 1) { // LDSP search can only be applied for search distance >= 2. SDSPFlg = true; } int iterationsLeft = searchRange * searchRange; while (!SDSPFlg) { /* 1. LDSP search */ for (int pointIdx = 0; pointIdx < LDSP.length; pointIdx++) { dx = (LDSP[pointIdx][0] + xCenter) - x; dy = (LDSP[pointIdx][1] + yCenter) - y; xidx = dx + searchDistance; yidx = dy + searchDistance; // Point to be searched is out of search area, skip it. if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) { continue; } /* We just calculate the blocks that haven't been calculated before */ if (computedFlg[xidx][yidx] == false) { sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy); computedFlg[xidx][yidx] = true; if (outputSearchErrorInfo) { DSAverageNum++; } if (outputSearchErrorInfo) { if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { // TODO huh? this is never true, compares to itself log.warning("It seems that there're some bugs in the DS algorithm."); } } } if (sumArray[xidx][yidx] <= minSum) { minSum = sumArray[xidx][yidx]; minPointIdx = pointIdx; } } /* 2. Check the minimum value position is in the center or not. */ xCenter = xCenter + LDSP[minPointIdx][0]; yCenter = yCenter + LDSP[minPointIdx][1]; if (minPointIdx == 4) { // It means it's in the center, so we should break the loop and go to SDSP search. SDSPFlg = true; } if (--iterationsLeft < 0) { log.warning("something is wrong with diamond search; did not find min in SDSP search"); SDSPFlg = true; } } /* 3. SDSP Search */ for (int[] element : SDSP) { dx = (element[0] + xCenter) - x; dy = (element[1] + yCenter) - y; xidx = dx + searchDistance; yidx = dy + searchDistance; // Point to be searched is out of search area, skip it. if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) { continue; } /* We just calculate the blocks that haven't been calculated before */ if (computedFlg[xidx][yidx] == false) { sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy); computedFlg[xidx][yidx] = true; if (outputSearchErrorInfo) { DSAverageNum++; } if (outputSearchErrorInfo) { if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { log.warning("It seems that there're some bugs in the DS algorithm."); } } } if (sumArray[xidx][yidx] <= minSum) { minSum = sumArray[xidx][yidx]; result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction result.dy = -dy - dy_init; result.sadValue = minSum; } // // debug // if(result.dx==-searchDistance && result.dy==-searchDistance){ // System.out.println(result); } if (outputSearchErrorInfo) { DSDx = result.dx; DSDy = result.dy; } break; case FullSearch: if ((e.timestamp) == 81160149) { System.out.printf("Scale %d with Refblock is: \n", subSampleBy); int xscale = (x >> subSampleBy); int yscale = (y >> subSampleBy); for (int xx = xscale - r; xx <= (xscale + r); xx++) { for (int yy = yscale - r; yy <= (yscale + r); yy++) { System.out.printf("%d\t", curSlice[subSampleBy][xx][yy]); } System.out.printf("\n"); } System.out.printf("\n"); System.out.printf("Tagblock is: \n"); for (int xx = xscale + dx_init - r - searchDistance; xx <= (xscale + dx_init + r + searchDistance); xx++) { for (int yy = yscale + dy_init - r - searchDistance; yy <= (yscale + dy_init + r + searchDistance); yy++) { System.out.printf("%d\t", prevSlice[subSampleBy][xx][yy]); } System.out.printf("\n"); } } for (dx = -searchDistance; dx <= searchDistance; dx++) { for (dy = -searchDistance; dy <= searchDistance; dy++) { sum = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy); sumArray[dx + searchDistance][dy + searchDistance] = sum; if (sum < minSum) { minSum = sum; result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction result.dy = -dy - dy_init; result.sadValue = minSum; } } } // System.out.printf("result is %s: \n", result.toString()); if (outputSearchErrorInfo) { FSCnt += 1; FSDx = result.dx; FSDy = result.dy; } else { break; } case CrossDiamondSearch: break; } // compute the indices into 2d histogram of all motion vector results. // It's a bit complicated because of multiple scales. // Also, we want the indexes to be centered in the histogram array so that searches at full scale appear at the middle // of the array and not at 0,0 corner. // Suppose searchDistance=1 and numScales=2. Then the histogram has size 2*2+1=5. // Therefore the scale 0 results need to have offset added to them to center results in histogram that // shows results over all scales. result.scale = subSampleBy; // convert dx in search steps to dx in pixels including subsampling // compute index assuming no subsampling or centering result.xidx = (result.dx + dx_init) + searchDistance; result.yidx = (result.dy + dy_init) + searchDistance; // compute final dx and dy including subsampling result.dx = (result.dx) << subSampleBy; result.dy = (result.dy) << subSampleBy; // compute final index including subsampling and centering // idxCentering is shift needed to be applyed to store this result finally into the hist, final int idxCentering = (searchDistance << (numScales - 1)) - ((searchDistance) << subSampleBy); // i.e. for subSampleBy=0 and numScales=2, shift=1 so that full scale search is centered in 5x5 hist result.xidx = (result.xidx << subSampleBy) + idxCentering; result.yidx = (result.yidx << subSampleBy) + idxCentering; // if (result.xidx < 0 || result.yidx < 0 || result.xidx > maxIdx || result.yidx > maxIdx) { // log.warning("something wrong with result=" + result); // return null; if (outputSearchErrorInfo) { if ((DSDx == FSDx) && (DSDy == FSDy)) { DSCorrectCnt += 1; } else { DSAveError[0] += Math.abs(DSDx - FSDx); DSAveError[1] += Math.abs(DSDy - FSDy); } if (0 == (FSCnt % 10000)) { log.log(Level.INFO, "Correct Diamond Search times are {0}, Full Search times are {1}, accuracy is {2}, averageNumberPercent is {3}, averageError is ({4}, {5})", new Object[]{DSCorrectCnt, FSCnt, DSCorrectCnt / FSCnt, DSAverageNum / (searchRange * searchRange * FSCnt), DSAveError[0] / FSCnt, DSAveError[1] / (FSCnt - DSCorrectCnt)}); } } // if (tmpSadResult.xidx == searchRange-1 && tmpSadResult.yidx == searchRange-1) { // tmpSadResult.sadValue = 1; // reject results to top right that are likely result of ambiguous search return result; } /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param xfull coordinate x in full resolution * @param yfull coordinate y in full resolution * @param dx the offset in pixels in the subsampled space of the past slice. * The motion vector is then *from* this position *to* the current slice. * @param dy * @param prevSlice * @param curSlice * @param subsampleBy the scale to search over * @return Distance value, max 1 when all pixels differ, min 0 when all the * same */ private float sadDistance(final int xfull, final int yfull, final int dx, final int dy, final byte[][][] curSlice, final byte[][][] prevSlice, final int subsampleBy) { final int x = xfull >> subsampleBy; final int y = yfull >> subsampleBy; final int r = ((blockDimension) / 2) << (numScales - 1 - subsampleBy); // int w = subSizeX >> subsampleBy, h = subSizeY >> subsampleBy; // int adx = dx > 0 ? dx : -dx; // abs val of dx and dy, to compute limits // int ady = dy > 0 ? dy : -dy; // // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception. // // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle // if (x - r - adx < 0 || x + r + adx >= w // || y - r - ady < 0 || y + r + ady >= h) { // return 1; // tobi changed to 1 again // Float.MAX_VALUE; // return very large distance for this match so it is not selected int validPixNumCurSlice = 0, validPixNumPrevSlice = 0; // The valid pixel number in the current block int nonZeroMatchCount = 0; // int saturatedPixNumCurSlice = 0, saturatedPixNumPrevSlice = 0; // The valid pixel number in the current block int sumDist = 0; // try { for (int xx = x - r; xx <= (x + r); xx++) { for (int yy = y - r; yy <= (y + r); yy++) { // if (xx < 0 || yy < 0 || xx >= w || yy >= h // || xx + dx < 0 || yy + dy < 0 || xx + dx >= w || yy + dy >= h) { //// log.warning("out of bounds slice access; something wrong"); // TODO fix this check above // continue; int currSliceVal = curSlice[subsampleBy][xx][yy]; // binary value on (xx, yy) for current slice int prevSliceVal = prevSlice[subsampleBy][xx + dx][yy + dy]; // binary value on (xx, yy) for previous slice at offset dx,dy in (possibly subsampled) slice int dist = (currSliceVal - prevSliceVal); if (dist < 0) { dist = (-dist); } sumDist += dist; // if (currSlicePol != prevSlicePol) { // hd += 1; // if (currSliceVal == sliceMaxValue || currSliceVal == -sliceMaxValue) { // saturatedPixNumCurSlice++; // pixels that are not saturated // if (prevSliceVal == sliceMaxValue || prevSliceVal == -sliceMaxValue) { // saturatedPixNumPrevSlice++; if (currSliceVal != 0) { validPixNumCurSlice++; // pixels that are not saturated } if (prevSliceVal != 0) { validPixNumPrevSlice++; } if (currSliceVal != 0 && prevSliceVal != 0) { nonZeroMatchCount++; // pixels that both have events in them } } } // } catch (ArrayIndexOutOfBoundsException ex) { // log.warning(ex.toString()); // debug // if(dx==-1 && dy==-1) return 0; else return Float.MAX_VALUE; sumDist = sumDist; final int blockDim = (2 * r) + 1; final int blockArea = (blockDim) * (blockDim); // TODO check math here for fraction correct with subsampling // TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE // Calculate the metric confidence value final int minValidPixNum = (int) (this.validPixOccupancy * blockArea); // final int maxSaturatedPixNum = (int) ((1 - this.validPixOccupancy) * blockArea); final float sadNormalizer = 1f / (blockArea * (rectifyPolarties ? 2 : 1) * sliceMaxValue); // if current or previous block has insufficient pixels with values or if all the pixels are filled up, then reject match if ((validPixNumCurSlice < minValidPixNum) || (validPixNumPrevSlice < minValidPixNum) || (nonZeroMatchCount < minValidPixNum) // || (saturatedPixNumCurSlice >= maxSaturatedPixNum) || (saturatedPixNumPrevSlice >= maxSaturatedPixNum) ) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. return 1; // tobi changed to 1 to represent max distance // Float.MAX_VALUE; } else { /* retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block. Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. */ final float finalDistance = sadNormalizer * ((sumDist * weightDistance) + (Math.abs(validPixNumCurSlice - validPixNumPrevSlice) * (1 - weightDistance))); return finalDistance; } } /** * Computes hamming weight around point x,y using blockDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ // private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { // private SADResult minJaccardDistance(int x, int y, byte[][] prevSlice, byte[][] curSlice) { // float minSum = Integer.MAX_VALUE, sum = 0; // SADResult sadResult = new SADResult(0, 0, 0); // for (int dx = -searchDistance; dx <= searchDistance; dx++) { // for (int dy = -searchDistance; dy <= searchDistance; dy++) { // sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice); // if (sum <= minSum) { // minSum = sum; // sadResult.dx = dx; // sadResult.dy = dy; // sadResult.sadValue = minSum; // return sadResult; /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSlice * @param curSlice * @return SAD value */ // private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { private float jaccardDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) { float M01 = 0, M10 = 0, M11 = 0; int blockRadius = blockDimension / 2; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { return 1; // changed back to 1 // Float.MAX_VALUE; } for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { final boolean c = curSlice[xx][yy], p = prevSlice[xx - dx][yy - dy]; if ((c == true) && (p == true)) { M11 += 1; } if ((c == true) && (p == false)) { M01 += 1; } if ((c == false) && (p == true)) { M10 += 1; } // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { // M11 += 1; // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) { // M01 += 1; // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { // M10 += 1; } } float retVal; if (0 == (M01 + M10 + M11)) { retVal = 0; } else { retVal = M11 / (M01 + M10 + M11); } retVal = 1 - retVal; return retVal; } // private SADResult minVicPurDistance(int blockX, int blockY) { // ArrayList<Integer[]> seq1 = new ArrayList(1); // SADResult sadResult = new SADResult(0, 0, 0); // int size = spikeTrains[blockX][blockY].size(); // int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0]; // for (int i = size - forwardEventNum; i < size; i++) { // seq1.appendCopy(spikeTrains[blockX][blockY].get(i)); //// if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) { //// return sadResult; // double minium = Integer.MAX_VALUE; // for (int i = -1; i < 2; i++) { // for (int j = -1; j < 2; j++) { // // Remove the seq1 itself // if ((0 == i) && (0 == j)) { // continue; // ArrayList<Integer[]> seq2 = new ArrayList(1); // if ((blockX >= 2) && (blockY >= 2)) { // ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j]; // if (tmpSpikes != null) { // for (int index = 0; index < tmpSpikes.size(); index++) { // if (tmpSpikes.get(index)[0] >= lastTs) { // seq2.appendCopy(tmpSpikes.get(index)); // double dis = vicPurDistance(seq1, seq2); // if (dis < minium) { // minium = dis; // sadResult.dx = -i; // sadResult.dy = -j; // lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1; // if ((sadResult.dx != 1) || (sadResult.dy != 0)) { // // sadResult = new SADResult(0, 0, 0); // return sadResult; // private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) { // int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0; // Iterator itr1 = seq1.iterator(); // Iterator itr2 = seq2.iterator(); // int length1 = seq1.size(); // int length2 = seq2.size(); // double[][] distanceMatrix = new double[length1 + 1][length2 + 1]; // for (int h = 0; h <= length1; h++) { // for (int k = 0; k <= length2; k++) { // if (h == 0) { // distanceMatrix[h][k] = k; // continue; // if (k == 0) { // distanceMatrix[h][k] = h; // continue; // double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1); // double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0]; // double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0]; // distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2))); // while (itr1.hasNext()) { // Integer[] ii = (Integer[]) itr1.next(); // if (ii[1] == 1) { // sum1Plus += 1; // } else { // sum1Minus += 1; // while (itr2.hasNext()) { // Integer[] ii = (Integer[]) itr2.next(); // if (ii[1] == 1) { // sum2Plus += 1; // } else { // sum2Minus += 1; // // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus); // return distanceMatrix[length1][length2]; // /** // * Computes min SAD shift around point x,y using blockDimension and // * searchDistance // * // * @param x coordinate in subsampled space // * @param y // * @param prevSlice // * @param curSlice // * @return SADResult that provides the shift and SAD value // */ // private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) { // // for now just do exhaustive search over all shifts up to +/-searchDistance // SADResult sadResult = new SADResult(0, 0, 0); // float minSad = 1; // for (int dx = -searchDistance; dx <= searchDistance; dx++) { // for (int dy = -searchDistance; dy <= searchDistance; dy++) { // float sad = sad(x, y, dx, dy, prevSlice, curSlice); // if (sad <= minSad) { // minSad = sad; // sadResult.dx = dx; // sadResult.dy = dy; // sadResult.sadValue = minSad; // return sadResult; // /** // * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx // * relative to curSliceIdx patch. // * // * @param x coordinate x in subSampled space // * @param y coordinate y in subSampled space // * @param dx block shift of x // * @param dy block shift of y // * @param prevSliceIdx // * @param curSliceIdx // * @return SAD value // */ // private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { // int blockRadius = blockDimension / 2; // // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. // if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) // || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { // return Float.MAX_VALUE; // float sad = 0, retVal = 0; // float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block // for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { // for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { // boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice // boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice // int imuWarningDialog = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0); // if (currSlicePol == true) { // validPixNumCurrSli += 1; // if (prevSlicePol == true) { // validPixNumPrevSli += 1; // if (imuWarningDialog <= 0) { // imuWarningDialog = -imuWarningDialog; // sad += imuWarningDialog; // // Calculate the metric confidence value // float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); // if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. // retVal = 1; // } else { // /* // retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block. // Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. // Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. // */ // retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); // return retVal; private class SADResult { int dx, dy; // best match offset in pixels to reference block from past slice block, i.e. motion vector points in this direction float vx, vy; // optical flow in pixels/second corresponding to this match float sadValue; // sum of absolute differences for this best match normalized by number of pixels in reference area int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW. dx, dy may be negative, like (-1, -1) represents SW. // However, for histgram index, it's not possible to use negative number. That's the reason for intrducing xidx and yidx. // boolean minSearchedFlg = false; // The flag indicates that this minimum have been already searched before. int scale; /** * Allocates new results initialized to zero */ public SADResult() { this(0, 0, 0, 0); } public SADResult(int dx, int dy, float sadValue, int scale) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } public void set(SADResult s) { this.dx = s.dx; this.dy = s.dy; this.sadValue = s.sadValue; this.xidx = s.xidx; this.yidx = s.yidx; this.scale = s.scale; } @Override public String toString() { return String.format("(dx,dy=%5d,%5d), (vx,vy=%.1f,%.1f px/s), SAD=%f, scale=%d", dx, dy, vx, vy, sadValue, scale); } } private class Statistics { double[] data; int size; public Statistics(double[] data) { this.data = data; size = data.length; } double getMean() { double sum = 0.0; for (double a : data) { sum += a; } return sum / size; } double getVariance() { double mean = getMean(); double temp = 0; for (double a : data) { temp += (a - mean) * (a - mean); } return temp / size; } double getStdDev() { return Math.sqrt(getVariance()); } public double median() { Arrays.sort(data); if ((data.length % 2) == 0) { return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0; } return data[data.length / 2]; } public double getMin() { Arrays.sort(data); return data[0]; } public double getMax() { Arrays.sort(data); return data[data.length - 1]; } } /** * @return the blockDimension */ public int getBlockDimension() { return blockDimension; } /** * @param blockDimension the blockDimension to set */ synchronized public void setBlockDimension(int blockDimension) { int old = this.blockDimension; // enforce odd value if ((blockDimension & 1) == 0) { // even if (blockDimension > old) { blockDimension++; } else { blockDimension } } // clip final value if (blockDimension < 1) { blockDimension = 1; } else if (blockDimension > 63) { blockDimension = 63; } this.blockDimension = blockDimension; getSupport().firePropertyChange("blockDimension", old, blockDimension); putInt("blockDimension", blockDimension); showBlockSizeAndSearchAreaTemporarily(); } /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ synchronized public void setSliceMethod(SliceMethod sliceMethod) { SliceMethod old = this.sliceMethod; this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); if (sliceMethod == SliceMethod.AreaEventNumber || sliceMethod == SliceMethod.ConstantIntegratedFlow) { showAreasForAreaCountsTemporarily(); } // if(sliceMethod==SliceMethod.ConstantIntegratedFlow){ // setDisplayGlobalMotion(true); getSupport().firePropertyChange("sliceMethod", old, this.sliceMethod); } public PatchCompareMethod getPatchCompareMethod() { return patchCompareMethod; } synchronized public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) { this.patchCompareMethod = patchCompareMethod; putString("patchCompareMethod", patchCompareMethod.toString()); } /** * * @return the search method */ public SearchMethod getSearchMethod() { return searchMethod; } /** * * @param searchMethod the method to be used for searching */ synchronized public void setSearchMethod(SearchMethod searchMethod) { SearchMethod old = this.searchMethod; this.searchMethod = searchMethod; putString("searchMethod", searchMethod.toString()); getSupport().firePropertyChange("searchMethod", old, this.searchMethod); } private int computeMaxSearchDistance() { int sumScales = 0; for (int i = 0; i < numScales; i++) { sumScales += (1 << i); } return searchDistance * sumScales; } private void computeAveragePossibleMatchDistance() { int n = 0; double s = 0; for (int xx = -searchDistance; xx <= searchDistance; xx++) { for (int yy = -searchDistance; yy <= searchDistance; yy++) { n++; s += Math.sqrt((xx * xx) + (yy * yy)); } } double d = s / n; // avg for one scale double s2 = 0; for (int i = 0; i < numScales; i++) { s2 += d * (1 << i); } double d2 = s2 / numScales; avgPossibleMatchDistance = (float) d2; log.info(String.format("searchDistance=%d numScales=%d: avgPossibleMatchDistance=%.1f", searchDistance, numScales, avgPossibleMatchDistance)); } @Override synchronized public void setSearchDistance(int searchDistance) { int old = this.searchDistance; if (searchDistance > 12) { searchDistance = 12; } else if (searchDistance < 1) { searchDistance = 1; // limit size } this.searchDistance = searchDistance; putInt("searchDistance", searchDistance); getSupport().firePropertyChange("searchDistance", old, searchDistance); resetFilter(); showBlockSizeAndSearchAreaTemporarily(); computeAveragePossibleMatchDistance(); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { int old = this.sliceDurationUs; if (sliceDurationUs < getSliceDurationMinLimitUS()) { sliceDurationUs = getSliceDurationMinLimitUS(); } else if (sliceDurationUs > getSliceDurationMaxLimitUS()) { sliceDurationUs = getSliceDurationMaxLimitUS(); // limit it to one second } this.sliceDurationUs = sliceDurationUs; /* If the slice duration is changed, reset FSCnt and DScorrect so we can get more accurate evaluation result */ FSCnt = 0; DSCorrectCnt = 0; putInt("sliceDurationUs", sliceDurationUs); getSupport().firePropertyChange("sliceDurationUs", old, this.sliceDurationUs); } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { final int div = sliceMethod == SliceMethod.AreaEventNumber ? numAreas : 1; final int old = this.sliceEventCount; if (sliceEventCount < MIN_SLICE_EVENT_COUNT_FULL_FRAME / div) { sliceEventCount = MIN_SLICE_EVENT_COUNT_FULL_FRAME / div; } else if (sliceEventCount > MAX_SLICE_EVENT_COUNT_FULL_FRAME / div) { sliceEventCount = MAX_SLICE_EVENT_COUNT_FULL_FRAME / div; } this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); getSupport().firePropertyChange("sliceEventCount", old, this.sliceEventCount); } public float getMaxAllowedSadDistance() { return maxAllowedSadDistance; } public void setMaxAllowedSadDistance(float maxAllowedSadDistance) { float old = this.maxAllowedSadDistance; if (maxAllowedSadDistance < 0) { maxAllowedSadDistance = 0; } else if (maxAllowedSadDistance > 1) { maxAllowedSadDistance = 1; } this.maxAllowedSadDistance = maxAllowedSadDistance; putFloat("maxAllowedSadDistance", maxAllowedSadDistance); getSupport().firePropertyChange("maxAllowedSadDistance", old, this.maxAllowedSadDistance); } public float getValidPixOccupancy() { return validPixOccupancy; } public void setValidPixOccupancy(float validPixOccupancy) { float old = this.validPixOccupancy; if (validPixOccupancy < 0) { validPixOccupancy = 0; } else if (validPixOccupancy > 1) { validPixOccupancy = 1; } this.validPixOccupancy = validPixOccupancy; putFloat("validPixOccupancy", validPixOccupancy); getSupport().firePropertyChange("validPixOccupancy", old, this.validPixOccupancy); } public float getWeightDistance() { return weightDistance; } public void setWeightDistance(float weightDistance) { if (weightDistance < 0) { weightDistance = 0; } else if (weightDistance > 1) { weightDistance = 1; } this.weightDistance = weightDistance; putFloat("weightDistance", weightDistance); } // private int totalFlowEvents=0, filteredOutFlowEvents=0; // private boolean filterOutInconsistentEvent(SADResult result) { // if (!isOutlierMotionFilteringEnabled()) { // return false; // totalFlowEvents++; // if (lastGoodSadResult == null) { // return false; // if (result.dx * lastGoodSadResult.dx + result.dy * lastGoodSadResult.dy >= 0) { // return false; // filteredOutFlowEvents++; // return true; synchronized private void checkArrays() { if (subSizeX == 0 || subSizeY == 0) { return; // don't do on init when chip is not known yet } // numSlices = getInt("numSlices", 3); // since resetFilter is called in super before numSlices is even initialized if (slices == null || slices.length != numSlices || slices[0] == null || slices[0].length != numScales) { if (numScales > 0 && numSlices > 0) { // deal with filter reconstruction where these fields are not set slices = new byte[numSlices][numScales][][]; for (int n = 0; n < numSlices; n++) { for (int s = 0; s < numScales; s++) { int nx = (subSizeX >> s) + 1 + blockDimension, ny = (subSizeY >> s) + 1 + blockDimension; if (slices[n][s] == null || slices[n][s].length != nx || slices[n][s][0] == null || slices[n][s][0].length != ny) { slices[n][s] = new byte[nx][ny]; } } } currentSliceIdx = 0; // start by filling slice 0 currentSlice = slices[currentSliceIdx]; sliceLastTs = Integer.MAX_VALUE; sliceStartTimeUs = new int[numSlices]; sliceEndTimeUs = new int[numSlices]; sliceSummedSADValues = new float[numSlices]; sliceSummedSADCounts = new int[numSlices]; } // log.info("allocated slice memory"); } // if (lastTimesMap != null) { // lastTimesMap = null; // save memory int rhDim = 2 * computeMaxSearchDistance() + 1; // e.g. coarse to fine search strategy if ((resultHistogram == null) || (resultHistogram.length != rhDim)) { resultHistogram = new int[rhDim][rhDim]; resultHistogramCount = 0; } checkNonGreedyRegionsAllocated(); } /** * * @param distResult * @return the confidence of the result. True means it's not good and should * be rejected, false means we should accept it. */ private synchronized boolean isNotSufficientlyAccurate(SADResult distResult) { boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true // additional test, normalized blaock distance must be small enough // distance has max value 1 if (distResult.sadValue >= maxAllowedSadDistance) { retVal = true; } return retVal; } /** * @return the skipProcessingEventsCount */ public int getSkipProcessingEventsCount() { return skipProcessingEventsCount; } /** * @param skipProcessingEventsCount the skipProcessingEventsCount to set */ public void setSkipProcessingEventsCount(int skipProcessingEventsCount) { int old = this.skipProcessingEventsCount; if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } if (skipProcessingEventsCount > MAX_SKIP_COUNT) { skipProcessingEventsCount = MAX_SKIP_COUNT; } this.skipProcessingEventsCount = skipProcessingEventsCount; getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); putInt("skipProcessingEventsCount", skipProcessingEventsCount); } /** * @return the displayResultHistogram */ public boolean isDisplayResultHistogram() { return displayResultHistogram; } /** * @param displayResultHistogram the displayResultHistogram to set */ public void setDisplayResultHistogram(boolean displayResultHistogram) { this.displayResultHistogram = displayResultHistogram; putBoolean("displayResultHistogram", displayResultHistogram); } /** * @return the adaptiveEventSkipping */ public boolean isAdaptiveEventSkipping() { return adaptiveEventSkipping; } /** * @param adaptiveEventSkipping the adaptiveEventSkipping to set */ synchronized public void setAdaptiveEventSkipping(boolean adaptiveEventSkipping) { boolean old = this.adaptiveEventSkipping; this.adaptiveEventSkipping = adaptiveEventSkipping; putBoolean("adaptiveEventSkipping", adaptiveEventSkipping); if (adaptiveEventSkipping && adaptiveEventSkippingUpdateCounterLPFilter != null) { adaptiveEventSkippingUpdateCounterLPFilter.reset(); } getSupport().firePropertyChange("adaptiveEventSkipping", old, this.adaptiveEventSkipping); } public boolean isOutputSearchErrorInfo() { return outputSearchErrorInfo; } public boolean isShowBlockMatches() { return showBlockMatches; } /** * @param showBlockMatches * @param showBlockMatches the option of displaying bitmap */ synchronized public void setShowBlockMatches(boolean showBlockMatches) { boolean old = this.showBlockMatches; this.showBlockMatches = showBlockMatches; putBoolean("showBlockMatches", showBlockMatches); getSupport().firePropertyChange("showBlockMatches", old, this.showBlockMatches); } public boolean isShowSlices() { return showSlices; } /** * @param showSlices * @param showSlices the option of displaying bitmap */ synchronized public void setShowSlices(boolean showSlices) { boolean old = this.showSlices; this.showSlices = showSlices; getSupport().firePropertyChange("showSlices", old, this.showSlices); putBoolean("showSlices", showSlices); } synchronized public void setOutputSearchErrorInfo(boolean outputSearchErrorInfo) { this.outputSearchErrorInfo = outputSearchErrorInfo; if (!outputSearchErrorInfo) { searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.FullSearch.toString())); // make sure method is reset } } private LowpassFilter adaptiveEventSkippingUpdateCounterLPFilter = null; private int adaptiveEventSkippingUpdateCounter = 0; private void adaptEventSkipping() { if (!adaptiveEventSkipping) { return; } if (chip.getAeViewer() == null) { return; } int old = skipProcessingEventsCount; if (chip.getAeViewer().isPaused() || chip.getAeViewer().isSingleStep()) { skipProcessingEventsCount = 0; getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); } if (adaptiveEventSkippingUpdateCounterLPFilter == null) { adaptiveEventSkippingUpdateCounterLPFilter = new LowpassFilter(chip.getAeViewer().getFrameRater().FPS_LOWPASS_FILTER_TIMECONSTANT_MS); } final float averageFPS = chip.getAeViewer().getFrameRater().getAverageFPS(); final int frameRate = chip.getAeViewer().getDesiredFrameRate(); boolean skipMore = averageFPS < (int) (0.75f * frameRate); boolean skipLess = averageFPS > (int) (0.25f * frameRate); float newSkipCount = skipProcessingEventsCount; if (skipMore) { newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter(1 + (skipChangeFactor * skipProcessingEventsCount), 1000 * (int) System.currentTimeMillis()); } else if (skipLess) { newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter((skipProcessingEventsCount / skipChangeFactor) - 1, 1000 * (int) System.currentTimeMillis()); } skipProcessingEventsCount = Math.round(newSkipCount); if (skipProcessingEventsCount > MAX_SKIP_COUNT) { skipProcessingEventsCount = MAX_SKIP_COUNT; } else if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); } /** * @return the adaptiveSliceDuration */ public boolean isAdaptiveSliceDuration() { return adaptiveSliceDuration; } /** * @param adaptiveSliceDuration the adaptiveSliceDuration to set */ synchronized public void setAdaptiveSliceDuration(boolean adaptiveSliceDuration) { boolean old = this.adaptiveSliceDuration; this.adaptiveSliceDuration = adaptiveSliceDuration; putBoolean("adaptiveSliceDuration", adaptiveSliceDuration); if (adaptiveSliceDurationLogging) { if (adaptiveSliceDurationLogger == null) { adaptiveSliceDurationLogger = new TobiLogger("PatchMatchFlow-SliceDurationControl", "slice duration or event count control logging"); adaptiveSliceDurationLogger.setColumnHeaderLine("eventTsSec\tpacketNumber\tpacketEvenNumber\tavgMatchDistance\tmatchRadiusError\tglobalTranslationSpeedPPS\tsliceDurationUs\tsliceEventCount"); adaptiveSliceDurationLogger.setSeparator("\t"); } adaptiveSliceDurationLogger.setEnabled(adaptiveSliceDuration); } getSupport().firePropertyChange("adaptiveSliceDuration", old, this.adaptiveSliceDuration); } /** * @return the processingTimeLimitMs */ public int getProcessingTimeLimitMs() { return processingTimeLimitMs; } /** * @param processingTimeLimitMs the processingTimeLimitMs to set */ public void setProcessingTimeLimitMs(int processingTimeLimitMs) { this.processingTimeLimitMs = processingTimeLimitMs; putInt("processingTimeLimitMs", processingTimeLimitMs); } /** * clears all scales for a particular time slice * * @param slice [scale][x][y] */ private void clearSlice(byte[][][] slice) { for (byte[][] scale : slice) { // for each scale for (byte[] row : scale) { // for each col Arrays.fill(row, (byte) 0); // fill col } } } private int dim = blockDimension + (2 * searchDistance); /** * Draws the block matching bitmap * * @param x * @param y * @param dx * @param dy * @param refBlock * @param searchBlock * @param subSampleBy */ synchronized private void drawMatching(SADResult result, PolarityEvent ein, byte[][][][] slices, float[] sadVals, int[] dxInitVals, int[] dyInitVals) { // synchronized private void drawMatching(int x, int y, int dx, int dy, byte[][] refBlock, byte[][] searchBlock, int subSampleBy) { for (int dispIdx = 0; dispIdx < numScales; dispIdx++) { int x = ein.x >> dispIdx, y = ein.y >> dispIdx; int dx = (int) result.dx >> dispIdx, dy = (int) result.dy >> dispIdx; byte[][] refBlock = slices[sliceIndex(1)][dispIdx], searchBlock = slices[sliceIndex(2)][dispIdx]; int subSampleBy = dispIdx; Legend sadLegend = null; final int refRadius = (blockDimension / 2) << (numScales - 1 - dispIdx); int dimNew = refRadius * 2 + 1 + (2 * (searchDistance)); if (blockMatchingFrame[dispIdx] == null) { String windowName = "Ref Block " + dispIdx; blockMatchingFrame[dispIdx] = new JFrame(windowName); blockMatchingFrame[dispIdx].setLayout(new BoxLayout(blockMatchingFrame[dispIdx].getContentPane(), BoxLayout.Y_AXIS)); blockMatchingFrame[dispIdx].setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); blockMatchingImageDisplay[dispIdx] = ImageDisplay.createOpenGLCanvas(); blockMatchingImageDisplay[dispIdx].setBorderSpacePixels(10); blockMatchingImageDisplay[dispIdx].setImageSize(dimNew, dimNew); blockMatchingImageDisplay[dispIdx].setSize(200, 200); blockMatchingImageDisplay[dispIdx].setGrayValue(0); blockMatchingDisplayLegend[dispIdx] = blockMatchingImageDisplay[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(blockMatchingImageDisplay[dispIdx]); blockMatchingFrame[dispIdx].getContentPane().add(panel); blockMatchingFrame[dispIdx].pack(); blockMatchingFrame[dispIdx].addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowBlockMatches(false); } }); } if (!blockMatchingFrame[dispIdx].isVisible()) { blockMatchingFrame[dispIdx].setVisible(true); } if (blockMatchingFrameTarget[dispIdx] == null) { String windowName = "Target Block " + dispIdx; blockMatchingFrameTarget[dispIdx] = new JFrame(windowName); blockMatchingFrameTarget[dispIdx].setLayout(new BoxLayout(blockMatchingFrameTarget[dispIdx].getContentPane(), BoxLayout.Y_AXIS)); blockMatchingFrameTarget[dispIdx].setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); blockMatchingImageDisplayTarget[dispIdx] = ImageDisplay.createOpenGLCanvas(); blockMatchingImageDisplayTarget[dispIdx].setBorderSpacePixels(10); blockMatchingImageDisplayTarget[dispIdx].setImageSize(dimNew, dimNew); blockMatchingImageDisplayTarget[dispIdx].setSize(200, 200); blockMatchingImageDisplayTarget[dispIdx].setGrayValue(0); blockMatchingDisplayLegendTarget[dispIdx] = blockMatchingImageDisplayTarget[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(blockMatchingImageDisplayTarget[dispIdx]); blockMatchingFrameTarget[dispIdx].getContentPane().add(panel); blockMatchingFrameTarget[dispIdx].pack(); blockMatchingFrameTarget[dispIdx].addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowBlockMatches(false); } }); } if (!blockMatchingFrameTarget[dispIdx].isVisible()) { blockMatchingFrameTarget[dispIdx].setVisible(true); } final int radius = (refRadius) + searchDistance; float scale = 1f / getSliceMaxValue(); try { // if ((x >= radius) && ((x + radius) < subSizeX) // && (y >= radius) && ((y + radius) < subSizeY)) { if (dimNew != blockMatchingImageDisplay[dispIdx].getWidth()) { dim = dimNew; blockMatchingImageDisplay[dispIdx].setImageSize(dimNew, dimNew); blockMatchingImageDisplay[dispIdx].clearLegends(); blockMatchingDisplayLegend[dispIdx] = blockMatchingImageDisplay[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); } if (dimNew != blockMatchingImageDisplayTarget[dispIdx].getWidth()) { dim = dimNew; blockMatchingImageDisplayTarget[dispIdx].setImageSize(dimNew, dimNew); blockMatchingImageDisplayTarget[dispIdx].clearLegends(); blockMatchingDisplayLegendTarget[dispIdx] = blockMatchingImageDisplayTarget[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); } // TextRenderer textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 12)); if (blockMatchingDisplayLegend[dispIdx] != null) { blockMatchingDisplayLegend[dispIdx].setLegendString("R: ref block area" + "\nScale: " + subSampleBy + "\nSAD: " + engFmt.format(sadVals[dispIdx]) + "\nTimestamp: " + ein.timestamp); } if (blockMatchingDisplayLegendTarget[dispIdx] != null) { blockMatchingDisplayLegendTarget[dispIdx].setLegendString("G: search area" + "\nx: " + ein.x + "\ny: " + ein.y + "\ndx_init: " + dxInitVals[dispIdx] + "\ndy_init: " + dyInitVals[dispIdx]); } /* Reset the image first */ blockMatchingImageDisplay[dispIdx].clearImage(); blockMatchingImageDisplayTarget[dispIdx].clearImage(); /* Rendering the reference patch in t-imuWarningDialog slice, it's on the center with color red */ for (int i = searchDistance; i < (refRadius * 2 + 1 + searchDistance); i++) { for (int j = searchDistance; j < (refRadius * 2 + 1 + searchDistance); j++) { float[] f = blockMatchingImageDisplay[dispIdx].getPixmapRGB(i, j); // Scale the pixel value to make it brighter for finer scale slice. f[0] = (1 << (numScales - 1 - dispIdx)) * scale * Math.abs(refBlock[((x - (refRadius)) + i) - searchDistance][((y - (refRadius)) + j) - searchDistance]); blockMatchingImageDisplay[dispIdx].setPixmapRGB(i, j, f); } } /* Rendering the area within search distance in t-2d slice, it's full of the whole search area with color green */ for (int i = 0; i < ((2 * radius) + 1); i++) { for (int j = 0; j < ((2 * radius) + 1); j++) { float[] f = blockMatchingImageDisplayTarget[dispIdx].getPixmapRGB(i, j); f[1] = scale * Math.abs(searchBlock[(x - dxInitVals[dispIdx] - radius) + i][(y - dyInitVals[dispIdx] - radius) + j]); blockMatchingImageDisplayTarget[dispIdx].setPixmapRGB(i, j, f); } } /* Rendering the best matching patch in t-2d slice, it's on the shifted position related to the center location with color blue */ // for (int i = searchDistance + dx; i < (blockDimension + searchDistance + dx); i++) { // for (int j = searchDistance + dy; j < (blockDimension + searchDistance + dy); j++) { // float[] f = blockMatchingImageDisplayTarget[dispIdx].getPixmapRGB(i, j); // f[2] = scale * Math.abs(searchBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]); // blockMatchingImageDisplayTarget[dispIdx].setPixmapRGB(i, j, f); } } catch (ArrayIndexOutOfBoundsException e) { } blockMatchingImageDisplay[dispIdx].repaint(); blockMatchingImageDisplayTarget[dispIdx].repaint(); } } synchronized private void drawTimeStampBlock(PolarityEvent ein) { int dim = 11; int sliceScale = 2; int eX = ein.x >> sliceScale, eY = ein.y >> sliceScale, eType = ein.type; if (timeStampBlockFrame == null) { String windowName = "FASTCornerBlock"; timeStampBlockFrame = new JFrame(windowName); timeStampBlockFrame.setLayout(new BoxLayout(timeStampBlockFrame.getContentPane(), BoxLayout.Y_AXIS)); timeStampBlockFrame.setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); timeStampBlockImageDisplay = ImageDisplay.createOpenGLCanvas(); timeStampBlockImageDisplay.setBorderSpacePixels(10); timeStampBlockImageDisplay.setImageSize(dim, dim); timeStampBlockImageDisplay.setSize(200, 200); timeStampBlockImageDisplay.setGrayValue(0); timeStampBlockImageDisplayLegend = timeStampBlockImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(timeStampBlockImageDisplay); timeStampBlockFrame.getContentPane().add(panel); timeStampBlockFrame.pack(); timeStampBlockFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowSlices(false); } }); } if (!timeStampBlockFrame.isVisible()) { timeStampBlockFrame.setVisible(true); } timeStampBlockImageDisplay.clearImage(); for (int i = 0; i < innerCircleSize; i++) { xInnerOffset[i] = innerCircle[i][0]; yInnerOffset[i] = innerCircle[i][1]; innerTsValue[i] = lastTimesMap[eX + xInnerOffset[i]][eY + yInnerOffset[i]][type]; innerTsValue[i] = slices[sliceIndex(1)][sliceScale][eX + xInnerOffset[i]][eY + yInnerOffset[i]]; if (innerTsValue[i] == 0x80000000) { innerTsValue[i] = 0; } } for (int i = 0; i < outerCircleSize; i++) { xOuterOffset[i] = outerCircle[i][0]; yOuterOffset[i] = outerCircle[i][1]; outerTsValue[i] = lastTimesMap[eX + xOuterOffset[i]][eY + yOuterOffset[i]][type]; outerTsValue[i] = slices[sliceIndex(1)][sliceScale][eX + xOuterOffset[i]][eY + yOuterOffset[i]]; if (outerTsValue[i] == 0x80000000) { outerTsValue[i] = 0; } } List innerList = Arrays.asList(ArrayUtils.toObject(innerTsValue)); int innerMax = (int) Collections.max(innerList); int innerMin = (int) Collections.min(innerList); float innerScale = 1f / (innerMax - innerMin); List outerList = Arrays.asList(ArrayUtils.toObject(outerTsValue)); int outerMax = (int) Collections.max(outerList); int outerMin = (int) Collections.min(outerList); float outerScale = 1f / (outerMax - outerMin); float scale = 1f / getSliceMaxValue(); timeStampBlockImageDisplay.setPixmapRGB(dim / 2, dim / 2, 0, lastTimesMap[eX][eY][type] * scale, 0); timeStampBlockImageDisplay.setPixmapRGB(dim / 2, dim / 2, 0, slices[sliceIndex(1)][sliceScale][eX][eY] * scale, 0); for (int i = 0; i < innerCircleSize; i++) { timeStampBlockImageDisplay.setPixmapRGB(xInnerOffset[i] + dim / 2, yInnerOffset[i] + dim / 2, innerScale * (innerTsValue[i] - innerMin), 0, 0); timeStampBlockImageDisplay.setPixmapRGB(xInnerOffset[i] + dim / 2, yInnerOffset[i] + dim / 2, scale * (innerTsValue[i]), 0, 0); } for (int i = 0; i < outerCircleSize; i++) { timeStampBlockImageDisplay.setPixmapRGB(xOuterOffset[i] + dim / 2, yOuterOffset[i] + dim / 2, 0, 0, outerScale * (outerTsValue[i] - outerMin)); timeStampBlockImageDisplay.setPixmapRGB(xOuterOffset[i] + dim / 2, yOuterOffset[i] + dim / 2, 0, 0, scale * (outerTsValue[i])); } if (timeStampBlockImageDisplayLegend != null) { timeStampBlockImageDisplayLegend.setLegendString(TIME_STAMP_BLOCK_LEGEND_SLICES); } timeStampBlockImageDisplay.repaint(); } private void drawSlices(byte[][][][] slices) { // log.info("drawing slices"); if (sliceBitMapFrame == null) { String windowName = "Slices"; sliceBitMapFrame = new JFrame(windowName); sliceBitMapFrame.setLayout(new BoxLayout(sliceBitMapFrame.getContentPane(), BoxLayout.Y_AXIS)); sliceBitMapFrame.setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); sliceBitmapImageDisplay = ImageDisplay.createOpenGLCanvas(); sliceBitmapImageDisplay.setBorderSpacePixels(10); sliceBitmapImageDisplay.setImageSize(sizex >> showSlicesScale, sizey >> showSlicesScale); sliceBitmapImageDisplay.setSize(200, 200); sliceBitmapImageDisplay.setGrayValue(0); sliceBitmapImageDisplayLegend = sliceBitmapImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(sliceBitmapImageDisplay); sliceBitMapFrame.getContentPane().add(panel); sliceBitMapFrame.pack(); sliceBitMapFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowSlices(false); } }); } if (!sliceBitMapFrame.isVisible()) { sliceBitMapFrame.setVisible(true); } int dimNewX = sizex >> showSlicesScale; int dimNewY = sizey >> showSlicesScale; if (dimNewX != sliceBitmapImageDisplay.getWidth() || dimNewY != sliceBitmapImageDisplay.getHeight()) { sliceBitmapImageDisplay.setImageSize(dimNewX, dimNewY); sliceBitmapImageDisplay.clearLegends(); sliceBitmapImageDisplayLegend = sliceBitmapImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); } float scale = 1f / getSliceMaxValue(); sliceBitmapImageDisplay.clearImage(); int d1 = sliceIndex(1), d2 = sliceIndex(2); if (showSlicesScale >= numScales) { showSlicesScale = numScales - 1; } int imageSizeX = sizex >> showSlicesScale; int imageSizeY = sizey >> showSlicesScale; byte[] grayImageBuffer = new byte[imageSizeX * imageSizeY]; for (int slice = 1; slice <= 2; slice++) { for (int x = 0; x < imageSizeX; x++) { for (int y = 0; y < imageSizeY; y++) { int pixelValue1 = slices[d1][showSlicesScale][x][y]; int pixelValue2 = slices[d2][showSlicesScale][x][y]; sliceBitmapImageDisplay.setPixmapRGB(x, y, scale * pixelValue1, scale * pixelValue2, 0); // The minimum of byte is ox0(0), the maximum is 0xFF(-1); // It is from 0 to 127 and then -128 to -1; int imagePixelVal = (int) (pixelValue1 * 255.0f / getSliceMaxValue() + 128) + (int) (pixelValue2 * 255.0f / getSliceMaxValue()); if (imagePixelVal == 0) { imagePixelVal = 0; // Background } grayImageBuffer[(imageSizeY - 1 - y) * imageSizeX + x] = (byte) imagePixelVal; } } } final BufferedImage theImage = new BufferedImage(imageSizeX, imageSizeY, BufferedImage.TYPE_BYTE_GRAY); theImage.getRaster().setDataElements(0, 0, imageSizeX, imageSizeY, grayImageBuffer); if (saveSliceGrayImage) { final Date d = new Date(); final String PNG = "png"; // final String fn = "EventSlice-" + AEDataFile.DATE_FORMAT.format(d) + "." + PNG; final String fn = "EventSlice-" + sliceEndTimeUs[d1] + "." + PNG; // if user is playing a file, use folder that file lives in String userDir = Paths.get(".").toAbsolutePath().normalize().toString(); File eventSliceDir = new File(userDir + File.separator + "EventSlices" + File.separator + getChip().getAeInputStream().getFile().getName()); if (!eventSliceDir.exists()) { eventSliceDir.mkdirs(); } File outputfile = new File(eventSliceDir + File.separator + fn); try { ImageIO.write(theImage, "png", outputfile); } catch (IOException ex) { Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); } saveSliceGrayImage = false; } if (sliceBitmapImageDisplayLegend != null) { sliceBitmapImageDisplayLegend.setLegendString(LEGEND_SLICES); } sliceBitmapImageDisplay.repaint(); } // /** // * @return the numSlices // */ // public int getNumSlices() { // return numSlices; // /** // * @param numSlices the numSlices to set // */ // synchronized public void setNumSlices(int numSlices) { // if (numSlices < 3) { // numSlices = 3; // } else if (numSlices > 8) { // numSlices = 8; // this.numSlices = numSlices; // putInt("numSlices", numSlices); /** * @return the sliceNumBits */ public int getSliceMaxValue() { return sliceMaxValue; } /** * @param sliceMaxValue the sliceMaxValue to set */ public void setSliceMaxValue(int sliceMaxValue) { int old = this.sliceMaxValue; if (sliceMaxValue < 1) { sliceMaxValue = 1; } else if (sliceMaxValue > 127) { sliceMaxValue = 127; } this.sliceMaxValue = sliceMaxValue; putInt("sliceMaxValue", sliceMaxValue); getSupport().firePropertyChange("sliceMaxValue", old, this.sliceMaxValue); } /** * @return the rectifyPolarties */ public boolean isRectifyPolarties() { return rectifyPolarties; } /** * @param rectifyPolarties the rectifyPolarties to set */ public void setRectifyPolarties(boolean rectifyPolarties) { boolean old = this.rectifyPolarties; this.rectifyPolarties = rectifyPolarties; putBoolean("rectifyPolarties", rectifyPolarties); getSupport().firePropertyChange("rectifyPolarties", old, this.rectifyPolarties); } /** * @return the useSubsampling */ public boolean isUseSubsampling() { return useSubsampling; } /** * @param useSubsampling the useSubsampling to set */ public void setUseSubsampling(boolean useSubsampling) { this.useSubsampling = useSubsampling; } /** * @return the numScales */ public int getNumScales() { return numScales; } /** * @param numScales the numScales to set */ synchronized public void setNumScales(int numScales) { int old = this.numScales; if (numScales < 1) { numScales = 1; } else if (numScales > 4) { numScales = 4; } this.numScales = numScales; putInt("numScales", numScales); setDefaultScalesToCompute(); scaleResultCounts = new int[numScales]; showBlockSizeAndSearchAreaTemporarily(); computeAveragePossibleMatchDistance(); getSupport().firePropertyChange("numScales", old, this.numScales); } /** * Computes pooled (summed) value of slice at location xx, yy, in subsampled * region around this point * * @param slice * @param x * @param y * @param subsampleBy pool over 1<<subsampleBy by 1<<subsampleBy area to sum * up the slice values @return */ private int pool(byte[][] slice, int x, int y, int subsampleBy) { if (subsampleBy == 0) { return slice[x][y]; } else { int n = 1 << subsampleBy; int sum = 0; for (int xx = x; xx < x + n + n; xx++) { for (int yy = y; yy < y + n + n; yy++) { if (xx >= subSizeX || yy >= subSizeY) { // log.warning("should not happen that xx="+xx+" or yy="+yy); continue; // TODO remove this check when iteration avoids this sum explictly } sum += slice[xx][yy]; } } return sum; } } /** * @return the scalesToCompute */ public String getScalesToCompute() { return scalesToCompute; } /** * @param scalesToCompute the scalesToCompute to set */ synchronized public void setScalesToCompute(String scalesToCompute) { this.scalesToCompute = scalesToCompute; if (scalesToCompute == null || scalesToCompute.isEmpty()) { setDefaultScalesToCompute(); } else { StringTokenizer st = new StringTokenizer(scalesToCompute, ", ", false); int n = st.countTokens(); if (n == 0) { setDefaultScalesToCompute(); } else { scalesToComputeArray = new Integer[n]; int i = 0; while (st.hasMoreTokens()) { try { int scale = Integer.parseInt(st.nextToken()); scalesToComputeArray[i++] = scale; } catch (NumberFormatException e) { log.warning("bad string in scalesToCompute field, use blank or 0,2 for example"); setDefaultScalesToCompute(); } } } } } private void setDefaultScalesToCompute() { scalesToComputeArray = new Integer[numScales]; for (int i = 0; i < numScales; i++) { scalesToComputeArray[i] = i; } } /** * @return the areaEventNumberSubsampling */ public int getAreaEventNumberSubsampling() { return areaEventNumberSubsampling; } /** * @param areaEventNumberSubsampling the areaEventNumberSubsampling to set */ synchronized public void setAreaEventNumberSubsampling(int areaEventNumberSubsampling) { int old = this.areaEventNumberSubsampling; if (areaEventNumberSubsampling < 3) { areaEventNumberSubsampling = 3; } else if (areaEventNumberSubsampling > 7) { areaEventNumberSubsampling = 7; } this.areaEventNumberSubsampling = areaEventNumberSubsampling; putInt("areaEventNumberSubsampling", areaEventNumberSubsampling); showAreasForAreaCountsTemporarily(); clearAreaCounts(); if (sliceMethod != SliceMethod.AreaEventNumber) { log.warning("AreaEventNumber method is not currently selected as sliceMethod"); } getSupport().firePropertyChange("areaEventNumberSubsampling", old, this.areaEventNumberSubsampling); } private void showAreasForAreaCountsTemporarily() { if (stopShowingStuffTask != null) { stopShowingStuffTask.cancel(); } stopShowingStuffTask = new TimerTask() { @Override public void run() { showBlockSizeAndSearchAreaTemporarily = false; // in case we are canceling a task that would clear this showAreaCountAreasTemporarily = false; } }; Timer showAreaCountsAreasTimer = new Timer(); showAreaCountAreasTemporarily = true; showAreaCountsAreasTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS); } private void showBlockSizeAndSearchAreaTemporarily() { if (stopShowingStuffTask != null) { stopShowingStuffTask.cancel(); } stopShowingStuffTask = new TimerTask() { @Override public void run() { showAreaCountAreasTemporarily = false; // in case we are canceling a task that would clear this showBlockSizeAndSearchAreaTemporarily = false; } }; Timer showBlockSizeAndSearchAreaTimer = new Timer(); showBlockSizeAndSearchAreaTemporarily = true; showBlockSizeAndSearchAreaTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS); } private void clearAreaCounts() { if (sliceMethod != SliceMethod.AreaEventNumber) { return; } if (areaCounts == null || areaCounts.length != 1 + (subSizeX >> areaEventNumberSubsampling)) { int nax = 1 + (subSizeX >> areaEventNumberSubsampling), nay = 1 + (subSizeY >> areaEventNumberSubsampling); numAreas = nax * nay; areaCounts = new int[nax][nay]; } else { for (int[] i : areaCounts) { Arrays.fill(i, 0); } } areaCountExceeded = false; } private void clearNonGreedyRegions() { if (!nonGreedyFlowComputingEnabled) { return; } checkNonGreedyRegionsAllocated(); nonGreedyRegionsCount = 0; for (boolean[] i : nonGreedyRegions) { Arrays.fill(i, false); } } private void checkNonGreedyRegionsAllocated() { if (nonGreedyRegions == null || nonGreedyRegions.length != 1 + (subSizeX >> areaEventNumberSubsampling)) { nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling)); nonGreedyRegions = new boolean[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)]; nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling)); } } public int getSliceDeltaT() { return sliceDeltaT; } /** * @return the enableImuTimesliceLogging */ public boolean isEnableImuTimesliceLogging() { return enableImuTimesliceLogging; } /** * @param enableImuTimesliceLogging the enableImuTimesliceLogging to set */ public void setEnableImuTimesliceLogging(boolean enableImuTimesliceLogging) { this.enableImuTimesliceLogging = enableImuTimesliceLogging; if (enableImuTimesliceLogging) { if (imuTimesliceLogger == null) { imuTimesliceLogger = new TobiLogger("imuTimeslice.txt", "IMU rate gyro deg/s and patchmatch timeslice duration in ms"); imuTimesliceLogger.setColumnHeaderLine("systemtime(ms) timestamp(us) timeslice(us) rate(deg/s)"); imuTimesliceLogger.setSeparator(" "); } } imuTimesliceLogger.setEnabled(enableImuTimesliceLogging); } /** * @return the nonGreedyFlowComputingEnabled */ public boolean isNonGreedyFlowComputingEnabled() { return nonGreedyFlowComputingEnabled; } /** * @param nonGreedyFlowComputingEnabled the nonGreedyFlowComputingEnabled to * set */ synchronized public void setNonGreedyFlowComputingEnabled(boolean nonGreedyFlowComputingEnabled) { boolean old = this.nonGreedyFlowComputingEnabled; this.nonGreedyFlowComputingEnabled = nonGreedyFlowComputingEnabled; putBoolean("nonGreedyFlowComputingEnabled", nonGreedyFlowComputingEnabled); if (nonGreedyFlowComputingEnabled) { clearNonGreedyRegions(); } getSupport().firePropertyChange("nonGreedyFlowComputingEnabled", old, nonGreedyFlowComputingEnabled); } /** * @return the nonGreedyFractionToBeServiced */ public float getNonGreedyFractionToBeServiced() { return nonGreedyFractionToBeServiced; } /** * @param nonGreedyFractionToBeServiced the nonGreedyFractionToBeServiced to * set */ public void setNonGreedyFractionToBeServiced(float nonGreedyFractionToBeServiced) { this.nonGreedyFractionToBeServiced = nonGreedyFractionToBeServiced; putFloat("nonGreedyFractionToBeServiced", nonGreedyFractionToBeServiced); } /** * @return the adapativeSliceDurationProportionalErrorGain */ public float getAdapativeSliceDurationProportionalErrorGain() { return adapativeSliceDurationProportionalErrorGain; } /** * @param adapativeSliceDurationProportionalErrorGain the * adapativeSliceDurationProportionalErrorGain to set */ public void setAdapativeSliceDurationProportionalErrorGain(float adapativeSliceDurationProportionalErrorGain) { this.adapativeSliceDurationProportionalErrorGain = adapativeSliceDurationProportionalErrorGain; putFloat("adapativeSliceDurationProportionalErrorGain", adapativeSliceDurationProportionalErrorGain); } /** * @return the adapativeSliceDurationUseProportionalControl */ public boolean isAdapativeSliceDurationUseProportionalControl() { return adapativeSliceDurationUseProportionalControl; } /** * @param adapativeSliceDurationUseProportionalControl the * adapativeSliceDurationUseProportionalControl to set */ public void setAdapativeSliceDurationUseProportionalControl(boolean adapativeSliceDurationUseProportionalControl) { this.adapativeSliceDurationUseProportionalControl = adapativeSliceDurationUseProportionalControl; putBoolean("adapativeSliceDurationUseProportionalControl", adapativeSliceDurationUseProportionalControl); } public boolean isPrintScaleCntStatEnabled() { return printScaleCntStatEnabled; } public void setPrintScaleCntStatEnabled(boolean printScaleCntStatEnabled) { this.printScaleCntStatEnabled = printScaleCntStatEnabled; putBoolean("printScaleCntStatEnabled", printScaleCntStatEnabled); } /** * @return the showSlicesScale */ public int getShowSlicesScale() { return showSlicesScale; } /** * @param showSlicesScale the showSlicesScale to set */ public void setShowSlicesScale(int showSlicesScale) { if (showSlicesScale < 0) { showSlicesScale = 0; } else if (showSlicesScale > numScales - 1) { showSlicesScale = numScales - 1; } this.showSlicesScale = showSlicesScale; } public int getSliceDurationMinLimitUS() { return sliceDurationMinLimitUS; } public void setSliceDurationMinLimitUS(int sliceDurationMinLimitUS) { this.sliceDurationMinLimitUS = sliceDurationMinLimitUS; putInt("sliceDurationMinLimitUS", sliceDurationMinLimitUS); } public int getSliceDurationMaxLimitUS() { return sliceDurationMaxLimitUS; } public void setSliceDurationMaxLimitUS(int sliceDurationMaxLimitUS) { this.sliceDurationMaxLimitUS = sliceDurationMaxLimitUS; putInt("sliceDurationMaxLimitUS", sliceDurationMaxLimitUS); } public boolean isShowCorners() { return showCorners; } public void setShowCorners(boolean showCorners) { boolean old=this.showCorners; this.showCorners = showCorners; putBoolean("showCorners", showCorners); getSupport().firePropertyChange("showCorners", old, this.showCorners); } public boolean isHWABMOFEnabled() { return HWABMOFEnabled; } public void setHWABMOFEnabled(boolean HWABMOFEnabled) { this.HWABMOFEnabled = HWABMOFEnabled; } public boolean isCalcOFonCornersEnabled() { return calcOFonCornersEnabled; } public void setCalcOFonCornersEnabled(boolean calcOFonCornersEnabled) { boolean old=this.calcOFonCornersEnabled; this.calcOFonCornersEnabled = calcOFonCornersEnabled; putBoolean("calcOFonCornersEnabled", calcOFonCornersEnabled); getSupport().firePropertyChange("calcOFonCornersEnabled", old, this.calcOFonCornersEnabled); } public float getCornerThr() { return cornerThr; } public void setCornerThr(float cornerThr) { this.cornerThr = cornerThr; if (this.cornerThr > 1) { this.cornerThr = 1; } putFloat("cornerThr", cornerThr); } public CornerCircleSelection getCornerCircleSelection() { return cornerCircleSelection; } public void setCornerCircleSelection(CornerCircleSelection cornerCircleSelection) { CornerCircleSelection old = this.cornerCircleSelection; this.cornerCircleSelection = cornerCircleSelection; putString("cornerCircleSelection", cornerCircleSelection.toString()); getSupport().firePropertyChange("cornerCircleSelection", old, this.cornerCircleSelection); } synchronized public void doStartRecordingForEDFLOW() { JFileChooser c = new JFileChooser(lastFileName); c.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt"); } public String getDescription() { return "text file"; } }); c.setSelectedFile(new File(lastFileName)); int ret = c.showSaveDialog(null); if (ret != JFileChooser.APPROVE_OPTION) { return; } String basename = c.getSelectedFile().toString(); if (basename.toLowerCase().endsWith(".txt")) { basename = basename.substring(0, basename.length() - 4); } lastFileName = basename; putString("lastFileName", lastFileName); String fn = basename + "-OFResult.txt"; try { dvsWriter = new PrintWriter(new File(fn)); } catch (FileNotFoundException ex) { Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); } dvsWriter.println("# created " + new Date().toString()); dvsWriter.println("# source-file: " + (chip.getAeInputStream() != null ? chip.getAeInputStream().getFile().toString() : "(live input)")); dvsWriter.println("# dvs-events: One event per line: timestamp(us) x y polarity(0=off,1=on) dx dy OFRetValid rotateFlg SFAST"); } synchronized public void doStopRecordingForEDFLOW() { dvsWriter.close(); dvsWriter = null; } // This is the BFAST (or SFAST in paper) corner dector. EFAST refer to HWCornerPointRender boolean PatchFastDetectorisFeature(PolarityEvent ein) { boolean found_streak = false; boolean found_streak_inner = false, found_streak_outer = false; int innerI = 0, outerI = 0, innerStreakSize = 0, outerStreakSize = 0; int scale = numScales - 1; int pix_x = ein.x >> scale; int pix_y = ein.y >> scale; byte featureSlice[][] = slices[sliceIndex(1)][scale]; int circle3_[][] = innerCircle; int circle4_[][] = outerCircle; final int innerSize = circle3_.length; final int outerSize = circle4_.length; int innerStartX = 0, innerEndX = 0, innerStartY = 0, innerEndY = 0; int outerStartX, outerEndX, outerStartY, outerEndY; // only check if not too close to border if (pix_x < 4 || pix_x >= (getChip().getSizeX() >> scale) - 4 || pix_y < 4 || pix_y >= (getChip().getSizeY() >> scale) - 4) { found_streak = false; return found_streak; } found_streak_inner = false; boolean exit_inner_loop = false; int centerValue = 0; int xInnerOffset[] = new int[innerCircleSize]; int yInnerOffset[] = new int[innerCircleSize]; // int innerTsValue[] = new int[innerCircleSize]; for (int i = 0; i < innerCircleSize; i++) { xInnerOffset[i] = innerCircle[i][0]; yInnerOffset[i] = innerCircle[i][1]; innerTsValue[i] = featureSlice[pix_x + xInnerOffset[i]][pix_y + yInnerOffset[i]]; } int xOuterOffset[] = new int[outerCircleSize]; int yOuterOffset[] = new int[outerCircleSize]; // int outerTsValue[] = new int[outerCircleSize]; for (int i = 0; i < outerCircleSize; i++) { xOuterOffset[i] = outerCircle[i][0]; yOuterOffset[i] = outerCircle[i][1]; outerTsValue[i] = featureSlice[pix_x + xOuterOffset[i]][pix_y + yOuterOffset[i]]; } isFeatureOutterLoop: for (int i = 0; i < innerSize; i++) { FastDetectorisFeature_label2: for (int streak_size = innerCircleSize - 1; streak_size >= 2; streak_size = streak_size - 1) { // check that streak event is larger than neighbor if (Math.abs(featureSlice[pix_x + circle3_[i][0]][pix_y + circle3_[i][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle3_[(i - 1 + innerSize) % innerSize][0]][pix_y + circle3_[(i - 1 + innerSize) % innerSize][1]] - centerValue)) { continue; } // check that streak event is larger than neighbor if (Math.abs(featureSlice[pix_x + circle3_[(i + streak_size - 1) % innerSize][0]][pix_y + circle3_[(i + streak_size - 1) % innerSize][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]] - centerValue)) { continue; } // find the smallest timestamp in corner min_t double min_t = Math.abs(featureSlice[pix_x + circle3_[i][0]][pix_y + circle3_[i][1]] - centerValue); FastDetectorisFeature_label1: for (int j = 1; j < streak_size; j++) { final double tj = Math.abs(featureSlice[pix_x + circle3_[(i + j) % innerSize][0]][pix_y + circle3_[(i + j) % innerSize][1]] - centerValue); if (tj < min_t) { min_t = tj; } } //check if corner timestamp is higher than corner boolean did_break = false; double max_t = featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]]; FastDetectorisFeature_label0: for (int j = streak_size; j < innerSize; j++) { final double tj = Math.abs(featureSlice[pix_x + circle3_[(i + j) % innerSize][0]][pix_y + circle3_[(i + j) % innerSize][1]] - centerValue); if (tj > max_t) { max_t = tj; } if (tj >= min_t - cornerThr * getSliceMaxValue()) { did_break = true; break; } } // The maximum value of the non-streak is on the border, remove it. if (!did_break) { if ((max_t >= 7) && (max_t == featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]] || max_t == featureSlice[pix_x + circle3_[(i + innerSize - 1) % innerSize][0]][pix_y + circle3_[(i + innerSize - 1) % innerSize][1]])) { // did_break = true; } } if (!did_break) { innerI = i; innerStreakSize = streak_size; innerStartX = innerCircle[innerI % innerSize][0]; innerEndX = innerCircle[(innerI + innerStreakSize - 1) % innerSize][0]; innerStartY = innerCircle[innerI % innerSize][1]; innerEndY = innerCircle[(innerI + innerStreakSize - 1) % innerSize][1]; int condDiff = (streak_size % 2 == 1) ? 0 : 1; // If streak_size is even, then set it to 1. Otherwise 0. if ((streak_size == innerCircleSize - 1) || Math.abs(innerStartX - innerEndX) <= condDiff || Math.abs(innerStartY - innerEndY) <= condDiff // || featureSlice[pix_x + innerStartX][pix_y + innerEndX] < 12 // || featureSlice[pix_x + innerEndX][pix_y + innerEndY] < 12 ) { found_streak_inner = false; } else { found_streak_inner = true; } exit_inner_loop = true; break; } } if (found_streak_inner || exit_inner_loop) { break; } } found_streak_outer = false; // if (found_streak) { found_streak_outer = false; boolean exit_outer_loop = false; FastDetectorisFeature_label6: for (int streak_size = outerCircleSize - 1; streak_size >= 3; streak_size FastDetectorisFeature_label5: for (int i = 0; i < outerSize; i++) { // check that first event is larger than neighbor if (Math.abs(featureSlice[pix_x + circle4_[i][0]][pix_y + circle4_[i][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle4_[(i - 1 + outerSize) % outerSize][0]][pix_y + circle4_[(i - 1 + outerSize) % outerSize][1]] - centerValue)) { continue; } // check that streak event is larger than neighbor if (Math.abs(featureSlice[pix_x + circle4_[(i + streak_size - 1) % outerSize][0]][pix_y + circle4_[(i + streak_size - 1) % outerSize][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle4_[(i + streak_size) % outerSize][0]][pix_y + circle4_[(i + streak_size) % outerSize][1]] - centerValue)) { continue; } double min_t = Math.abs(featureSlice[pix_x + circle4_[i][0]][pix_y + circle4_[i][1]] - centerValue); FastDetectorisFeature_label4: for (int j = 1; j < streak_size; j++) { final double tj = Math.abs(featureSlice[pix_x + circle4_[(i + j) % outerSize][0]][pix_y + circle4_[(i + j) % outerSize][1]] - centerValue); if (tj < min_t) { min_t = tj; } } boolean did_break = false; double max_t = featureSlice[pix_x + circle4_[(i + streak_size) % outerSize][0]][pix_y + circle4_[(i + streak_size) % outerSize][1]]; float thr = cornerThr * getSliceMaxValue(); if (streak_size >= 9) { thr += 1; } FastDetectorisFeature_label3: for (int j = streak_size; j < outerSize; j++) { final double tj = Math.abs(featureSlice[pix_x + circle4_[(i + j) % outerSize][0]][pix_y + circle4_[(i + j) % outerSize][1]] - centerValue); if (tj > max_t) { max_t = tj; } if (tj >= min_t - thr) { did_break = true; break; } } if (!did_break) { if (streak_size == 9 && (max_t >= 7)) { int tmp = 0; } } if (!did_break) { outerI = i; outerStreakSize = streak_size; outerStartX = outerCircle[outerI % outerSize][0]; outerEndX = outerCircle[(outerI + outerStreakSize - 1) % outerSize][0]; outerStartY = outerCircle[outerI % outerSize][1]; outerEndY = outerCircle[(outerI + outerStreakSize - 1) % outerSize][1]; int condDiff = (streak_size % 2 == 1) ? 0 : 1; // If streak_size is even, then set it to 1. Otherwise 0. if ((streak_size == outerCircleSize - 1) || Math.abs(outerStartX - outerEndX) <= condDiff || Math.abs(outerStartY - outerEndY) <= condDiff // || featureSlice[pix_x + outerStartX][pix_y + outerStartY] < 12 // || featureSlice[pix_x + outerEndX][pix_y + outerEndX] < 12 ) { found_streak_outer = false; } else { found_streak_outer = true; } if (min_t - max_t != 15 || streak_size != 10) { // found_streak_outer = false; } exit_outer_loop = true; break; } } if (found_streak_outer || exit_outer_loop) { break; } } } switch (cornerCircleSelection) { case InnerCircle: found_streak = found_streak_inner; break; case OuterCircle: found_streak = found_streak_outer; break; case OR: found_streak = found_streak_inner || found_streak_outer; break; case AND: found_streak = found_streak_inner && found_streak_outer; break; default: found_streak = found_streak_inner && found_streak_outer; break; } return found_streak; } /** * @return the outlierRejectionEnabled */ public boolean isOutlierRejectionEnabled() { return outlierRejectionEnabled; } /** * @param outlierRejectionEnabled the outlierRejectionEnabled to set */ public void setOutlierRejectionEnabled(boolean outlierRejectionEnabled) { this.outlierRejectionEnabled = outlierRejectionEnabled; putBoolean("outlierRejectionEnabled", outlierRejectionEnabled); } /** * @return the outlierRejectionThresholdSigma */ public float getOutlierRejectionThresholdSigma() { return outlierRejectionThresholdSigma; } /** * @param outlierRejectionThresholdSigma the outlierRejectionThresholdSigma * to set */ public void setOutlierRejectionThresholdSigma(float outlierRejectionThresholdSigma) { this.outlierRejectionThresholdSigma = outlierRejectionThresholdSigma; putFloat("outlierRejectionThresholdSigma", outlierRejectionThresholdSigma); } private boolean isOutlierFlowVector(PatchMatchFlow.SADResult result) { if (!outlierRejectionEnabled) { return false; } GlobalMotion gm = outlierRejectionMotionFlowStatistics.getGlobalMotion(); // update global flow here before outlier rejection, otherwise stats are not updated and std shrinks to zero gm.update(vx, vy, v, (x << getSubSampleShift()), (y << getSubSampleShift())); float speed = (float) Math.sqrt(result.vx * result.vx + result.vy * result.vy); // if the current vector speed is too many stds outside the mean speed then it is an outlier if (Math.abs(speed - gm.meanGlobalSpeed) > outlierRejectionThresholdSigma * gm.sdGlobalSpeed) { return true; } // if((Math.abs(result.vx-gm.meanGlobalVx)>outlierRejectionThresholdSigma*gm.sdGlobalVx) // || (Math.abs(result.vy-gm.meanGlobalVy)>outlierRejectionThresholdSigma*gm.sdGlobalVy)) // return true; return false; } /** * @return the useEFASTnotSFAST */ public boolean isUseEFASTnotSFAST() { return useEFASTnotSFAST; } /** * @param useEFASTnotSFAST the useEFASTnotSFAST to set */ public void setUseEFASTnotSFAST(boolean useEFASTnotSFAST) { this.useEFASTnotSFAST = useEFASTnotSFAST; putBoolean("useEFASTnotSFAST", useEFASTnotSFAST); checkForEASTCornerDetectorEnclosedFilter(); } private void checkForEASTCornerDetectorEnclosedFilter() { if (useEFASTnotSFAST) { // add enclosed filter if not there if (keypointFilter == null) { keypointFilter = new HWCornerPointRenderer(chip); } if (!getEnclosedFilterChain().contains(keypointFilter)) { getEnclosedFilterChain().add(keypointFilter); // use for EFAST } keypointFilter.setFilterEnabled(isFilterEnabled()); if (getChip().getAeViewer().getFilterFrame() != null) { getChip().getAeViewer().getFilterFrame().rebuildContents(); } } else { if (keypointFilter != null && getEnclosedFilterChain().contains(keypointFilter)) { getEnclosedFilterChain().remove(keypointFilter); if (getChip().getAeViewer().getFilterFrame() != null) { getChip().getAeViewer().getFilterFrame().rebuildContents(); } } } } /** * @return the outlierRejectionWindowSize */ public int getOutlierRejectionWindowSize() { return outlierRejectionWindowSize; } /** * @param outlierRejectionWindowSize the outlierRejectionWindowSize to set */ public void setOutlierRejectionWindowSize(int outlierRejectionWindowSize) { this.outlierRejectionWindowSize = outlierRejectionWindowSize; putInt("outlierRejectionWindowSize", outlierRejectionWindowSize); outlierRejectionMotionFlowStatistics.setWindowSize(outlierRejectionWindowSize); } /** * @return the cornerSize */ public int getCornerSize() { return cornerSize; } /** * @param cornerSize the cornerSize to set */ public void setCornerSize(int cornerSize) { this.cornerSize = cornerSize; } }
package cgeo.geocaching.maps.mapsforge.v6; import cgeo.geocaching.AbstractDialogFragment; import cgeo.geocaching.AbstractDialogFragment.TargetInfo; import cgeo.geocaching.CacheListActivity; import cgeo.geocaching.CachePopup; import cgeo.geocaching.CompassActivity; import cgeo.geocaching.EditWaypointActivity; import cgeo.geocaching.Intents; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.WaypointPopup; import cgeo.geocaching.activity.AbstractActionBarActivity; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.connector.gc.GCMap; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.CoordinatesType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.location.Viewport; import cgeo.geocaching.maps.LivemapStrategy; import cgeo.geocaching.maps.MapMode; import cgeo.geocaching.maps.MapOptions; import cgeo.geocaching.maps.MapProviderFactory; import cgeo.geocaching.maps.MapState; import cgeo.geocaching.maps.interfaces.MapSource; import cgeo.geocaching.maps.interfaces.OnMapDragListener; import cgeo.geocaching.maps.mapsforge.MapsforgeMapSource; import cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle; import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemRef; import cgeo.geocaching.maps.mapsforge.v6.layers.HistoryLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.ITileLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.NavigationLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.PositionLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.TapHandlerLayer; import cgeo.geocaching.maps.routing.Routing; import cgeo.geocaching.maps.routing.RoutingMode; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.sensors.GeoData; import cgeo.geocaching.sensors.GeoDirHandler; import cgeo.geocaching.sensors.Sensors; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.storage.DataStore; import cgeo.geocaching.utils.AngleUtils; import cgeo.geocaching.utils.DisposableHandler; import cgeo.geocaching.utils.Formatter; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.functions.Action1; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources.NotFoundException; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ListAdapter; import android.widget.TextView; import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import butterknife.ButterKnife; import io.reactivex.disposables.CompositeDisposable; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.mapsforge.core.model.LatLong; import org.mapsforge.core.util.Parameters; import org.mapsforge.map.android.graphics.AndroidGraphicFactory; import org.mapsforge.map.android.graphics.AndroidResourceBitmap; import org.mapsforge.map.android.input.MapZoomControls; import org.mapsforge.map.android.util.AndroidUtil; import org.mapsforge.map.layer.Layers; import org.mapsforge.map.layer.cache.TileCache; import org.mapsforge.map.layer.renderer.TileRendererLayer; import org.mapsforge.map.model.DisplayModel; import org.mapsforge.map.rendertheme.ExternalRenderTheme; import org.mapsforge.map.rendertheme.InternalRenderTheme; import org.mapsforge.map.rendertheme.XmlRenderTheme; import org.mapsforge.map.rendertheme.rule.RenderThemeHandler; import org.xmlpull.v1.XmlPullParserException; @SuppressLint("ClickableViewAccessibility") public class NewMap extends AbstractActionBarActivity { private MfMapView mapView; private TileCache tileCache; private ITileLayer tileLayer; private HistoryLayer historyLayer; private PositionLayer positionLayer; private NavigationLayer navigationLayer; private CachesBundle caches; private final MapHandlers mapHandlers = new MapHandlers(new TapHandler(this), new DisplayHandler(this), new ShowProgressHandler(this)); private DistanceView distanceView; private ArrayList<Location> trailHistory = null; private String targetGeocode = null; private Geopoint lastNavTarget = null; private final Queue<String> popupGeocodes = new ConcurrentLinkedQueue<>(); private ProgressDialog waitDialog; private LoadDetails loadDetailsThread; private final UpdateLoc geoDirUpdate = new UpdateLoc(this); /** * initialization with an empty subscription to make static code analysis tools more happy */ private final CompositeDisposable resumeDisposables = new CompositeDisposable(); private CheckBox myLocSwitch; private MapOptions mapOptions; private TargetView targetView; private static boolean followMyLocation = true; private static final String BUNDLE_MAP_STATE = "mapState"; private static final String BUNDLE_TRAIL_HISTORY = "trailHistory"; // Handler messages // DisplayHandler public static final int UPDATE_TITLE = 0; public static final int INVALIDATE_MAP = 1; // ShowProgressHandler public static final int HIDE_PROGRESS = 0; public static final int SHOW_PROGRESS = 1; // LoadDetailsHandler public static final int UPDATE_PROGRESS = 0; public static final int FINISHED_LOADING_DETAILS = 1; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidGraphicFactory.createInstance(this.getApplication()); Parameters.MAXIMUM_BUFFER_SIZE = 6500000; // Get parameters from the intent mapOptions = new MapOptions(this, getIntent().getExtras()); // Get fresh map information from the bundle if any if (savedInstanceState != null) { mapOptions.mapState = savedInstanceState.getParcelable(BUNDLE_MAP_STATE); trailHistory = savedInstanceState.getParcelableArrayList(BUNDLE_TRAIL_HISTORY); followMyLocation = mapOptions.mapState.followsMyLocation(); } else { followMyLocation = followMyLocation && mapOptions.mapMode == MapMode.LIVE; } ActivityMixin.onCreate(this, true); // set layout ActivityMixin.setTheme(this); setContentView(R.layout.map_mapsforge_v6); setTitle(); // initialize map mapView = (MfMapView) findViewById(R.id.mfmapv5); mapView.setClickable(true); mapView.getMapScaleBar().setVisible(true); mapView.setBuiltInZoomControls(true); // create a tile cache of suitable size. always initialize it based on the smallest tile size to expect (256 for online tiles) tileCache = AndroidUtil.createTileCache(this, "mapcache", 256, 1f, this.mapView.getModel().frameBufferModel.getOverdrawFactor()); // attach drag handler final DragHandler dragHandler = new DragHandler(this); mapView.setOnMapDragListener(dragHandler); // prepare initial settings of mapView if (mapOptions.mapState != null) { this.mapView.getModel().mapViewPosition.setCenter(MapsforgeUtils.toLatLong(mapOptions.mapState.getCenter())); this.mapView.setMapZoomLevel((byte) mapOptions.mapState.getZoomLevel()); this.targetGeocode = mapOptions.mapState.getTargetGeocode(); this.lastNavTarget = mapOptions.mapState.getLastNavTarget(); mapOptions.isLiveEnabled = mapOptions.mapState.isLiveEnabled(); mapOptions.isStoredEnabled = mapOptions.mapState.isStoredEnabled(); } else if (mapOptions.searchResult != null) { final Viewport viewport = DataStore.getBounds(mapOptions.searchResult.getGeocodes()); if (viewport != null) { postZoomToViewport(viewport); } } else if (StringUtils.isNotEmpty(mapOptions.geocode)) { final Viewport viewport = DataStore.getBounds(mapOptions.geocode); if (viewport != null) { postZoomToViewport(viewport); } targetGeocode = mapOptions.geocode; } else if (mapOptions.coords != null) { postZoomToViewport(new Viewport(mapOptions.coords, 0, 0)); } else { postZoomToViewport(new Viewport(Settings.getMapCenter().getCoords(), 0, 0)); } prepareFilterBar(); Routing.connect(); } private void postZoomToViewport(final Viewport viewport) { mapView.post(new Runnable() { @Override public void run() { mapView.zoomToViewport(viewport); } }); } @Override public boolean onCreateOptionsMenu(final Menu menu) { final boolean result = super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.map_activity, menu); MapProviderFactory.addMapviewMenuItems(menu); final MenuItem item = menu.findItem(R.id.menu_toggle_mypos); myLocSwitch = new CheckBox(this); myLocSwitch.setButtonDrawable(R.drawable.ic_menu_myposition); item.setActionView(myLocSwitch); initMyLocationSwitchButton(myLocSwitch); return result; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { super.onPrepareOptionsMenu(menu); for (final MapSource mapSource : MapProviderFactory.getMapSources()) { final MenuItem menuItem = menu.findItem(mapSource.getNumericalId()); if (menuItem != null) { menuItem.setVisible(mapSource.isAvailable()); } } try { final MenuItem itemMapLive = menu.findItem(R.id.menu_map_live); if (mapOptions.isLiveEnabled) { itemMapLive.setTitle(res.getString(R.string.map_live_disable)); } else { itemMapLive.setTitle(res.getString(R.string.map_live_enable)); } itemMapLive.setVisible(mapOptions.coords == null); final Set<String> visibleGeocodes = caches.getVisibleGeocodes(); menu.findItem(R.id.menu_store_caches).setVisible(false); menu.findItem(R.id.menu_store_caches).setVisible(!caches.isDownloading() && !visibleGeocodes.isEmpty()); menu.findItem(R.id.menu_store_unsaved_caches).setVisible(false); menu.findItem(R.id.menu_store_unsaved_caches).setVisible(!caches.isDownloading() && new SearchResult(visibleGeocodes).hasUnsavedCaches()); menu.findItem(R.id.menu_mycaches_mode).setChecked(Settings.isExcludeMyCaches()); menu.findItem(R.id.menu_disabled_mode).setChecked(Settings.isExcludeDisabledCaches()); menu.findItem(R.id.menu_direction_line).setChecked(Settings.isMapDirection()); //TODO: circles menu.findItem(R.id.menu_circle_mode).setChecked(this.searchOverlay.getCircles()); menu.findItem(R.id.menu_circle_mode).setVisible(false); menu.findItem(R.id.menu_trail_mode).setChecked(Settings.isMapTrail()); menu.findItem(R.id.menu_theme_mode).setVisible(tileLayerHasThemes()); menu.findItem(R.id.menu_as_list).setVisible(!caches.isDownloading() && caches.getVisibleItemsCount() > 1); menu.findItem(R.id.submenu_strategy).setVisible(mapOptions.isLiveEnabled); switch (Settings.getLiveMapStrategy()) { case FAST: menu.findItem(R.id.menu_strategy_fast).setChecked(true); break; case AUTO: menu.findItem(R.id.menu_strategy_auto).setChecked(true); break; default: // DETAILED menu.findItem(R.id.menu_strategy_detailed).setChecked(true); break; } menu.findItem(R.id.submenu_routing).setVisible(Routing.isAvailable()); switch (Settings.getRoutingMode()) { case STRAIGHT: menu.findItem(R.id.menu_routing_straight).setChecked(true); break; case WALK: menu.findItem(R.id.menu_routing_walk).setChecked(true); break; case BIKE: menu.findItem(R.id.menu_routing_bike).setChecked(true); break; case CAR: menu.findItem(R.id.menu_routing_car).setChecked(true); break; } menu.findItem(R.id.menu_hint).setVisible(mapOptions.mapMode == MapMode.SINGLE); menu.findItem(R.id.menu_compass).setVisible(mapOptions.mapMode == MapMode.SINGLE); } catch (final RuntimeException e) { Log.e("NewMap.onPrepareOptionsMenu", e); } return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { final int id = item.getItemId(); switch (id) { case android.R.id.home: ActivityMixin.navigateUp(this); return true; case R.id.menu_trail_mode: Settings.setMapTrail(!Settings.isMapTrail()); historyLayer.requestRedraw(); ActivityMixin.invalidateOptionsMenu(this); return true; case R.id.menu_direction_line: Settings.setMapDirection(!Settings.isMapDirection()); navigationLayer.requestRedraw(); ActivityMixin.invalidateOptionsMenu(this); return true; case R.id.menu_map_live: mapOptions.isLiveEnabled = !mapOptions.isLiveEnabled; if (mapOptions.isLiveEnabled) { mapOptions.isStoredEnabled = true; } if (mapOptions.mapMode == MapMode.LIVE) { Settings.setLiveMap(mapOptions.isLiveEnabled); } caches.enableStoredLayers(mapOptions.isStoredEnabled); caches.handleLiveLayers(mapOptions.isLiveEnabled); ActivityMixin.invalidateOptionsMenu(this); if (mapOptions.mapMode != MapMode.SINGLE) { mapOptions.title = StringUtils.EMPTY; } else { // reset target cache on single mode map targetGeocode = mapOptions.geocode; } return true; case R.id.menu_store_caches: return storeCaches(caches.getVisibleGeocodes()); case R.id.menu_store_unsaved_caches: return storeCaches(getUnsavedGeocodes(caches.getVisibleGeocodes())); case R.id.menu_circle_mode: // overlayCaches.switchCircles(); // mapView.repaintRequired(overlayCaches); // ActivityMixin.invalidateOptionsMenu(activity); return true; case R.id.menu_mycaches_mode: Settings.setExcludeMine(!Settings.isExcludeMyCaches()); caches.invalidate(); ActivityMixin.invalidateOptionsMenu(this); if (!Settings.isExcludeMyCaches()) { Tile.cache.clear(); } return true; case R.id.menu_disabled_mode: Settings.setExcludeDisabled(!Settings.isExcludeDisabledCaches()); caches.invalidate(); ActivityMixin.invalidateOptionsMenu(this); if (!Settings.isExcludeDisabledCaches()) { Tile.cache.clear(); } return true; case R.id.menu_theme_mode: selectMapTheme(); return true; case R.id.menu_as_list: { CacheListActivity.startActivityMap(this, new SearchResult(caches.getVisibleGeocodes())); return true; } case R.id.menu_strategy_fast: { item.setChecked(true); Settings.setLiveMapStrategy(LivemapStrategy.FAST); return true; } case R.id.menu_strategy_auto: { item.setChecked(true); Settings.setLiveMapStrategy(LivemapStrategy.AUTO); return true; } case R.id.menu_strategy_detailed: { item.setChecked(true); Settings.setLiveMapStrategy(LivemapStrategy.DETAILED); return true; } case R.id.menu_routing_straight: { item.setChecked(true); Settings.setRoutingMode(RoutingMode.STRAIGHT); navigationLayer.requestRedraw(); return true; } case R.id.menu_routing_walk: { item.setChecked(true); Settings.setRoutingMode(RoutingMode.WALK); navigationLayer.requestRedraw(); return true; } case R.id.menu_routing_bike: { item.setChecked(true); Settings.setRoutingMode(RoutingMode.BIKE); navigationLayer.requestRedraw(); return true; } case R.id.menu_routing_car: { item.setChecked(true); Settings.setRoutingMode(RoutingMode.CAR); navigationLayer.requestRedraw(); return true; } case R.id.menu_hint: menuShowHint(); return true; case R.id.menu_compass: menuCompass(); return true; default: final MapSource mapSource = MapProviderFactory.getMapSource(id); if (mapSource != null) { item.setChecked(true); changeMapSource(mapSource); return true; } } return false; } private Set<String> getUnsavedGeocodes(final Set<String> geocodes) { final Set<String> unsavedGeocodes = new HashSet<>(); for (final String geocode : geocodes) { if (!DataStore.isOffline(geocode, null)) { unsavedGeocodes.add(geocode); } } return unsavedGeocodes; } private boolean storeCaches(final Set<String> geocodes) { if (!caches.isDownloading()) { if (geocodes.isEmpty()) { ActivityMixin.showToast(this, res.getString(R.string.warn_save_nothing)); return true; } if (Settings.getChooseList()) { // let user select list to store cache in new StoredList.UserInterface(this).promptForMultiListSelection(R.string.list_title, new Action1<Set<Integer>>() { @Override public void call(final Set<Integer> selectedListIds) { storeCaches(geocodes, selectedListIds); } }, true, Collections.singleton(StoredList.TEMPORARY_LIST.id), false); } else { storeCaches(geocodes, Collections.singleton(StoredList.STANDARD_LIST_ID)); } } return true; } private void menuCompass() { final Geocache cache = getCurrentTargetCache(); if (cache != null) { CompassActivity.startActivityCache(this, cache); } } private void menuShowHint() { final Geocache cache = getCurrentTargetCache(); if (cache != null) { cache.showHintToast(this); } } private void prepareFilterBar() { // show the filter warning bar if the filter is set if (Settings.getCacheType() != CacheType.ALL) { final String cacheType = Settings.getCacheType().getL10n(); final TextView filterTitleView = ButterKnife.findById(this, R.id.filter_text); filterTitleView.setText(cacheType); findViewById(R.id.filter_bar).setVisibility(View.VISIBLE); } else { findViewById(R.id.filter_bar).setVisibility(View.GONE); } } /** * @param view Not used here, required by layout */ public void showFilterMenu(final View view) { // do nothing, the filter bar only shows the global filter } private void selectMapTheme() { final File[] themeFiles = Settings.getMapThemeFiles(); String currentTheme = StringUtils.EMPTY; final String currentThemePath = Settings.getCustomRenderThemeFilePath(); if (StringUtils.isNotEmpty(currentThemePath)) { final File currentThemeFile = new File(currentThemePath); currentTheme = currentThemeFile.getName(); } final List<String> names = new ArrayList<>(); names.add(res.getString(R.string.map_theme_builtin)); int currentItem = 0; for (final File file : themeFiles) { if (currentTheme.equalsIgnoreCase(file.getName())) { currentItem = names.size(); } names.add(file.getName()); } final int selectedItem = currentItem; final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.map_theme_select); builder.setSingleChoiceItems(names.toArray(new String[names.size()]), selectedItem, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int newItem) { if (newItem != selectedItem) { // Adjust index because of <default> selection if (newItem > 0) { Settings.setCustomRenderThemeFile(themeFiles[newItem - 1].getPath()); } else { Settings.setCustomRenderThemeFile(StringUtils.EMPTY); } setMapTheme(); } dialog.cancel(); } }); builder.show(); } protected void setMapTheme() { if (tileLayer == null || tileLayer.getTileLayer() == null) { return; } if (!tileLayer.hasThemes()) { tileLayer.getTileLayer().requestRedraw(); return; } final TileRendererLayer rendererLayer = (TileRendererLayer) tileLayer.getTileLayer(); final String themePath = Settings.getCustomRenderThemeFilePath(); if (StringUtils.isEmpty(themePath)) { rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER); } else { try { final XmlRenderTheme xmlRenderTheme = new ExternalRenderTheme(new File(themePath)); // Validate the theme file RenderThemeHandler.getRenderTheme(AndroidGraphicFactory.INSTANCE, new DisplayModel(), xmlRenderTheme); rendererLayer.setXmlRenderTheme(xmlRenderTheme); } catch (final IOException e) { Log.w("Failed to set render theme", e); ActivityMixin.showApplicationToast(getString(R.string.err_rendertheme_file_unreadable)); rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER); } catch (final XmlPullParserException e) { Log.w("render theme invalid", e); ActivityMixin.showApplicationToast(getString(R.string.err_rendertheme_invalid)); rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER); } } tileCache.purge(); rendererLayer.requestRedraw(); } private void changeMapSource(@NonNull final MapSource newSource) { final MapSource oldSource = Settings.getMapSource(); final boolean restartRequired = !MapProviderFactory.isSameActivity(oldSource, newSource); // Update MapSource in settings Settings.setMapSource(newSource); if (restartRequired) { mapRestart(); } else if (mapView != null) { // changeMapSource can be called by onCreate() switchTileLayer(newSource); } } /** * Restart the current activity with the default map source. */ private void mapRestart() { mapOptions.mapState = currentMapState(); finish(); mapOptions.startIntent(this, Settings.getMapProvider().getMapClass()); } /** * Get the current map state from the map view if it exists or from the mapStateIntent field otherwise. * * @return the current map state as an array of int, or null if no map state is available */ private MapState currentMapState() { if (mapView == null) { return null; } final Geopoint mapCenter = mapView.getViewport().getCenter(); return new MapState(mapCenter.getCoords(), mapView.getMapZoomLevel(), followMyLocation, false, null, null, mapOptions.isLiveEnabled, false); } private void switchTileLayer(final MapSource newSource) { final ITileLayer oldLayer = this.tileLayer; ITileLayer newLayer = null; if (newSource instanceof MapsforgeMapSource) { newLayer = ((MapsforgeMapSource) newSource).createTileLayer(tileCache, this.mapView.getModel().mapViewPosition); } // Exchange layer if (newLayer != null) { this.mapView.getModel().displayModel.setFixedTileSize(newLayer.getFixedTileSize()); final MapZoomControls zoomControls = mapView.getMapZoomControls(); zoomControls.setZoomLevelMax(newLayer.getZoomLevelMax()); zoomControls.setZoomLevelMin(newLayer.getZoomLevelMin()); final Layers layers = this.mapView.getLayerManager().getLayers(); int index = 0; if (oldLayer != null) { index = layers.indexOf(oldLayer.getTileLayer()) + 1; } layers.add(index, newLayer.getTileLayer()); this.tileLayer = newLayer; this.setMapTheme(); } else { this.tileLayer = null; } // Cleanup if (oldLayer != null) { this.mapView.getLayerManager().getLayers().remove(oldLayer.getTileLayer()); oldLayer.getTileLayer().onDestroy(); } tileCache.purge(); } private void resumeTileLayer() { if (this.tileLayer != null) { this.tileLayer.onResume(); } } private void pauseTileLayer() { if (this.tileLayer != null) { this.tileLayer.onPause(); } } private boolean tileLayerHasThemes() { if (tileLayer != null) { return tileLayer.hasThemes(); } return false; } @Override protected void onResume() { super.onResume(); resumeTileLayer(); } @Override protected void onStart() { super.onStart(); initializeLayers(); } private void initializeLayers() { switchTileLayer(Settings.getMapSource()); // History Layer this.historyLayer = new HistoryLayer(trailHistory); this.mapView.getLayerManager().getLayers().add(this.historyLayer); // NavigationLayer Geopoint navTarget = lastNavTarget; if (navTarget == null) { navTarget = mapOptions.coords; if (navTarget == null && StringUtils.isNotEmpty(mapOptions.geocode)) { final Viewport bounds = DataStore.getBounds(mapOptions.geocode); if (bounds != null) { navTarget = bounds.center; } } } this.navigationLayer = new NavigationLayer(navTarget); this.mapView.getLayerManager().getLayers().add(this.navigationLayer); // TapHandler final TapHandlerLayer tapHandlerLayer = new TapHandlerLayer(this.mapHandlers.getTapHandler()); this.mapView.getLayerManager().getLayers().add(tapHandlerLayer); // Caches bundle if (mapOptions.searchResult != null) { this.caches = new CachesBundle(mapOptions.searchResult, this.mapView, this.mapHandlers); } else if (StringUtils.isNotEmpty(mapOptions.geocode)) { this.caches = new CachesBundle(mapOptions.geocode, this.mapView, this.mapHandlers); } else if (mapOptions.coords != null) { this.caches = new CachesBundle(mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers); } else { caches = new CachesBundle(this.mapView, this.mapHandlers); } // Stored enabled map caches.enableStoredLayers(mapOptions.isStoredEnabled); // Live enabled map caches.handleLiveLayers(mapOptions.isLiveEnabled); // Position layer this.positionLayer = new PositionLayer(); this.mapView.getLayerManager().getLayers().add(positionLayer); //Distance view this.distanceView = new DistanceView(navTarget, (TextView) findViewById(R.id.distance)); //Target view this.targetView = new TargetView((TextView) findViewById(R.id.target), StringUtils.EMPTY, StringUtils.EMPTY); final Geocache target = getCurrentTargetCache(); if (target != null) { targetView.setTarget(target.getGeocode(), target.getName()); } this.resumeDisposables.add(this.geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR)); } @Override public void onPause() { savePrefs(); pauseTileLayer(); super.onPause(); } @Override protected void onStop() { waitDialog = null; terminateLayers(); super.onStop(); } private void terminateLayers() { this.resumeDisposables.clear(); this.caches.onDestroy(); this.caches = null; this.mapView.getLayerManager().getLayers().remove(this.positionLayer); this.positionLayer = null; this.mapView.getLayerManager().getLayers().remove(this.navigationLayer); this.navigationLayer = null; this.mapView.getLayerManager().getLayers().remove(this.historyLayer); this.historyLayer = null; if (this.tileLayer != null) { this.mapView.getLayerManager().getLayers().remove(this.tileLayer.getTileLayer()); this.tileLayer.getTileLayer().onDestroy(); this.tileLayer = null; } } /** * store caches, invoked by "store offline" menu item * * @param listIds the lists to store the caches in */ private void storeCaches(final Set<String> geocodes, final Set<Integer> listIds) { final int count = geocodes.size(); final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(count, this); waitDialog = new ProgressDialog(this); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setCancelMessage(loadDetailsHandler.disposeMessage()); waitDialog.setMax(count); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(final DialogInterface arg0) { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } } catch (final Exception e) { Log.e("CGeoMap.storeCaches.onCancel", e); } } }); final float etaTime = count * 7.0f / 60.0f; final int roundedEta = Math.round(etaTime); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta, roundedEta)); } loadDetailsHandler.setStart(); waitDialog.show(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes, listIds); loadDetailsThread.start(); } @Override protected void onDestroy() { this.tileCache.destroy(); this.mapView.getModel().mapViewPosition.destroy(); this.mapView.destroy(); AndroidResourceBitmap.clearResourceBitmaps(); Routing.disconnect(); super.onDestroy(); } @Override protected void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); final MapState state = prepareMapState(); outState.putParcelable(BUNDLE_MAP_STATE, state); if (historyLayer != null) { outState.putParcelableArrayList(BUNDLE_TRAIL_HISTORY, historyLayer.getHistory()); } } private MapState prepareMapState() { return new MapState(MapsforgeUtils.toGeopoint(mapView.getModel().mapViewPosition.getCenter()), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled); } private void centerMap(final Geopoint geopoint) { mapView.getModel().mapViewPosition.setCenter(new LatLong(geopoint.getLatitude(), geopoint.getLongitude())); } public Location getCoordinates() { final LatLong center = mapView.getModel().mapViewPosition.getCenter(); final Location loc = new Location("newmap"); loc.setLatitude(center.latitude); loc.setLongitude(center.longitude); return loc; } private void initMyLocationSwitchButton(final CheckBox locSwitch) { myLocSwitch = locSwitch; /* * TODO: Switch back to ImageSwitcher for animations? * myLocSwitch.setFactory(this); * myLocSwitch.setInAnimation(activity, android.R.anim.fade_in); * myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); */ myLocSwitch.setOnClickListener(new MyLocationListener(this)); switchMyLocationButton(); } // switch My Location button image private void switchMyLocationButton() { myLocSwitch.setChecked(followMyLocation); if (followMyLocation) { myLocationInMiddle(Sensors.getInstance().currentGeo()); } } public void showAddWaypoint(final LatLong tapLatLong) { final Geocache cache = getCurrentTargetCache(); if (cache != null) { EditWaypointActivity.startActivityAddWaypoint(this, cache, new Geopoint(tapLatLong.latitude, tapLatLong.longitude)); } } // set my location listener private static class MyLocationListener implements View.OnClickListener { @NonNull private final WeakReference<NewMap> mapRef; MyLocationListener(@NonNull final NewMap map) { mapRef = new WeakReference<>(map); } private void onFollowMyLocationClicked() { followMyLocation = !followMyLocation; final NewMap map = mapRef.get(); if (map != null) { map.switchMyLocationButton(); } } @Override public void onClick(final View view) { onFollowMyLocationClicked(); } } // Set center of map to my location if appropriate. private void myLocationInMiddle(final GeoData geo) { if (followMyLocation) { centerMap(geo.getCoords()); } } private static final class DisplayHandler extends Handler { @NonNull private final WeakReference<NewMap> mapRef; DisplayHandler(@NonNull final NewMap map) { this.mapRef = new WeakReference<>(map); } @Override public void handleMessage(final Message msg) { final NewMap map = mapRef.get(); if (map == null) { return; } final int what = msg.what; switch (what) { case UPDATE_TITLE: map.setTitle(); map.setSubtitle(); break; case INVALIDATE_MAP: map.mapView.repaint(); break; default: break; } } } private void setTitle() { final String title = calculateTitle(); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(title); } } @NonNull private String calculateTitle() { if (mapOptions.isLiveEnabled) { return res.getString(R.string.map_live); } if (mapOptions.mapMode == MapMode.SINGLE) { final Geocache cache = getSingleModeCache(); if (cache != null) { return cache.getName(); } } return StringUtils.defaultIfEmpty(mapOptions.title, res.getString(R.string.map_map)); } private void setSubtitle() { final String subtitle = calculateSubtitle(); if (StringUtils.isEmpty(subtitle)) { return; } final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setSubtitle(subtitle); } } @NonNull private String calculateSubtitle() { if (!mapOptions.isLiveEnabled && mapOptions.mapMode == MapMode.SINGLE) { final Geocache cache = getSingleModeCache(); if (cache != null) { return Formatter.formatMapSubtitle(cache); } } // count caches in the sub title final int visible = countVisibleCaches(); final int total = countTotalCaches(); final StringBuilder subtitle = new StringBuilder(); if (total != 0) { if (visible != total && Settings.isDebug()) { subtitle.append(visible).append('/').append(res.getQuantityString(R.plurals.cache_counts, total, total)); } else { subtitle.append(res.getQuantityString(R.plurals.cache_counts, visible, visible)); } } // if (Settings.isDebug() && lastSearchResult != null && StringUtils.isNotBlank(lastSearchResult.getUrl())) { // subtitle.append(" [").append(lastSearchResult.getUrl()).append(']'); return subtitle.toString(); } private int countVisibleCaches() { return caches != null ? caches.getVisibleItemsCount() : 0; } private int countTotalCaches() { return caches != null ? caches.getItemsCount() : 0; } /** * Updates the progress. */ private static final class ShowProgressHandler extends Handler { private int counter = 0; @NonNull private final WeakReference<NewMap> mapRef; ShowProgressHandler(@NonNull final NewMap map) { this.mapRef = new WeakReference<>(map); } @Override public void handleMessage(final Message msg) { final int what = msg.what; if (what == HIDE_PROGRESS) { if (--counter == 0) { showProgress(false); } } else if (what == SHOW_PROGRESS) { showProgress(true); counter++; } } private void showProgress(final boolean show) { final NewMap map = mapRef.get(); if (map == null) { return; } map.setProgressBarIndeterminateVisibility(show); } } private static final class LoadDetailsHandler extends DisposableHandler { private final int detailTotal; private int detailProgress; private long detailProgressTime; private final WeakReference<NewMap> mapRef; LoadDetailsHandler(final int detailTotal, final NewMap map) { super(); this.detailTotal = detailTotal; this.detailProgress = 0; this.mapRef = new WeakReference<>(map); } public void setStart() { detailProgressTime = System.currentTimeMillis(); } @Override public void handleRegularMessage(final Message msg) { final NewMap map = mapRef.get(); if (map == null) { return; } if (msg.what == UPDATE_PROGRESS) { if (detailProgress < detailTotal) { detailProgress++; } if (map.waitDialog != null) { final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); final int secondsRemaining; if (detailProgress > 0) { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress; } else { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed; } map.waitDialog.setProgress(detailProgress); if (secondsRemaining < 40) { map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getString(R.string.caches_eta_ltm)); } else { final int minsRemaining = secondsRemaining / 60; map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining)); } } } else if (msg.what == FINISHED_LOADING_DETAILS && map.waitDialog != null) { map.waitDialog.dismiss(); map.waitDialog.setOnCancelListener(null); } } @Override public void handleDispose() { final NewMap map = mapRef.get(); if (map == null) { return; } if (map.loadDetailsThread != null) { map.loadDetailsThread.stopIt(); } } } // class: update location private static class UpdateLoc extends GeoDirHandler { // use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible // minimum time in milliseconds between position overlay updates private static final long MIN_UPDATE_INTERVAL = 500; // minimum change of heading in grad for position overlay update private static final float MIN_HEADING_DELTA = 15f; // minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update private static final float MIN_LOCATION_DELTA = 0.01f; @NonNull Location currentLocation = Sensors.getInstance().currentGeo(); float currentHeading; private long timeLastPositionOverlayCalculation = 0; /** * weak reference to the outer class */ @NonNull private final WeakReference<NewMap> mapRef; UpdateLoc(@NonNull final NewMap map) { mapRef = new WeakReference<>(map); } @Override public void updateGeoDir(@NonNull final GeoData geo, final float dir) { currentLocation = geo; currentHeading = AngleUtils.getDirectionNow(dir); repaintPositionOverlay(); } @NonNull public Location getCurrentLocation() { return currentLocation; } /** * Repaint position overlay but only with a max frequency and if position or heading changes sufficiently. */ void repaintPositionOverlay() { final long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis > timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL) { timeLastPositionOverlayCalculation = currentTimeMillis; try { final NewMap map = mapRef.get(); if (map != null) { final boolean needsRepaintForDistanceOrAccuracy = needsRepaintForDistanceOrAccuracy(); final boolean needsRepaintForHeading = needsRepaintForHeading(); if (needsRepaintForDistanceOrAccuracy && NewMap.followMyLocation) { map.centerMap(new Geopoint(currentLocation)); } if (needsRepaintForDistanceOrAccuracy || needsRepaintForHeading) { map.historyLayer.setCoordinates(currentLocation); map.navigationLayer.setCoordinates(currentLocation); map.distanceView.setCoordinates(currentLocation); map.positionLayer.setCoordinates(currentLocation); map.positionLayer.setHeading(currentHeading); map.positionLayer.requestRedraw(); } } } catch (final RuntimeException e) { Log.w("Failed to update location", e); } } } boolean needsRepaintForHeading() { final NewMap map = mapRef.get(); if (map == null) { return false; } return Math.abs(AngleUtils.difference(currentHeading, map.positionLayer.getHeading())) > MIN_HEADING_DELTA; } boolean needsRepaintForDistanceOrAccuracy() { final NewMap map = mapRef.get(); if (map == null) { return false; } final Location lastLocation = map.getCoordinates(); float dist = Float.MAX_VALUE; if (lastLocation != null) { if (lastLocation.getAccuracy() != currentLocation.getAccuracy()) { return true; } dist = currentLocation.distanceTo(lastLocation); } final float[] mapDimension = new float[1]; if (map.mapView.getWidth() < map.mapView.getHeight()) { final double span = map.mapView.getLongitudeSpan() / 1e6; Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension); } else { final double span = map.mapView.getLatitudeSpan() / 1e6; Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension); } return dist > (mapDimension[0] * MIN_LOCATION_DELTA); } } private static class DragHandler implements OnMapDragListener { @NonNull private final WeakReference<NewMap> mapRef; DragHandler(@NonNull final NewMap parent) { mapRef = new WeakReference<>(parent); } @Override public void onDrag() { final NewMap map = mapRef.get(); if (map != null && NewMap.followMyLocation) { NewMap.followMyLocation = false; map.switchMyLocationButton(); } } } public void showSelection(@NonNull final List<GeoitemRef> items) { if (items.isEmpty()) { return; } if (items.size() == 1) { showPopup(items.get(0)); return; } try { final ArrayList<GeoitemRef> sorted = new ArrayList<>(items); Collections.sort(sorted, GeoitemRef.NAME_COMPARATOR); final LayoutInflater inflater = LayoutInflater.from(this); final ListAdapter adapter = new ArrayAdapter<GeoitemRef>(this, R.layout.cacheslist_item_select, sorted) { @NonNull @Override public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) { final View view = convertView == null ? inflater.inflate(R.layout.cacheslist_item_select, parent, false) : convertView; final TextView tv = (TextView) view.findViewById(R.id.text); final GeoitemRef item = getItem(position); tv.setText(item.getName()); //Put the image on the TextView tv.setCompoundDrawablesWithIntrinsicBounds(item.getMarkerId(), 0, 0, 0); final TextView infoView = (TextView) view.findViewById(R.id.info); StringBuilder text = new StringBuilder(item.getItemCode()); if (item.getType() == CoordinatesType.WAYPOINT && StringUtils.isNotEmpty(item.getGeocode())) { text.append(Formatter.SEPARATOR).append(item.getGeocode()); Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); if (cache != null) { text.append(Formatter.SEPARATOR).append(cache.getName()); } } infoView.setText(text.toString()); return view; } }; final AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(res.getString(R.string.map_select_multiple_items)) .setAdapter(adapter, new SelectionClickListener(sorted)) .create(); dialog.setCanceledOnTouchOutside(true); dialog.show(); } catch (final NotFoundException e) { Log.e("NewMap.showSelection", e); } } private class SelectionClickListener implements DialogInterface.OnClickListener { @NonNull private final List<GeoitemRef> items; SelectionClickListener(@NonNull final List<GeoitemRef> items) { this.items = items; } @Override public void onClick(final DialogInterface dialog, final int which) { if (which >= 0 && which < items.size()) { final GeoitemRef item = items.get(which); showPopup(item); } } } private void showPopup(final GeoitemRef item) { if (item == null || StringUtils.isEmpty(item.getGeocode())) { return; } try { if (item.getType() == CoordinatesType.CACHE) { final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); if (cache != null) { final RequestDetailsThread requestDetailsThread = new RequestDetailsThread(cache, this); requestDetailsThread.start(); return; } return; } if (item.getType() == CoordinatesType.WAYPOINT && item.getId() >= 0) { popupGeocodes.add(item.getGeocode()); WaypointPopup.startActivityAllowTarget(this, item.getId(), item.getGeocode()); } } catch (final NotFoundException e) { Log.e("NewMap.showPopup", e); } } @Nullable private Geocache getSingleModeCache() { if (StringUtils.isNotBlank(mapOptions.geocode)) { return DataStore.loadCache(mapOptions.geocode, LoadFlags.LOAD_CACHE_OR_DB); } return null; } @Nullable private Geocache getCurrentTargetCache() { if (StringUtils.isNotBlank(targetGeocode)) { return DataStore.loadCache(targetGeocode, LoadFlags.LOAD_CACHE_OR_DB); } return null; } private void savePrefs() { Settings.setMapZoom(MapMode.SINGLE, mapView.getMapZoomLevel()); Settings.setMapCenter(new MapsforgeGeoPoint(mapView.getModel().mapViewPosition.getCenter())); } private static class RequestDetailsThread extends Thread { @NonNull private final Geocache cache; @NonNull private final WeakReference<NewMap> map; RequestDetailsThread(@NonNull final Geocache cache, @NonNull final NewMap map) { this.cache = cache; this.map = new WeakReference<>(map); } public boolean requestRequired() { return CacheType.UNKNOWN == cache.getType() || cache.getDifficulty() == 0; } @Override public void run() { final NewMap map = this.map.get(); if (map == null) { return; } if (requestRequired()) { try { /* final SearchResult search = */ GCMap.searchByGeocodes(Collections.singleton(cache.getGeocode())); } catch (final Exception ex) { Log.w("Error requesting cache popup info", ex); ActivityMixin.showToast(map, R.string.err_request_popup_info); } } map.popupGeocodes.add(cache.getGeocode()); CachePopup.startActivityAllowTarget(map, cache.getGeocode()); } } /** * Thread to store the caches in the viewport. Started by Activity. */ private class LoadDetails extends Thread { private final DisposableHandler handler; private final Collection<String> geocodes; private final Set<Integer> listIds; LoadDetails(final DisposableHandler handler, final Collection<String> geocodes, final Set<Integer> listIds) { this.handler = handler; this.geocodes = geocodes; this.listIds = listIds; } public void stopIt() { handler.dispose(); } @Override public void run() { if (CollectionUtils.isEmpty(geocodes)) { return; } for (final String geocode : geocodes) { try { if (handler.isDisposed()) { break; } if (!DataStore.isOffline(geocode, null)) { Geocache.storeCache(null, geocode, listIds, false, handler); } } catch (final Exception e) { Log.e("CGeoMap.LoadDetails.run", e); } finally { handler.sendEmptyMessage(UPDATE_PROGRESS); } } // we're done caches.invalidate(geocodes); invalidateOptionsMenuCompatible(); handler.sendEmptyMessage(FINISHED_LOADING_DETAILS); } } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == AbstractDialogFragment.REQUEST_CODE_TARGET_INFO) { if (resultCode == AbstractDialogFragment.RESULT_CODE_SET_TARGET) { final TargetInfo targetInfo = data.getExtras().getParcelable(Intents.EXTRA_TARGET_INFO); if (targetInfo != null) { lastNavTarget = targetInfo.coords; if (navigationLayer != null) { navigationLayer.setDestination(targetInfo.coords); navigationLayer.requestRedraw(); } if (distanceView != null) { distanceView.setDestination(targetInfo.coords); distanceView.setCoordinates(geoDirUpdate.getCurrentLocation()); } if (StringUtils.isNotBlank(targetInfo.geocode)) { targetGeocode = targetInfo.geocode; final Geocache target = getCurrentTargetCache(); targetView.setTarget(targetGeocode, target != null ? target.getName() : StringUtils.EMPTY); } } } final List<String> changedGeocodes = new ArrayList<>(); String geocode = popupGeocodes.poll(); while (geocode != null) { changedGeocodes.add(geocode); geocode = popupGeocodes.poll(); } if (caches != null) { caches.invalidate(changedGeocodes); } } } }
package io.mangoo.core; import java.util.HashMap; import java.util.Map; import java.util.Objects; import io.mangoo.enums.Default; import io.mangoo.enums.Header; import io.mangoo.enums.Required; import io.undertow.util.HttpString; /** * * @author svenkubiak * */ public final class Server { private static Map<HttpString, String> headers = Map.of( Header.X_CONTENT_TYPE_OPTIONS.toHttpString(), Default.APPLICATION_HEADERS_XCONTENTTYPEOPTIONS.toString(), Header.X_FRAME_OPTIONS.toHttpString(), Default.APPLICATION_HEADERS_XFRAMEOPTIONS.toString(), Header.X_XSS_PPROTECTION.toHttpString(), Default.APPLICATION_HEADERS_XSSPROTECTION.toString(), Header.REFERER_POLICY.toHttpString(), Default.APPLICATION_HEADERS_REFERERPOLICY.toString(), Header.FEATURE_POLICY.toHttpString(), Default.APPLICATION_HEADERS_FEATUREPOLICY.toString(), Header.CONTENT_SECURITY_POLICY.toHttpString(), Default.APPLICATION_HEADERS_CONTENTSECURITYPOLICY.toString(), Header.SERVER.toHttpString(), Default.APPLICATION_HEADERS_SERVER.toString() ); private Server() { } public static Map<HttpString, String> headers() { return headers; } /** * Sets a custom header that is used globally on server responses * * @param name The name of the header * @param value The value of the header */ public static void header(Header name, String value) { Objects.requireNonNull(name, Required.NAME.toString()); Map<HttpString, String> newHeaders = new HashMap<>(headers); newHeaders.put(name.toHttpString(), value); headers = newHeaders; } }
//FILE: ContrastPanel.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // CVS: $Id$ package org.micromanager.graph; import ij.ImagePlus; import ij.process.ColorProcessor; import ij.process.ImageStatistics; import ij.process.ImageProcessor; import ij.process.LUT; import ij.process.ShortProcessor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.SpringLayout; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.micromanager.utils.ContrastSettings; import org.micromanager.utils.GammaSliderCalculator; import org.micromanager.utils.ImageController; import org.micromanager.utils.ReportingUtils; import org.micromanager.utils.NumberUtils; /** * Slider and histogram panel for adjusting contrast and brightness. * */ public class ContrastPanel extends JPanel implements ImageController, PropertyChangeListener { private static final long serialVersionUID = 1L; private JComboBox modeComboBox_; private HistogramPanel histogramPanel_; private JLabel maxField_; private JLabel minField_; private JLabel avgField_; private JLabel varField_; private SpringLayout springLayout; private ImagePlus image_; private GraphData histogramData_; private JSlider sliderLow_; private JSlider sliderHigh_; private JSlider sliderGamma_; private GammaSliderCalculator gammaSliderCalculator_; private JFormattedTextField gammaValue_; private NumberFormat numberFormat_; private double gamma_ = 1.0; private int maxIntensity_ = 255; private double min_ = 0.0; private double max_ = 255.0; private int binSize_ = 1; private static final int HIST_BINS = 256; private int numLevels_ = 256; //private DecimalFormat twoDForm_ = new DecimalFormat(" ContrastSettings cs8bit_; ContrastSettings cs16bit_; private JCheckBox stretchCheckBox_; private boolean logScale_ = false; private JCheckBox logHistCheckBox_; /** * Create the panel */ public ContrastPanel() { super(); setToolTipText("Switch between linear and log histogram"); setFont(new Font("", Font.PLAIN, 10)); springLayout = new SpringLayout(); setLayout(springLayout); numberFormat_ = NumberFormat.getNumberInstance(); final JButton fullScaleButton_ = new JButton(); fullScaleButton_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { setFullScale(); } }); fullScaleButton_.setFont(new Font("Arial", Font.PLAIN, 10)); fullScaleButton_ .setToolTipText("Set display levels to full pixel range"); fullScaleButton_.setText("Full"); add(fullScaleButton_); springLayout.putConstraint(SpringLayout.EAST, fullScaleButton_, 80, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, fullScaleButton_, 5, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, fullScaleButton_, 25, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, fullScaleButton_, 5, SpringLayout.NORTH, this); final JButton autoScaleButton = new JButton(); autoScaleButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { setAutoScale(); } }); autoScaleButton.setFont(new Font("Arial", Font.PLAIN, 10)); autoScaleButton .setToolTipText("Set display levels to maximum contrast"); autoScaleButton.setText("Auto"); add(autoScaleButton); springLayout.putConstraint(SpringLayout.EAST, autoScaleButton, 80, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, autoScaleButton, 5, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, autoScaleButton, 46, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, autoScaleButton, 26, SpringLayout.NORTH, this); minField_ = new JLabel(); minField_.setFont(new Font("", Font.PLAIN, 10)); add(minField_); springLayout.putConstraint(SpringLayout.EAST, minField_, 95, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, minField_, 45, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, minField_, 78, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, minField_, 64, SpringLayout.NORTH, this); maxField_ = new JLabel(); maxField_.setFont(new Font("", Font.PLAIN, 10)); add(maxField_); springLayout.putConstraint(SpringLayout.EAST, maxField_, 95, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, maxField_, 45, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, maxField_, 94, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, maxField_, 80, SpringLayout.NORTH, this); JLabel minLabel = new JLabel(); minLabel.setFont(new Font("", Font.PLAIN, 10)); minLabel.setText("Min"); add(minLabel); springLayout.putConstraint(SpringLayout.SOUTH, minLabel, 78, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, minLabel, 64, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.EAST, minLabel, 30, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, minLabel, 5, SpringLayout.WEST, this); JLabel maxLabel = new JLabel(); maxLabel.setFont(new Font("", Font.PLAIN, 10)); maxLabel.setText("Max"); add(maxLabel); springLayout.putConstraint(SpringLayout.SOUTH, maxLabel, 94, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, maxLabel, 80, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.EAST, maxLabel, 30, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, maxLabel, 5, SpringLayout.WEST, this); JLabel avgLabel = new JLabel(); avgLabel.setFont(new Font("", Font.PLAIN, 10)); avgLabel.setText("Avg"); add(avgLabel); springLayout.putConstraint(SpringLayout.EAST, avgLabel, 42, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, avgLabel, 5, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, avgLabel, 110, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, avgLabel, 96, SpringLayout.NORTH, this); avgField_ = new JLabel(); avgField_.setFont(new Font("", Font.PLAIN, 10)); add(avgField_); springLayout.putConstraint(SpringLayout.EAST, avgField_, 95, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, avgField_, 45, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, avgField_, 110, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, avgField_, 96, SpringLayout.NORTH, this); JLabel varLabel = new JLabel(); varLabel.setFont(new Font("", Font.PLAIN, 10)); varLabel.setText("Std Dev"); add(varLabel); springLayout.putConstraint(SpringLayout.SOUTH, varLabel, 126, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, varLabel, 112, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.EAST, varLabel, 42, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, varLabel, 5, SpringLayout.WEST, this); varField_ = new JLabel(); varField_.setFont(new Font("", Font.PLAIN, 10)); add(varField_); springLayout.putConstraint(SpringLayout.EAST, varField_, 95, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, varField_, 45, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, varField_, 126, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, varField_, 112, SpringLayout.NORTH, this); sliderLow_ = new JSlider(); sliderLow_.addChangeListener(new ChangeListener() { public void stateChanged(final ChangeEvent e) { onSliderMove(); } }); sliderLow_.setToolTipText("Minimum display level"); add(sliderLow_); sliderHigh_ = new JSlider(); sliderHigh_.addChangeListener(new ChangeListener() { public void stateChanged(final ChangeEvent e) { onSliderMove(); } }); sliderHigh_.setToolTipText("Maximum display level"); add(sliderHigh_); springLayout.putConstraint(SpringLayout.EAST, sliderHigh_, -1, SpringLayout.EAST, this); springLayout.putConstraint(SpringLayout.WEST, sliderHigh_, 0, SpringLayout.WEST, sliderLow_); final int gammaLow = 0; final int gammaHigh = 100; gammaSliderCalculator_ = new GammaSliderCalculator(gammaLow, gammaHigh); sliderGamma_ = new JSlider(); sliderGamma_.addChangeListener(new ChangeListener() { public void stateChanged(final ChangeEvent e) { onGammaSliderMove(); } }); sliderGamma_.setToolTipText("Gamma"); sliderGamma_.setMinimum(gammaLow); sliderGamma_.setMaximum(gammaHigh); add(sliderGamma_); springLayout.putConstraint(SpringLayout.EAST, sliderGamma_, -1, SpringLayout.EAST, this); springLayout.putConstraint(SpringLayout.WEST, sliderGamma_, 0, SpringLayout.WEST, sliderLow_); JLabel gammaLabel = new JLabel(); gammaLabel.setFont(new Font("Arial", Font.PLAIN, 10)); gammaLabel.setPreferredSize(new Dimension(40, 15)); gammaLabel.setText("Gamma"); add(gammaLabel); springLayout.putConstraint(SpringLayout.WEST, gammaLabel, 5, SpringLayout.WEST, this); gammaValue_ = new JFormattedTextField(numberFormat_); gammaValue_.setFont(new Font("Arial", Font.PLAIN, 10)); gammaValue_.setValue(gamma_); gammaValue_.addPropertyChangeListener("value", this); gammaValue_.setPreferredSize(new Dimension(35, 15)); add(gammaValue_); springLayout.putConstraint(SpringLayout.WEST, gammaValue_, 45, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.EAST, gammaValue_, 95, SpringLayout.WEST, this); histogramPanel_ = new HistogramPanel(); histogramPanel_.setMargins(1, 1); histogramPanel_.setTextVisible(false); histogramPanel_.setGridVisible(false); add(histogramPanel_); springLayout.putConstraint(SpringLayout.EAST, histogramPanel_, -5, SpringLayout.EAST, this); springLayout.putConstraint(SpringLayout.WEST, histogramPanel_, 100, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, sliderLow_, 29, SpringLayout.SOUTH, histogramPanel_); springLayout.putConstraint(SpringLayout.NORTH, sliderLow_, 4, SpringLayout.SOUTH, histogramPanel_); springLayout.putConstraint(SpringLayout.SOUTH, sliderHigh_, 53, SpringLayout.SOUTH, histogramPanel_); springLayout.putConstraint(SpringLayout.NORTH, sliderHigh_, 28, SpringLayout.SOUTH, histogramPanel_); springLayout.putConstraint(SpringLayout.SOUTH, sliderGamma_, 77, SpringLayout.SOUTH, histogramPanel_); springLayout.putConstraint(SpringLayout.SOUTH, gammaValue_, 0, SpringLayout.SOUTH, sliderGamma_); springLayout.putConstraint(SpringLayout.NORTH, gammaValue_, 0, SpringLayout.NORTH, sliderGamma_); springLayout.putConstraint(SpringLayout.SOUTH, gammaLabel, 0, SpringLayout.SOUTH, sliderGamma_); springLayout.putConstraint(SpringLayout.NORTH, gammaLabel, 0, SpringLayout.NORTH, sliderGamma_); springLayout.putConstraint(SpringLayout.SOUTH, histogramPanel_, -81, SpringLayout.SOUTH, this); springLayout.putConstraint(SpringLayout.NORTH, histogramPanel_, 0, SpringLayout.NORTH, fullScaleButton_); stretchCheckBox_ = new JCheckBox(); stretchCheckBox_.setFont(new Font("", Font.PLAIN, 10)); stretchCheckBox_.setText("Auto-stretch"); stretchCheckBox_.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ce) { if (stretchCheckBox_.isSelected()) setAutoScale(); sliderLow_.setEnabled(!stretchCheckBox_.isSelected()); sliderHigh_.setEnabled(!stretchCheckBox_.isSelected()); }; }); add(stretchCheckBox_); springLayout.putConstraint(SpringLayout.EAST, sliderLow_, -1, SpringLayout.EAST, this); springLayout.putConstraint(SpringLayout.WEST, sliderLow_, 0, SpringLayout.EAST, stretchCheckBox_); springLayout.putConstraint(SpringLayout.EAST, stretchCheckBox_, -2, SpringLayout.WEST, histogramPanel_); springLayout.putConstraint(SpringLayout.WEST, stretchCheckBox_, 1, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.SOUTH, stretchCheckBox_, 185, SpringLayout.NORTH, this); springLayout.putConstraint(SpringLayout.NORTH, stretchCheckBox_, 160, SpringLayout.NORTH, this); modeComboBox_ = new JComboBox(); modeComboBox_.setFont(new Font("", Font.PLAIN, 10)); modeComboBox_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { setIntensityMode(modeComboBox_.getSelectedIndex()-1); } }); modeComboBox_.setModel(new DefaultComboBoxModel(new String[] { "camera", "8bit", "10bit", "12bit", "14bit", "16bit" })); add(modeComboBox_); springLayout.putConstraint(SpringLayout.EAST, modeComboBox_, 0, SpringLayout.EAST, maxField_); springLayout.putConstraint(SpringLayout.WEST, modeComboBox_, 0, SpringLayout.WEST, minLabel); springLayout.putConstraint(SpringLayout.SOUTH, modeComboBox_, 27, SpringLayout.SOUTH, varLabel); springLayout.putConstraint(SpringLayout.NORTH, modeComboBox_, 5, SpringLayout.SOUTH, varLabel); logHistCheckBox_ = new JCheckBox(); logHistCheckBox_.setFont(new Font("", Font.PLAIN, 10)); logHistCheckBox_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { if (logHistCheckBox_.isSelected()) logScale_ = true; else logScale_ = false; update(); } }); logHistCheckBox_.setText("Log hist."); add(logHistCheckBox_); springLayout.putConstraint(SpringLayout.SOUTH, logHistCheckBox_, 0, SpringLayout.NORTH, minField_); springLayout.putConstraint(SpringLayout.NORTH, logHistCheckBox_, -18, SpringLayout.NORTH, minField_); springLayout.putConstraint(SpringLayout.EAST, logHistCheckBox_, 74, SpringLayout.WEST, this); springLayout.putConstraint(SpringLayout.WEST, logHistCheckBox_, 1, SpringLayout.WEST, this); } public void setPixelBitDepth(int depth, boolean forceDepth) { // histogram for 32bits is not supported in this implementation if(depth >= 32) depth = 8; numLevels_ = 1 << depth; maxIntensity_ = numLevels_ - 1; binSize_ = (maxIntensity_ + 1)/ HIST_BINS; // override histogram depth based on the selected mode if (!forceDepth && modeComboBox_.getSelectedIndex() > 0) { setIntensityMode(modeComboBox_.getSelectedIndex()-1); } if (forceDepth) { // update the mode display to camera-auto modeComboBox_.setSelectedIndex(0); } } private void setIntensityMode(int mode) { switch (mode) { case 0: maxIntensity_ = 255; break; case 1: maxIntensity_ = 1023; break; case 2: maxIntensity_ = 4095; break; case 3: maxIntensity_ = 16383; break; case 4: maxIntensity_ = 65535; break; default: break; } binSize_ = (maxIntensity_ + 1) / HIST_BINS; update(); } protected void onSliderMove() { int min = sliderLow_.getValue(); int max = sliderHigh_.getValue(); // correct slider relative positions if necessary if (min >= max) { if (sliderHigh_.getValueIsAdjusting() && max > 0) min = max - 1; else if (max < maxIntensity_) max += 1; sliderHigh_.setValue(max); sliderLow_.setValue(min); } updateCursors(); applyContrastSettings(); } protected void onGammaSliderMove() { gamma_ = gammaSliderCalculator_.sliderToGamma(sliderGamma_.getValue()); if (gammaValue_ != null) { // gamma_ = Double.valueOf(numberFormat_.format(gamma_)); gammaValue_.setValue(gamma_); } } // only used for Gamma public void propertyChange(PropertyChangeEvent e) { try { gamma_ = (double) NumberUtils.displayStringToDouble(numberFormat_.format(gammaValue_.getValue())); } catch (ParseException p) { ReportingUtils.logError(p, "ContrastPanel, Function propertyChange"); } sliderGamma_.setValue(gammaSliderCalculator_.gammaToSlider(gamma_)); setLutGamma(gamma_); } private void setLutGamma(double gamma_) { if (image_ == null) return; if (gamma_ == 1) return; // TODO: deal with color images if (image_.getProcessor() instanceof ColorProcessor) return; //if (!ip.isDefaultLut()) // funny, does not work // return; ImageProcessor ip = image_.getProcessor(); double maxValue = 255.0; byte[] r = new byte[256]; byte[] g = new byte[256]; byte[] b = new byte[256]; for (int i=0; i<256; i++) { double val = Math.pow((double) i/maxValue, gamma_) * (double)maxValue; r[i] = (byte) val; g[i] = (byte) val; b[i] = (byte) val; } LUT lut = new LUT(8, 256, r, g, b); ip.setColorModel(lut); image_.updateAndDraw(); } public void update() { // calculate histogram if (image_ == null || image_.getProcessor() == null) return; int rawHistogram[] = image_.getProcessor().getHistogram(); if (histogramData_ == null) histogramData_ = new GraphData(); // preprocess histogram to conform to the current mode and to use only // 256 bins int histogram[] = new int[HIST_BINS]; int limit = Math.min(rawHistogram.length / binSize_, HIST_BINS); int total = 0; for (int i = 0; i < limit; i++) { histogram[i] = 0; for (int j = 0; j < binSize_; j++) { histogram[i] += rawHistogram[i * binSize_ + j]; } total += histogram[i]; } // work around what is apparently a bug in ImageJ if (total == 0) { if (image_.getProcessor().getMin() == 0) histogram[0] = image_.getWidth() * image_.getHeight(); else histogram[limit-1] = image_.getWidth() * image_.getHeight(); } // log scale if (logScale_) { for (int i = 0; i < histogram.length; i++) histogram[i] = histogram[i] > 0 ? (int) (1000 * Math .log(histogram[i])) : 0; } if (stretchCheckBox_.isSelected()) setAutoScale(); histogramData_.setData(histogram); histogramPanel_.setData(histogramData_); histogramPanel_.setAutoScale(); ImageStatistics stats = image_.getStatistics(); maxField_.setText(NumberUtils.intToDisplayString((int)stats.max)); max_ = stats.max; minField_.setText(NumberUtils.intToDisplayString((int)stats.min)); min_ = stats.min; avgField_.setText(NumberUtils.intToDisplayString((int)stats.mean)); //varField_.setText(Double.toString(Double.valueOf(twoDForm_.format(stats.stdDev)))); varField_.setText(NumberUtils.doubleToDisplayString(stats.stdDev)); if (min_ == max_) if (min_ == 0) max_ += 1; else min_ -= 1; setLutGamma(gamma_); updateSliders(); image_.updateAndDraw(); } private void updateSliders(boolean force, int min, int max) { // set sliders without activating them. ChangeListener[] l1 = sliderLow_.getChangeListeners(); ChangeListener[] l2 = sliderHigh_.getChangeListeners(); for (ChangeListener l:l1) sliderLow_.removeChangeListener(l); for (ChangeListener l:l2) sliderHigh_.removeChangeListener(l); sliderLow_.setMinimum(0); sliderLow_.setMaximum(maxIntensity_); if (!sliderLow_.isEnabled() || force) sliderLow_.setValue(min); sliderHigh_.setMinimum(0); sliderHigh_.setMaximum(maxIntensity_); if (!sliderHigh_.isEnabled() || force) { sliderHigh_.setValue(max); } for (ChangeListener l:l1) sliderLow_.addChangeListener(l); for (ChangeListener l:l2) sliderHigh_.addChangeListener(l); updateCursors(); } private void updateSliders(boolean force) { updateSliders(force, Math.max((int)min_, 0), Math.min((int)max_, maxIntensity_)); } private void updateSliders() { updateSliders(false); } // override from ImageController public void setImagePlus(ImagePlus ip, ContrastSettings cs8bit, ContrastSettings cs16bit) { cs8bit_ = cs8bit; cs16bit_ = cs16bit; image_ = ip; setIntensityMode(modeComboBox_.getSelectedIndex()-1); } /** * Auto-scales image display to clip at minimum and maximum pixel values. * */ private void setAutoScale() { if (image_ == null) { return; } // protect against an 'Unhandled Exception' inside getStatistics if ( null != image_.getProcessor()){ ImageStatistics stats = image_.getStatistics(); int min = (int) stats.min; int max = (int) stats.max; if (min == max) if (min == 0) max += 1; else min -= 1; updateSliders(true, min, max); } else{ ReportingUtils.logError("Internal error: ImageProcessor is null"); } image_.updateAndDraw(); } private void setFullScale() { if (image_ == null) return; image_.getProcessor().setMinAndMax(0, maxIntensity_); updateSliders(true, 0, maxIntensity_); image_.updateAndDraw(); } private void updateCursors() { if (image_ == null) return; histogramPanel_.setCursors(sliderLow_.getValue() / binSize_, sliderHigh_.getValue() / binSize_); histogramPanel_.repaint(); if (cs8bit_ == null || cs16bit_ == null) return; if (image_.getProcessor() != null) { // record settings if (image_.getProcessor() instanceof ShortProcessor) { cs16bit_.min = sliderLow_.getValue(); cs16bit_.max = sliderHigh_.getValue(); image_.getProcessor().setMinAndMax(cs16bit_.min, cs16bit_.max); } else { cs8bit_.min = sliderLow_.getValue(); cs8bit_.max = sliderHigh_.getValue(); image_.getProcessor().setMinAndMax(cs8bit_.min, cs8bit_.max); } } } public void setContrastSettings(ContrastSettings cs8bit, ContrastSettings cs16bit) { cs8bit_ = cs8bit; cs16bit_ = cs16bit; } public void applyContrastSettings() { applyContrastSettings(cs8bit_, cs16bit_); }; public void applyContrastSettings(ContrastSettings contrast8, ContrastSettings contrast16) { applyContrastSettings(image_, contrast8, contrast16); } public void applyContrastSettings(ImagePlus img, ContrastSettings contrast8, ContrastSettings contrast16) { if (img == null) return; if (img.getProcessor() instanceof ShortProcessor) { img.getProcessor().setMinAndMax(contrast16.min, contrast16.max); } else { img.getProcessor().setMinAndMax(contrast8.min, contrast8.max); } updateSliders(); img.updateAndDraw(); } public void setContrastStretch(boolean stretch) { stretchCheckBox_.setSelected(stretch); } public boolean isContrastStretch() { return stretchCheckBox_.isSelected(); } public ContrastSettings getContrastSettings() { if (image_.getProcessor() instanceof ShortProcessor) return cs16bit_; else return cs8bit_; } }
package com.markupartist.sthlmtraveling; import com.markupartist.sthlmtraveling.service.DeviationService; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceActivity; import android.widget.Toast; public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { private static final String TAG = "SettingsActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals("prefered_language_preference")) { MyApplication application = (MyApplication) getApplication(); application.reloadLocaleForApplication(); Toast.makeText(this, R.string.restart_app_for_full_effect, Toast.LENGTH_LONG).show(); } else if (key.equals("notification_deviations_enabled")) { DeviationService.startAsRepeating(SettingsActivity.this); } Toast.makeText(this, R.string.settings_saved, Toast.LENGTH_LONG).show(); } @Override protected void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); // Unregister the listener whenever a key changes getPreferenceScreen().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } }
package nallar.tickthreading.patcher; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException; import javassist.RemappingPool; import nallar.tickthreading.Log; import nallar.tickthreading.mappings.ClassDescription; import nallar.tickthreading.mappings.FieldDescription; import nallar.tickthreading.mappings.MCPMappings; import nallar.tickthreading.mappings.Mappings; import nallar.tickthreading.mappings.MethodDescription; import nallar.tickthreading.util.CollectionsUtil; import nallar.tickthreading.util.DomUtil; import nallar.tickthreading.util.LocationUtil; import nallar.tickthreading.util.VersionUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class PatchManager { private Document configDocument; private Object patchTypes; // Patch name -> patch method descriptor private final Map<String, PatchMethodDescriptor> patches = new HashMap<String, PatchMethodDescriptor>(); public final ClassRegistry classRegistry = new ClassRegistry(); public File backupDirectory; public String patchEnvironment = "forge"; public Map<String, CtClass> patchingClasses; public PatchManager(InputStream configStream, Class<? extends Patches> patchClass) throws IOException, SAXException { this(configStream, patchClass, new File(LocationUtil.directoryOf(patchClass).getAbsoluteFile().getParentFile(), "TickThreadingBackups")); } public PatchManager(InputStream configStream, Class<? extends Patches> patchClass, File backupDirectory) throws IOException, SAXException { loadPatches(patchClass); loadConfig(configStream); this.backupDirectory = backupDirectory; } public void loadBackups(Iterable<File> filesToLoad) { try { classRegistry.disableJavassistLoading = true; classRegistry.loadFiles(filesToLoad); classRegistry.loadPatchHashes(this); classRegistry.restoreBackups(backupDirectory); classRegistry.clearClassInfo(); classRegistry.disableJavassistLoading = false; } catch (IOException e) { Log.severe("Failed to load jars for backup restore"); } } void loadPatches(Class<? extends Patches> patchClass) { try { patchTypes = patchClass.getDeclaredConstructors()[0].newInstance(this, classRegistry); } catch (Exception e) { Log.severe("Failed to instantiate patch class", e); } for (Method method : patchClass.getDeclaredMethods()) { for (Annotation annotation : method.getDeclaredAnnotations()) { if (annotation instanceof Patch) { PatchMethodDescriptor patchMethodDescriptor = new PatchMethodDescriptor(method, (Patch) annotation); patches.put(patchMethodDescriptor.name, patchMethodDescriptor); } } } } void loadConfig(InputStream configInputStream) throws IOException, SAXException { configDocument = DomUtil.readDocumentFromInputStream(configInputStream); } static boolean minecraftCommonDeobfuscate(Element classElement, Mappings mappings) { if ("minecraftCommon".equals(((Element) classElement.getParentNode()).getTagName())) { ((MCPMappings) mappings).seargeMappings = false; String className = classElement.getAttribute("id"); ClassDescription deobfuscatedClass = new ClassDescription(className); ClassDescription obfuscatedClass = mappings.map(deobfuscatedClass); if (obfuscatedClass != null) { classElement.setAttribute("id", obfuscatedClass.name); } NodeList patchElements = classElement.getChildNodes(); for (Element patchElement : DomUtil.elementList(patchElements)) { String textContent = patchElement.getTextContent().trim(); List<MethodDescription> methodDescriptionList = MethodDescription.fromListString(deobfuscatedClass.name, textContent); if (!textContent.isEmpty()) { patchElement.setAttribute("deobf", methodDescriptionList.get(0).getShortName()); //noinspection unchecked patchElement.setTextContent(MethodDescription.toListString((List<MethodDescription>) mappings.map(methodDescriptionList))); } String field = patchElement.getAttribute("field"), prefix = ""; if (!field.isEmpty()) { if (field.startsWith("this.")) { field = field.substring("this.".length()); prefix = "this."; } String after = "", type = className; if (field.indexOf('.') != -1) { after = field.substring(field.indexOf('.')); field = field.substring(0, field.indexOf('.')); if (!field.isEmpty() && (field.charAt(0) == '$') && prefix.isEmpty()) { Set<String> parameters = new HashSet<String>(); for (MethodDescription methodDescription : methodDescriptionList) { parameters.add(methodDescription.getParameters()); } if (parameters.size() == 1) { MethodDescription methodDescription = mappings.rmap(mappings.map(methodDescriptionList.get(0))); methodDescription = methodDescription == null ? methodDescriptionList.get(0) : methodDescription; type = methodDescription.getParameterList().get(Integer.valueOf(field.substring(1)) - 1); prefix = field + '.'; field = after.substring(1); after = ""; } } } FieldDescription obfuscatedField = mappings.map(new FieldDescription(type, field)); if (obfuscatedField != null) { patchElement.setAttribute("field", prefix + obfuscatedField.name + after); } } String clazz = patchElement.getAttribute("class"); if (!clazz.isEmpty()) { ClassDescription obfuscatedClazz = mappings.map(new ClassDescription(clazz)); if (obfuscatedClazz != null) { patchElement.setAttribute("class", obfuscatedClazz.name); } } } return true; } return false; } static void postDeobfuscate(Element classElement, Mappings mappings) { for (Element patchElement : DomUtil.elementList(classElement.getChildNodes())) { Map<String, String> attributes = DomUtil.getAttributes(patchElement); for (String key : attributes.keySet()) { String code = patchElement.getAttribute(key); if (!code.isEmpty()) { String obfuscatedCode = mappings.obfuscate(code); if (!code.equals(obfuscatedCode)) { patchElement.setAttribute(key, obfuscatedCode); } } } String textContent = patchElement.getTextContent(); if (textContent != null && !textContent.isEmpty()) { String obfuscatedTextContent = mappings.obfuscate(textContent); if (!textContent.equals(obfuscatedTextContent)) { patchElement.setTextContent(obfuscatedTextContent); } } } } public Map<String, Integer> getHashes() { Map<String, Integer> hashes = new TreeMap<String, Integer>(); List<Element> modElements = DomUtil.elementList(configDocument.getDocumentElement().getChildNodes()); for (Element modElement : modElements) { for (Element classElement : DomUtil.getElementsByTag(modElement, "class")) { String className = classElement.getAttribute("id"); if (className.startsWith("net.minecraft.")) { continue; } hashes.put(className, DomUtil.getHash(classElement) + VersionUtil.TTVersionString().hashCode() * 31); } } return hashes; } public void runPatches(Mappings mappings) { List<Element> modElements = DomUtil.elementList(configDocument.getDocumentElement().getChildNodes()); patchingClasses = new HashMap<String, CtClass>(); Map<String, Boolean> isSrg = new HashMap<String, Boolean>(); for (Element modElement : modElements) { for (Element classElement : DomUtil.getElementsByTag(modElement, "class")) { boolean isMinecraft = minecraftCommonDeobfuscate(classElement, mappings); String className = classElement.getAttribute("id"); if (!classRegistry.shouldPatch(className)) { Log.info(className + " is already patched, skipping."); continue; } String environment = classElement.getAttribute("env"); if (!environment.isEmpty() && !environment.equals(patchEnvironment)) { continue; } Boolean isSrg_; if (!classElement.getAttribute("srg").isEmpty()) { isSrg_ = classRegistry.classes.isSrg = true; } else if (isMinecraft) { isSrg_ = classRegistry.classes.isSrg = false; } else { isSrg_ = classRegistry.classes.setSrgFor(className); } if (mappings instanceof MCPMappings) { ((MCPMappings) mappings).seargeMappings = isSrg_; } postDeobfuscate(classElement, mappings); Boolean previousSrg = isSrg.put(className, isSrg_); if (previousSrg != null && previousSrg != isSrg_) { Log.severe("Class " + className + " was previously marked as srg: " + previousSrg + ", now marked as " + isSrg_); continue; } CtClass ctClass; try { ctClass = classRegistry.getClass(className); } catch (NotFoundException e) { Log.info(className + " will not be patched, as it was not found."); continue; } ClassPool classPool = classRegistry.classes; boolean shouldRemove = false; if (classPool instanceof RemappingPool) { RemappingPool remappingPool = (RemappingPool) classPool; shouldRemove = remappingPool.addCurrentPackage(ctClass.getPackageName()); } try { List<Element> patchElements = DomUtil.elementList(classElement.getChildNodes()); boolean patched = false; for (Element patchElement : patchElements) { PatchMethodDescriptor patch = patches.get(patchElement.getTagName()); if (patch == null) { Log.severe("Patch " + patchElement.getTagName() + " was not found."); continue; } try { Object result = patch.run(patchElement, ctClass); patched = true; if (result instanceof CtClass) { ctClass = (CtClass) result; } } catch (Exception e) { Log.severe("Failed to patch " + ctClass.getName() + " with " + patch.name, e); } } if (patched) { patchingClasses.put(className, ctClass); } } finally { if (shouldRemove) { ((RemappingPool) classPool).removeCurrentPackage(); } } if (!isSrg_) { classRegistry.classes.markChanged(className); } } } for (Map.Entry<String, CtClass> entry : patchingClasses.entrySet()) { String className = entry.getKey(); CtClass ctClass = entry.getValue(); Boolean isSrg_ = isSrg.get(className); classRegistry.classes.isSrg = isSrg_ != null ? isSrg_ : classRegistry.classes.setSrgFor(className); Patches.findUnusedFields(ctClass); try { ctClass.getClassFile().compact(); classRegistry.update(className, ctClass.toBytecode()); } catch (Exception e) { Log.severe("Javassist failed to save " + className, e); } } patchingClasses = null; } public void save(File file) throws TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); Result output = new StreamResult(file); Source input = new DOMSource(configDocument); transformer.transform(input, output); } public class PatchMethodDescriptor { public final String name; public final List<String> requiredAttributes; public final Method patchMethod; public final boolean isClassPatch; public final boolean emptyConstructor; public PatchMethodDescriptor(Method method, Patch patch) { String name = patch.name(); if (Arrays.asList(method.getParameterTypes()).contains(Map.class)) { this.requiredAttributes = CollectionsUtil.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(Element patchElement, CtClass ctClass) { Map<String, String> attributes = DomUtil.getAttributes(patchElement); String textContent = patchElement.getTextContent().trim(); Map<String, String> attributesClean = new HashMap<String, String>(attributes); attributesClean.remove("code"); Log.fine("Patching " + ctClass.getName() + " with " + this.name + '(' + CollectionsUtil.joinMap(attributesClean) + ')' + (textContent.isEmpty() ? "" : " {" + textContent + '}')); if (requiredAttributes != null && !attributes.keySet().containsAll(requiredAttributes)) { Log.severe("Missing required attributes " + requiredAttributes.toString() + " when patching " + ctClass.getName()); return null; } if ("^all^".equals(textContent)) { attributes.put("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); } } else if (isClassPatch || (!emptyConstructor && textContent.isEmpty())) { return run(ctClass, attributes); } else if (textContent.isEmpty()) { for (CtConstructor ctConstructor : ctClass.getDeclaredConstructors()) { run(ctConstructor, attributes); } } else if ("^static^".equals(textContent)) { CtConstructor ctBehavior = ctClass.getClassInitializer(); if (ctBehavior == null) { Log.severe("No static initializer found patching " + ctClass.getName() + " with " + toString()); } else { run(ctBehavior, attributes); } } else { List<MethodDescription> methodDescriptions = MethodDescription.fromListString(ctClass.getName(), textContent); for (MethodDescription methodDescription : methodDescriptions) { CtMethod ctMethod; try { ctMethod = methodDescription.inClass(ctClass); } catch (Throwable t) { Log.warning("", t); continue; } run(ctMethod, attributes); } } return null; } private Object run(CtClass ctClass, Map<String, String> attributes) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchTypes, ctClass); } else { return patchMethod.invoke(patchTypes, ctClass, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { Log.severe("Code: " + attributes.get("code")); } Log.severe("Error patching " + ctClass.getName() + " with " + toString(), t); return null; } } private Object run(CtBehavior ctBehavior, Map<String, String> attributes) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchTypes, ctBehavior); } else { return patchMethod.invoke(patchTypes, ctBehavior, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { Log.severe("Code: " + attributes.get("code")); } Log.severe("Error patching " + ctBehavior.getName() + " in " + ctBehavior.getDeclaringClass().getName() + " with " + toString(), t); return null; } } @Override public String toString() { return name; } } }
package de.danoeh.antennapod.activity; import android.content.Intent; import android.content.res.Resources.Theme; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import com.actionbarsherlock.app.SherlockPreferenceActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import de.danoeh.antennapod.PodcastApp; import de.danoeh.antennapod.R; import de.danoeh.antennapod.asynctask.FlattrClickWorker; import de.danoeh.antennapod.asynctask.OpmlExportWorker; import de.danoeh.antennapod.feed.FeedManager; import de.danoeh.antennapod.util.flattr.FlattrUtils; /** The main preference activity */ public class PreferenceActivity extends SherlockPreferenceActivity { private static final String TAG = "PreferenceActivity"; private static final String PREF_FLATTR_THIS_APP = "prefFlattrThisApp"; private static final String PREF_FLATTR_AUTH = "pref_flattr_authenticate"; private static final String PREF_FLATTR_REVOKE = "prefRevokeAccess"; private static final String PREF_OPML_EXPORT = "prefOpmlExport"; private static final String PREF_ABOUT = "prefAbout"; @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(PodcastApp.getThemeResourceId()); getSupportActionBar().setDisplayHomeAsUpEnabled(true); addPreferencesFromResource(R.xml.preferences); findPreference(PREF_FLATTR_THIS_APP).setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { new FlattrClickWorker(PreferenceActivity.this, FlattrUtils.APP_URL).executeAsync(); return true; } }); findPreference(PREF_FLATTR_REVOKE).setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FlattrUtils.revokeAccessToken(PreferenceActivity.this); checkItemVisibility(); return true; } }); findPreference(PREF_ABOUT).setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { PreferenceActivity.this.startActivity(new Intent( PreferenceActivity.this, AboutActivity.class)); return true; } }); findPreference(PREF_OPML_EXPORT).setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (!FeedManager.getInstance().getFeeds().isEmpty()) { new OpmlExportWorker(PreferenceActivity.this) .executeAsync(); } return true; } }); findPreference(PodcastApp.PREF_THEME).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Intent i = getIntent(); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); finish(); startActivity(i); return true; } }); } @Override protected void onResume() { super.onResume(); checkItemVisibility(); } @SuppressWarnings("deprecation") private void checkItemVisibility() { boolean hasFlattrToken = FlattrUtils.hasToken(); findPreference(PREF_FLATTR_AUTH).setEnabled(!hasFlattrToken); findPreference(PREF_FLATTR_REVOKE).setEnabled(hasFlattrToken); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); break; default: return false; } return true; } @Override protected void onApplyThemeResource(Theme theme, int resid, boolean first) { theme.applyStyle(PodcastApp.getThemeResourceId(), true); } }
package de.matthiasmann.twlthemeeditor.gui; import de.matthiasmann.twl.DesktopArea; import de.matthiasmann.twl.Event; import de.matthiasmann.twl.GUI; import de.matthiasmann.twl.Widget; import de.matthiasmann.twl.renderer.CacheContext; import de.matthiasmann.twl.renderer.lwjgl.LWJGLRenderer; import de.matthiasmann.twl.theme.ThemeManager; import de.matthiasmann.twlthemeeditor.datamodel.ThemeLoadErrorTracker; import java.io.IOException; import java.net.URL; import java.nio.IntBuffer; import org.lwjgl.BufferUtils; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; /** * * @author Matthias Mann */ public class PreviewWidget extends Widget { private final IntBuffer viewPortBuffer; private URL url; private LWJGLRenderer render; private ThemeManager theme; private GUI testGUI; private boolean reloadTheme; private Class<? extends Widget> widgetClass; private Widget testWidget; private Runnable testWidgetChangedCB; private final ExceptionHolder exceptionHolder; private Object themeLoadErrorLocation; private static final int EXCEPTION_INIT = 0; private static final int EXCEPTION_WIDGET = 1; private static final int EXCEPTION_THEME = 2; private static final int EXCEPTION_EXECUTE = 3; public PreviewWidget() { this.viewPortBuffer = BufferUtils.createIntBuffer(16); this.exceptionHolder = new ExceptionHolder( "Initialization", "Widget creation", "Theme load", "Execution"); setCanAcceptKeyboardFocus(true); } public void setURL(URL url) { this.url = url; this.reloadTheme = true; } public void setWidgetClass(Class<? extends Widget> widgetClass) { this.widgetClass = widgetClass; this.testWidget = null; } public Widget getTestWidget() { return testWidget; } public void setTestWidgetChangedCB(Runnable testWidgetChangedCB) { this.testWidgetChangedCB = testWidgetChangedCB; } public void reloadTheme() { reloadTheme = true; } public ExceptionHolder getExceptionHolder() { return exceptionHolder; } public Object getThemeLoadErrorLocation() { return themeLoadErrorLocation; } public void clearException(int nr) { if(nr == EXCEPTION_THEME) { themeLoadErrorLocation = null; reloadTheme = true; } exceptionHolder.setException(nr, null); } @Override protected void paintWidget(GUI gui) { if(!exceptionHolder.hasException()) { // don't execute callbacks in critical section exceptionHolder.setDeferCallbacks(true); GL11.glGetInteger(GL11.GL_VIEWPORT, viewPortBuffer); int viewPortTop = viewPortBuffer.get(1) + viewPortBuffer.get(3); GL11.glPushAttrib(GL11.GL_VIEWPORT_BIT); GL11.glViewport(getInnerX(), viewPortTop - (getInnerY() + getInnerHeight()), getInnerWidth(), getInnerHeight()); // CRITICAL REGION: GL STATE IS MODIFIED - DON'T CALL ANY APP CODE try { executeTestEnv(gui); } catch (Throwable ex) { // don't let anything escape ! exceptionHolder.setException(EXCEPTION_EXECUTE, ex); } finally { GL11.glPopAttrib(); // END OF CRITICAL REGION } exceptionHolder.setDeferCallbacks(false); } } private void executeTestEnv(GUI gui) { if(render == null && !initRenderer()) { return; } render.syncViewportSize(); if(testGUI == null) { DesktopArea area = new DesktopArea() { @Override protected void restrictChildrenToInnerArea() { final int top = getInnerY(); final int left = getInnerX(); final int right = getInnerRight(); final int bottom = getInnerBottom(); final int width = Math.max(0, right-left); final int height = Math.max(0, bottom-top); for(int i=0,n=getNumChildren() ; i<n ; i++) { Widget w = getChild(i); int minWidth = w.getMinWidth(); int minHeight = w.getMinHeight(); w.setSize( Math.min(Math.max(width, minWidth), Math.max(w.getWidth(), minWidth)), Math.min(Math.max(height, minHeight), Math.max(w.getHeight(), minHeight))); w.setPosition( Math.max(left, Math.min(right - w.getWidth(), w.getX())), Math.max(top, Math.min(bottom - w.getHeight(), w.getY()))); } } }; area.setTheme(""); testGUI = new GUI(area, render); } if((theme == null || reloadTheme) && !loadTheme()) { return; } if(testWidget == null && widgetClass != null) { testGUI.getRootPane().removeAllChildren(); try { testWidget = widgetClass.newInstance(); testGUI.getRootPane().add(testWidget); if(testWidgetChangedCB != null) { gui.invokeLater(testWidgetChangedCB); } testWidget.adjustSize(); } catch (Throwable ex) { exceptionHolder.setException(EXCEPTION_WIDGET, ex); } } testGUI.setSize(); testGUI.updateTime(); testGUI.updateTimers(); testGUI.handleKeyRepeat(); testGUI.handleTooltips(); testGUI.invokeRunables(); testGUI.validateLayout(); testGUI.draw(); testGUI.setCursor(); } private boolean initRenderer() { assert(render == null); try { render = new LWJGLRenderer(); render.setUseSWMouseCursors(true); return true; } catch(LWJGLException ex) { exceptionHolder.setException(EXCEPTION_INIT, ex); render = null; return false; } } private boolean loadTheme() { reloadTheme = false; if(url != null) { ThemeLoadErrorTracker tracker = new ThemeLoadErrorTracker(); ThemeLoadErrorTracker.push(tracker); CacheContext oldCacheContext = render.getActiveCacheContext(); CacheContext newCacheContext = render.createNewCacheContext(); render.setActiveCacheContext(newCacheContext); try { ThemeManager newTheme = ThemeManager.createThemeManager(url, render); testGUI.applyTheme(newTheme); oldCacheContext.destroy(); if(theme != null) { theme.destroy(); } theme = newTheme; testGUI.destroy(); return true; } catch (IOException ex) { exceptionHolder.setException(EXCEPTION_THEME, ex); render.setActiveCacheContext(oldCacheContext); newCacheContext.destroy(); themeLoadErrorLocation = tracker.findErrorLocation(); } finally { if(ThemeLoadErrorTracker.pop() != tracker) { throw new IllegalStateException("Wrong error tracker"); } } } return false; } @Override protected boolean handleEvent(Event evt) { if(testGUI != null) { switch (evt.getType()) { case MOUSE_MOVED: case MOUSE_DRAGED: case MOUSE_ENTERED: case MOUSE_EXITED: testGUI.handleMouse(evt.getMouseX() - getInnerX(), evt.getMouseY() - getInnerY(), -1, false); return true; case MOUSE_BTNDOWN: case MOUSE_BTNUP: testGUI.handleMouse(evt.getMouseX() - getInnerX(), evt.getMouseY() - getInnerY(), evt.getMouseButton(), evt.getType() == Event.Type.MOUSE_BTNDOWN); return true; case KEY_PRESSED: case KEY_RELEASED: testGUI.handleKey(translateKeyCode(evt.getKeyCode()), evt.getKeyChar(), evt.getType() == Event.Type.KEY_PRESSED); return true; } } return super.handleEvent(evt); } protected int translateKeyCode(int keyCode) { if(keyCode == Keyboard.KEY_F6) { return Keyboard.KEY_TAB; } return keyCode; } }
package de.mazdermind.MultiWiiOps.UI.Cockpit; import java.awt.Color; import java.awt.GridLayout; import javax.swing.JLabel; import de.mazdermind.MultiWiiOps.UI.TestPanel; public class StatusPanel extends JLabel { private static final long serialVersionUID = 5999631872010288870L; public StatusPanel() { setLayout(new GridLayout(2, 6, 20, 20)); setOpaque(false); add(new TestPanel("ACC", Color.GREEN)); add(new TestPanel("BARO", Color.GREEN)); add(new TestPanel("MAG", Color.GREEN)); add(new TestPanel("ARM", Color.YELLOW)); add(new TestPanel("STABLE", Color.YELLOW)); add(new TestPanel("HORIZON", Color.YELLOW)); add(new TestPanel("GPS", Color.GREEN)); add(new TestPanel("SONAR", Color.GREEN)); add(new TestPanel("OPTIC", Color.GREEN)); add(new TestPanel("ALTHOLD", Color.YELLOW)); add(new TestPanel("HEADFREE", Color.YELLOW)); add(new TestPanel("HEADADJ", Color.YELLOW)); } }
package edu.isi.pegasus.planner.common; import edu.isi.pegasus.planner.classes.NameValue; import edu.isi.pegasus.common.util.CommonProperties; import edu.isi.pegasus.common.util.Boolean; import edu.isi.pegasus.planner.catalog.classes.Profiles; import edu.isi.pegasus.planner.namespace.Dagman; import edu.isi.pegasus.planner.namespace.Namespace; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.FileOutputStream; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.MissingResourceException; import java.util.Properties; import java.util.Set; import java.util.HashSet; import java.util.Map; /** * A Central Properties class that keeps track of all the properties used by * Pegasus. All other classes access the methods in this class to get the value * of the property. It access the CommonProperties class to read the property file. * * @author Karan Vahi * @author Gaurang Mehta * * @version $Revision$ * * @see org.griphyn.common.util.CommonProperties */ public class PegasusProperties implements Cloneable { /** * the name of the property to disable invoke functionality */ public static final String DISABLE_INVOKE_PROPERTY = "pegasus.gridstart.invoke.disable"; public static final String PEGASUS_KICKSTART_STAT_PROPERTY = "pegasus.gridstart.kickstart.stat"; public static final String PEGASUS_WORKER_NODE_EXECUTION_PROPERTY = "pegasus.execute.*.filesystem.local"; public static final String PEGASUS_TRANSFER_WORKER_PACKAGE_PROPERTY = "pegasus.transfer.worker.package"; public static final String PEGASUS_TRANSFORMATION_CATALOG_PROPERTY = "pegasus.catalog.transformation"; public static final String PEGASUS_TRANSFORMATION_CATALOG_FILE_PROPERTY = "pegasus.catalog.transformation.file"; public static final String PEGASUS_REPLICA_CATALOG_PROPERTY = "pegasus.catalog.replica"; public static final String PEGASUS_REPLICA_CATALOG_FILE_PROPERTY = "pegasus.catalog.replica.file"; public static final String PEGASUS_SITE_CATALOG_PROPERTY = "pegasus.catalog.site"; public static final String PEGASUS_SITE_CATALOG_FILE_PROPERTY = "pegasus.catalog.site.file"; public static final String PEGASUS_LOG_METRICS_PROPERTY = "pegasus.log.metrics"; public static final String PEGASUS_LOG_METRICS_PROPERTY_FILE = "pegasus.log.metrics.file"; public static final String PEGASUS_APP_METRICS_PREFIX = "pegasus.metrics.app"; //Replica Catalog Constants public static final String DEFAULT_RC_COLLECTION = "GriphynData"; public static final String DEFAULT_RLI_URL = null; public static final String DEFAULT_RLS_QUERY_MODE = "bulk"; public static final String DEFAULT_RLS_EXIT_MODE = "error"; //public static final String DEFAULT_REPLICA_MODE = "rls"; public static final String DEFAULT_RLS_QUERY_ATTRIB = "false"; public static final String DEFAULT_LRC_IGNORE_URL = null; public static final String DEFAULT_RLS_TIMEOUT = "30"; public static final String DEFAULT_EXEC_DIR = ""; public static final String DEFAULT_STORAGE_DIR = ""; public static final String DEFAULT_TC_MODE = "Text"; public static final String TC_TEXT_FILE = "tc.txt"; public static final String DEFAULT_POOL_MODE = "XML"; public static final String DEFAULT_CONDOR_BIN_DIR = ""; public static final String DEFAULT_CONDOR_CONFIG_DIR = ""; public static final String CONDOR_KICKSTART = "kickstart-condor"; //transfer constants public static final String DEFAULT_STAGING_DELIMITER = "-"; public static final String DEFAULT_TRANSFER_PROCESSES = "4"; public static final String DEFAULT_TRANSFER_STREAMS = "1"; //grid start constants public static final String DEFAULT_INVOKE_LENGTH = "4000"; //site selector constants public static final String DEFAULT_SITE_SELECTOR = "Random"; public static final String DEFAULT_SITE_SELECTOR_TIMEOUT = "300"; public static final String DEFAULT_SITE_SELECTOR_KEEP = "onerror"; ///some simulator constants that are used public static final String DEFAULT_DATA_MULTIPLICATION_FACTOR = "1"; public static final String DEFAULT_COMP_MULTIPLICATION_FACTOR = "1"; public static final String DEFAULT_COMP_ERROR_PERCENTAGE = "0"; public static final String DEFAULT_COMP_VARIANCE_PERCENTAGE = "0"; //collapsing constants public static final String DEFAULT_JOB_AGGREGATOR = "SeqExec"; //some tranformation catalog constants public static final String DEFAULT_TC_MAPPER_MODE = "All"; public static final String DEFAULT_TX_SELECTOR_MODE = "Random"; //logging constants public static final String DEFAULT_LOGGING_FILE = "stdout"; /** * Default properties that applies priorities to all kinds of transfer * jobs. */ public static final String ALL_TRANSFER_PRIORITY_PROPERTY_KEY = "pegasus.transfer.*.priority"; /** * The property key designated the root workflow uuid. */ public static final String ROOT_WORKFLOW_UUID_PROPERTY_KEY = "pegasus.workflow.root.uuid"; /** * The default value to be assigned for dagman.maxpre . */ public static final String DEFAULT_DAGMAN_MAX_PRE_VALUE = "1"; /** * An enum defining The dial for cleanup algorithm */ public enum CLEANUP_SCOPE{ fullahead, deferred }; /** * An enum defining the dial for integrity checking */ public enum INTEGRITY_DIAL{ none, full }; /** * The default DAXCallback that is loaded, if none is specified by the user. */ private static final String DEFAULT_DAX_CALLBACK = "DAX2Graph"; /** * The value of the PEGASUS_HOME environment variable. */ private String mPegasusHome; /** * The object holding all the properties pertaining to the VDS system. */ private CommonProperties mProps; /** * The default path to the transformation catalog. */ private String mDefaultTC; /** * The default transfer priority that needs to be applied to the transfer * jobs. */ private String mDefaultTransferPriority; /** * The set containing the deprecated properties specified by the user. */ private Set mDeprecatedProperties; /** * The pointer to the properties file that is written out in the submit directory. */ private String mPropsInSubmitDir; /** * Profiles that are specified in the properties */ private Profiles mProfiles; private static Map<Profiles.NAMESPACES,String> mNamepsaceToPropertiesPrefix; public Map<Profiles.NAMESPACES, String> namespaceToPropertiesPrefix(){ if( mNamepsaceToPropertiesPrefix == null ){ mNamepsaceToPropertiesPrefix = new HashMap<Profiles.NAMESPACES, String>(); mNamepsaceToPropertiesPrefix.put( Profiles.NAMESPACES.condor, "condor" ); mNamepsaceToPropertiesPrefix.put( Profiles.NAMESPACES.dagman, "dagman" ); mNamepsaceToPropertiesPrefix.put( Profiles.NAMESPACES.globus, "globus" ); mNamepsaceToPropertiesPrefix.put( Profiles.NAMESPACES.env, "env" ); mNamepsaceToPropertiesPrefix.put( Profiles.NAMESPACES.hints, "hints" ); mNamepsaceToPropertiesPrefix.put( Profiles.NAMESPACES.pegasus, "pegasus" ); mNamepsaceToPropertiesPrefix.put( Profiles.NAMESPACES.selector, "selector" ); mNamepsaceToPropertiesPrefix.put( Profiles.NAMESPACES.stat, "stat" ); } return mNamepsaceToPropertiesPrefix; } /** * Returns an instance to this properties object. * * @return a handle to the Properties class. */ public static PegasusProperties getInstance( ){ return getInstance( null ); } /** * Returns an instance to this properties object. * * @param confProperties the path to conf properties, that supersede the * loading of properties from $PEGASUS_HOME/.pegasusrc * * @return a handle to the Properties class. */ public static PegasusProperties getInstance( String confProperties ){ return nonSingletonInstance( confProperties ); } /** * To get a reference to the the object. The properties file that is loaded is * from the path specified in the argument. * This is *not implemented* as singleton. However the invocation of this * does modify the internally held singleton object. * * @param confProperties the path to conf properties, that supersede the * loading of properties from $PEGASUS_HOME/.pegasusrc * * @return a handle to the Properties class. */ protected static PegasusProperties nonSingletonInstance( String confProperties ) { return new PegasusProperties( confProperties ); } /** * To get a reference to the the object. The properties file that is loaded is * from the path specified in the argument. * * This is *not implemented* as singleton. However the invocation of this * does modify the internally held singleton object. * * * @return a handle to the Properties class. */ public static PegasusProperties nonSingletonInstance() { //return nonSingletonInstance( CommonProperties.PROPERTY_FILENAME ); return nonSingletonInstance( null ); } /** * The constructor that constructs the default paths to the various * configuration files, and populates the singleton instance as required. If * the properties file passed is null, then the singleton instance is * invoked, else the non singleton instance is invoked. * * @param confProperties the path to conf properties, that supersede the * loading of properties from $PEGASUS_HOME/.pegasusrc */ private PegasusProperties( String confProperties ) { // mLogger = LogManager.getInstance(); mDeprecatedProperties = new HashSet(5); initializePropertyFile( confProperties ); mDefaultTC = getDefaultPathToTC(); mDefaultTransferPriority= getDefaultTransferPriority(); } /** * Retrieves profiles from the properties * * @param properties the common properties so far * * @return profiles object. */ public Profiles retrieveProfilesFromProperties( ) { //retrieve up all the profiles that are specified in //the properties if( mProfiles == null ){ mProfiles = retrieveProfilesFromProperties( mProps ); //System.out.println( mProfiles ); } return mProfiles; } /** * Retrieves profiles from the properties * * @param properties the common properties so far * * @return profiles object. */ protected Profiles retrieveProfilesFromProperties( CommonProperties properties ) { Profiles profiles = new Profiles( ); //retrieve some matching properties first //traverse through all the enum keys for ( Profiles.NAMESPACES n : Profiles.NAMESPACES.values() ){ Properties p = properties.matchingSubset( namespaceToPropertiesPrefix().get( n ), false ); for( Map.Entry<Object,Object> entry : p.entrySet() ){ profiles.addProfile( n, (String)entry.getKey(), (String)entry.getValue() ); } } return profiles; } /** * Returns the clone of the object. * * @return the clone */ public Object clone(){ PegasusProperties props; try{ //this will do a shallow clone for all member variables //that is fine for the string variables props = ( PegasusProperties ) super.clone(); //clone the CommonProperties props.mProfiles = ( this.mProfiles == null ) ? null :(Profiles) this.mProfiles.clone(); props.mProps = ( this.mProps == null ) ? null: (CommonProperties) this.mProps.clone(); } catch( CloneNotSupportedException e ){ //somewhere in the hierarch chain clone is not implemented throw new RuntimeException("Clone not implemented in the base class of " + this.getClass().getName(), e ); } return props; } /** * Accessor to the bin directory of the Pegasus install * * @return the "etc" directory of the VDS runtime system. */ public File getBinDir() { return mProps.getBinDir(); } /** * Accessor to the schema directory of the Pegasus install * * @return the "etc" directory of the VDS runtime system. */ public File getSchemaDir() { return mProps.getSchemaDir(); } /** * Accessor to the bin directory of the Pegasus install * * @return the "etc" directory of the VDS runtime system. */ public File getSharedDir() { return mProps.getSharedStateDir(); } /** * Returns all the profiles relevant to a particular namespace * * @param ns the namespace corresponding to which you need the profiles */ public Namespace getProfiles( Profiles.NAMESPACES ns ){ return this.retrieveProfilesFromProperties().get( ns ); } /** * Returns the default path to the transformation catalog. * * @return tc.txt in the current working directory */ public String getDefaultPathToTC() { File f = new File( ".", PegasusProperties.TC_TEXT_FILE); //System.err.println("Default Path to SC is " + f.getAbsolutePath()); return f.getAbsolutePath(); } /** * Returns the default path to the condor kickstart. Currently the path * defaults to $PEGASUS_HOME/bin/kickstart-condor. * * @return default path to kickstart condor. */ public String getDefaultPathToCondorKickstart() { StringBuffer sb = new StringBuffer( 50 ); sb.append( mPegasusHome ); sb.append( File.separator ); sb.append( "bin" ); sb.append( File.separator ); sb.append( CONDOR_KICKSTART ); return sb.toString(); } /** * Gets the handle to the properties file. The singleton instance is * invoked if the properties file is null (partly due to the way CommonProperties * is implemented ), else the non singleton is invoked. * * @param confProperties the path to conf properties, that supersede the * loading of properties from $PEGASUS_HOME/.pegasusrc * * */ private void initializePropertyFile( String confProperties ) { try { /* mProps = ( confProperties == null ) ? //invoke the singleton instance CommonProperties.instance() : //invoke the non singleton instance CommonProperties.nonSingletonInstance( confProperties ); */ //we always load non singleton instance? //Karan April 27, 2011 mProps = CommonProperties.nonSingletonInstance( confProperties ); } catch ( IOException e ) { System.err.println( "unable to read property file: " + e.getMessage() ); System.exit( 1 ); } catch ( MissingResourceException e ) { System.err.println( "A required property is missing: " + e.getMessage() ); System.exit( 1 ); } } /** * It allows you to get any property from the property file without going * through the corresponding accesor function in this class. For coding * and clarity purposes, the function should be used judiciously, and the * accessor function should be used as far as possible. * * @param key the property whose value is desired. * @return String */ public String getProperty( String key ) { return mProps.getProperty( key ); } /** * Returns the CommonProperties that this object encapsulates. Use only when * absolutely necessary. Use accessor methods whereever possible. * * @return CommonProperties */ public CommonProperties getVDSProperties(){ return this.mProps; } /** * Accessor: Overwrite any properties from within the program. * * @param key is the key to look up * @param value is the new property value to place in the system. * @return the old value, or null if it didn't exist before. */ public Object setProperty( String key, String value ) { return mProps.setProperty( key, value ); } /** * Extracts a specific property key subset from the known properties. * The prefix may be removed from the keys in the resulting dictionary, * or it may be kept. In the latter case, exact matches on the prefix * will also be copied into the resulting dictionary. * * @param prefix is the key prefix to filter the properties by. * @param keepPrefix if true, the key prefix is kept in the resulting * dictionary. As side-effect, a key that matches the prefix exactly * will also be copied. If false, the resulting dictionary's keys are * shortened by the prefix. An exact prefix match will not be copied, * as it would result in an empty string key. * * @return a property dictionary matching the filter key. May be * an empty dictionary, if no prefix matches were found. * * @see #getProperty( String ) is used to assemble matches */ public Properties matchingSubset( String prefix, boolean keepPrefix ) { return mProps.matchingSubset( prefix, keepPrefix ); } /** * Returns the properties matching a particular prefix as a list of * sorted name value pairs, where name is the full name of the matching * property (including the prefix) and value is it's value in the properties * file. * * @param prefix the prefix for the property names. * @param system boolean indicating whether to match only System properties * or all including the ones in the property file. * * @return list of <code>NameValue</code> objects corresponding to the matched * properties sorted by keys. * null if no matching property is found. */ public List getMatchingProperties( String prefix, boolean system ) { //sanity check if ( prefix == null ) { return null; } Properties p = (system)? System.getProperties(): matchingSubset(prefix,true); java.util.Enumeration e = p.propertyNames(); List l = ( e.hasMoreElements() ) ? new java.util.ArrayList() : null; while ( e.hasMoreElements() ) { String key = ( String ) e.nextElement(); NameValue nv = new NameValue( key, p.getProperty( key ) ); l.add( nv ); } Collections.sort(l); return ( l.isEmpty() ) ? null : l; } /** * Accessor to $PEGASUS_HOME/etc. The files in this directory have a low * change frequency, are effectively read-only, they reside on a * per-machine basis, and they are valid usually for a single user. * * @return the "etc" directory of the VDS runtime system. */ public File getSysConfDir() { return mProps.getSysConfDir(); } /** * Removes a property from the soft state. * * @param key the key * * @return the corresponding value if key exits, else null */ public String removeProperty( String key ){ return mProps.removeProperty( key ); } //PROPERTIES RELATED TO SCHEMAS /** * Returns the location of the schema for the DAX. * * Referred to by the "pegasus.schema.dax" property. * * @return location to the DAX schema. */ public String getDAXSchemaLocation() { return this.getDAXSchemaLocation( null ); } /** * Returns the location of the schema for the DAX. * * Referred to by the "pegasus.schema.dax" property. * * @param defaultLocation the default location to the schema. * * @return location to the DAX schema specified in the properties file, * else the default location if no value specified. */ public String getDAXSchemaLocation( String defaultLocation ) { return mProps.getProperty( "pegasus.schema.dax", defaultLocation ); } /** * Returns the location of the schema for the PDAX. * * Referred to by the "pegasus.schema.pdax" property * * @param defaultLocation the default location to the schema. * * @return location to the PDAX schema specified in the properties file, * else the default location if no value specified. */ public String getPDAXSchemaLocation( String defaultLocation ) { return mProps.getProperty( "pegasus.schema.pdax", defaultLocation ); } //DIRECTORY CREATION PROPERTIES /** * Returns the name of the class that the user wants, to insert the * create directory jobs in the graph in case of creating random * directories. * * Referred to by the "pegasus.dir.create.strategy" property. * * @return the create dir classname if specified in the properties file, * else Minimal. */ public String getCreateDirClass() { return getProperty( "pegasus.dir.create.strategy", "pegasus.dir.create", "Minimal" ); } /** * Returns the name of the class that the user wants, to render the directory * creation jobs. It dictates what mechanism is used to create the directory * for a workflow. * * Referred to by the "pegasus.dir.create.impl" property. * * @return the create dir classname if specified in the properties file, * else DefaultImplementation. */ public String getCreateDirImplementation() { return mProps.getProperty( "pegasus.dir.create.impl", "DefaultImplementation" ); } /** * It specifies whether to use the extended timestamp format for generation * of timestamps that are used to create the random directory name, and for * the classads generation. * * Referred to by the "pegasus.dir.timestamp.extended" property. * * @return the value specified in the properties file if valid boolean, else * false. */ public boolean useExtendedTimeStamp() { return Boolean.parse(mProps.getProperty( "pegasus.dir.timestamp.extended"), false ); } /** * Returns a boolean indicating whether to use timestamp for directory * name creation or not. * * Referred to by "pegasus.dir.useTimestamp" property. * * @return the boolean value specified in the properties files, else false. */ public boolean useTimestampForDirectoryStructure(){ return Boolean.parse( mProps.getProperty( "pegasus.dir.useTimestamp" ), false ); } /** * Returns the execution directory suffix or absolute specified * that is appended/replaced to the exec-mount-point specified in the * pool catalog for the various pools. * * Referred to by the "pegasus.dir.exec" property * * @return the value specified in the properties file, * else the default suffix. * * @see #DEFAULT_EXEC_DIR */ public String getExecDirectory() { return mProps.getProperty( "pegasus.dir.exec", DEFAULT_EXEC_DIR ); } /** * Returns the the path to the logs directory on the submit host. * This is the directory where the condor logs for the workflows are * created. The logs directory should be on the local filesystem else * condor may complain * * Referred to by the "pegasus.dir.submit.logs" property * * @return the value in the properties file, else null */ public String getSubmitLogsDirectory(){ return mProps.getProperty( "pegasus.dir.submit.logs" ); } /** * Returns a boolean indicating whether the submit directory for the sub * workflows should include the label of the sub workflow or not. * * Referred to by the "pegasus.dir.submit.subwf.labelbased" property * * @return the value in the properties file, else false */ public boolean labelBasedSubmitDirectoryForSubWorkflows(){ return Boolean.parse( mProps.getProperty( "pegasus.dir.submit.subwf.labelbased" ), false ); } /** * Returns the storage directory suffix or absolute specified * that is appended/replaced to the storage-mount-point specified in the * pool catalog for the various pools. * * Referred to by the "pegasus.dir.storage" property. * * @return the value specified in the properties file, * else the default suffix. * * @see #DEFAULT_STORAGE_DIR */ public String getStorageDirectory() { return mProps.getProperty( "pegasus.dir.storage", DEFAULT_STORAGE_DIR ); } /** * Returns a boolean indicating whether to have a deep storage directory * structure or not while staging out data to the output site. * * Referred to by the "pegasus.dir.storage.deep" property. * * @return the boolean value specified in the properties files, else false. */ public boolean useDeepStorageDirectoryStructure(){ return Boolean.parse( mProps.getProperty( "pegasus.dir.storage.deep" ), false ); } //PROPERTIES RELATED TO CLEANUP /** * Returns the name of the Strategy class that the user wants, to insert the * cleanup jobs in the graph. * * Referred to by the "pegasus.file.cleanup.strategy" property. * * @return the create dir classname if specified in the properties file, * else InPlace. */ public String getCleanupStrategy() { return mProps.getProperty( "pegasus.file.cleanup.strategy", "InPlace" ); } /** * Returns the name of the class that the user wants, to render the cleanup * jobs. It dictates what mechanism is used to remove the files on a remote * system. * * Referred to by the "pegasus.file.cleanup.impl" property. * * @return the cleanup implementation classname if specified in the properties file, * else Cleanup. */ public String getCleanupImplementation() { return mProps.getProperty( "pegasus.file.cleanup.impl", "Cleanup" ); } /** * Returns the maximum number of clean up jobs created per level of the workflow * in case of InPlace cleanup. * * Referred to by the "pegasus.file.cleanup.clusters.num" property * * @return the value in the property file , else null */ public String getMaximumCleanupJobsPerLevel() { return mProps.getProperty( "pegasus.file.cleanup.clusters.num" ); } /** * Returns the fraction of cleanup jobs clustered into a single clustered * cleanup job. * * Referred to by the "pegasus.file.cleanup.clusters.size" property * * @return the value in the property file , else null */ public String getClusterSizeCleanupJobsPerLevel() { return mProps.getProperty( "pegasus.file.cleanup.clusters.size" ); } /** * Returns the maximum available space per site. * * Referred to by the "pegasus.file.cleanup.constraint.maxspace" property * * @return the value in the property file , else null */ public String getCleanupConstraintMaxSpace() { return mProps.getProperty( "pegasus.file.cleanup.constraint.maxspace" ); } /** * Returns the scope for file cleanup. It is used to trigger cleanup in case * of deferred planning. The vaild property values accepted are * - fullahead * - deferred * * Referred to by the property "pegasus.file.cleanup.scope" * * * @return the value in property file if specified, else fullahead */ public CLEANUP_SCOPE getCleanupScope(){ CLEANUP_SCOPE scope = CLEANUP_SCOPE.fullahead; String value = mProps.getProperty( "pegasus.file.cleanup.scope" ); if( value == null ){ return scope; } //try to assign a cleanup value try{ scope = CLEANUP_SCOPE.valueOf( value ); }catch( IllegalArgumentException iae ){ //ignore do nothing. } return scope; } //PROPERTIES RELATED TO THE TRANSFORMATION CATALOG /** * Returns the mode to be used for accessing the Transformation Catalog. * * Referred to by the "pegasus.catalog.transformation" property. * * @return the value specified in properties file, * else DEFAULT_TC_MODE. * * @see #DEFAULT_TC_MODE */ public String getTCMode() { return mProps.getProperty( PegasusProperties.PEGASUS_TRANSFORMATION_CATALOG_PROPERTY, DEFAULT_TC_MODE ); } /** * Returns the location of the transformation catalog. * * Referred to by "pegasus.catalog.transformation.file" property. * * @return the value specified in the properties file, * else default path specified by mDefaultTC. * * @see #mDefaultTC */ public String getTCPath() { return mProps.getProperty( PegasusProperties.PEGASUS_TRANSFORMATION_CATALOG_FILE_PROPERTY, mDefaultTC ); } /** * Returns the mode for loading the transformation mapper that sits in * front of the transformation catalog. * * Referred to by the "pegasus.catalog.transformation.mapper" property. * * @return the value specified in the properties file, * else default tc mapper mode. * * @see #DEFAULT_TC_MAPPER_MODE */ public String getTCMapperMode() { return mProps.getProperty( "pegasus.catalog.transformation.mapper", DEFAULT_TC_MAPPER_MODE ); } //REPLICA CATALOG PROPERTIES /** * Returns the replica mode. It identifies the ReplicaMechanism being used * by Pegasus to determine logical file locations. * * Referred to by the "pegasus.catalog.replica" property. * * @return the replica mode, that is used to load the appropriate * implementing class if property is specified, * else null */ public String getReplicaMode() { return mProps.getProperty( PEGASUS_REPLICA_CATALOG_PROPERTY ); } /** * Returns the url to the RLI of the RLS. * * Referred to by the "pegasus.rls.url" property. * * @return the value specified in properties file, * else DEFAULT_RLI_URL. * * @see #DEFAULT_RLI_URL */ public String getRLIURL() { return mProps.getProperty( "pegasus.catalog.replica.url", DEFAULT_RLI_URL ); } /** * It returns the timeout value in seconds after which to timeout in case of * no activity from the RLS. * * Referred to by the "pegasus.rc.rls.timeout" property. * * @return the timeout value if specified else, * DEFAULT_RLS_TIMEOUT. * * @see #DEFAULT_RLS_TIMEOUT */ public int getRLSTimeout() { String prop = mProps.getProperty( "pegasus.catalog.replica.rls.timeout", DEFAULT_RLS_TIMEOUT ); int val; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return Integer.parseInt( DEFAULT_RLS_TIMEOUT ); } return val; } //PROPERTIES RELATED TO SITE CATALOG /** * Returns the mode to be used for accessing the pool information. * * Referred to by the "pegasus.catalog.site" property. * * @return the pool mode, that is used to load the appropriate * implementing class if the property is specified, * else default pool mode specified by DEFAULT_POOL_MODE * * @see #DEFAULT_POOL_MODE */ public String getPoolMode() { return mProps.getProperty( PegasusProperties.PEGASUS_SITE_CATALOG_PROPERTY, DEFAULT_POOL_MODE ); } /** * Returns the location of the schema for the DAX. * * Referred to by the "pegasus.schema.sc" property. * * @return the location of pool schema if specified in properties file, * else null. */ public String getPoolSchemaLocation() { return this.getPoolSchemaLocation( null ); } /** * Returns the location of the schema for the site catalog file. * * Referred to by the "pegasus.schema.sc" property * * @param defaultLocation the default location where the schema should be * if no other location is specified. * * @return the location specified by the property, * else defaultLocation. */ public String getPoolSchemaLocation( String defaultLocation ) { return mProps.getProperty("pegasus.schema.sc", defaultLocation ); } //PROVENANCE CATALOG PROPERTIES /** * Returns the provenance store to use to log the refiner actions. * * Referred to by the "pegasus.catalog.provenance.refinement" property. * * @return the value set in the properties, else null if not set. */ public String getRefinementProvenanceStore( ){ return mProps.getProperty( "pegasus.catalog.provenance.refinement" ); } //TRANSFER MECHANISM PROPERTIES /** * Returns the transfer implementation that is to be used for constructing * the transfer jobs. * * Referred to by the "pegasus.transfer.*.impl" property. * * @return the transfer implementation */ public String getTransferImplementation(){ return getTransferImplementation( "pegasus.transfer.*.impl" ); } /** * Returns the sls transfer implementation that is to be used for constructing * the transfer jobs. * * Referred to by the "pegasus.transfer.lite.*.impl" property. * * @return the transfer implementation * */ /* PM-810 done away. public String getSLSTransferImplementation(){ return getTransferImplementation( "pegasus.transfer.lite.*.impl" ); } */ /** * Returns the transfer implementation. * * @param property property name. * * @return the transfer implementation, * else the one specified by "pegasus.transfer.*.impl", */ public String getTransferImplementation( String property ){ return mProps.getProperty( property, getDefaultTransferImplementation()); } /** * Returns a boolean indicating whether to stage sls files via Pegasus * First Level Staging or let Condor do it. * * Referred to by the property "pegasus.transfer.stage.lite.file" * * @return boolean value mentioned in the properties or else the default * value which is true. */ public boolean stageSLSFilesViaFirstLevelStaging( ){ return Boolean.parse( mProps.getProperty( "pegasus.transfer.stage.lite.file" ), false ); } /** * Returns the default list of third party sites. * * Referred to by the "pegasus.transfer.*.thirdparty.sites" property. * * @return the value specified in the properties file, else * null. */ private String getDefaultThirdPartySites(){ return mProps.getProperty("pegasus.transfer.*.thirdparty.sites"); } /** * Returns the default transfer implementation to be picked up for * constructing transfer jobs. * * Referred to by the "pegasus.transfer.*.impl" property. * * @return the value specified in the properties file, else * null. */ private String getDefaultTransferImplementation(){ return mProps.getProperty("pegasus.transfer.*.impl"); } /** * Returns a boolean indicating whether to bypass first level staging of * inputs. Useful in case of PegasusLite setup * * Referred to by the "pegasus.transfer.bypass.input.staging" property. * * @return boolean value specified , else false */ public boolean bypassFirstLevelStagingForInputs( ){ return Boolean.parse( mProps.getProperty( "pegasus.transfer.bypass.input.staging" ), false ); } /** * Returns the default priority for the transfer jobs if specified in * the properties file. * * @return the value specified in the properties file, else null if * non integer value or no value specified. */ private String getDefaultTransferPriority(){ String prop = mProps.getProperty( this.ALL_TRANSFER_PRIORITY_PROPERTY_KEY); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return null; } return Integer.toString( val ); } /** * Returns the base source URL where pointing to the directory where the * worker package executables for pegasus releases are kept. * * Referred to by the "pegasus.transfer.setup.source.base.url * * @return the value in the property file, else null */ public String getBaseSourceURLForSetupTransfers( ){ return mProps.getProperty( "pegasus.transfer.setup.source.base.url" ); } /** * Returns the transfer refiner that is to be used for adding in the * transfer jobs in the workflow * * Referred to by the "pegasus.transfer.refiner" property. * * @return the transfer refiner, else null */ public String getTransferRefiner(){ return mProps.getProperty("pegasus.transfer.refiner"); } /** * Returns whether to introduce quotes around url's before handing to * g-u-c and condor. * * Referred to by "pegasus.transfer.single.quote" property. * * @return boolean value specified in the properties file, else * true in case of non boolean value being specified or property * not being set. */ public boolean quoteTransferURL() { return Boolean.parse(mProps.getProperty( "pegasus.transfer.single.quote"), true); } /** * It returns the number of processes of g-u-c that the transfer script needs to * spawn to do the transfers. This is applicable only in the case where the * transfer executable has the capability of spawning processes. It should * not be confused with the number of streams that each process opens. * By default it is set to 4. In case a non integer value is specified in * the properties file it returns the default value. * * Referred to by "pegasus.transfer.throttle.processes" property. * * @return the number of processes specified in properties file, else * DEFAULT_TRANSFER_PROCESSES * * @see #DEFAULT_TRANSFER_PROCESSES */ public String getNumOfTransferProcesses() { String prop = mProps.getProperty( "pegasus.transfer.throttle.processes", DEFAULT_TRANSFER_PROCESSES ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return DEFAULT_TRANSFER_PROCESSES; } return Integer.toString( val ); } /** * It returns the number of streams that each transfer process uses to do the * ftp transfer. By default it is set to 1.In case a non integer * value is specified in the properties file it returns the default value. * * Referred to by "pegasus.transfer.throttle.streams" property. * * @return the number of streams specified in the properties file, else * DEFAULT_TRANSFER_STREAMS. * * @see #DEFAULT_TRANSFER_STREAMS */ public String getNumOfTransferStreams() { String prop = mProps.getProperty( "pegasus.transfer.throttle.streams", DEFAULT_TRANSFER_STREAMS ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return DEFAULT_TRANSFER_STREAMS; } return Integer.toString( val ); } /** * It specifies whether the underlying transfer mechanism being used should * use the force option if available to transfer the files. * * Referred to by "pegasus.transfer.force" property. * * @return boolean value specified in the properties file,else * false in case of non boolean value being specified or * property not being set. */ public boolean useForceInTransfer() { return Boolean.parse(mProps.getProperty( "pegasus.transfer.force"), false); } /** * It returns whether the use of symbolic links in case where the source * and destination files happen to be on the same file system. * * Referred to by "pegasus.transfer.links" property. * * @return boolean value specified in the properties file, else * false in case of non boolean value being specified or * property not being set. */ public boolean getUseOfSymbolicLinks() { String value = mProps.getProperty( "pegasus.transfer.links" ); return Boolean.parse(value,false); } /** * Returns the comma separated list of third party sites, specified in the * properties. * * @param property property name. * * @return the comma separated list of sites. */ public String getThirdPartySites(String property){ String value = mProps.getProperty(property); return value; } /** * Returns the comma separated list of third party sites for which * the third party transfers are executed on the remote sites. * * * @param property property name. * * @return the comma separated list of sites. */ public String getThirdPartySitesRemote(String property){ return mProps.getProperty(property); } /** * Returns the delimiter to be used for constructing the staged executable * name, during transfer of executables to remote sites. * * Referred to by the "pegasus.transfer.staging.delimiter" property. * * @return the value specified in the properties file, else * DEFAULT_STAGING_DELIMITER * * @see #DEFAULT_STAGING_DELIMITER */ public String getStagingDelimiter(){ return mProps.getProperty("pegasus.transfer.staging.delimiter", DEFAULT_STAGING_DELIMITER); } /** * Returns the list of sites for which the chmod job creation has to be * disabled for executable staging. * * Referred to by the "pegasus.transfer.disable.chmod" property. * * @return a comma separated list of site names. */ public String getChmodDisabledSites() { return mProps.getProperty( "pegasus.transfer.disable.chmod.sites" ); } /** * It specifies if the worker package needs to be staged to the remote site * or not. * * Referred to by "pegasus.transfer.worker.package" property. * * @return boolean value specified in the properties file,else * false in case of non boolean value being specified or * property not being set. */ public boolean transferWorkerPackage() { return Boolean.parse( mProps.getProperty( PEGASUS_TRANSFER_WORKER_PACKAGE_PROPERTY ), false ); } /** * A Boolean property to indicate whether to enforce strict checks against * provided worker package for jobs in PegasusLite mode. * if a job comes with worker package and it does not match fully with * worker node architecture , it will revert to Pegasus download website. * Default value is true. * * Referred to by "pegasus.transfer.worker.package.strict" property. * * @return boolean value specified in the properties file,else * true in case of non boolean value being specified or * property not being set. */ public boolean enforceStrictChecksForWorkerPackage() { return Boolean.parse( mProps.getProperty( "pegasus.transfer.worker.package.strict" ), true ); } /** * A Boolean property to indicate whether a pegasus lite job is allowed to * download from Pegasus website. * * Referred to by "pegasus.transfer.worker.package.autodownload" property. * * @return boolean value specified in the properties file,else * true in case of non boolean value being specified or * property not being set. */ public boolean allowDownloadOfWorkerPackageFromPegasusWebsite() { return Boolean.parse( mProps.getProperty( "pegasus.transfer.worker.package.autodownload" ), true ); } /** * Returns the arguments with which the transfer executable needs * to be invoked. * * Referred to by "pegasus.transfer.arguments" property. * * @return the arguments specified in the properties file, * else null if property is not specified. */ public String getTransferArguments() { return mProps.getProperty("pegasus.transfer.arguments"); } /** * Returns the extra arguments with which the transfer executable used in * PegasusLite needs to be invoked. * * Referred to by "pegasus.transfer.lite.arguments" property. * * @return the arguments specified in the properties file, * else null if property is not specified. */ public String getSLSTransferArguments() { return mProps.getProperty("pegasus.transfer.lite.arguments"); } /** * Returns the priority to be set for the stage in transfer job. * * Referred to by "pegasus.transfer.stagein.priority" property if set, * else by "pegasus.transfer.*.priority" property. * * @return the priority as String if a valid integer specified in the * properties, else null. */ public String getTransferStageInPriority(){ return getTransferPriority("pegasus.transfer.stagein.priority"); } /** * Returns the priority to be set for the stage out transfer job. * * Referred to by "pegasus.transfer.stageout.priority" property if set, * else by "pegasus.transfer.*.priority" property. * * @return the priority as String if a valid integer specified in the * properties, else null. */ public String getTransferStageOutPriority(){ return getTransferPriority("pegasus.transfer.stageout.priority"); } /** * Returns the priority to be set for the interpool transfer job. * * Referred to by "pegasus.transfer.inter.priority" property if set, * else by "pegasus.transfer.*.priority" property. * * @return the priority as String if a valid integer specified in the * properties, else null. */ public String getTransferInterPriority(){ return getTransferPriority("pegasus.transfer.inter.priority"); } /** * Returns the transfer priority. * * @param property property name. * * @return the priority as String if a valid integer specified in the * properties as value to property, else null. */ private String getTransferPriority(String property){ String value = mProps.getProperty(property, mDefaultTransferPriority); int val = -1; try { val = Integer.parseInt( value ); } catch ( Exception e ) { } //if value in properties file is corrupted //again use the default transfer priority return ( val < 0 ) ? mDefaultTransferPriority : Integer.toString( val ); } //REPLICA SELECTOR FUNCTIONS /** * Returns the mode for loading the transformation selector that selects * amongst the various candidate transformation catalog entry objects. * * Referred to by the "pegasus.selector.transformation" property. * * @return the value specified in the properties file, * else default transformation selector. * * @see #DEFAULT_TC_MAPPER_MODE */ public String getTXSelectorMode() { return mProps.getProperty( "pegasus.selector.transformation", DEFAULT_TX_SELECTOR_MODE ); } /** * Returns the name of the selector to be used for selection amongst the * various replicas of a single lfn. * * Referred to by the "pegasus.selector.replica" property. * * @return the name of the selector if the property is specified, * else null */ public String getReplicaSelector(){ return mProps.getProperty( "pegasus.selector.replica" ); } /** * Returns a comma separated list of sites, that are restricted in terms of * data movement from the site. * * Referred to by the "pegasus.rc.restricted.sites" property. * * @return comma separated list of sites. */ // public String getRestrictedSites(){ // return mProps.getProperty("pegasus.rc.restricted.sites",""); /** * Returns a comma separated list of sites, from which to prefer data * transfers for all sites. * * Referred to by the "pegasus.selector.replica.*.prefer.stagein.sites" property. * * @return comma separated list of sites. */ public String getAllPreferredSites(){ return mProps.getProperty( "pegasus.selector.replica.*.prefer.stagein.sites",""); } /** * Returns a comma separated list of sites, from which to ignore data * transfers for all sites. Replaces the old pegasus.rc.restricted.sites * property. * * Referred to by the "pegasus.selector.ignore.*.prefer.stagein.sites" property. * * @return comma separated list of sites. */ public String getAllIgnoredSites(){ return mProps.getProperty("pegasus.selector.replica.*.ignore.stagein.sites", ""); } //SITE SELECTOR PROPERTIES /** * Returns the class name of the site selector, that needs to be invoked to do * the site selection. * * Referred to by the "pegasus.selector.site" property. * * @return the classname corresponding to the site selector that needs to be * invoked if specified in the properties file, else the default * selector specified by DEFAULT_SITE_SELECTOR. * * @see #DEFAULT_SITE_SELECTOR */ public String getSiteSelectorMode() { return mProps.getProperty( "pegasus.selector.site", DEFAULT_SITE_SELECTOR ); } /** * Returns the path to the external site selector that needs to be called * out to make the decision of site selection. * * Referred to by the "pegasus.selector.site.path" property. * * @return the path to the external site selector if specified in the * properties file, else null. */ public String getSiteSelectorPath() { return mProps.getProperty( "pegasus.selector.site.path" ); } /** * It returns the timeout value in seconds after which to timeout in case of * no activity from the external site selector. * * Referred to by the "pegasus.selector.site.timeout" property. * * @return the timeout value if specified else, * DEFAULT_SITE_SELECTOR_TIMEOUT. * * @see #DEFAULT_SITE_SELECTOR_TIMEOUT */ public int getSiteSelectorTimeout() { String prop = mProps.getProperty( "pegasus.selector.site.timeout", DEFAULT_SITE_SELECTOR_TIMEOUT ); int val; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return Integer.parseInt( DEFAULT_SITE_SELECTOR_TIMEOUT ); } return val; } /** * Returns a value designating whether we need to keep the temporary files * that are passed to the external site selectors. The check for the valid * tristate value should be done at the calling function end. This just * passes on the value user specified in the properties file. * * Referred to by the "pegasus.selector.site.keep.tmp" property. * * @return the value of the property is specified, else * DEFAULT_SITE_SELECTOR_KEEP * * @see #DEFAULT_SITE_SELECTOR_KEEP */ public String getSiteSelectorKeep() { return mProps.getProperty( "pegasus.selector.site.keep.tmp", DEFAULT_SITE_SELECTOR_KEEP ); } //PROPERTIES RELATED TO KICKSTART AND EXITCODE /** * Returns the GRIDSTART that is to be used to launch the jobs on the grid. * * Referred to by the "pegasus.gridstart" property. * * @return the value specified in the property file, * else null * */ public String getGridStart(){ return mProps.getProperty("pegasus.gridstart" ); } /** * Returns a boolean indicating whether kickstart should set x bit on * staged executables before launching them. * * Referred to by the "pegasus.gridstart.kickstart.set.xbit" property. * * @return the value specified in the property file, * else false * */ public boolean setXBitWithKickstart(){ return Boolean.parse( mProps.getProperty( "pegasus.gridstart.kickstart.set.xbit" ), false ); } /** * Return a boolean indicating whether to turn the stat option for kickstart * on or not. By default it is turned on. * * Referred to by the "pegasus.gridstart.kickstart.stat" property. * * @return value specified in the property file, * else null. */ public String doStatWithKickstart(){ return mProps.getProperty( PEGASUS_KICKSTART_STAT_PROPERTY ) ; } /** * Return a boolean indicating whether to generate the LOF files for the jobs * or not. This is used to generate LOF files, but not trigger the stat option * * Referred to by the "pegasus.gridstart.kickstart.generate.loft" property. * * @return the boolean value specified in the property file, * else false if not specified or non boolean specified. */ public boolean generateLOFFiles(){ return Boolean.parse( mProps.getProperty( "pegasus.gridstart.generate.lof"), false ); } /** * Returns a boolean indicating whether to use invoke in kickstart always * or not. * * Referred to by the "pegasus.gridstart.invoke.always" property. * * @return the boolean value specified in the property file, * else false if not specified or non boolean specified. */ public boolean useInvokeInGridStart(){ return Boolean.parse( mProps.getProperty( "pegasus.gridstart.invoke.always"), false ); } /** * Returns a boolean indicating whether to disable use of invoke or not. * * Referred to by the "pegasus.gridstart.invoke.disable" property. * * @return the boolean value specified in the property file, * else false if not specified or non boolean specified. */ public boolean disableInvokeInGridStart(){ return Boolean.parse( mProps.getProperty( PegasusProperties.DISABLE_INVOKE_PROPERTY ), false ); } /** * Returns the trigger value for invoking an application through kickstart * using kickstart. If the arguments value being constructed in the condor * submit file is more than this value, then invoke is used to pass the * arguments to the remote end. Helps in bypassing the Condor 4K limit. * * Referred to by "pegasus.gridstart.invoke.length" property. * * @return the long value specified in the properties files, else * DEFAULT_INVOKE_LENGTH * * @see #DEFAULT_INVOKE_LENGTH */ public long getGridStartInvokeLength(){ long value = new Long(this.DEFAULT_INVOKE_LENGTH).longValue(); String st = mProps.getProperty( "pegasus.gridstart.invoke.length", this.DEFAULT_INVOKE_LENGTH ); try { value = new Long( st ).longValue(); } catch ( Exception e ) { //ignore malformed values from //the property file } return value; } /** * Returns a boolean indicating whehter to pass extra options to kickstart * or not. The extra options have appeared only in VDS version 1.4.2 (like -L * and -T). * * Referred to by "pegasus.gridstart.label" property. * * @return the boolean value specified in the property file, * else true if not specified or non boolean specified. */ public boolean generateKickstartExtraOptions(){ return Boolean.parse( mProps.getProperty( "pegasus.gridstart.label"), true ); } /** * Returns the mode adding the postscripts for the jobs. At present takes in * only two values all or none default being none. * * Referred to by the "pegasus.exitcode.scope" property. * * @return the mode specified by the property, else * DEFAULT_POSTSCRIPT_MODE * * @see #DEFAULT_POSTSCRIPT_MODE */ /* public String getPOSTScriptScope() { return mProps.getProperty( "pegasus.exitcode.dial", DEFAULT_POSTSCRIPT_MODE ); } */ /** * Returns the postscript to use with the jobs in the workflow. They * maybe overriden by values specified in the profiles. * * Referred to by the "pegasus.exitcode.impl" property. * * @return the postscript to use for the workflow, else null if not * specified in the properties. */ /* public String getPOSTScript(){ return mProps.getProperty( "pegasus.exitcode.impl" ); } */ /** * Returns the path to the exitcode executable to be used. * * Referred to by the "pegasus.exitcode.path.[value]" property, where [value] * is replaced by the value passed an input to this function. * * @param value the short name of the postscript whose path we want. * * @return the path to the postscript if specified in properties file. */ /* public String getPOSTScriptPath( String value ){ value = ( value == null ) ? "*" : value; StringBuffer key = new StringBuffer(); key.append( "pegasus.exitcode.path." ).append( value ); return mProps.getProperty( key.toString() ); } */ /** * Returns the argument string containing the arguments by which exitcode is * invoked. * * Referred to by the "pegasus.exitcode.arguments" property. * * @return String containing the arguments,else empty string. */ /* public String getPOSTScriptArguments() { return mProps.getProperty( "pegasus.exitcode.arguments", ""); } */ /** * Returns a boolean indicating whether to turn debug on or not for exitcode. * By default false is returned. * * Referred to by the "pegasus.exitcode.debug" property. * * @return boolean value. */ public boolean setPostSCRIPTDebugON(){ return Boolean.parse( mProps.getProperty( "pegasus.exitcode.debug"), false ); } /** * Returns the argument string containing the arguments by which prescript is * invoked. * * Referred to by the "pegasus.prescript.arguments" property. * * @return String containing the arguments. * null if not specified. */ /* public String getPrescriptArguments() { return mProps.getProperty( "pegasus.prescript.arguments","" ); } */ //PROPERTIES RELATED TO REMOTE SCHEDULERS /** * Returns the project names that need to be appended to the RSL String * while creating the submit files. Referred to by * pegasus.remote.projects property. If present, Pegasus ends up * inserting an RSL string (project = value) in the submit file. * * @return a comma separated list of key value pairs if property specified, * else null. */ // public String getRemoteSchedulerProjects() { // return mProps.getProperty( "pegasus.remote.scheduler.projects" ); /** * Returns the queue names that need to be appended to the RSL String while * creating the submit files. Referred to by the pegasus.remote.queues * property. If present, Pegasus ends up inserting an RSL string * (project = value) in the submit file. * * @return a comma separated list of key value pairs if property specified, * else null. */ // public String getRemoteSchedulerQueues() { // return mProps.getProperty( "pegasus.remote.scheduler.queues" ); /** * Returns the maxwalltimes for the various pools that need to be appended * to the RSL String while creating the submit files. Referred to by the * pegasus.scheduler.remote.queues property. If present, Pegasus ends up * inserting an RSL string (project = value) in the submit file. * * * @return a comma separated list of key value pairs if property specified, * else null. */ // public String getRemoteSchedulerMaxWallTimes() { // return mProps.getProperty( "pegasus.remote.scheduler.min.maxwalltime" ); /** * Returns the minimum walltimes that need to be enforced. * * Referred to by "pegasus.scheduler.remote.min.[key]" property. * * @param key the appropriate globus RSL key. Generally are * maxtime|maxwalltime|maxcputime * * @return the integer value as specified, -1 in case of no value being specified. */ // public int getMinimumRemoteSchedulerTime( String key ){ // StringBuffer property = new StringBuffer(); // property.append( "pegasus.remote.scheduler.min." ).append( key ); // int val = -1; // try { // val = Integer.parseInt( mProps.getProperty( property.toString() ) ); // } catch ( Exception e ) { // return val; //PROPERTIES RELATED TO CONDOR /** * Completely disable placing a symlink for Condor common log (indiscriminately). * * Starting 4.2.1 this defaults to "false" . * * Referred to by the "pegasus.condor.logs.symlink" property. * * @return value specified by the property. Defaults to false. */ public boolean symlinkCommonLog() { return Boolean.parse( mProps.getProperty( "pegasus.condor.logs.symlink" ), false ); } /** * Whether Pegasus should associate condor concurrency limits or not * * * Referred to by the "pegasus.condor.concurrency.limits" property. * * @return value specified by the property. Defaults to false. */ public boolean associateCondorConcurrencyLimits() { return Boolean.parse( mProps.getProperty( "pegasus.condor.concurrency.limits" ), false ); } /** * Returns a boolean indicating whether we want to Condor Quote the * arguments of the job or not. * * Referred to by the "pegasus.condor.arguments.quote" property. * * @return boolean */ public boolean useCondorQuotingForArguments(){ return Boolean.parse( mProps.getProperty( "pegasus.condor.arguments.quote" ), true); } /** * Returns the number of times Condor should retry running a job in case * of failure. The retry ends up reinvoking the prescript, that can change * the site selection decision in case of failure. * * Referred to by the "pegasus.dagman.retry" property. * * @return an int denoting the number of times to retry. * null if not specified or invalid entry. */ /* public String getCondorRetryValue() { String prop = mProps.getProperty( "pegasus.dagman.retry" ); int val = -1; try { val = Integer.parseInt( prop ); } catch ( Exception e ) { return null; } return Integer.toString( val ); } */ /** * Tells whether to stream condor output or not. By default it is true , * meaning condor streams the output from the remote hosts back to the submit * hosts, instead of staging it. This helps in saving filedescriptors at the * jobmanager end. * * If it is set to false, output is not streamed back. The line * "stream_output = false" should be added in the submit files for kickstart * jobs. * * Referred to by the "pegasus.condor.output.stream" property. * * @return the boolean value specified by the property, else * false in case of invalid value or property not being specified. * */ /* public boolean streamCondorOutput() { return Boolean.parse(mProps.getProperty( "pegasus.condor.output.stream"), false ); } */ /** * Tells whether to stream condor error or not. By default it is true , * meaning condor streams the error from the remote hosts back to the submit * hosts instead of staging it in. This helps in saving filedescriptors at * the jobmanager end. * * Referred to by the "pegasus.condor.error.stream" property. * * If it is set to false, output is not streamed back. The line * "stream_output = false" should be added in the submit files for kickstart * jobs. * * @return the boolean value specified by the property, else * false in case of invalid value or property not being specified. */ /* public boolean streamCondorError() { return Boolean.parse(mProps.getProperty( "pegasus.condor.error.stream"), false ); } */ //PROPERTIES RELATED TO STORK /** * Returns the credential name to be used for the stork transfer jobs. * * Referred to by the "pegasus.transfer.stork.cred" property. * * @return the credential name if specified by the property, * else null. */ public String getCredName() { return mProps.getProperty( "pegasus.transfer.stork.cred" ); } //SOME LOGGING PROPERTIES /** * Returns the log manager to use. * * Referred to by the "pegasus.log.manager" property. * * @return the value in the properties file, else Default */ public String getLogManager() { return mProps.getProperty( "pegasus.log.manager", "Default" ); } /** * Returns the log formatter to use. * * Referred to by the "pegasus.log.formatter" property. * * @return the value in the properties file, else Simple */ public String getLogFormatter() { return mProps.getProperty( "pegasus.log.formatter", "Simple" ); } /** * Returns the http url for log4j properties for windward project. * * Referred to by the "log4j.configuration" property. * * @return the value in the properties file, else null */ public String getHttpLog4jURL() { //return mProps.getProperty( "pegasus.log.windward.log4j.http.url" ); return mProps.getProperty( "log4j.configuration" ); } /** * Returns the file to which all the logging needs to be directed to. * * Referred to by the "pegasus.log.*" property. * * @return the value of the property that is specified, else * null */ public String getLoggingFile(){ return mProps.getProperty("pegasus.log.*"); } /** * Returns the location of the local log file where you want the messages to * be logged. Not used for the moment. * * Referred to by the "pegasus.log4j.log" property. * * @return the value specified in the property file,else null. */ public String getLog4JLogFile() { return mProps.getProperty( "pegasus.log4j.log" ); } /** * Returns a boolean indicating whether to write out the planner metrics * or not. * * Referred to by the "pegasus.log.metrics" property. * * @return boolean in the properties, else true */ public boolean writeOutMetrics(){ return Boolean.parse(mProps.getProperty(PegasusProperties.PEGASUS_LOG_METRICS_PROPERTY ), true ) && (this.getMetricsLogFile() != null); } /** * Returns the path to the file that is used to be logging metrics * * Referred to by the "pegasus.log.metrics.file" property. * * @return path to the metrics file if specified, else rundir/pegasus.metrics */ public String getMetricsLogFile(){ String file = mProps.getProperty( PegasusProperties.PEGASUS_LOG_METRICS_PROPERTY_FILE ); return file; } /** * Returns a boolean indicating whether to log JVM memory usage or not. * * Referred to by the "pegasus.log.memory.usage" property. * * @return boolean value specified in properties else false. */ public boolean logMemoryUsage(){ return Boolean.parse( mProps.getProperty( "pegasus.log.memory.usage" ) , false ); } //SOME MISCELLANEOUS PROPERTIES /** * Returns a boolean indicating whether we assign job priorities or not * to the jobs * * Referred to by the "pegasus.job.priority.assign" property. * * @return boolean value specified in properties else true. */ public boolean assignDefaultJobPriorities() { return Boolean.parse( mProps.getProperty( "pegasus.job.priority.assign" ) , true ); } /** * Returns a boolean indicating whether we create registration jobs or not. * * Referred to by the "pegasus.register" property. * * @return boolean value specified in properties else true. */ public boolean createRegistrationJobs() { return Boolean.parse( mProps.getProperty( "pegasus.register" ) , true ); } /** * Returns a boolean indicating whether to register a deep LFN or not. * * Referred to by the "pegasus.register.deep" property. * * @return boolean value specified in properties else true. */ public boolean registerDeepLFN() { return Boolean.parse( mProps.getProperty( "pegasus.register.deep" ) , true ); } /** * Returns a boolean indicating whether to have jobs executing on worker * node tmp or not. * * Referred to by the "pegasus.execute.*.filesystem.local" property. * * @return boolean value in the properties file, else false if not specified * or an invalid value specified. */ public boolean executeOnWorkerNode( ){ return Boolean.parse( mProps.getProperty( PegasusProperties.PEGASUS_WORKER_NODE_EXECUTION_PROPERTY ) , false ); } /** * Returns a boolean indicating whether to treat the entries in the cache * files as a replica catalog or not. * * @return boolean */ public boolean treatCacheAsRC(){ return Boolean.parse(mProps.getProperty( "pegasus.catalog.replica.cache.asrc" ), false); } /** * Returns a boolean indicating whether to treat the file locations in the DAX * as a replica catalog or not. * * Referred to by the "pegasus.catalog.replica.dax.asrc" property. * * @return boolean value in the properties file, else false if not specified * or an invalid value specified. */ public boolean treatDAXLocationsAsRC(){ return Boolean.parse(mProps.getProperty( "pegasus.catalog.replica.dax.asrc" ), false); } /** * Returns a boolean indicating whether to preserver line breaks. * * Referred to by the "pegasus.parser.dax.preserve.linebreaks" property. * * @return boolean value in the properties file, else false if not specified * or an invalid value specified. */ public boolean preserveParserLineBreaks( ){ return Boolean.parse( mProps.getProperty( "pegasus.parser.dax.preserve.linebreaks" ), false) ; } /** * Returns a boolean indicating whether to automatically * add edges as a result of underlying data dependecnies between jobs. * * Referred to by the "pegasus.parser.dax.data.dependencies" property. * * @return boolean value in the properties file, else true if not specified * or an invalid value specified. */ public boolean addDataDependencies(){ return Boolean.parse( mProps.getProperty( "pegasus.parser.dax.data.dependencies" ), true) ; } /** * Returns the path to the wings properties file. * * Referred to by the "pegasus.wings.properties" property. * * @return value in the properties file, else null. */ public String getWingsPropertiesFile( ){ return mProps.getProperty( "pegasus.wings.properties" ) ; } /** * Returns the request id. * * Referred to by the "pegasus.wings.request-id" property. * * @return value in the properties file, else null. */ public String getWingsRequestID( ){ return mProps.getProperty( "pegasus.wings.request.id" ) ; } /** * Returns the timeout value in seconds after which to timeout in case of * opening sockets to grid ftp server. * * Referred to by the "pegasus.auth.gridftp.timeout" property. * * @return the timeout value if specified else, * null. * * @see #DEFAULT_SITE_SELECTOR_TIMEOUT */ public String getGridFTPTimeout(){ return mProps.getProperty("pegasus.auth.gridftp.timeout"); } /** * Returns which submit mode to be used to submit the jobs on to the grid. * * Referred to by the "pegasus.code.generator" property. * * @return the submit mode specified in the property file, * else the default i.e condor. */ public String getSubmitMode() { return mProps.getProperty( "pegasus.code.generator", "condor" ); } /** * Returns the mode for parsing the dax while writing out the partitioned * daxes. * * Referred to by the "pegasus.partition.parser.load" property. * * @return the value specified in the properties file, else * the default value i.e single. */ public String getPartitionParsingMode() { return mProps.getProperty( "pegasus.partition.parser.load", "single" ); } /** * Returns the scope for the data reusue module. * * Referred to by the "pegasus.data.reuse.scope" property. * * @return the value specified in the properties file, else null */ public String getDataReuseScope() { return mProps.getProperty( "pegasus.data.reuse.scope" ); } //JOB COLLAPSING PROPERTIES /** * Returns a comma separated list for the node collapsing criteria for the * execution pools. This determines how many jobs one fat node gobbles up. * * Referred to by the "pegasus.clusterer.nodes" property. * * @return the value specified in the properties file, else null. */ public String getCollapseFactors() { return mProps.getProperty( "pegasus.clusterer.nodes" ); } /** * Returns the users horizontal clustering preference. This property * determines how to cluster horizontal jobs. If this property is set with a * value value of runtime, the jobs will be grouped into into clusters * according to their runtimes as specified by <code>job.runtime</code> * property. For all other cases the default horizontal clustering approach * will be used. * * @return the value specified in the properties file, else null. */ public String getHorizontalClusterPreference() { return mProps.getProperty( "pegasus.clusterer.preference" ); } /** * Returns what job aggregator is to be used to aggregate multiple * compute jobs into a single condor job. * * Referred to by the "pegasus.cluster.job.aggregator" property. * * @return the value specified in the properties file, else * DEFAULT_JOB_AGGREGATOR * * @see #DEFAULT_JOB_AGGREGATOR */ public String getJobAggregator(){ return mProps.getProperty("pegasus.clusterer.job.aggregator",DEFAULT_JOB_AGGREGATOR); } /** * Returns whether the seqexec job aggregator should log progress to a log or not. * * Referred to by the "pegasus.clusterer.job.aggregator.seqexec.log" property. * * @return the value specified in the properties file, else false * */ public boolean logJobAggregatorProgress(){ return Boolean.parse( getProperty( "pegasus.clusterer.job.aggregator.seqexec.log" ), false ); } /** * Returns whether the seqexec job aggregator should write to a global log or not. * This comes into play only if "pegasus.clusterer.job.aggregator.seqexec.log" * is set to true. * * Referred to by the "pegasus.clusterer.job.aggregator.seqexec.log.global" property. * * @return the value specified in the properties file, else true * */ public boolean logJobAggregatorProgressToGlobal(){ return Boolean.parse( getProperty( "pegasus.clusterer.job.aggregator.seqexec.log.global", "pegasus.clusterer.job.aggregator.seqexec.hasgloballog"), true ); } /** * Returns a boolean indicating whether seqexec trips on the first job failure. * * Referred to by the "pegasus.clusterer.job.aggregator.seqexec.firstjobfail" property. * * @return the value specified in the properties file, else true * */ public boolean abortOnFirstJobFailure(){ return Boolean.parse( mProps.getProperty( "pegasus.clusterer.job.aggregator.seqexec.firstjobfail" ), true ); } /** * Returns a boolean indicating whether clustering should be allowed for * single jobs or not * * Referred to by the "pegasus.clusterer.allow.single" property. * * @return the value specified in the properties file, else false * */ public boolean allowClusteringOfSingleJobs(){ return Boolean.parse( mProps.getProperty( "pegasus.clusterer.allow.single" ), false ); } /** * Returns a boolean indicating whether to enable integrity checking or not. * * * @return true if integrity dial is set as full or not specified, else false * */ public boolean doIntegrityChecking() { return this.getIntegrityDial() == INTEGRITY_DIAL.full; } /** * Returns the integrity dial enum * * Referred to by the "pegasus.integrity.checking" property. * * @return the value specified in the properties file, else INTEGRITY_DIAL.full * * @see INTEGRITY_DIAL */ public INTEGRITY_DIAL getIntegrityDial(){ INTEGRITY_DIAL dial = INTEGRITY_DIAL.full; String value = mProps.getProperty( "pegasus.integrity.checking" ); if( value == null ){ return dial; } //try to assign a dial value try{ dial = INTEGRITY_DIAL.valueOf( value ); }catch( IllegalArgumentException iae ){ throw new IllegalArgumentException( "Invalid value specified for integrity checking " + value, iae); } return dial; } //DEFERRED PLANNING PROPERTIES /** * Returns the root workflow UUID if defined in the properties, else null * * Referred to by the "pegasus.workflow.root.uuid" property. * * @return the value in the properties file else, null */ public String getRootWorkflowUUID() { return mProps.getProperty( ROOT_WORKFLOW_UUID_PROPERTY_KEY, null ); } /** * Returns the DAXCallback that is to be used while parsing the DAX. * * Referred to by the "pegasus.partitioner.parser.dax.callback" property. * * @return the value specified in the properties file, else * DEFAULT_DAX_CALLBACK * * @see #DEFAULT_DAX_CALLBACK */ public String getPartitionerDAXCallback(){ return mProps.getProperty("pegasus.partitioner.parser.dax.callback",DEFAULT_DAX_CALLBACK); } /** * Returns the key that is to be used as a label key, for labelled * partitioning. * * Referred to by the "pegasus.partitioner.label.key" property. * * @return the value specified in the properties file. */ public String getPartitionerLabelKey(){ return mProps.getProperty( "pegasus.partitioner.label.key" ); } /** * Returns the bundle value for a particular transformation. * * Referred to by the "pegasus.partitioner.horziontal.bundle.[txname]" property, * where [txname] is replaced by the name passed an input to this function. * * @param name the logical name of the transformation. * * @return the path to the postscript if specified in properties file, * else null. */ public String getHorizontalPartitionerBundleValue( String name ){ StringBuffer key = new StringBuffer(); key.append( "pegasus.partitioner.horizontal.bundle." ).append( name ); return mProps.getProperty( key.toString() ); } /** * Returns the collapse value for a particular transformation. * * Referred to by the "pegasus.partitioner.horziontal.collapse.[txname]" property, * where [txname] is replaced by the name passed an input to this function. * * @param name the logical name of the transformation. * * @return the path to the postscript if specified in properties file, * else null. */ public String getHorizontalPartitionerCollapseValue( String name ){ StringBuffer key = new StringBuffer(); key.append( "pegasus.partitioner.horizontal.collapse." ).append( name ); return mProps.getProperty( key.toString() ); } /** * Returns the key that is to be used as a label key, for labelled * clustering. * * Referred to by the "pegasus.clusterer.label.key" property. * * @return the value specified in the properties file. */ public String getClustererLabelKey(){ return mProps.getProperty( "pegasus.clusterer.label.key"); } /** * Returns the estimator to be used * * Referred to by the "pegasus.estimator" property * * @return value specified else null */ public String getEstimator() { return mProps.getProperty( "pegasus.estimator"); } /** * Returns the path to the property file that has been writting out in * the submit directory. * * @return path to the property file * * @exception RuntimeException in case of file not being generated. */ public String getPropertiesInSubmitDirectory( ){ if ( mPropsInSubmitDir == null || mPropsInSubmitDir.length() == 0 ){ throw new RuntimeException( "Properties file does not exist in directory " ); } return mPropsInSubmitDir; } /** * Writes out the properties to a temporary file in the directory passed. * * @param directory the directory in which the properties file needs to * be written to. * * * @return the absolute path to the properties file written in the directory. * * @throws IOException in case of error while writing out file. */ public String writeOutProperties( String directory ) throws IOException{ return this.writeOutProperties( directory, true ); } /** * Writes out the properties to a temporary file in the directory passed. * * @param directory the directory in which the properties file needs to * be written to. * @param sanitizePath boolean indicating whether to sanitize paths for * certain properties or not. * * @return the absolute path to the properties file written in the directory. * * @throws IOException in case of error while writing out file. */ public String writeOutProperties( String directory , boolean sanitizePath ) throws IOException{ return this.writeOutProperties( directory, sanitizePath, true ); } /** * Writes out the properties to a temporary file in the directory passed. * * @param directory the directory in which the properties file needs to * be written to. * @param sanitizePath boolean indicating whether to sanitize paths for * certain properties or not. * @param setInternalVariable whether to set the internal variable that stores * the path to the properties file. * * @return the absolute path to the properties file written in the directory. * * @throws IOException in case of error while writing out file. */ public String writeOutProperties( String directory , boolean sanitizePath, boolean setInternalVariable ) throws IOException{ File dir = new File(directory); //sanity check on the directory sanityCheck( dir ); //we only want to write out the Pegasus properties for time being //and any profiles that were mentioned in the properties. Properties properties = new Properties(); for ( Profiles.NAMESPACES n : Profiles.NAMESPACES.values() ){ Properties p = this.mProps.matchingSubset( namespaceToPropertiesPrefix().get( n ), true ); properties.putAll( p ); } //check if we need to sanitize paths for certain properties or not if( sanitizePath ){ sanitizePathForProperty( properties, "pegasus.catalog.site.file" ); sanitizePathForProperty( properties, "pegasus.catalog.replica.file" ); sanitizePathForProperty( properties, "pegasus.catalog.transformation.file" ); } //put in a sensible default for dagman maxpre for pegasus-run to //pick up if not specified beforehand StringBuffer buffer = new StringBuffer(); buffer.append( Dagman.NAMESPACE_NAME ).append( "." ).append( Dagman.MAXPRE_KEY.toLowerCase() ); String key = buffer.toString(); if( !properties.containsKey( key ) ){ //add defautl value properties.put( key , DEFAULT_DAGMAN_MAX_PRE_VALUE ); } //create a temporary file in directory File f = File.createTempFile( "pegasus.", ".properties", dir ); //the header of the file StringBuffer header = new StringBuffer(64); header.append("Pegasus USER PROPERTIES AT RUNTIME \n") .append("#ESCAPES IN VALUES ARE INTRODUCED"); //create an output stream to this file and write out the properties OutputStream os = new FileOutputStream(f); properties.store( os, header.toString() ); os.close(); //also set it to the internal variable if ( setInternalVariable ){ mPropsInSubmitDir = f.getAbsolutePath(); return mPropsInSubmitDir; } else { return f.getAbsolutePath(); } } /** * Santizes the value in the properties . Ensures that the path is absolute. * * @param properties the properties * @param key the key whose value needs to be sanitized */ private void sanitizePathForProperty(Properties properties, String key ) { if( properties.containsKey(key) ){ String value = properties.getProperty( key ); if( value != null ){ properties.setProperty( key, new File( value ).getAbsolutePath() ); } } } /** * Checks the destination location for existence, if it can * be created, if it is writable etc. * * @param dir is the new base directory to optionally create. * * @throws IOException in case of error while writing out files. */ protected static void sanityCheck( File dir ) throws IOException{ if ( dir.exists() ) { // location exists if ( dir.isDirectory() ) { // ok, isa directory if ( dir.canWrite() ) { // can write, all is well return; } else { // all is there, but I cannot write to dir throw new IOException( "Cannot write to existing directory " + dir.getPath() ); } } else { // exists but not a directory throw new IOException( "Destination " + dir.getPath() + " already " + "exists, but is not a directory." ); } } else { // does not exist, try to make it if ( ! dir.mkdirs() ) { //try to get around JVM bug. JIRA PM-91 if( dir.getPath().endsWith( "." ) ){ //just try to create the parent directory if( !dir.getParentFile().mkdirs() ){ throw new IOException( "Unable to create directory " + dir.getPath() ); } return; } throw new IOException( "Unable to create directory destination " + dir.getPath() ); } } } /** * This function is used to check whether a deprecated property is used or * not. If a deprecated property is used,it logs a warning message specifying * the new property. If both properties are not set by the user, the function * returns the default property. If no default property then null. * * @param newProperty the new property that should be used. * @param deprecatedProperty the deprecated property that needs to be * replaced. * * @return the appropriate value. */ private String getProperty( String newProperty, String deprecatedProperty ) { return this.getProperty( newProperty, deprecatedProperty, null ); } /** * This function is used to check whether a deprecated property is used or * not. If a deprecated property is used,it logs a warning message specifying * the new property. If both properties are not set by the user, the * function returns the default property. If no default property then null. * * * @param newProperty the new property that should be used. * @param deprecatedProperty the deprecated property that needs to be * replaced. * @param defaultValue the default value that should be returned. * * @return the appropriate value. */ private String getProperty( String newProperty, String deprecatedProperty, String defaultValue ) { String value = null; //try for the new property //first value = mProps.getProperty( newProperty ); if ( value == null ) { //try the deprecated property if set value = mProps.getProperty( deprecatedProperty ); //if the value is not null if ( value != null ) { //print the warning message logDeprecatedWarning(deprecatedProperty,newProperty); return value; } else { //else return the default value return defaultValue; } } return value; } /** * Logs a warning about the deprecated property. Logs a warning only if * it has not been displayed before. * * @param deprecatedProperty the deprecated property that needs to be * replaced. * @param newProperty the new property that should be used. */ private void logDeprecatedWarning(String deprecatedProperty, String newProperty){ if(!mDeprecatedProperties.contains(deprecatedProperty)){ //log only if it had already not been logged StringBuffer sb = new StringBuffer(); sb.append( "The property " ).append( deprecatedProperty ). append( " has been deprecated. Use " ).append( newProperty ). append( " instead." ); // mLogger.log(sb.toString(),LogManager.WARNING_MESSAGE_LEVEL ); System.err.println( "[WARNING] " + sb.toString() ); //push the property in to indicate it has already been //warned about mDeprecatedProperties.add(deprecatedProperty); } } /** * Returns a boolean indicating whether to use third party transfers for * all types of transfers or not. * * Referred to by the "pegasus.transfer.*.thirdparty" property. * * @return the boolean value in the properties files, * else false if no value specified, or non boolean specified. */ // private boolean useThirdPartyForAll(){ // return Boolean.parse("pegasus.transfer.*.thirdparty", // false); /** * Gets the reference to the internal singleton object. This method is * invoked with the assumption that the singleton method has been invoked once * and has been populated. Also that it has not been disposed by the garbage * collector. Can be potentially a buggy way to invoke. * * @return a handle to the Properties class. */ // public static PegasusProperties singletonInstance() { // return singletonInstance( null ); /** * Gets a reference to the internal singleton object. * * @param propFileName name of the properties file to picked * from $PEGASUS_HOME/etc/ directory. * * @return a handle to the Properties class. */ // public static PegasusProperties singletonInstance( String propFileName ) { // if ( pegProperties == null ) { // //only the default properties file // //can be picked up due to the way // //Singleton implemented in CommonProperties.??? // pegProperties = new PegasusProperties( null ); // return pegProperties; }
package edu.jhu.thrax.hadoop.extraction; import java.io.IOException; import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import edu.jhu.thrax.datatypes.Rule; import edu.jhu.thrax.extraction.RuleExtractor; import edu.jhu.thrax.extraction.RuleExtractorFactory; import edu.jhu.thrax.hadoop.datatypes.RuleWritable; import edu.jhu.thrax.util.MalformedInput; import edu.jhu.thrax.util.TestSetFilter; import edu.jhu.thrax.util.exceptions.ConfigurationException; import edu.jhu.thrax.util.exceptions.EmptyAlignmentException; import edu.jhu.thrax.util.exceptions.EmptySentenceException; import edu.jhu.thrax.util.exceptions.InconsistentAlignmentException; import edu.jhu.thrax.util.exceptions.MalformedInputException; import edu.jhu.thrax.util.exceptions.MalformedParseException; import edu.jhu.thrax.util.exceptions.NotEnoughFieldsException; public class ExtractionMapper extends Mapper<LongWritable, Text, RuleWritable, IntWritable> { private RuleExtractor extractor; private IntWritable one = new IntWritable(1); private boolean filter = false; protected void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); try { extractor = RuleExtractorFactory.create(conf); } catch (ConfigurationException ex) { System.err.println(ex.getMessage()); } } protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { context.progress(); if (extractor == null) return; String line = value.toString(); try { for (Rule r : extractor.extract(line)) { RuleWritable rw = new RuleWritable(r); context.write(rw, one); } } catch (NotEnoughFieldsException e) { context.getCounter(MalformedInput.NOT_ENOUGH_FIELDS).increment(1); } catch (EmptySentenceException e) { context.getCounter(MalformedInput.EMPTY_SENTENCE).increment(1); } catch (MalformedParseException e) { context.getCounter(MalformedInput.MALFORMED_PARSE).increment(1); } catch (EmptyAlignmentException e) { context.getCounter(MalformedInput.EMPTY_ALIGNMENT).increment(1); } catch (InconsistentAlignmentException e) { context.getCounter(MalformedInput.INCONSISTENT_ALIGNMENT).increment(1); } catch (MalformedInputException e) { context.getCounter(MalformedInput.UNKNOWN).increment(1); } } }
package edu.ntnu.idi.goldfish.preprocessors; import edu.ntnu.idi.goldfish.mahout.SMDataModel; import edu.ntnu.idi.goldfish.mahout.SMPreference; import org.apache.commons.math3.stat.correlation.PearsonsCorrelation; import org.apache.mahout.cf.taste.common.NoSuchItemException; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.model.Preference; import org.apache.mahout.cf.taste.model.PreferenceArray; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Preprocessor { private final int THRESHOLD = 3; private Map<String, Float> correlations = new HashMap<String, Float>(); private static Set<String> pseudoRatings = new HashSet<String>(); public static DataModel getPreprocessedDataModel(String path) throws TasteException, IOException { SMDataModel model; model = new SMDataModel(new File(path)); Preprocessor pre = new Preprocessor(); pre.preprocess(model); return model; } public Preprocessor() { } public static boolean isPseudoPreference(Preference pref) { return pseudoRatings.contains(String.format("%d_%d", pref.getUserID(), pref.getItemID())); } public void preprocess(SMDataModel model) throws TasteException { // iterate through all users LongPrimitiveIterator it = model.getItemIDs(); while (it.hasNext()) { long itemID = it.next(); // iterate through all prefs for user PreferenceArray prefs = model.getPreferencesForItem(itemID); for (Preference p : prefs) { SMPreference pref = (SMPreference) p; boolean hasExplicit = pref.getValue(0) >= 1; if (!hasExplicit) { boolean hasImplicit = false; float[] vals = pref.getValues(); for (int i = 1; i < vals.length; i++) { if (vals[i] >= 1) { hasImplicit = true; break; } } // iterate through implicit values and use the one with // highest correlation // find out if we have enough explicit-implicit rating // pars if (hasImplicit && prefs.length() >= THRESHOLD) { int bestCorrelated = -1; for (int i = 1; i < vals.length; i++) { if (bestCorrelated == -1 || getCorrelation(model, itemID, i) > getCorrelation(model, itemID, bestCorrelated)) { bestCorrelated = i; } } TrendLine t = new PolyTrendLine(1); double[] explRatings = getRatings(model, itemID, 0); double[] implRatings = getRatings(model, itemID, bestCorrelated); t.setValues(explRatings, implRatings); // check if abs(correlation) > 0.5 double correlation = getCorrelation(model, itemID, bestCorrelated); if (Math.abs(correlation) > 0.5) { float pseudoRating = (float) Math.round(t.predict(pref.getValue(bestCorrelated))); // float pseudoRating = getPseudoRatingClosestNeighbor(prefs, pref, bestCorrelated); pref.setValue(pseudoRating, 0); // set explicit // value pseudoRatings.add(String.format("%d_%d", pref.getUserID(), pref.getItemID())); } } } } } } private float getPseudoRatingClosestNeighbor(PreferenceArray prefs, SMPreference currentPref, int bestCorrelated) { float diff = Float.MAX_VALUE; SMPreference closestPref = null; for (Preference pref : prefs) { SMPreference p = (SMPreference) pref; float tempDiff = Math.abs(currentPref.getValue(1) - p.getValue(bestCorrelated)); if (tempDiff < diff) { diff = tempDiff; closestPref = p; } } return closestPref.getValue(0); } public double getCorrelation(SMDataModel model, long itemID, int implicitIndex) throws NoSuchItemException { double[] expl = getRatings(model, itemID, 0); double[] impl = getRatings(model, itemID, implicitIndex); PearsonsCorrelation pc = new PearsonsCorrelation(); return pc.correlation(expl, impl); } /** * * @param model * @param itemID * @param index * 0 = explicit, 1,2...n = implicit * @return * @throws NoSuchItemException */ public double[] getRatings(SMDataModel model, long itemID, int index) throws NoSuchItemException{ PreferenceArray prefs = model.getPreferencesForItem(itemID); double[] ratings = new double[prefs.length()]; for (int i = 0; i < prefs.length(); i++) { SMPreference p = (SMPreference) prefs.get(i); ratings[i] = p.getValue(index); } return ratings; } }
package edu.usc.glidein.service.state; import edu.usc.glidein.service.exec.CondorEvent; import edu.usc.glidein.service.exec.CondorEventListener; /** TODO: Implement CancelSiteListener */ public class CancelSiteListener implements CondorEventListener { public CancelSiteListener() { } public void handleEvent(CondorEvent event) { } }
package fitnesse.testsystems.slim.tables; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import fitnesse.slim.SlimCommandRunningClient; import fitnesse.slim.converters.BooleanConverter; import fitnesse.slim.converters.VoidConverter; import fitnesse.slim.instructions.CallAndAssignInstruction; import fitnesse.slim.instructions.CallInstruction; import fitnesse.slim.instructions.Instruction; import fitnesse.slim.instructions.MakeInstruction; import fitnesse.testsystems.slim.HtmlTable; import fitnesse.testsystems.slim.HtmlTableScanner; import fitnesse.testsystems.slim.SlimTestContext; import fitnesse.testsystems.slim.SlimTestContextImpl; import fitnesse.testsystems.slim.Table; import fitnesse.testsystems.slim.TableScanner; import fitnesse.wiki.WikiPage; import fitnesse.wiki.WikiPageUtil; import fitnesse.wiki.mem.InMemoryPage; import fitnesse.wikitext.Utils; import org.junit.Before; import org.junit.Test; import util.ListUtility; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static util.ListUtility.list; public class ScriptTableTest { private WikiPage root; private List<SlimAssertion> assertions; private final String scriptTableHeader = "|Script|\n"; public ScriptTable st; private SlimTestContextImpl testContext; private class LocalizedScriptTable extends ScriptTable { public LocalizedScriptTable(Table table, String tableId, SlimTestContext context) { super(table, tableId, context); } @Override protected String getTableType() { return "localizedScriptTable"; } @Override protected String getTableKeyword() { return "localized script"; } @Override protected String getStartKeyword() { return "localized start"; } @Override protected String getCheckKeyword() { return "localized check"; } @Override protected String getCheckNotKeyword() { return "localized check not"; } @Override protected String getEnsureKeyword() { return "localized ensure"; } @Override protected String getRejectKeyword() { return "localized reject"; } @Override protected String getNoteKeyword() { return "localized note"; } @Override protected String getShowKeyword() { return "localized show"; } } @Before public void setUp() throws Exception { root = InMemoryPage.makeRoot("root"); assertions = new ArrayList<SlimAssertion>(); } private ScriptTable buildInstructionsForWholeTable(String pageContents, boolean localized) throws Exception { st = makeScriptTable(pageContents, localized); assertions.addAll(st.getAssertions()); return st; } private ScriptTable makeScriptTable(String tableText, boolean localized) throws Exception { WikiPageUtil.setPageContents(root, tableText); TableScanner ts = new HtmlTableScanner(root.getData().getHtml()); Table t = ts.getTable(0); testContext = new SlimTestContextImpl(); if (localized) return new LocalizedScriptTable(t, "id", testContext); else return new ScriptTable(t, "id", testContext); } private void assertScriptResults(String scriptStatements, List<List<?>> scriptResults, String table, boolean localized) throws Exception { buildInstructionsFor(scriptStatements, localized); List<List<?>> resultList = ListUtility.<List<?>>list(list(localized ? "localizedScriptTable_id_0": "scriptTable_id_0", "OK")); resultList.addAll(scriptResults); Map<String, Object> pseudoResults = SlimCommandRunningClient.resultToMap(resultList); SlimAssertion.evaluateExpectations(assertions, pseudoResults); assertEquals(table, Utils.unescapeWiki(st.getTable().toString())); } private void buildInstructionsFor(String scriptStatements, boolean localized) throws Exception { buildInstructionsForWholeTable(scriptTableHeader + scriptStatements, localized); } private List<Instruction> instructions() { return SlimAssertion.getInstructions(assertions); } @Test public void instructionsForScriptTable() throws Exception { buildInstructionsFor("||\n", false); assertEquals(0, assertions.size()); } @Test public void startStatement() throws Exception { buildInstructionsFor("|start|Bob|\n", false); List<MakeInstruction> expectedInstructions = list( new MakeInstruction("scriptTable_id_0", "scriptTableActor", "Bob") ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedStartStatement() throws Exception { buildInstructionsFor("|localized start|Bob|\n", true); List<MakeInstruction> expectedInstructions = list( new MakeInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "Bob") ); assertEquals(expectedInstructions, instructions()); } @Test public void scriptWithActor() throws Exception { buildInstructionsForWholeTable("|script|Bob|\n", false); List<MakeInstruction> expectedInstructions = list( new MakeInstruction("scriptTable_id_0", "scriptTableActor", "Bob") ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedScriptWithActor() throws Exception { buildInstructionsForWholeTable("|localized script|Bob|\n", true); List<MakeInstruction> expectedInstructions = list( new MakeInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "Bob") ); assertEquals(expectedInstructions, instructions()); } @Test public void startStatementWithArguments() throws Exception { buildInstructionsFor("|start|Bob martin|x|y|\n", false); List<MakeInstruction> expectedInstructions = list( new MakeInstruction("scriptTable_id_0", "scriptTableActor", "BobMartin", new Object[]{"x", "y"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedStartStatementWithArguments() throws Exception { buildInstructionsFor("|localized start|Bob martin|x|y|\n", true); List<MakeInstruction> expectedInstructions = list( new MakeInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "BobMartin", new Object[]{"x", "y"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void scriptStatementWithArguments() throws Exception { buildInstructionsForWholeTable("|script|Bob martin|x|y|\n", false); List<MakeInstruction> expectedInstructions = list( new MakeInstruction("scriptTable_id_0", "scriptTableActor", "BobMartin", new Object[]{"x", "y"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedScriptStatementWithArguments() throws Exception { buildInstructionsForWholeTable("|localized script|Bob martin|x|y|\n", true); List<MakeInstruction> expectedInstructions = list( new MakeInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "BobMartin", new Object[]{"x", "y"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void simpleFunctionCall() throws Exception { buildInstructionsFor("|function|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function") ); assertEquals(expectedInstructions, instructions()); } @Test public void functionCallWithOneArgument() throws Exception { buildInstructionsFor("|function|arg|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void functionCallWithOneArgumentAndTrailingName() throws Exception { buildInstructionsFor("|function|arg|trail|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "functionTrail", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void complexFunctionCallWithManyArguments() throws Exception { buildInstructionsFor("|eat|3|meals with|12|grams protein|3|grams fat |\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "eatMealsWithGramsProteinGramsFat", new Object[]{"3", "12", "3"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void functionCallWithSequentialArgumentProcessingAndOneArgument() throws Exception { buildInstructionsFor("|function;|arg0|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"arg0"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void functionCallWithSequentialArgumentProcessingAndMultipleArguments() throws Exception { buildInstructionsFor("|function;|arg0|arg1|arg2|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"arg0", "arg1", "arg2"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void functionCallWithSequentialArgumentProcessingEmbedded() throws Exception { buildInstructionsFor("|set name|Marisa|department and title;|QA|Tester|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "setNameDepartmentAndTitle", new Object[]{"Marisa", "QA", "Tester"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void functionCallWithSequentialArgumentProcessingEmbedded2() throws Exception { buildInstructionsFor("|set name|Marisa|department|QA|title and length of employment;|Tester|2 years|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "setNameDepartmentTitleAndLengthOfEmployment", new Object[]{"Marisa", "QA", "Tester", "2 years"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void checkWithFunction() throws Exception { buildInstructionsFor("|check|function|arg|result|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedCheckWithFunction() throws Exception { buildInstructionsFor("|localized check|function|arg|result|\n", true); List<CallInstruction> expectedInstructions = list( new CallInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void checkNotWithFunction() throws Exception { buildInstructionsFor("|check not|function|arg|result|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedCheckNotWithFunction() throws Exception { buildInstructionsFor("|localized check not|function|arg|result|\n", true); List<CallInstruction> expectedInstructions = list( new CallInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void checkWithFunctionAndTrailingName() throws Exception { buildInstructionsFor("|check|function|arg|trail|result|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "functionTrail", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedCheckWithFunctionAndTrailingName() throws Exception { buildInstructionsFor("|localized check|function|arg|trail|result|\n", true); List<CallInstruction> expectedInstructions = list( new CallInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "functionTrail", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void rejectWithFunctionCall() throws Exception { buildInstructionsFor("|reject|function|arg|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedRejectWithFunctionCall() throws Exception { buildInstructionsFor("|localized reject|function|arg|\n", true); List<CallInstruction> expectedInstructions = list( new CallInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void ensureWithFunctionCall() throws Exception { buildInstructionsFor("|ensure|function|arg|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedEnsureWithFunctionCall() throws Exception { buildInstructionsFor("|localized ensure|function|arg|\n", true); List<CallInstruction> expectedInstructions = list( new CallInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void showWithFunctionCall() throws Exception { buildInstructionsFor("|show|function|arg|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void localizedShowWithFunctionCall() throws Exception { buildInstructionsFor("|localized show|function|arg|\n", true); List<CallInstruction> expectedInstructions = list( new CallInstruction("localizedScriptTable_id_0", "localizedScriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void setSymbol() throws Exception { buildInstructionsFor("|$V=|function|arg|\n", false); List<CallAndAssignInstruction> expectedInstructions = list( new CallAndAssignInstruction("scriptTable_id_0", "V", "scriptTableActor", "function", new Object[]{"arg"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void useSymbol() throws Exception { buildInstructionsFor("|function|$V|\n", false); List<CallInstruction> expectedInstructions = list( new CallInstruction("scriptTable_id_0", "scriptTableActor", "function", new Object[]{"$V"}) ); assertEquals(expectedInstructions, instructions()); } @Test public void noteDoesNothing() throws Exception { buildInstructionsFor("|note|blah|blah|\n", false); List<Instruction> expectedInstructions = Collections.emptyList(); assertEquals(expectedInstructions, instructions()); } @Test public void localizedNoteDoesNothing() throws Exception { buildInstructionsFor("|localized note|blah|blah|\n", true); List<Instruction> expectedInstructions = Collections.emptyList(); assertEquals(expectedInstructions, instructions()); } @Test public void initialBlankCellDoesNothing() throws Exception { buildInstructionsFor("||blah|blah|\n", false); List<Instruction> expectedInstructions = Collections.emptyList(); assertEquals(expectedInstructions, instructions()); } @Test public void initialHashDoesNothing() throws Exception { buildInstructionsFor("|!-#comment-!|blah|blah|\n", false); List<Instruction> expectedInstructions = Collections.emptyList(); assertEquals(expectedInstructions, instructions()); } @Test public void initialStarDoesNothing() throws Exception { buildInstructionsFor("|*comment|blah|blah|\n", false); List<Instruction> expectedInstructions = Collections.emptyList(); assertEquals(expectedInstructions, instructions()); } @Test public void voidActionHasNoEffectOnColor() throws Exception { assertScriptResults("|func|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", VoidConverter.VOID_TAG) ), "[[Script], [func]]", false ); } @Test public void actionReturningNullHasNoEffectOnColor() throws Exception { assertScriptResults("|func|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "null") ), "[[Script], [func]]", false ); } @Test public void trueActionPasses() throws Exception { assertScriptResults("|func|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", BooleanConverter.TRUE) ), "[[Script], [pass(func)]]", false ); } @Test public void falseActionFails() throws Exception { assertScriptResults("|func|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", BooleanConverter.FALSE) ), "[[Script], [fail(func)]]", false ); } @Test public void checkPasses() throws Exception { assertScriptResults("|check|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "3") ), "[[Script], [check, func, pass(3)]]", false ); } @Test public void localizedCheckPasses() throws Exception { assertScriptResults("|localized check|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", "3") ), "[[Script], [localized check, func, pass(3)]]", true ); } @Test public void checkNotFails() throws Exception { assertScriptResults("|check not|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "3") ), "[[Script], [check not, func, fail(3)]]", false ); } @Test public void localizedCheckNotFails() throws Exception { assertScriptResults("|localized check not|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", "3") ), "[[Script], [localized check not, func, fail(3)]]", true ); } @Test public void checkFails() throws Exception { assertScriptResults("|check|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "4") ), "[[Script], [check, func, fail(a=4;e=3)]]", false ); } @Test public void localizedCheckFails() throws Exception { assertScriptResults("|localized check|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", "4") ), "[[Script], [localized check, func, fail(a=4;e=3)]]", true ); } @Test public void checkNotPasses() throws Exception { assertScriptResults("|check not|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "4") ), "[[Script], [check not, func, pass(a=4;e=3)]]", false ); } @Test public void localizedCheckNotPasses() throws Exception { assertScriptResults("|localized check not|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", "4") ), "[[Script], [localized check not, func, pass(a=4;e=3)]]", true ); } @Test public void ensurePasses() throws Exception { assertScriptResults("|ensure|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", BooleanConverter.TRUE) ), "[[Script], [pass(ensure), func, 3]]", false ); } @Test public void localizedEnsurePasses() throws Exception { assertScriptResults("|localized ensure|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", BooleanConverter.TRUE) ), "[[Script], [pass(localized ensure), func, 3]]", true ); } @Test public void ensureFails() throws Exception { assertScriptResults("|ensure|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", BooleanConverter.FALSE) ), "[[Script], [fail(ensure), func, 3]]", false ); } @Test public void localizedEnsureFails() throws Exception { assertScriptResults("|localized ensure|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", BooleanConverter.FALSE) ), "[[Script], [fail(localized ensure), func, 3]]", true ); } @Test public void rejectPasses() throws Exception { assertScriptResults("|reject|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", BooleanConverter.FALSE) ), "[[Script], [pass(reject), func, 3]]", false ); } @Test public void localizedRejectPasses() throws Exception { assertScriptResults("|localized reject|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", BooleanConverter.FALSE) ), "[[Script], [pass(localized reject), func, 3]]", true ); } @Test public void rejectFails() throws Exception { assertScriptResults("|reject|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", BooleanConverter.TRUE) ), "[[Script], [fail(reject), func, 3]]", false ); } @Test public void localizedRejectFails() throws Exception { assertScriptResults("|localized reject|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", BooleanConverter.TRUE) ), "[[Script], [fail(localized reject), func, 3]]", true ); } @Test public void show() throws Exception { assertScriptResults("|show|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "kawabunga") ), "[[Script], [show, func, 3, kawabunga]]", false ); } @Test public void showDoesEscapes() throws Exception { assertScriptResults("|show|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "1 < 0") ), "[[Script], [show, func, 3, 1 < 0]]", false ); assertTrue(st.getTable() instanceof HtmlTable); String html = ((HtmlTable) st.getTable()).toHtml(); assertTrue(html, html.contains("1 &lt; 0")); } @Test public void showDoesNotEscapeValidHtml() throws Exception { assertScriptResults("|show|func|3|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "<a href=\"http://myhost/turtle.html\">kawabunga</a>") ), "[[Script], [show, func, 3, <a href=\"http://myhost/turtle.html\">kawabunga</a>]]", false ); assertTrue(st.getTable() instanceof HtmlTable); String html = ((HtmlTable) st.getTable()).toHtml(); assertTrue(html.contains("<a href=\"http://myhost/turtle.html\">kawabunga</a>")); } @Test public void localizedShow() throws Exception { assertScriptResults("|localized show|func|3|\n", ListUtility.<List<?>>list( list("localizedScriptTable_id_0", "kawabunga") ), "[[Script], [localized show, func, 3, kawabunga]]", true ); } @Test public void symbolReplacement() throws Exception { assertScriptResults( "|$V=|function|\n" + "|check|funcion|$V|$V|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "3"), list("scriptTable_id_1", "3") ), "[[Script], [$V<-[3], function], [check, funcion, $V->[3], pass($V->[3])]]", false ); } @Test public void sameSymbolTwiceReplacement() throws Exception { assertScriptResults( "|$V=|function|\n" + "|check|funcion|$V $V|$V|\n", ListUtility.<List<?>>list( list("scriptTable_id_0", "3"), list("scriptTable_id_1", "3") ), "[[Script], [$V<-[3], function], [check, funcion, $V->[3] $V->[3], pass($V->[3])]]", false ); } }
package gov.nih.nci.calab.ui.search; /** * This class searches workflows based on user supplied criteria. * * @author pansu */ /* CVS $Id: SearchWorkflowAction.java,v 1.6 2006-04-13 17:27:58 pansu Exp $ */ import gov.nih.nci.calab.dto.search.WorkflowResultBean; import gov.nih.nci.calab.service.search.SearchWorkflowService; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.ui.core.AbstractBaseAction; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; public class SearchWorkflowAction extends AbstractBaseAction { private static Logger logger = Logger.getLogger(SearchWorkflowAction.class); public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; ActionMessages msgs = new ActionMessages(); try { DynaValidatorForm theForm = (DynaValidatorForm) form; String assayName = (String) theForm.get("assayName"); String assayType = ((String) theForm.get("assayType")).trim(); String assayRunDateBeginStr = (String) theForm .get("assayRunDateBegin"); String assayRunDateEndStr = (String) theForm.get("assayRunDateEnd"); Date assayRunDateBegin = assayRunDateBeginStr.length() == 0 ? null : StringUtils.convertToDate(assayRunDateBeginStr, "MM/dd/yyyy"); Date assayRunDateEnd = assayRunDateEndStr.length() == 0 ? null : StringUtils.convertToDate(assayRunDateEndStr, "MM/dd/yyyy"); String aliquotName = (String) theForm.get("aliquotName"); boolean includeMaskedAliquots = ((String) theForm .get("includeMaskedAliquots")).equals("on") ? true : false; String fileName = (String) theForm.get("fileName"); boolean isFileInput = ((String) theForm.get("isFileIn")) .equals("on") ? true : false; boolean isFileOutput = ((String) theForm.get("isFileOut")) .equals("on") ? true : false; String fileSubmissionDateBeginStr = (String) theForm .get("fileSubmissionDateBegin"); String fileSubmissionDateEndStr = (String) theForm .get("fileSubmissionDateEnd"); Date fileSubmissionDateBegin = fileSubmissionDateBeginStr.length() == 0 ? null : StringUtils.convertToDate(fileSubmissionDateBeginStr, "MM/dd/yyyy"); Date fileSubmissionDateEnd = fileSubmissionDateEndStr.length() == 0 ? null : StringUtils.convertToDate(fileSubmissionDateEndStr, "MM/dd/yyyy"); String fileSubmitter = (String) theForm.get("fileSubmitter"); boolean includeMaskedFiles = ((String) theForm .get("includeMaskedFiles")).equals("on") ? true : false; String criteriaJoin = (String) theForm.get("criteriaJoin"); // pass the parameters to the searchWorkflowService SearchWorkflowService searchWorkflowService = new SearchWorkflowService(); List<WorkflowResultBean> workflows = searchWorkflowService .searchWorkflows(assayName, assayType, assayRunDateBegin, assayRunDateEnd, aliquotName, includeMaskedAliquots, fileName, isFileInput, isFileOutput, fileSubmissionDateBegin, fileSubmissionDateEnd, fileSubmitter, includeMaskedFiles, criteriaJoin); if (workflows == null || workflows.isEmpty()) { ActionMessage msg = new ActionMessage( "message.searchWorkflow.noResult"); msgs.add("message", msg); saveMessages(request, msgs); forward = mapping.getInputForward(); } else { request.setAttribute("workflows", workflows); forward = mapping.findForward("success"); } } catch (Exception e) { ActionMessage error = new ActionMessage("error.searchWorkflow"); msgs.add("error", error); saveMessages(request, msgs); logger.error("Caught exception searching workflow data", e); forward = mapping.getInputForward(); } return forward; } public boolean loginRequired() { return true; } }
package gov.nih.nci.ncicb.cadsr.loader.parser; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.persister.OCRRoleNameBuilder; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressListener; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressEvent; import gov.nih.nci.ncicb.xmiinout.handler.*; import gov.nih.nci.ncicb.xmiinout.domain.*; import java.util.*; /** * A writer for XMI files * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> */ public class XMIWriter2 implements ElementWriter { private String output = null; private HashMap<String, UMLClass> classMap = new HashMap<String, UMLClass>(); private HashMap<String, UMLAttribute> attributeMap = new HashMap<String, UMLAttribute>(); private HashMap<String, UMLAssociation> assocMap = new HashMap<String, UMLAssociation>(); private HashMap<String, UMLAssociationEnd> assocEndMap = new HashMap<String, UMLAssociationEnd>(); private ElementsLists cadsrObjects = null; private ReviewTracker ownerReviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner), curatorReviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator); private ChangeTracker changeTracker = ChangeTracker.getInstance(); private ProgressListener progressListener; private UMLModel model = null; private XmiInOutHandler handler = null; public XMIWriter2() { } public void write(ElementsLists elements) throws ParserException { try { handler = (XmiInOutHandler)(UserSelections.getInstance().getProperty("XMI_HANDLER")); model = handler.getModel("EA Model"); this.cadsrObjects = elements; sendProgressEvent(0, 0, "Parsing Model"); readModel(); // doReviewTagLogic(); sendProgressEvent(0, 0, "Marking Human reviewed"); markHumanReviewed(); sendProgressEvent(0, 0, "Updating Elements"); updateChangedElements(); sendProgressEvent(0, 0, "ReWriting Model"); handler.save(output); } catch (Exception ex) { throw new RuntimeException("Error initializing model", ex); } } public void setOutput(String url) { this.output = url; } public void setProgressListener(ProgressListener listener) { progressListener = listener; } private void readModel() { for(UMLPackage pkg : model.getPackages()) doPackage(pkg); for(UMLAssociation assoc : model.getAssociations()) { List<UMLAssociationEnd> ends = assoc.getAssociationEnds(); UMLAssociationEnd aEnd = ends.get(0); UMLAssociationEnd bEnd = ends.get(1); UMLAssociationEnd source = bEnd, target = aEnd; // direction B? if (bEnd.isNavigable() && !aEnd.isNavigable()) { source = aEnd; target = bEnd; } String key = assoc.getRoleName()+"~"+source.getRoleName()+"~"+target.getRoleName(); assocMap.put(key,assoc); assocEndMap.put(key+"~source",source); assocEndMap.put(key+"~target",target); } } private void updateChangedElements() { List<ObjectClass> ocs = cadsrObjects.getElements(DomainObjectFactory.newObjectClass()); List<DataElement> des = cadsrObjects.getElements(DomainObjectFactory.newDataElement()); List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); List<ObjectClassRelationship> ocrs = cadsrObjects.getElements(DomainObjectFactory.newObjectClassRelationship()); int goal = ocs.size() + des.size() + vds.size() + ocrs.size(); int status = 0; sendProgressEvent(status, goal, ""); for(ObjectClass oc : ocs) { String fullClassName = null; for(AlternateName an : oc.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } sendProgressEvent(status++, goal, "Class: " + fullClassName); UMLClass clazz = classMap.get(fullClassName); boolean changed = changeTracker.get(fullClassName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = clazz.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith("ObjectClass") || tv.getName().startsWith("ObjectQualifier")); clazz.removeTaggedValue(tv.getName()); } String [] conceptCodes = oc.getPreferredName().split(":"); addConceptTvs(clazz, conceptCodes, XMIParser2.TV_TYPE_CLASS); } } for(DataElement de : des) { DataElementConcept dec = de.getDataElementConcept(); String fullPropName = null; for(AlternateName an : de.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_FULL_NAME)) fullPropName = an.getName(); } sendProgressEvent(status++, goal, "Attribute: " + fullPropName); UMLAttribute att = attributeMap.get(fullPropName); boolean changed = changeTracker.get(fullPropName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith("Property") || tv.getName().startsWith("PropertyQualifier")); att.removeTaggedValue(tv.getName()); } // Map to Existing DE if(!StringUtil.isEmpty(de.getPublicId()) && de.getVersion() != null) { att.addTaggedValue(XMIParser2.TV_DE_ID, de.getPublicId()); att.addTaggedValue(XMIParser2.TV_DE_VERSION, de.getVersion().toString()); } else { att.removeTaggedValue(XMIParser2.TV_DE_ID); att.removeTaggedValue(XMIParser2.TV_DE_VERSION); if(!StringUtil.isEmpty(de.getValueDomain().getPublicId()) && de.getValueDomain().getVersion() != null) { att.addTaggedValue(XMIParser2.TV_VD_ID, de.getValueDomain().getPublicId()); att.addTaggedValue(XMIParser2.TV_VD_VERSION, de.getValueDomain().getVersion().toString()); } else { att.removeTaggedValue(XMIParser2.TV_VD_ID); att.removeTaggedValue(XMIParser2.TV_VD_VERSION); } String [] conceptCodes = dec.getProperty().getPreferredName().split(":"); addConceptTvs(att, conceptCodes, XMIParser2.TV_TYPE_PROPERTY); } } } for(ValueDomain vd : vds) { sendProgressEvent(status++, goal, "Value Domain: " + vd.getLongName()); for(PermissibleValue pv : vd.getPermissibleValues()) { ValueMeaning vm = pv.getValueMeaning(); String fullPropName = "ValueDomains." + vd.getLongName() + "." + vm.getLongName(); UMLAttribute att = attributeMap.get(fullPropName); boolean changed = changeTracker.get(fullPropName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith(XMIParser2.TV_TYPE_VM) || tv.getName().startsWith(XMIParser2.TV_TYPE_VM + "Qualifier")) att.removeTaggedValue(tv.getName()); } String [] conceptCodes = ConceptUtil.getConceptCodes(vm); addConceptTvs(att, conceptCodes, XMIParser2.TV_TYPE_VM); } } } for(ObjectClassRelationship ocr : ocrs) { ConceptDerivationRule rule = ocr.getConceptDerivationRule(); ConceptDerivationRule srule = ocr.getSourceRoleConceptDerivationRule(); ConceptDerivationRule trule = ocr.getTargetRoleConceptDerivationRule(); OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); String fullName = nameBuilder.buildRoleName(ocr); sendProgressEvent(status++, goal, "Relationship: " + fullName); String key = ocr.getLongName()+"~"+ocr.getSourceRole()+"~"+ocr.getTargetRole(); UMLAssociation assoc = assocMap.get(key); UMLAssociationEnd source = assocEndMap.get(key+"~source"); UMLAssociationEnd target = assocEndMap.get(key+"~target"); boolean changed = changeTracker.get(fullName); boolean changedSource = changeTracker.get(fullName+" Source"); boolean changedTarget = changeTracker.get(fullName+" Target"); if(changed) { dropCurrentAssocTvs(assoc); List<ComponentConcept> rConcepts = rule.getComponentConcepts(); String[] rcodes = new String[rConcepts.size()]; int i = 0; for (ComponentConcept con: rConcepts) { rcodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(assoc, rcodes, XMIParser2.TV_TYPE_ASSOC_ROLE); } if(changedSource) { dropCurrentAssocTvs(source); List<ComponentConcept> sConcepts = srule.getComponentConcepts(); String[] scodes = new String[sConcepts.size()]; int i = 0; for (ComponentConcept con: sConcepts) { scodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(source, scodes, XMIParser2.TV_TYPE_ASSOC_SOURCE); } if(changedTarget) { dropCurrentAssocTvs(target); List<ComponentConcept> tConcepts = trule.getComponentConcepts(); String[] tcodes = new String[tConcepts.size()]; int i = 0; for (ComponentConcept con: tConcepts) { tcodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(target, tcodes, XMIParser2.TV_TYPE_ASSOC_TARGET); } } changeTracker.clear(); } private void dropCurrentAssocTvs(UMLTaggableElement elt) { Collection<UMLTaggedValue> allTvs = elt.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { String name = tv.getName(); if(name.startsWith(XMIParser2.TV_TYPE_ASSOC_ROLE) || name.startsWith(XMIParser2.TV_TYPE_ASSOC_SOURCE)|| name.startsWith(XMIParser2.TV_TYPE_ASSOC_TARGET)) { elt.removeTaggedValue(name); } } } private void addConceptTvs(UMLTaggableElement elt, String[] conceptCodes, String type) { if(conceptCodes.length == 0) return; addConceptTv(elt, conceptCodes[conceptCodes.length - 1], type, "", 0); for(int i= 1; i < conceptCodes.length; i++) { addConceptTv(elt, conceptCodes[conceptCodes.length - i - 1], type, XMIParser2.TV_QUALIFIER, i); } } private void addConceptTv(UMLTaggableElement elt, String conceptCode, String type, String pre, int n) { Concept con = LookupUtil.lookupConcept(conceptCode); if(con == null) return; String tvName = type + pre + XMIParser2.TV_CONCEPT_CODE + ((n>0)?""+n:""); if(con.getPreferredName() != null) elt.addTaggedValue(tvName,con.getPreferredName()); tvName = type + pre + XMIParser2.TV_CONCEPT_DEFINITION + ((n>0)?""+n:""); if(con.getPreferredDefinition() != null) elt.addTaggedValue(tvName,con.getPreferredDefinition()); tvName = type + pre + XMIParser2.TV_CONCEPT_DEFINITION_SOURCE + ((n>0)?""+n:""); if(con.getDefinitionSource() != null) elt.addTaggedValue(tvName,con.getDefinitionSource()); tvName = type + pre + XMIParser2.TV_CONCEPT_PREFERRED_NAME + ((n>0)?""+n:""); if(con.getLongName() != null) elt.addTaggedValue (tvName, con.getLongName()); tvName = type + pre + XMIParser2.TV_TYPE_VM + ((n>0)?""+n:""); if(con.getLongName() != null) elt.addTaggedValue (tvName, con.getLongName()); } // private void doReviewTagLogic() { // RunMode runMode = (RunMode)(UserSelections.getInstance().getProperty("MODE")); // ReviewTracker tracker = null; // if(runMode.equals(RunMode.Curator)) { // tracker = ownerReviewTracker; // } else { // tracker = curatorReviewTracker; // List<DataElement> des = cadsrObjects.getElements(DomainObjectFactory.newDataElement()); // List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); // for(DataElement de : des) { // DataElementConcept dec = de.getDataElementConcept(); // String fullPropName = null; // for(AlternateName an : de.getAlternateNames()) { // if(an.getType().equals(AlternateName.TYPE_FULL_NAME)) // fullPropName = an.getName(); // boolean changed = changeTracker.get(fullPropName); // if(changed) { // ReviewEvent event = new ReviewEvent(); // event.setUserObject(de); // event.setReviewed(false); // tracker.reviewChanged(event); private void markHumanReviewed() throws ParserException { try{ List<ObjectClass> ocs = cadsrObjects.getElements(DomainObjectFactory.newObjectClass()); List<DataElementConcept> decs = cadsrObjects.getElements(DomainObjectFactory.newDataElementConcept()); List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); List<ObjectClassRelationship> ocrs = cadsrObjects.getElements(DomainObjectFactory.newObjectClassRelationship()); for(ObjectClass oc : ocs) { String fullClassName = null; for(AlternateName an : oc.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } UMLClass clazz = classMap.get(fullClassName); Boolean reviewed = ownerReviewTracker.get(fullClassName); if(reviewed != null) { clazz.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); clazz.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } reviewed = curatorReviewTracker.get(fullClassName); if(reviewed != null) { clazz.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); clazz.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(DataElementConcept dec : decs) { String fullClassName = null; for(AlternateName an : dec.getObjectClass().getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } String fullPropName = fullClassName + "." + dec.getProperty().getLongName(); Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed != null) { UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) { UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(ValueDomain vd : vds) { for(PermissibleValue pv : vd.getPermissibleValues()) { ValueMeaning vm = pv.getValueMeaning(); String fullPropName = "ValueDomains." + vd.getLongName() + "." + vm.getLongName(); Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed == null) { continue; } UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); reviewed = curatorReviewTracker.get(fullPropName); if(reviewed == null) { continue; } umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(ObjectClassRelationship ocr : ocrs) { final OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); final String fullPropName = nameBuilder.buildRoleName(ocr); final String tPropName = fullPropName + " Target"; final String sPropName = fullPropName + " Source"; final String key = ocr.getLongName()+"~"+ocr.getSourceRole()+"~"+ocr.getTargetRole(); final UMLAssociation assoc = assocMap.get(key); final UMLAssociationEnd target = assocEndMap.get(key+"~target"); final UMLAssociationEnd source = assocEndMap.get(key+"~source"); // ROLE Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed != null) refreshOwnerTag(assoc, reviewed); reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) refreshCuratorTag(assoc, reviewed); // SOURCE reviewed = ownerReviewTracker.get(sPropName); if(reviewed != null) refreshOwnerTag(source, reviewed); reviewed = curatorReviewTracker.get(sPropName); if(reviewed != null) refreshCuratorTag(source, reviewed); // TARGET reviewed = ownerReviewTracker.get(tPropName); if(reviewed != null) refreshOwnerTag(target, reviewed); reviewed = curatorReviewTracker.get(tPropName); if(reviewed != null) refreshCuratorTag(target, reviewed); } } catch (RuntimeException e) { throw new ParserException(e); } } private void refreshCuratorTag(UMLTaggableElement umlElement, boolean reviewed) { umlElement.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlElement.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } private void refreshOwnerTag(UMLTaggableElement umlElement, boolean reviewed) { umlElement.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlElement.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } private void doPackage(UMLPackage pkg) { for(UMLClass clazz : pkg.getClasses()) { String className = null; if(clazz.getStereotype() != null && clazz.getStereotype().equals(XMIParser2.VD_STEREOTYPE)) { className = "ValueDomains." + clazz.getName(); } else { className = getPackageName(pkg) + "." + clazz.getName(); } classMap.put(className, clazz); for(UMLAttribute att : clazz.getAttributes()) { attributeMap.put(className + "." + att.getName(), att); } } for(UMLPackage subPkg : pkg.getPackages()) { doPackage(subPkg); } } protected void sendProgressEvent(int status, int goal, String message) { if(progressListener != null) { ProgressEvent pEvent = new ProgressEvent(); pEvent.setMessage(message); pEvent.setStatus(status); pEvent.setGoal(goal); progressListener.newProgressEvent(pEvent); } } private String getPackageName(UMLPackage pkg) { StringBuffer pack = new StringBuffer(); String s = null; do { s = null; if(pkg != null) { s = pkg.getName(); if(s.indexOf(" ") == -1) { if(pack.length() > 0) pack.insert(0, '.'); pack.insert(0, s); } pkg = pkg.getParent(); } } while (s != null); return pack.toString(); } }
package jade.core.replication; import jade.core.HorizontalCommand; import jade.core.VerticalCommand; import jade.core.GenericCommand; import jade.core.Service; import jade.core.BaseService; import jade.core.ServiceManager; import jade.core.ServiceException; import jade.core.Sink; import jade.core.Filter; import jade.core.Node; import jade.core.Profile; import jade.core.ProfileException; import jade.core.IMTPException; import jade.core.AgentContainer; /** A kernel-level service to manage a ring of Main Containers, keeping the various replicas in sync and providing failure detection and recovery to make JADE tolerate Main Container crashes. @author Giovanni Rimassa - FRAMeTech s.r.l. */ public class AddressNotificationService extends BaseService { private static final String[] OWNED_COMMANDS = new String[] { AddressNotificationSlice.SM_ADDRESS_ADDED, AddressNotificationSlice.SM_ADDRESS_REMOVED }; public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); myContainer = ac; // Create a local slice localSlice = new ServiceComponent(p); } public String getName() { return AddressNotificationSlice.NAME; } public Class getHorizontalInterface() { try { return Class.forName(AddressNotificationSlice.NAME + "Slice"); } catch(ClassNotFoundException cnfe) { return null; } } public Service.Slice getLocalSlice() { return localSlice; } public Filter getCommandFilter(boolean direction) { return null; } public Sink getCommandSink(boolean side) { if(side == Sink.COMMAND_SOURCE) { return senderSink; } else { return null; } } public String[] getOwnedCommands() { return OWNED_COMMANDS; } public void boot(Profile p) throws ServiceException { try { // Get the Service Manager address list, if this node isn't hosting one itself... Node n = getLocalNode(); if(!n.hasServiceManager()) { // Retrieve the address list from the competent Service Manager... AddressNotificationSlice mainSlice = (AddressNotificationSlice)getSlice(MAIN_SLICE); String[] addresses; try { addresses = mainSlice.getServiceManagerAddresses(); } catch(IMTPException imtpe) { // Try to get a newer slice and repeat... mainSlice = (AddressNotificationSlice)getFreshSlice(MAIN_SLICE); try { addresses = mainSlice.getServiceManagerAddresses(); } catch(IMTPException imtpe2) { throw new ServiceException("Could not retrieve Service Manager address list"); } } for(int i = 0; i < addresses.length; i++) { try { myServiceManager.addAddress(addresses[i]); } catch(IMTPException imtpe) { // It should never happen... imtpe.printStackTrace(); } } } } catch(IMTPException imtpe) { throw new ServiceException("Boot failure", imtpe); } } private class CommandSourceSink implements Sink { // Implementation of the Sink interface public void consume(VerticalCommand cmd) { try { String name = cmd.getName(); if(name.equals(AddressNotificationSlice.SM_ADDRESS_ADDED)) { handleAddressAdded(cmd); } else if(name.equals(AddressNotificationSlice.SM_ADDRESS_REMOVED)) { handleAddressRemoved(cmd); } } catch(IMTPException imtpe) { imtpe.printStackTrace(); } catch(ServiceException se) { se.printStackTrace(); } } // Vertical command handler methods public void handleAddressAdded(VerticalCommand cmd) throws IMTPException, ServiceException { Object[] params = cmd.getParams(); String addr = (String)params[0]; // Broadcast the new address to all the slices... GenericCommand hCmd = new GenericCommand(AddressNotificationSlice.H_ADDSERVICEMANAGERADDRESS, AddressNotificationSlice.NAME, null); hCmd.addParam(addr); broadcastToSlices(hCmd); } private void handleAddressRemoved(VerticalCommand cmd) throws IMTPException, ServiceException { Object[] params = cmd.getParams(); String addr = (String)params[0]; // Broadcast the address to all the slices... GenericCommand hCmd = new GenericCommand(AddressNotificationSlice.H_REMOVESERVICEMANAGERADDRESS, AddressNotificationSlice.NAME, null); hCmd.addParam(addr); broadcastToSlices(hCmd); } } // End of CommandSourceSink class private class ServiceComponent implements Service.Slice { public ServiceComponent(Profile p) { myServiceManager = myContainer.getServiceManager(); } // Implementation of the Service.Slice interface public Service getService() { return AddressNotificationService.this; } public Node getNode() throws ServiceException { try { return AddressNotificationService.this.getLocalNode(); } catch(IMTPException imtpe) { throw new ServiceException("Problem in contacting the IMTP Manager", imtpe); } } public VerticalCommand serve(HorizontalCommand cmd) { VerticalCommand result = null; try { String cmdName = cmd.getName(); Object[] params = cmd.getParams(); if(cmdName.equals(AddressNotificationSlice.H_ADDSERVICEMANAGERADDRESS)) { String addr = (String)params[0]; addServiceManagerAddress(addr); } else if(cmdName.equals(AddressNotificationSlice.H_REMOVESERVICEMANAGERADDRESS)) { String addr = (String)params[0]; removeServiceManagerAddress(addr); } else if(cmdName.equals(AddressNotificationSlice.H_GETSERVICEMANAGERADDRESSES)) { cmd.setReturnValue(getServiceManagerAddresses()); } } catch(Throwable t) { cmd.setReturnValue(t); if(result != null) { result.setReturnValue(t); } } finally { return result; } } private void addServiceManagerAddress(String addr) throws IMTPException { try { String localSMAddr = myServiceManager.getLocalAddress(); if(!addr.equals(localSMAddr)) { myServiceManager.addAddress(addr); } } catch(IMTPException imtpe) { imtpe.printStackTrace(); } } private void removeServiceManagerAddress(String addr) throws IMTPException { myServiceManager.removeAddress(addr); } private String[] getServiceManagerAddresses() throws IMTPException { return myServiceManager.getAddresses(); } } // End of ServiceComponent class private AgentContainer myContainer; private ServiceComponent localSlice; // The command sink, source side private final CommandSourceSink senderSink = new CommandSourceSink(); private ServiceManager myServiceManager; private void broadcastToSlices(HorizontalCommand cmd) throws IMTPException, ServiceException { Object[] slices = getAllSlices(); for(int i = 0; i < slices.length; i++) { AddressNotificationSlice slice = (AddressNotificationSlice)slices[i]; slice.serve(cmd); } } }
package com.weblyzard.api.client; import com.weblyzard.api.model.document.Document; import com.weblyzard.api.model.document.XmlDocument; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.JAXBException; /** @author philipp.kuntschik@htwchur.ch */ public class JeremiaClient extends BasicClient { private static final String SUBMIT_DOCUMENT_SERVICE_URL = "/jeremia/rest/submit_document"; public JeremiaClient() { super(); } public JeremiaClient(String weblyzardUrl) { super(weblyzardUrl); } public JeremiaClient(String weblyzardUrl, String username, String password) { super(weblyzardUrl, username, password); } public XmlDocument submitDocumentRaw(Document data) throws WebApplicationException { Response response = super.getTarget(SUBMIT_DOCUMENT_SERVICE_URL) .request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(data)); super.checkResponseStatus(response); XmlDocument result = response.readEntity(XmlDocument.class); response.close(); return result; } public Document submitDocument(Document data) throws WebApplicationException, JAXBException { XmlDocument response = submitDocumentRaw(data); if (response.getXmlContent() == null) return null; return Document.unmarshallDocumentXmlString(response.getXmlContent()); } }
package nl.b3p.viewer.admin.stripes; import java.util.*; import javax.annotation.security.RolesAllowed; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.controller.LifecycleStage; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidateNestedProperties; import nl.b3p.viewer.config.app.*; import nl.b3p.viewer.config.security.Group; import nl.b3p.viewer.config.services.*; import org.json.*; import org.stripesstuff.stripersist.Stripersist; /** * * @author Jytte Schaeffer */ @UrlBinding("/action/layer") @StrictBinding @RolesAllowed({"Admin","RegistryAdmin"}) public class LayerActionBean implements ActionBean { private static final String JSP = "/WEB-INF/jsp/services/layer.jsp"; private ActionBeanContext context; @Validate @ValidateNestedProperties({ @Validate(field = "titleAlias"), @Validate(field = "legendImageUrl") }) private Layer layer; @Validate private String parentId; private List<Group> allGroups; private List<String> applicationsUsedIn = new ArrayList(); @Validate private List<String> groupsRead = new ArrayList<String>(); @Validate private List<String> groupsWrite = new ArrayList<String>(); @Validate private Map<String, String> details = new HashMap<String, String>(); @Validate private SimpleFeatureType simpleFeatureType; @Validate private Long featureSourceId; private List featureSources; //<editor-fold defaultstate="collapsed" desc="getters & setters"> public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } public Map<String, String> getDetails() { return details; } public void setDetails(Map<String, String> details) { this.details = details; } public Layer getLayer() { return layer; } public void setLayer(Layer layer) { this.layer = layer; } public List<Group> getAllGroups() { return allGroups; } public void setAllGroups(List<Group> allGroups) { this.allGroups = allGroups; } public List<String> getGroupsRead() { return groupsRead; } public void setGroupsRead(List<String> groupsRead) { this.groupsRead = groupsRead; } public List<String> getGroupsWrite() { return groupsWrite; } public void setGroupsWrite(List<String> groupsWrite) { this.groupsWrite = groupsWrite; } public List<String> getApplicationsUsedIn() { return applicationsUsedIn; } public void setApplicationsUsedIn(List<String> applicationsUsedIn) { this.applicationsUsedIn = applicationsUsedIn; } public SimpleFeatureType getSimpleFeatureType() { return simpleFeatureType; } public void setSimpleFeatureType(SimpleFeatureType simpleFeatureType) { this.simpleFeatureType = simpleFeatureType; } public Long getFeatureSourceId() { return featureSourceId; } public void setFeatureSourceId(Long featureSourceId) { this.featureSourceId = featureSourceId; } public List getFeatureSources() { return featureSources; } public void setFeatureSources(List featureSources) { this.featureSources = featureSources; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } //</editor-fold> @Before(stages = LifecycleStage.BindingAndValidation) @SuppressWarnings("unchecked") public void load() { allGroups = Stripersist.getEntityManager().createQuery("from Group").getResultList(); featureSources = Stripersist.getEntityManager().createQuery("from FeatureSource").getResultList(); } @DefaultHandler public Resolution edit() { if (layer != null) { details = layer.getDetails(); groupsRead.addAll(layer.getReaders()); groupsWrite.addAll(layer.getWriters()); if (layer.getFeatureType() != null) { simpleFeatureType = layer.getFeatureType(); featureSourceId = simpleFeatureType.getFeatureSource().getId(); } findApplicationsUsedIn(); } return new ForwardResolution(JSP); } private void findApplicationsUsedIn() { GeoService service = layer.getService(); String layerName = layer.getName(); List<ApplicationLayer> applicationLayers = Stripersist.getEntityManager().createQuery("from ApplicationLayer where service = :service" + " and layerName = :layerName").setParameter("service", service).setParameter("layerName", layerName).getResultList(); for (Iterator it = applicationLayers.iterator(); it.hasNext();) { ApplicationLayer appLayer = (ApplicationLayer) it.next(); /* * The parent level of the applicationLayer is needed to find out in * which application the Layer is used. This solution is not good * when there are many levels. */ List<Level> levels = Stripersist.getEntityManager().createQuery("from Level").getResultList(); for (Iterator iter = levels.iterator(); iter.hasNext();) { Level level = (Level) iter.next(); if (level != null && level.getLayers().contains(appLayer)) { String name = getApplicationName(level); if (!applicationsUsedIn.contains(name)) { applicationsUsedIn.add(name); } } } } } private String getApplicationName(Level level) { String applicationName = null; if (level.getParent() == null) { Application application = (Application) Stripersist.getEntityManager().createQuery("from Application where root = :level").setParameter("level", level).getSingleResult(); if (application.getVersion() != null) { applicationName = application.getName() + " V" + application.getVersion(); } else { applicationName = application.getName(); } } else { applicationName = getApplicationName(level.getParent()); } return applicationName; } public Resolution save() { layer.getDetails().clear(); layer.getDetails().putAll(details); layer.getReaders().clear(); for (String groupName : groupsRead) { layer.getReaders().add(groupName); } layer.getWriters().clear(); for (String groupName : groupsWrite) { layer.getWriters().add(groupName); } if (simpleFeatureType != null) { layer.setFeatureType(simpleFeatureType); } Stripersist.getEntityManager().persist(layer); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("De kaartlaag is opgeslagen")); return new ForwardResolution(JSP); } }
package org.apache.commons.collections; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * Hashtable-based {@link Map} implementation that allows * mappings to be removed by the garbage collector.<P> * * When you construct a <Code>ReferenceMap</Code>, you can * specify what kind of references are used to store the * map's keys and values. If non-hard references are * used, then the garbage collector can remove mappings * if a key or value becomes unreachable, or if the * JVM's memory is running low. For information on how * the different reference types behave, see * {@link Reference}.<P> * * Different types of references can be specified for keys * and values. The keys can be configured to be weak but * the values hard, in which case this class will behave * like a {@link java.util.WeakHashMap}. However, you * can also specify hard keys and weak values, or any other * combination. The default constructor uses hard keys * and soft values, providing a memory-sensitive cache.<P> * * The algorithms used are basically the same as those * in {@link java.util.HashMap}. In particular, you * can specify a load factor and capacity to suit your * needs. All optional {@link Map} operations are * supported.<P> * * However, this {@link Map} implementation does <I>not</I> * allow null elements. Attempting to add a null key or * or a null value to the map will raise a * <Code>NullPointerException</Code>.<P> * * As usual, this implementation is not synchronized. You * can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a <Code>ReferenceMap</Code>. * * @author Paul Jack * @see java.lang.ref.Reference */ public class ReferenceMap extends AbstractMap implements Serializable { /** * For serialization. */ final private static long serialVersionUID = -3370601314380922368L; /** * Constant indicating that hard references should be used. */ final public static int HARD = 0; /** * Constant indiciating that soft references should be used. */ final public static int SOFT = 1; /** * Constant indicating that weak references should be used. */ final public static int WEAK = 2; /** * The reference type for keys. Must be HARD, SOFT, WEAK. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private int keyType; /** * The reference type for values. Must be HARD, SOFT, WEAK. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private int valueType; /** * The threshold variable is calculated by multiplying * table.length and loadFactor. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private float loadFactor; // -- Non-serialized instance variables /** * ReferenceQueue used to eliminate stale mappings. * @see #purge */ private transient ReferenceQueue queue = new ReferenceQueue(); /** * The hash table. Its length is always a power of two. */ private transient Entry[] table; /** * Number of mappings in this map. */ private transient int size; /** * When size reaches threshold, the map is resized. * @see resize */ private transient int threshold; /** * Number of times this map has been modified. */ private transient volatile int modCount; /** * Cached key set. May be null if key set is never accessed. */ private transient Set keySet; /** * Cached entry set. May be null if entry set is never accessed. */ private transient Set entrySet; /** * Cached values. May be null if values() is never accessed. */ private transient Collection values; /** * Constructs a new <Code>ReferenceMap</Code> that will * use hard references to keys and soft references to values. */ public ReferenceMap() { this(HARD, SOFT); } /** * Constructs a new <Code>ReferenceMap</Code> that will * use the specified types of references. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link WEAK} */ public ReferenceMap(int keyType, int valueType) { this(keyType, valueType, 16, 0.75f); } /** * Constructs a new <Code>ReferenceMap</Code> with the * specified reference types, load factor and initial * capacity. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor) { super(); verify("keyType", keyType); verify("valueType", valueType); if (capacity <= 0) { throw new IllegalArgumentException("capacity must be positive"); } if ((loadFactor <= 0.0f) || (loadFactor >= 1.0f)) { throw new IllegalArgumentException("Load factor must be greater than 0 and less than 1."); } this.keyType = keyType; this.valueType = valueType; int v = 1; while (v < capacity) v *= 2; this.table = new Entry[v]; this.loadFactor = loadFactor; this.threshold = (int)(v * loadFactor); } // used by constructor private static void verify(String name, int type) { if ((type < HARD) || (type > WEAK)) { throw new IllegalArgumentException(name + " must be HARD, SOFT, WEAK."); } } /** * Writes this object to the given output stream. * * @param out the output stream to write to * @throws IOException if the stream raises it */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(table.length); // Have to use null-terminated list because size might shrink // during iteration for (Iterator iter = entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); } out.writeObject(null); } /** * Reads the contents of this object from the given input stream. * * @param inp the input stream to read from * @throws IOException if the stream raises it * @throws ClassNotFoundException if the stream raises it */ private void readObject(ObjectInputStream inp) throws IOException, ClassNotFoundException { inp.defaultReadObject(); table = new Entry[inp.readInt()]; threshold = (int)(table.length * loadFactor); queue = new ReferenceQueue(); Object key = inp.readObject(); while (key != null) { Object value = inp.readObject(); put(key, value); key = inp.readObject(); } } /** * Constructs a reference of the given type to the given * referent. The reference is registered with the queue * for later purging. * * @param type HARD, SOFT or WEAK * @param referent the object to refer to * @param hash the hash code of the <I>key</I> of the mapping; * this number might be different from referent.hashCode() if * the referent represents a value and not a key */ private Object toReference(int type, Object referent, int hash) { switch (type) { case HARD: return referent; case SOFT: return new SoftRef(hash, referent, queue); case WEAK: return new WeakRef(hash, referent, queue); default: throw new Error(); } } /** * Returns the entry associated with the given key. * * @param key the key of the entry to look up * @return the entry associated with that key, or null * if the key is not in this map */ private Entry getEntry(Object key) { if (key == null) return null; int hash = key.hashCode(); int index = indexFor(hash); for (Entry entry = table[index]; entry != null; entry = entry.next) { if ((entry.hash == hash) && key.equals(entry.getKey())) { return entry; } } return null; } /** * Converts the given hash code into an index into the * hash table. */ private int indexFor(int hash) { // mix the bits to avoid bucket collisions... hash += ~(hash << 15); hash ^= (hash >>> 10); hash += (hash << 3); hash ^= (hash >>> 6); hash += ~(hash << 11); hash ^= (hash >>> 16); return hash & (table.length - 1); } /** * Resizes this hash table by doubling its capacity. * This is an expensive operation, as entries must * be copied from the old smaller table to the new * bigger table. */ private void resize() { Entry[] old = table; table = new Entry[old.length * 2]; for (int i = 0; i < old.length; i++) { Entry next = old[i]; while (next != null) { Entry entry = next; next = next.next; int index = indexFor(entry.hash); entry.next = table[index]; table[index] = entry; } old[i] = null; } threshold = (int)(table.length * loadFactor); } /** * Purges stale mappings from this map.<P> * * Ordinarily, stale mappings are only removed during * a write operation; typically a write operation will * occur often enough that you'll never need to manually * invoke this method.<P> * * Note that this method is not synchronized! Special * care must be taken if, for instance, you want stale * mappings to be removed on a periodic basis by some * background thread. */ private void purge() { Reference ref = queue.poll(); while (ref != null) { purge(ref); ref = queue.poll(); } } private void purge(Reference ref) { // The hashCode of the reference is the hashCode of the // mapping key, even if the reference refers to the // mapping value... int hash = ref.hashCode(); int index = indexFor(hash); Entry previous = null; Entry entry = table[index]; while (entry != null) { if (entry.purge(ref)) { if (previous == null) table[index] = entry.next; else previous.next = entry.next; this.size return; } previous = entry; entry = entry.next; } } /** * Returns the size of this map. * * @return the size of this map */ public int size() { purge(); return size; } /** * Returns <Code>true</Code> if this map is empty. * * @return <Code>true</Code> if this map is empty */ public boolean isEmpty() { purge(); return size == 0; } /** * Returns <Code>true</Code> if this map contains the given key. * * @return true if the given key is in this map */ public boolean containsKey(Object key) { purge(); Entry entry = getEntry(key); if (entry == null) return false; return entry.getValue() != null; } /** * Returns the value associated with the given key, if any. * * @return the value associated with the given key, or <Code>null</Code> * if the key maps to no value */ public Object get(Object key) { purge(); Entry entry = getEntry(key); if (entry == null) return null; return entry.getValue(); } /** * Associates the given key with the given value.<P> * Neither the key nor the value may be null. * * @param key the key of the mapping * @param value the value of the mapping * @return the last value associated with that key, or * null if no value was associated with the key * @throws NullPointerException if either the key or value * is null */ public Object put(Object key, Object value) { if (key == null) throw new NullPointerException("null keys not allowed"); if (value == null) throw new NullPointerException("null values not allowed"); purge(); if (size + 1 > threshold) resize(); int hash = key.hashCode(); int index = indexFor(hash); Entry entry = table[index]; while (entry != null) { if ((hash == entry.hash) && key.equals(entry.getKey())) { Object result = entry.getValue(); entry.setValue(value); return result; } entry = entry.next; } this.size++; modCount++; key = toReference(keyType, key, hash); value = toReference(valueType, value, hash); table[index] = new Entry(key, hash, value, table[index]); return null; } /** * Removes the key and its associated value from this map. * * @param key the key to remove * @return the value associated with that key, or null if * the key was not in the map */ public Object remove(Object key) { if (key == null) return null; purge(); int hash = key.hashCode(); int index = indexFor(hash); Entry previous = null; Entry entry = table[index]; while (entry != null) { if ((hash == entry.hash) && key.equals(entry.getKey())) { if (previous == null) table[index] = entry.next; else previous.next = entry.next; this.size modCount++; return entry.getValue(); } previous = entry; entry = entry.next; } return null; } /** * Clears this map. */ public void clear() { Arrays.fill(table, null); size = 0; while (queue.poll() != null); // drain the queue } /** * Returns a set view of this map's entries. * * @return a set view of this map's entries */ public Set entrySet() { if (entrySet != null) return entrySet; entrySet = new AbstractSet() { public int size() { return ReferenceMap.this.size(); } public void clear() { ReferenceMap.this.clear(); } public boolean contains(Object o) { if (o == null) return false; if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Entry e2 = getEntry(e.getKey()); return (e2 != null) && e.equals(e2); } public boolean remove(Object o) { boolean r = contains(o); if (r) { Map.Entry e = (Map.Entry)o; ReferenceMap.this.remove(e.getKey()); } return r; } public Iterator iterator() { return new EntryIterator(); } public Object[] toArray() { return toArray(new Object[0]); } public Object[] toArray(Object[] arr) { ArrayList list = new ArrayList(); Iterator iterator = iterator(); while (iterator.hasNext()) { Entry e = (Entry)iterator.next(); list.add(new DefaultMapEntry(e.getKey(), e.getValue())); } return list.toArray(arr); } }; return entrySet; } /** * Returns a set view of this map's keys. * * @return a set view of this map's keys */ public Set keySet() { if (keySet != null) return keySet; keySet = new AbstractSet() { public int size() { return size; } public Iterator iterator() { return new KeyIterator(); } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { Object r = ReferenceMap.this.remove(o); return r != null; } public void clear() { ReferenceMap.this.clear(); } }; return keySet; } /** * Returns a collection view of this map's values. * * @return a collection view of this map's values. */ public Collection values() { if (values != null) return values; values = new AbstractCollection() { public int size() { return size; } public void clear() { ReferenceMap.this.clear(); } public Iterator iterator() { return new ValueIterator(); } }; return values; } // If getKey() or getValue() returns null, it means // the mapping is stale and should be removed. private class Entry implements Map.Entry { Object key; Object value; int hash; Entry next; public Entry(Object key, int hash, Object value, Entry next) { this.key = key; this.hash = hash; this.value = value; this.next = next; } public Object getKey() { return (keyType > HARD) ? ((Reference)key).get() : key; } public Object getValue() { return (valueType > HARD) ? ((Reference)value).get() : value; } public Object setValue(Object object) { Object old = getValue(); if (valueType > HARD) ((Reference)value).clear(); value = toReference(valueType, object, hash); return old; } public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; Object key = entry.getKey(); Object value = entry.getValue(); if ((key == null) || (value == null)) return false; return key.equals(getKey()) && value.equals(getValue()); } public int hashCode() { Object v = getValue(); return hash ^ ((v == null) ? 0 : v.hashCode()); } public String toString() { return getKey() + "=" + getValue(); } boolean purge(Reference ref) { boolean r = (keyType > HARD) && (key == ref); r = r || ((valueType > HARD) && (value == ref)); if (r) { if (keyType > HARD) ((Reference)key).clear(); if (valueType > HARD) ((Reference)value).clear(); } return r; } } private class EntryIterator implements Iterator { // These fields keep track of where we are in the table. int index; Entry entry; Entry previous; // These Object fields provide hard references to the // current and next entry; this assures that if hasNext() // returns true, next() will actually return a valid element. Object nextKey, nextValue; Object currentKey, currentValue; int expectedModCount; public EntryIterator() { index = (size() != 0 ? table.length : 0); // have to do this here! size() invocation above // may have altered the modCount. expectedModCount = modCount; } public boolean hasNext() { checkMod(); while (nextNull()) { Entry e = entry; int i = index; while ((e == null) && (i > 0)) { i e = table[i]; } entry = e; index = i; if (e == null) { currentKey = null; currentValue = null; return false; } nextKey = e.getKey(); nextValue = e.getValue(); if (nextNull()) entry = entry.next; } return true; } private void checkMod() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } private boolean nextNull() { return (nextKey == null) || (nextValue == null); } protected Entry nextEntry() { checkMod(); if (nextNull() && !hasNext()) throw new NoSuchElementException(); previous = entry; entry = entry.next; currentKey = nextKey; currentValue = nextValue; nextKey = null; nextValue = null; return previous; } public Object next() { return nextEntry(); } public void remove() { checkMod(); if (previous == null) throw new IllegalStateException(); ReferenceMap.this.remove(currentKey); previous = null; currentKey = null; currentValue = null; expectedModCount = modCount; } } private class ValueIterator extends EntryIterator { public Object next() { return nextEntry().getValue(); } } private class KeyIterator extends EntryIterator { public Object next() { return nextEntry().getKey(); } } // These two classes store the hashCode of the key of // of the mapping, so that after they're dequeued a quick // lookup of the bucket in the table can occur. private static class SoftRef extends SoftReference { private int hash; public SoftRef(int hash, Object r, ReferenceQueue q) { super(r, q); this.hash = hash; } public int hashCode() { return hash; } } private static class WeakRef extends WeakReference { private int hash; public WeakRef(int hash, Object r, ReferenceQueue q) { super(r, q); this.hash = hash; } public int hashCode() { return hash; } } }
package org.jdesktop.swingx.border; import org.jdesktop.swingx.graphics.GraphicsUtilities; import javax.swing.border.Border; import java.awt.*; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Implements a DropShadow for components. In general, the DropShadowBorder will * work with any rectangular components that do not have a default border * installed as part of the look and feel, or otherwise. For example, * DropShadowBorder works wonderfully with JPanel, but horribly with JComboBox. * <p> * Note: {@code DropShadowBorder} should usually be added to non-opaque * components, otherwise the background is likely to bleed through. * * @author rbair */ public class DropShadowBorder implements Border, Serializable { private static enum Position {TOP, TOP_LEFT, LEFT, BOTTOM_LEFT, BOTTOM, BOTTOM_RIGHT, RIGHT, TOP_RIGHT} private static final Map<Double,Map<Position,BufferedImage>> CACHE = new HashMap<Double,Map<Position,BufferedImage>>(); private final Color shadowColor; private final int shadowSize; private final float shadowOpacity; private final int cornerSize; private final boolean showTopShadow; private final boolean showLeftShadow; private final boolean showBottomShadow; private final boolean showRightShadow; public DropShadowBorder() { this(Color.BLACK, 5); } public DropShadowBorder(Color shadowColor, int shadowSize) { this(shadowColor, shadowSize, .5f, 12, false, false, true, true); } public DropShadowBorder(boolean showLeftShadow) { this(Color.BLACK, 5, .5f, 12, false, showLeftShadow, true, true); } public DropShadowBorder(Color shadowColor, int shadowSize, float shadowOpacity, int cornerSize, boolean showTopShadow, boolean showLeftShadow, boolean showBottomShadow, boolean showRightShadow) { this.shadowColor = shadowColor; this.shadowSize = shadowSize; this.shadowOpacity = shadowOpacity; this.cornerSize = cornerSize; this.showTopShadow = showTopShadow; this.showLeftShadow = showLeftShadow; this.showBottomShadow = showBottomShadow; this.showRightShadow = showRightShadow; } /** * {@inheritDoc} */ public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { /* * 1) Get images for this border * 2) Paint the images for each side of the border that should be painted */ Map<Position,BufferedImage> images = getImages((Graphics2D)graphics); Graphics2D g2 = (Graphics2D)graphics.create(); //The location and size of the shadows depends on which shadows are being //drawn. For instance, if the left & bottom shadows are being drawn, then //the left shadow extends all the way down to the corner, a corner is drawn, //and then the bottom shadow begins at the corner. If, however, only the //bottom shadow is drawn, then the bottom-left corner is drawn to the //right of the corner, and the bottom shadow is somewhat shorter than before. int shadowOffset = 2; //the distance between the shadow and the edge Point topLeftShadowPoint = null; if (showLeftShadow || showTopShadow) { topLeftShadowPoint = new Point(); if (showLeftShadow && !showTopShadow) { topLeftShadowPoint.setLocation(x, y + shadowOffset); } else if (showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x, y); } else if (!showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x + shadowSize, y); } } Point bottomLeftShadowPoint = null; if (showLeftShadow || showBottomShadow) { bottomLeftShadowPoint = new Point(); if (showLeftShadow && !showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); } else if (showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); } else if (!showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); } } Point bottomRightShadowPoint = null; if (showRightShadow || showBottomShadow) { bottomRightShadowPoint = new Point(); if (showRightShadow && !showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize - shadowSize); } else if (showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); } else if (!showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y + height - shadowSize); } } Point topRightShadowPoint = null; if (showRightShadow || showTopShadow) { topRightShadowPoint = new Point(); if (showRightShadow && !showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowOffset); } else if (showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y); } else if (!showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); } } g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); if (showLeftShadow) { Rectangle leftShadowRect = new Rectangle(x, topLeftShadowPoint.y + shadowSize, shadowSize, bottomLeftShadowPoint.y - topLeftShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.LEFT), leftShadowRect.x, leftShadowRect.y, leftShadowRect.width, leftShadowRect.height, null); } if (showBottomShadow) { Rectangle bottomShadowRect = new Rectangle(bottomLeftShadowPoint.x + shadowSize, y + height - shadowSize, bottomRightShadowPoint.x - bottomLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.BOTTOM), bottomShadowRect.x, bottomShadowRect.y, bottomShadowRect.width, bottomShadowRect.height, null); } if (showRightShadow) { Rectangle rightShadowRect = new Rectangle(x + width - shadowSize, topRightShadowPoint.y + shadowSize, shadowSize, bottomRightShadowPoint.y - topRightShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.RIGHT), rightShadowRect.x, rightShadowRect.y, rightShadowRect.width, rightShadowRect.height, null); } if (showTopShadow) { Rectangle topShadowRect = new Rectangle(topLeftShadowPoint.x + shadowSize, y, topRightShadowPoint.x - topLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.TOP), topShadowRect.x, topShadowRect.y, topShadowRect.width, topShadowRect.height, null); } if (showLeftShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_LEFT), topLeftShadowPoint.x, topLeftShadowPoint.y, null); } if (showLeftShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_LEFT), bottomLeftShadowPoint.x, bottomLeftShadowPoint.y, null); } if (showRightShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_RIGHT), bottomRightShadowPoint.x, bottomRightShadowPoint.y, null); } if (showRightShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_RIGHT), topRightShadowPoint.x, topRightShadowPoint.y, null); } g2.dispose(); } private Map<Position,BufferedImage> getImages(Graphics2D g2) { //first, check to see if an image for this size has already been rendered //if so, use the cache. Else, draw and save Map<Position,BufferedImage> images = CACHE.get(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12));//TODO do a real hash if (images == null) { images = new HashMap<Position,BufferedImage>(); /* * To draw a drop shadow, I have to: * 1) Create a rounded rectangle * 2) Create a BufferedImage to draw the rounded rect in * 3) Translate the graphics for the image, so that the rectangle * is centered in the drawn space. The border around the rectangle * needs to be shadowWidth wide, so that there is space for the * shadow to be drawn. * 4) Draw the rounded rect as shadowColor, with an opacity of shadowOpacity * 5) Create the BLUR_KERNEL * 6) Blur the image * 7) copy off the corners, sides, etc into images to be used for * drawing the Border */ int rectWidth = cornerSize + 1; RoundRectangle2D rect = new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); int imageWidth = rectWidth + shadowSize * 2; BufferedImage image = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); Graphics2D buffer = (Graphics2D)image.getGraphics(); buffer.setPaint(new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(), (int)(shadowOpacity * 255))); // buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); buffer.translate(shadowSize, shadowSize); buffer.fill(rect); buffer.dispose(); float blurry = 1.0f / (float)(shadowSize * shadowSize); float[] blurKernel = new float[shadowSize * shadowSize]; for (int i=0; i<blurKernel.length; i++) { blurKernel[i] = blurry; } ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); BufferedImage targetImage = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); ((Graphics2D)targetImage.getGraphics()).drawImage(image, blur, -(shadowSize/2), -(shadowSize/2)); int x = 1; int y = 1; int w = shadowSize; int h = shadowSize; images.put(Position.TOP_LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = h; w = shadowSize; h = 1; images.put(Position.LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = rectWidth; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_LEFT, getSubImage(targetImage, x, y, w, h)); x = cornerSize + 1; y = rectWidth; w = 1; h = shadowSize; images.put(Position.BOTTOM, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = x; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = cornerSize + 1; w = shadowSize; h = 1; images.put(Position.RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = 1; w = shadowSize; h = shadowSize; images.put(Position.TOP_RIGHT, getSubImage(targetImage, x, y, w, h)); x = shadowSize; y = 1; w = 1; h = shadowSize; images.put(Position.TOP, getSubImage(targetImage, x, y, w, h)); image.flush(); CACHE.put(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12), images); //TODO do a real hash } return images; } /** * Returns a new BufferedImage that represents a subregion of the given * BufferedImage. (Note that this method does not use * BufferedImage.getSubimage(), which will defeat image acceleration * strategies on later JDKs.) */ private BufferedImage getSubImage(BufferedImage img, int x, int y, int w, int h) { BufferedImage ret = GraphicsUtilities.createCompatibleTranslucentImage(w, h); Graphics2D g2 = ret.createGraphics(); g2.drawImage(img, 0, 0, w, h, x, y, x+w, y+h, null); g2.dispose(); return ret; } /** * @inheritDoc */ public Insets getBorderInsets(Component c) { int top = showTopShadow ? shadowSize : 0; int left = showLeftShadow ? shadowSize : 0; int bottom = showBottomShadow ? shadowSize : 0; int right = showRightShadow ? shadowSize : 0; return new Insets(top, left, bottom, right); } /** * {@inheritDoc} */ public boolean isBorderOpaque() { return false; } public boolean isShowTopShadow() { return showTopShadow; } public boolean isShowLeftShadow() { return showLeftShadow; } public boolean isShowRightShadow() { return showRightShadow; } public boolean isShowBottomShadow() { return showBottomShadow; } public int getShadowSize() { return shadowSize; } public Color getShadowColor() { return shadowColor; } public float getShadowOpacity() { return shadowOpacity; } public int getCornerSize() { return cornerSize; } }
package org.jdesktop.swingx.border; import org.jdesktop.swingx.graphics.GraphicsUtilities; import javax.swing.border.Border; import java.awt.*; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Implements a DropShadow for components. In general, the DropShadowBorder will * work with any rectangular components that do not have a default border * installed as part of the look and feel, or otherwise. For example, * DropShadowBorder works wonderfully with JPanel, but horribly with JComboBox. * <p> * Note: {@code DropShadowBorder} should usually be added to non-opaque * components, otherwise the background is likely to bleed through.</p> * <p>Note: Since generating drop shadows is relatively expensive operation, * {@code DropShadowBorder} keeps internal static cache that allows sharing * same border for multiple re-rendering and between different instances of the * class. Since this cache is shared at class level and never reset, it might * bleed your app memory in case you tend to create many different borders * rapidly.</p> * @author rbair */ public class DropShadowBorder implements Border, Serializable { private static final long serialVersionUID = 715287754750604058L; private static enum Position {TOP, TOP_LEFT, LEFT, BOTTOM_LEFT, BOTTOM, BOTTOM_RIGHT, RIGHT, TOP_RIGHT} private static final Map<Double,Map<Position,BufferedImage>> CACHE = new HashMap<Double,Map<Position,BufferedImage>>(); private Color shadowColor; public void setShadowColor(Color shadowColor) { this.shadowColor = shadowColor; } public void setShadowSize(int shadowSize) { this.shadowSize = shadowSize; } public void setShadowOpacity(float shadowOpacity) { this.shadowOpacity = shadowOpacity; } public void setCornerSize(int cornerSize) { this.cornerSize = cornerSize; } public void setShowTopShadow(boolean showTopShadow) { this.showTopShadow = showTopShadow; } public void setShowLeftShadow(boolean showLeftShadow) { this.showLeftShadow = showLeftShadow; } public void setShowBottomShadow(boolean showBottomShadow) { this.showBottomShadow = showBottomShadow; } public void setShowRightShadow(boolean showRightShadow) { this.showRightShadow = showRightShadow; } private int shadowSize; private float shadowOpacity; private int cornerSize; private boolean showTopShadow; private boolean showLeftShadow; private boolean showBottomShadow; private boolean showRightShadow; public DropShadowBorder() { this(Color.BLACK, 5); } public DropShadowBorder(Color shadowColor, int shadowSize) { this(shadowColor, shadowSize, .5f, 12, false, false, true, true); } public DropShadowBorder(boolean showLeftShadow) { this(Color.BLACK, 5, .5f, 12, false, showLeftShadow, true, true); } public DropShadowBorder(Color shadowColor, int shadowSize, float shadowOpacity, int cornerSize, boolean showTopShadow, boolean showLeftShadow, boolean showBottomShadow, boolean showRightShadow) { this.shadowColor = shadowColor; this.shadowSize = shadowSize; this.shadowOpacity = shadowOpacity; this.cornerSize = cornerSize; this.showTopShadow = showTopShadow; this.showLeftShadow = showLeftShadow; this.showBottomShadow = showBottomShadow; this.showRightShadow = showRightShadow; } /** * {@inheritDoc} */ public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { /* * 1) Get images for this border * 2) Paint the images for each side of the border that should be painted */ Map<Position,BufferedImage> images = getImages((Graphics2D)graphics); Graphics2D g2 = (Graphics2D)graphics.create(); //The location and size of the shadows depends on which shadows are being //drawn. For instance, if the left & bottom shadows are being drawn, then //the left shadow extends all the way down to the corner, a corner is drawn, //and then the bottom shadow begins at the corner. If, however, only the //bottom shadow is drawn, then the bottom-left corner is drawn to the //right of the corner, and the bottom shadow is somewhat shorter than before. int shadowOffset = 2; //the distance between the shadow and the edge Point topLeftShadowPoint = null; if (showLeftShadow || showTopShadow) { topLeftShadowPoint = new Point(); if (showLeftShadow && !showTopShadow) { topLeftShadowPoint.setLocation(x, y + shadowOffset); } else if (showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x, y); } else if (!showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x + shadowSize, y); } } Point bottomLeftShadowPoint = null; if (showLeftShadow || showBottomShadow) { bottomLeftShadowPoint = new Point(); if (showLeftShadow && !showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); } else if (showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); } else if (!showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); } } Point bottomRightShadowPoint = null; if (showRightShadow || showBottomShadow) { bottomRightShadowPoint = new Point(); if (showRightShadow && !showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize - shadowSize); } else if (showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); } else if (!showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y + height - shadowSize); } } Point topRightShadowPoint = null; if (showRightShadow || showTopShadow) { topRightShadowPoint = new Point(); if (showRightShadow && !showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowOffset); } else if (showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y); } else if (!showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); } } g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); if (showLeftShadow) { Rectangle leftShadowRect = new Rectangle(x, topLeftShadowPoint.y + shadowSize, shadowSize, bottomLeftShadowPoint.y - topLeftShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.LEFT), leftShadowRect.x, leftShadowRect.y, leftShadowRect.width, leftShadowRect.height, null); } if (showBottomShadow) { Rectangle bottomShadowRect = new Rectangle(bottomLeftShadowPoint.x + shadowSize, y + height - shadowSize, bottomRightShadowPoint.x - bottomLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.BOTTOM), bottomShadowRect.x, bottomShadowRect.y, bottomShadowRect.width, bottomShadowRect.height, null); } if (showRightShadow) { Rectangle rightShadowRect = new Rectangle(x + width - shadowSize, topRightShadowPoint.y + shadowSize, shadowSize, bottomRightShadowPoint.y - topRightShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.RIGHT), rightShadowRect.x, rightShadowRect.y, rightShadowRect.width, rightShadowRect.height, null); } if (showTopShadow) { Rectangle topShadowRect = new Rectangle(topLeftShadowPoint.x + shadowSize, y, topRightShadowPoint.x - topLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.TOP), topShadowRect.x, topShadowRect.y, topShadowRect.width, topShadowRect.height, null); } if (showLeftShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_LEFT), topLeftShadowPoint.x, topLeftShadowPoint.y, null); } if (showLeftShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_LEFT), bottomLeftShadowPoint.x, bottomLeftShadowPoint.y, null); } if (showRightShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_RIGHT), bottomRightShadowPoint.x, bottomRightShadowPoint.y, null); } if (showRightShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_RIGHT), topRightShadowPoint.x, topRightShadowPoint.y, null); } g2.dispose(); } private Map<Position,BufferedImage> getImages(Graphics2D g2) { //first, check to see if an image for this size has already been rendered //if so, use the cache. Else, draw and save Map<Position,BufferedImage> images = CACHE.get(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12));//TODO do a real hash if (images == null) { images = new HashMap<Position,BufferedImage>(); /* * To draw a drop shadow, I have to: * 1) Create a rounded rectangle * 2) Create a BufferedImage to draw the rounded rect in * 3) Translate the graphics for the image, so that the rectangle * is centered in the drawn space. The border around the rectangle * needs to be shadowWidth wide, so that there is space for the * shadow to be drawn. * 4) Draw the rounded rect as shadowColor, with an opacity of shadowOpacity * 5) Create the BLUR_KERNEL * 6) Blur the image * 7) copy off the corners, sides, etc into images to be used for * drawing the Border */ int rectWidth = cornerSize + 1; RoundRectangle2D rect = new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); int imageWidth = rectWidth + shadowSize * 2; BufferedImage image = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); Graphics2D buffer = (Graphics2D)image.getGraphics(); buffer.setPaint(new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(), (int)(shadowOpacity * 255))); // buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); buffer.translate(shadowSize, shadowSize); buffer.fill(rect); buffer.dispose(); float blurry = 1.0f / (float)(shadowSize * shadowSize); float[] blurKernel = new float[shadowSize * shadowSize]; for (int i=0; i<blurKernel.length; i++) { blurKernel[i] = blurry; } ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); BufferedImage targetImage = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); ((Graphics2D)targetImage.getGraphics()).drawImage(image, blur, -(shadowSize/2), -(shadowSize/2)); int x = 1; int y = 1; int w = shadowSize; int h = shadowSize; images.put(Position.TOP_LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = h; w = shadowSize; h = 1; images.put(Position.LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = rectWidth; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_LEFT, getSubImage(targetImage, x, y, w, h)); x = cornerSize + 1; y = rectWidth; w = 1; h = shadowSize; images.put(Position.BOTTOM, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = x; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = cornerSize + 1; w = shadowSize; h = 1; images.put(Position.RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = 1; w = shadowSize; h = shadowSize; images.put(Position.TOP_RIGHT, getSubImage(targetImage, x, y, w, h)); x = shadowSize; y = 1; w = 1; h = shadowSize; images.put(Position.TOP, getSubImage(targetImage, x, y, w, h)); image.flush(); CACHE.put(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12), images); //TODO do a real hash } return images; } /** * Returns a new BufferedImage that represents a subregion of the given * BufferedImage. (Note that this method does not use * BufferedImage.getSubimage(), which will defeat image acceleration * strategies on later JDKs.) */ private BufferedImage getSubImage(BufferedImage img, int x, int y, int w, int h) { BufferedImage ret = GraphicsUtilities.createCompatibleTranslucentImage(w, h); Graphics2D g2 = ret.createGraphics(); g2.drawImage(img, 0, 0, w, h, x, y, x+w, y+h, null); g2.dispose(); return ret; } /** * @inheritDoc */ public Insets getBorderInsets(Component c) { int top = showTopShadow ? shadowSize : 0; int left = showLeftShadow ? shadowSize : 0; int bottom = showBottomShadow ? shadowSize : 0; int right = showRightShadow ? shadowSize : 0; return new Insets(top, left, bottom, right); } /** * {@inheritDoc} */ public boolean isBorderOpaque() { return false; } public boolean isShowTopShadow() { return showTopShadow; } public boolean isShowLeftShadow() { return showLeftShadow; } public boolean isShowRightShadow() { return showRightShadow; } public boolean isShowBottomShadow() { return showBottomShadow; } public int getShadowSize() { return shadowSize; } public Color getShadowColor() { return shadowColor; } public float getShadowOpacity() { return shadowOpacity; } public int getCornerSize() { return cornerSize; } }
package org.opentdc.workrecords.opencrx; import java.util.ArrayList; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.naming.NamingException; import javax.servlet.ServletContext; import org.openmdx.base.exception.ServiceException; import org.openmdx.base.naming.Path; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.NotFoundException; import org.opentdc.service.exception.NotImplementedException; import org.opentdc.workrecords.ServiceProvider; import org.opentdc.workrecords.WorkRecordModel; public class OpencrxImpl implements ServiceProvider { public static final String XRI_ACTIVITY_SEGMENT = "xri://@openmdx*org.opencrx.kernel.activity1"; public static final String XRI_ACCOUNT_SEGMENT = "xri://@openmdx*org.opencrx.kernel.account1"; public static final short ACTIVITY_GROUP_TYPE_PROJECT = 40; public static final short ACCOUNT_ROLE_CUSTOMER = 100; public static final short ACTIVITY_CLASS_INCIDENT = 2; public static final short ICAL_TYPE_NA = 0; public static final short ICAL_CLASS_NA = 0; public static final short ICAL_TYPE_VEVENT = 1; private static PersistenceManagerFactory pmf = null; private static String providerName = null; private static String segmentName = null; private static org.opencrx.kernel.activity1.jmi1.Segment activitySegment = null; private static String url = null; private static String userName = null; private static String password = null; private static String mimeType = null; // instance variables protected Logger logger = Logger.getLogger(this.getClass().getName()); public OpencrxImpl(ServletContext context) { logger.info("> OpencrxImpl()"); if (url == null) { url = context.getInitParameter("backend.url"); } if (userName == null) { userName = context.getInitParameter("backend.userName"); } if (password == null) { password = context.getInitParameter("backend.password"); } if (mimeType == null) { mimeType = context.getInitParameter("backend.mimeType"); } if (providerName == null) { providerName = context.getInitParameter("backend.providerName"); } if (segmentName == null) { segmentName = context.getInitParameter("backend.segmentName"); } if (activitySegment == null) { activitySegment = getActivitySegment(getPersistenceManager()); } logger.info("OpencrxImpl() initialized"); } /** * List all workrecords. * * @return a list of all workrecords. */ @Override public ArrayList<WorkRecordModel> listWorkRecords() { // TODO: implement listWorkRecords logger.info("listWorkRecords() -> " + countWorkRecords() + " workrecords"); throw new NotImplementedException("listWorkRecords is not yet implemented"); } /** * Create a new WorkRecord. * * @param workrecord * @return the newly created workrecord (can be different than workrecord param) * @throws DuplicateException * if a workrecord with the same ID already exists. */ @Override public WorkRecordModel createWorkRecord(WorkRecordModel workrecord) throws DuplicateException { if (readWorkRecord(workrecord.getId()) != null) { // object with same ID exists already throw new DuplicateException(); } // TODO: implement createWorkRecord logger.info("createWorkRecord() -> " + countWorkRecords() + " workrecords"); throw new NotImplementedException( "method createWorkRecord is not yet implemented for opencrx storage"); // logger.info("createWorkRecord() -> " + workrecord); } /** * Find a WorkRecord by ID. * * @param id * the WorkRecord ID * @return the WorkRecord * @throws NotFoundException * if there exists no WorkRecord with this ID */ @Override public WorkRecordModel readWorkRecord(String xri) throws NotFoundException { WorkRecordModel _workrecord = null; // TODO: implement readWorkRecord() throw new NotImplementedException( "method readWorkRecord() is not yet implemented for opencrx storage"); // logger.info("readWorkRecord(" + xri + ") -> " + _workrecord); } @Override public WorkRecordModel updateWorkRecord(WorkRecordModel workrecord) throws NotFoundException { WorkRecordModel _workrecord = null; // TODO implement updateWorkRecord() throw new NotImplementedException( "method updateWorkRecord() is not yet implemented for opencrx storage."); } @Override public void deleteWorkRecord(String id) throws NotFoundException { // TODO implement deleteWorkRecord() throw new NotImplementedException( "method deleteWorkRecord() is not yet implemented for opencrx storage."); } @Override public int countWorkRecords() { int _count = -1; // TODO: implement countWorkRecords() throw new NotImplementedException( "method countWorkRecords() is not yet implemented for opencrx storage."); // logger.info("countWorkRecords() = " + _count); // return _count; } /** * Get persistence manager for configured user. * * @return the PersistenceManager * @throws ServiceException * @throws NamingException */ public PersistenceManager getPersistenceManager() { if (pmf == null) { try { pmf = org.opencrx.kernel.utils.Utils .getPersistenceManagerFactoryProxy(url, userName, password, mimeType); } catch (NamingException e) { e.printStackTrace(); } catch (ServiceException e) { e.printStackTrace(); } } return pmf.getPersistenceManager(userName, null); } /** * Get activity segment. * * @param pm * @return */ public static org.opencrx.kernel.activity1.jmi1.Segment getActivitySegment( PersistenceManager pm) { return (org.opencrx.kernel.activity1.jmi1.Segment) pm .getObjectById(new Path(XRI_ACTIVITY_SEGMENT).getDescendant( "provider", providerName, "segment", segmentName)); } }
package jp.riken.kscope.dialog; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.ListSelectionModel; import javax.swing.RowFilter; import javax.swing.RowSorter; import javax.swing.ScrollPaneConstants; import javax.swing.SortOrder; import javax.swing.RowSorter.SortKey; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import jp.riken.kscope.Message; import jp.riken.kscope.common.Constant; import jp.riken.kscope.dialog.RemoteBuildPropertiesDialog.CustomCellRenderer; import jp.riken.kscope.properties.ProjectProperties; import jp.riken.kscope.properties.RemoteBuildProperties; public class ManageSettingsFilesDialog extends javax.swing.JDialog implements ActionListener { private static final long serialVersionUID = 1L; private static boolean debug = true; private JButton btnOk; private int result = Constant.CANCEL_DIALOG; private FileProjectNewDialog FPNdialog; private DefaultTableModel modelProperties; private final String[] COLUMN_HEADERS = { Message.getString("managesettingsfiles.table.key"), Message.getString("managesettingsfiles.table.value") }; private String selected_file; TreeMap<String,String> settings; private JList<String> file_list; public ManageSettingsFilesDialog(FileProjectNewDialog FPNdialog) { this.FPNdialog = FPNdialog; initGUI(); } public int showDialog() { // Center on screen this.setLocationRelativeTo(null); this.setModal(true); //this.toFront(); this.setVisible(true); return this.result; } private void initGUI() { if (debug) { System.out.println("called initGUI"); } try { BorderLayout thisLayout = new BorderLayout(); thisLayout.setHgap(5); thisLayout.setVgap(5); getContentPane().setLayout(thisLayout); // OK Button panel { JPanel panelButtons = new JPanel(); FlowLayout jPanel1Layout = new FlowLayout(); jPanel1Layout.setHgap(10); jPanel1Layout.setVgap(10); panelButtons.setLayout(jPanel1Layout); getContentPane().add(panelButtons, BorderLayout.SOUTH); panelButtons.setPreferredSize(new java.awt.Dimension(500, 46)); panelButtons.setBorder(BorderFactory.createLineBorder(Color.white)); java.awt.Dimension buttonSize = new java.awt.Dimension(96, 22); { btnOk = new JButton(); btnOk.setText(Message.getString("dialog.common.button.ok")); btnOk.setPreferredSize(buttonSize); btnOk.addActionListener(this); panelButtons.add(btnOk); } } // Top level panel { JPanel panelContent = new JPanel(); BorderLayout panelContentLayout = new BorderLayout(); getContentPane().add(panelContent, BorderLayout.CENTER); //Border border = new EmptyBorder(7,7,0,7); panelContent.setLayout(panelContentLayout); // Left panel { JPanel panelList = new JPanel(); panelList.setPreferredSize(new Dimension(220, 250)); panelList.setBorder(new EmptyBorder(7,7,0,7)); BorderLayout panelListLayout = new BorderLayout(); panelList.setLayout(panelListLayout); panelContent.add(panelList, BorderLayout.WEST); // Label { JLabel lblList = new JLabel(); lblList.setText(Message.getString("managesettingsfiles.filelist.title")); panelList.add(lblList, BorderLayout.NORTH); } // North panel JPanel panelListNorth = new JPanel(); panelListNorth.setLayout(new BorderLayout()); // List of files with settings in "remote" folder file_list = new JList<String>(FPNdialog.getRemoteSettings()); file_list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); file_list.setLayoutOrientation(JList.VERTICAL); file_list.addListSelectionListener(new SharedListSelectionHandler() { }); JScrollPane listScroller = new JScrollPane(file_list); //listScroller.setPreferredSize(new Dimension(200, 100)); panelListNorth.add(listScroller,BorderLayout.CENTER); panelList.add(panelListNorth,BorderLayout.CENTER); } // Right (Settings) panel { JPanel panelSettings = new JPanel(); panelSettings.setPreferredSize(new Dimension(500, 250)); panelSettings.setBorder(new EmptyBorder(7,0,0,7)); BorderLayout panelSettingsLayout = new BorderLayout(); panelContent.add(panelSettings, BorderLayout.CENTER); panelSettings.setLayout(panelSettingsLayout); { JLabel lblSettings = new JLabel(); lblSettings.setText(Message.getString("managesettingsfiles.rightpane.title")); panelSettings.add(lblSettings, BorderLayout.NORTH); } JPanel panelProperty = new JPanel(); panelSettings.add(panelProperty, BorderLayout.CENTER); panelProperty.setLayout(new BorderLayout()); // Displays settings from "settings" variable modelProperties = new DefaultTableModel() { private static final long serialVersionUID = -6996565435968749645L; public int getColumnCount() { return COLUMN_HEADERS.length; } public int getRowCount() { if (settings == null) return 0; return settings.size(); } public Object getValueAt(int row, int column) { if (column > COLUMN_HEADERS.length) { System.err.println("Table has " + COLUMN_HEADERS.length + " columns. You asked for column number" + column); return null; } if (column == 0) { return getParameterName(row); } else if (column == 1) { return settings.get(getParameterName(row)); } return null; } public boolean isCellEditable(int row, int column) { if (column == 1) { return true; } return false; } public void setValueAt(Object value, int row, int column) { if (column > COLUMN_HEADERS.length) { System.err.println("Table has " + COLUMN_HEADERS.length + " columns. You asked for column number" + column); return; } if (column == 1) { settings.put(getParameterName(row), value.toString()); } fireTableCellUpdated(row, column); } }; // end modelProperties modelProperties.setColumnIdentifiers(COLUMN_HEADERS); final CustomCellRenderer ccr = new CustomCellRenderer(); JTable tblProperties = new JTable(modelProperties) { /** * JTabe class with customizable CellRenderer for hiding passwords. * Hides cell in column 2 if value in column 1 contains string "pass". */ private static final long serialVersionUID = 1L; public TableCellRenderer getCellRenderer(int row, int column) { String value = (String) this.getValueAt(row, 0); if (column == 1 && value.indexOf("pass") >=0 ) { return ccr; } return super.getCellRenderer(row, column); } }; tblProperties.getColumnModel().getColumn(0).setMinWidth(150); tblProperties.getColumnModel().getColumn(1).setMinWidth(250); tblProperties.setRowMargin(5); tblProperties.setRowHeight(20); DefaultTableCellRenderer num_cell_renderer = new DefaultTableCellRenderer(); num_cell_renderer.setHorizontalAlignment(JLabel.LEFT); num_cell_renderer.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); tblProperties.getColumnModel().getColumn(0).setCellRenderer(num_cell_renderer); JScrollPane scrollList = new JScrollPane(tblProperties); scrollList.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollList.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); scrollList.setColumnHeader(new JViewport() { private static final long serialVersionUID = -8778306342340592940L; @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.height = 30; return d; } }); panelProperty.add(scrollList, BorderLayout.CENTER); } } setTitle(Message.getString("managesettingsfiles.title")); setSize(750, 400); } catch (Exception e) { e.printStackTrace(); } } /** * Get key of parameter number n from TreeMap "settings" * @param n * @return key String or null */ protected String getParameterName(int n) { if (n > settings.size()) { System.err.println("Too large row number ("+n+"). Have only "+settings.size()+" settings."); return null; } String key = (String) settings.keySet().toArray()[n]; return key; } private TreeMap<String, String> getSettingsFromFile(String filename) throws FileNotFoundException { Map <String,String> settings = RemoteBuildProperties.getSettingsFromFile(filename); TreeMap<String, String> tm_settings = new TreeMap<String,String>(settings); return tm_settings; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == this.btnOk) { this.result = Constant.CLOSE_DIALOG; dispose(); } if (debug) System.out.println("actionPerformed() of ManageSettingsFilesDialog exited"); } class SharedListSelectionHandler implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { String file = file_list.getSelectedValue(); if (file == selected_file) return; selected_file = file; System.out.println("Selected "+file); try { settings = getSettingsFromFile(file); modelProperties.fireTableDataChanged(); } catch (FileNotFoundException ex) { System.err.println("File "+file+" not found"); } } } }
package com.google.code.jscep; import java.security.KeyPair; import java.security.cert.CertStore; import java.security.cert.X509Certificate; import java.util.concurrent.Callable; import com.google.code.jscep.request.GetCertInitial; import com.google.code.jscep.request.PkiOperation; import com.google.code.jscep.transaction.Transaction; import com.google.code.jscep.transaction.TransactionFactory; import com.google.code.jscep.transport.Transport; public class PendingEnrollmentTask extends AbstractEnrollmentTask { private final Transport transport; private final X509Certificate ca; private final KeyPair keyPair; private final X509Certificate identity; public PendingEnrollmentTask(Transport transport, X509Certificate ca, KeyPair keyPair, X509Certificate identity) { this.transport = transport; this.ca = ca; this.keyPair = keyPair; this.identity = identity; } @Override public EnrollmentResult call() throws Exception { Transaction trans = TransactionFactory.createTransaction(transport, ca, identity, keyPair); PkiOperation req = new GetCertInitial(ca.getIssuerX500Principal(), identity.getSubjectX500Principal()); try { CertStore store = trans.performOperation(req); return new EnrollmentResult(getCertificates(store.getCertificates(null))); } catch (RequestPendingException e) { Callable<EnrollmentResult> task = new PendingEnrollmentTask(transport, ca, keyPair, identity); return new EnrollmentResult(task); } } }
package algorithms.misc; import algorithms.imageProcessing.FFTUtil; import algorithms.matrix.MatrixUtil; import java.util.Arrays; public class KernelDensityEstimator { final static double BIG = 0.8 * Double.MAX_VALUE; /** * assuming a zero-centered mean gaussian kernel, return the bandwidth which minimizes the * mean integrated squared error (MISE). * NOTE, the method ruleOfThumbBandwidthGaussianKernel() is preferred. * <pre> * Silverman 1981, "Kernel Density Estimation Using theFast Fourier Transform" * </pre> * @param standardDeviation * @param nSample * @return */ public static double optimalBandwidthGaussianKernel(double standardDeviation, int nSample) { return 1.06 * standardDeviation * Math.pow(nSample, -1./5); } public static double ruleOfThumbBandwidthGaussianKernel(double standardDeviation, double IQR, int nSample) { return 0.9 * Math.min(standardDeviation, IQR/1.34) * Math.pow(nSample, -1./5); } public static class KDE { public Complex[] u; /** * the x bins of the histogram of the data used in creating u. */ public double[] hx; /** * kernel bandwidth */ public double h; /** * the kde calculated from u and h. * kde = inverse FFT(f_n(s)) * = inverse FFT( exp(-(0.5) * h^2 * s^2) * u(s) ) */ public double[] kde; } public static KDE viaFFTGaussKernel(double[] x, double h, int histNBins, double histBinWidth, double histMinBin, double histMaxBin) { // the histogram length (hist[1].length) is a power of 2 and the range is enlarged by at least 2*3*h double[][] hist = createFineHistogram(x, h, histNBins, histBinWidth, histMinBin, histMaxBin); //assert(assertHistRange(hist[0], MiscMath0.getMinMax(x), h) == true); // normalization is performed by default: FFTUtil fft = new FFTUtil(); // u is the portion that can be re-used on subsequent iterations. e.g. when iterating // to find minimum bandwidth h. Complex[] u = fft.create1DFFT(hist[1], true); assert(u.length == hist[0].length); return viaFFTGaussKernel(u, hist[0], h); } public static KDE viaFFTGaussKernel(double[] x, double h) { //TODO: consider using PeriodicFFT from the curvature scale space project instead of FFT // to avoid edge effects. // the histogram length (hist[1].length) is a power of 2 and the range is enlarged by at least 2*3*h double[][] hist = createFineHistogram(x, h); //assert(assertHistRange(hist[0], MiscMath0.getMinMax(x), h) == true); // normalization is performed by default: FFTUtil fft = new FFTUtil(); // u is the portion that can be re-used on subsequent iterations. e.g. when iterating // to find minimum bandwidth h. Complex[] u = fft.create1DFFT(hist[1], true); assert(u.length == hist[0].length); return viaFFTGaussKernel(u, hist[0], h); /* summary of the paper: note that the f_n(x) is highly inefficient to use directly on a grid of points. where f_n(x) = (1./(n*h)) * sum i=1 to n of (K((x - X_i)/h) EQN (1) first, discretize the data to a fine grid then use FFT to convolve the data w/ the kernel to calculate . *Take FFT of eqn (1): FFT(f_n(s)) = (sqrt(2*pi)) * FFT(K(h*s))*u(s) where u(s) is the fourier transform of the data u(s) = (1./sqrt(2*pi)) * (1/n) * sum j=1 to n of ( exp(i*s*X_j) ) where i is imaginary ** A discrete approx of u(s) is found by constructing a histogram on a grid of 2^k cells and then apply the FFT to it. (follow Gentelman and Sande as imple. by Monro 1976 ** The Munroe 1966 FFT takes an array of X(M) of M=2^k real values and returns their discrete fourier transform Y stored with the real parts of Y_0 to Y_{M/2} in locations X(1) to X((M/2)_1) and the imaginary parts of Y_1 to Y_{(M/2)-1} stored M/2 locations above their corresponding real parts. *Substitute the fourier transform of the Gaussian Kernel K(h*s) FFT(f_n(s)) = exp(-(0.5) * h^2 * s^2) * u(s) EQN (3) *Then f_n(s) = inverse FFT(f_n(s)) negative values of f_n are set to 0. ** note that if several different uses of this algorithm for different h are employed, that the discrete FFT has to be calculated only once and can be reused. ** The algorithm also avoids exponential underflow by setting FFT(f_n(s)) equal to 0 if 0.5*h*h*s*s is > BIG which is large for the machine. The discrete fourier transform should be performed on an interval larger than the interval of interest because of wrap around edge conditions. they recommend enlarging the interval by 3*h at each end. Note that the enlargement is not needed for circular data. */ } protected static Complex[] convertToComplex(double[] a) { Complex[] c = new Complex[a.length]; for (int i = 0; i < a.length; ++i) { c[i] = new Complex(a[i], 0); } return c; } /** * calculate a fine resolution histogram for x, for a larger data range than x's. * (NOTE that if the data are circular, a method can be created to calculate the histogram * using the same data range as x, not larger) * @param x * @return a 2-dimensional array of the histogram where hist[0] holds the centers of the histogram bins, * and hist[1] holds the counts within the bins. */ public static double[][] createFineHistogram(double[] x, double h) { // the number of bins need to be a power of 2, and larger than x.length. int nBins = (int)Math.pow(2, Math.ceil(Math.log(x.length * 11)/Math.log(2))); nBins = (int)Math.pow(2, Math.ceil(Math.log(x.length * 3)/Math.log(2))); // the power of 10 was inspired by method vbwkde, variable n_dct from documentation: //TODO: improve this with an estimate for available memory of machine if (nBins > 16384) { nBins = 16384; } // unless the data are circular, the range has to be larger than the range of x in order to // avoid wrap around edge conditions double[] minMaxX = MiscMath0.getMinMax(x); double range = minMaxX[1] - minMaxX[0]; double dr; double he = 3.*h; if (0.5 * range > he) { dr = 0.5 * range; } else { dr = he; } double min = minMaxX[0] - dr; double max = minMaxX[1] + dr; // nBins = (maxX - minX)/binWidth double binWidth = (max - min)/nBins; return createFineHistogram(x, h, nBins, binWidth, min, max); } /** * calculate a fine resolution histogram for x, for a larger data range than x's. * (NOTE that if the data are circular, a method can be created to calculate the histogram * using the same data range as x, not larger) * @param x * @return a 2-dimensional array of the histogram where hist[0] holds the centers of the histogram bins, * and hist[1] holds the counts within the bins. */ protected static double[][] createFineHistogram(double[] x, double h, int nBins, double binWidth, double minBin, double maxBin) { //if (!MiscMath0.isAPowerOf2(nBins)) { System.out.printf("nBins=%d, binWidth=%.4f min=%.4f, max=%.4f\n", nBins, binWidth, minBin, maxBin); System.out.flush(); double[][] hist = new double[2][]; hist[0] = new double[nBins]; hist[1] = new double[nBins]; for (int i = 0; i < nBins; i++) { hist[0][i] = minBin + i*binWidth + (binWidth/2.); } int bin; for (int i = 0; i < x.length; i++) { bin = (int) ((x[i] - minBin)/binWidth); if ((bin > -1) && (bin < nBins)) { hist[1][bin]++; } } // divide by x.length for (int i = 0; i < hist[1].length; ++i) { hist[1][i] /= x.length; } return hist; } /** * calculate a substitute for the fine resolution histogram for x for use in the * risk estimator that uses cross-validation. * @param x * @return a 2-dimensional array of the histogram where hist[0] holds the centers of the histogram bins, * and hist[1] holds the counts within the bins. */ protected static double[] createFineHistogramSubstitute(double[] x) { double[] yHist = new double[x.length]; Arrays.fill(yHist, 1.); // divide by x.length for (int i = 0; i < yHist.length; ++i) { yHist[i] /= x.length; } return yHist; } public static KDE viaFFTGaussKernel(Complex[] u, double[] histBins, double h) { // perform the fourier transform of the Gaussian Kernel K(h*s) // FFT( K(h*s) ) = exp(-(0.5) * h^2 * s^2) // s = (x - xTilde[i])/h; K(s*h) // FFT(f_n(s)) = exp(-(0.5) * h^2 * s^2) * u(s) EQN (3) // Then f_n(s) = inverse FFT(f_n(s)) // negative values of f_n are set to 0. // note that if several different uses of this algorithm for different h are employed, // that the discrete FFT has to be calculated only once and can be reused. // The algorithm also avoids exponential underflow by setting // FFT(f_n(s)) equal to 0 if 0.5*h*h*s*s is > BIG which is large for the machine. int i; double zh; // element-wise multiplication Complex[] eqn3 = new Complex[histBins.length]; for (i = 0; i < histBins.length; ++i) { zh = histBins[i] * h; if (zh < BIG) { eqn3[i] = u[i].times(-0.5 * zh * zh); } //if (eqn3[i].re() < 0) { // eqn3[i] = new Complex(0, 0); } FFTUtil fft = new FFTUtil(); Complex[] kdeC = fft.create1DFFT(eqn3, false); double[] kd = new double[kdeC.length]; for (i = 0; i < kdeC.length; ++i) { kd[i] = kdeC[i].abs(); } KDE kde = new KDE(); kde.u = Arrays.copyOf(u, u.length); kde.h = h; kde.hx = Arrays.copyOf(histBins, histBins.length); kde.kde = Arrays.copyOf(kd, kd.length); return kde; } protected static boolean assertHistRange(double[] histBins, double[] dataMinMax, double h) { if (histBins.length < 3) { throw new IllegalArgumentException("histBins.length must be >= 3"); } double dataRange = dataMinMax[1] - dataMinMax[0]; double histBinSize = histBins[1] - histBins[0]; double histRange = histBins[histBins.length - 1] - histBins[0] + histBinSize; // assert histRange + 6h >= dataRange return (histRange + 6.*h) >= dataRange; } /** NOTE: this method is replaced by the Silverman FFT approach. Wasserman chap 20: let X_0,...X_{N-1) denote the observed data which is a sample from f (= probability distribution). K is the kernel. the KDE estimator f_hat(x) = (1/n) * sum_i=0_to_{N-1} ( (1/h^d) * K((x - X_i)/h) where d is the dimensionality once the kde is estimated, that is, f_hat(x), the risk can be estimated with Wasserman eqn (20.24) J_hat(h) = integral( f_hat^2(x)*dz ) - (2/n) * summation_i=1_to_n( f_hat_{-i)(X_i) } where -i denotes "leave one out" of the sample. */ /** estimate the KDE for a single value x. NOTE that this method is not efficent if used to calculate many x. one should instead use the FFT method. <pre> Wasserman chap 20: let X_0,...X_{N-1) denote the observed data which is a sample from f (= probability distribution). K is the kernel. the1-Dimensional KDE estimator f_hat(x) = (1/n) * sum_i=0_to_{N-1} ( (1/h) * K((x - X_i)/h). runtime complexity is O(xTilde.length). </pre> * @param kernel * @param x * @param xTilde the observed data * @param h the kernel bandwidth * @return the kde at x */ public static double univariateKernelDensityEstimate(IKernel kernel, double x, double[] xTilde, double h) { return kernel.kernel(x, xTilde, h); } public static double crossValidationScore(Complex[] u, double[] histBins, double h) { /* let K(z, sigma) = normal (gaussian) kernel with mean 0 and variance sigma^2. r_hat(h) = (K(0, sqrt(2)*h)/(n-1)) + ((n-2)/(n*((n-1)^2))) * summation over i where i!=j of (K(Xi-Xj, sqrt(2)*h)) - (2/(n*(n-1))) * summation over i where i!=j of (K(Xi-Xj, h)) The 2nd and 3rd terms can be estimated using the properties of convolution and discrete FFTs, similar to the way the kernel density is estimated using FFTs. */ int n = histBins.length; // perform the fourier transform of the Gaussian Kernel K(h*s) // FFT( K(h*s) ) = exp(-(0.5) * h^2 * s^2) // s = (x - xTilde[i])/h; K(s*h) <== multiply h differently for term1, term2, term3 double sh = Math.sqrt(2) * h; double term1 = 0; int i; double zh; double m; //((n-2)/(n*((n-1)^2))) * summation over i where i!=j of (K(Xi-Xj, sqrt(2)*h)) double term2 = 0; //(2/(n*(n-1))) * summation over i where i!=j of (K(Xi-Xj, h)) double term3 = 0; for (i = 0; i < n; ++i) { zh = histBins[i] * sh; if (zh < BIG) { m = -0.5 * zh * zh; term1 += Math.exp(m); m = u[i].times(m).abs(); // if (m >= 0) { term2 += m; } zh = histBins[i] * h; if (zh < BIG) { m = u[i].times(-0.5 * zh * zh).abs(); // if (m >= 0) { term3 += m; } } term1 /= (n - 1.); term2 *= ((n-2.)/(n*(Math.pow((n-1.), 2)))); term3 *= ((n-2.)/(n*(n-1.))); // this isn't correct double r = term1 + term2 - term3; /* try again, but with the Wasserman eqn (20.25) r_hat(h) ~ (1/(h*n*n)) * sum_i( sum_j( K_ast((X_i-X_j)/h) + (2/(n*h)) * K(0) K K_2(z) = integral( K(z-y)*K(y)*dy ) K_ast(x) = K_2(x) - 2*K(x) z = (X_i-X_j)/h; K_ast((X_i-X_j)/h) = K_ast(z) = K_2(z) - 2*K(z) = integral( K(z-y)*K(y)*dy ) - 2*K(z) */ throw new UnsupportedOperationException("not yet implemented"); } static double riskEstimatorLeaveOneOut() { // r_hat(h) = integral( (p_hat(x))^2*dx - (2/n) * summation_i=1_to_n( p_hat(X_i) ) // the 3rd compoonent on the right hand side is dropped as it's a constant (and so cancels out in comparisons // for bandwidth selection) and it is nearly negligible as n increases. // for the "leave-one-out" algorithm, p_hat is the density estimator after removing // the "i-th" observation. // for the "data-splitting" algorithm, // X_i is split into half randomly, and that instead of the entire X_i is used // in the summation above. // Note that splitting in half is V-fold or k-fold of 2, but a larger number can be used instead. throw new UnsupportedOperationException("not yet implemented"); } static double riskEstimatorDataSplitting() { // r_hat(h) = integral( (p_hat(x))^2*dx - (2/n) * summation_i=1_to_n( p_hat(X_i) ) // the 3rd compoonent on the right hand side is dropped as it's a constant (and so cancels out in comparisons // for bandwidth selection) and it is nearly negligible as n increases. // for the "leave-one-out" algorithm, p_hat is the density estimator after removing // the "i-th" observation. // for the "data-splitting" algorithm, // X_i is split into half randomly, and that instead of the entire X_i is used // in the summation above. // Note that splitting in half is V-fold or k-fold of 2, but a larger number can be used instead. throw new UnsupportedOperationException("not yet implemented"); } static double riskEstimatorGaussianKernel() { // r_hat(h) = integral( (p_hat(x))^2*dx - (2/n) * summation_i=1_to_n( p_hat(X_i) ) // the 3rd compoonent on the right hand side is dropped as it's a constant (and so cancels out in comparisons // for bandwidth selection) and it is nearly negligible as n increases. // for the "leave-one-out" algorithm, p_hat is the density estimator after removing // the "i-th" observation. // for the "data-splitting" algorithm, // X_i is split into half randomly, and that instead of the entire X_i is used // in the summation above. // Note that splitting in half is V-fold or k-fold of 2, but a larger number can be used instead. throw new UnsupportedOperationException("not yet implemented"); } }
package application.controllers; import core.graph.Graph; import core.graph.PhylogeneticTree; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.geometry.Rectangle2D; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.MenuBar; import javafx.scene.control.ScrollPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.Screen; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.ResourceBundle; /** * MainController for GUI. */ public class MainController extends Controller<BorderPane> { @FXML private ScrollPane screen; @FXML private MenuBar menuBar; private ListView list; private TextFlow infoList; private VBox listVBox; private Text id; private ScrollPane infoScroller; private int currentView = 9; private GraphController graphController; private TreeController treeController; Rectangle2D screenSize; /** * Constructor to create MainController based on abstract Controller. */ public MainController() { super(new BorderPane()); loadFXMLfile("/fxml/main.fxml"); } /** * Initialize method for the controller. * * @param location location for relative paths. * @param resources resources to localize the root object. */ @SuppressFBWarnings("URF_UNREAD_FIELD") public final void initialize(URL location, ResourceBundle resources) { screenSize = Screen.getPrimary().getVisualBounds(); createMenu(); } private void createInfoList(String info) { listVBox = new VBox(); infoScroller = new ScrollPane(); listVBox.setPrefWidth(248.0); listVBox.setMaxWidth(248.0); infoScroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); infoScroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); infoScroller.prefHeightProperty().bind(listVBox.heightProperty()); infoScroller.prefWidth(screenSize.getWidth() / 5); if (info.isEmpty()) { createList(); } createNodeInfo(); infoScroller.setContent(infoList); listVBox.getChildren().addAll(list, infoScroller); } /** * Create a list on the right side of the screen with all genomes. */ public void createList() { list = new ListView<>(); list.setPlaceholder(new Label("No Genomes Loaded.")); list.prefHeightProperty().bind(listVBox.heightProperty()); list.prefWidthProperty().bind(listVBox.widthProperty()); list.setOnKeyPressed(graphController.getZoomController().getZoomBox().getKeyHandler()); infoScroller.setOnKeyPressed(graphController.getZoomController() .getZoomBox().getKeyHandler()); list.setOnMouseClicked(event -> { if (!(list.getSelectionModel().getSelectedItem() == null)) { fillGraph(list.getSelectionModel().getSelectedItem()); try { graphController.takeSnapshot(); } catch (IOException e) { e.printStackTrace(); } } }); } /** * Create an info panel to show the information on a node. */ private void createNodeInfo() { infoList = new TextFlow(); infoList.prefHeightProperty().bind(infoScroller.heightProperty()); infoList.prefWidthProperty().bind(infoScroller.widthProperty()); id = new Text(); id.setText("Select Node to view info"); infoList.getChildren().addAll(id); } /** * Modify the information of the Node. * * @param id desired info. */ public void modifyNodeInfo(String id) { this.id.setText(id); } /** * Method to fill the graph. * * @param ref the reference string. */ public void fillGraph(Object ref) { if (graphController == null) { Graph graph = null; try { graph = new Graph(); } catch (IOException e) { e.printStackTrace(); } graphController = new GraphController(graph, ref, this, currentView); } else { try { graphController.init(ref, currentView); } catch (IOException e) { e.printStackTrace(); } } screen = graphController.getRoot(); this.getRoot().setCenter(screen); try { graphController.takeSnapshot(); } catch (IOException e) { e.printStackTrace(); } graphController.getZoomController().createZoomBox(); StackPane zoombox = graphController.getZoomController().getZoomBox().getZoomBox(); this.getRoot().setBottom(zoombox); graphController.initKeyHandler(); createInfoList(""); List<String> genomes = graphController.getGenomes(); genomes.sort(Comparator.naturalOrder()); list.setItems(FXCollections.observableArrayList(genomes)); showListVBox(); } /** * If selections are made in the phylogenetic tree, * this method will visualize/highlight them specifically. * * @param s a List of selected strains. */ public void soloStrainSelection(List<String> s) { //ToDo: add function to visualize only the selected strains. graphController.getGraph().setGenomes(new ArrayList<>()); fillGraph(s.get(0)); System.out.println("Selected " + s.get(0 )+ "as a ref, drawing everything."); } /** * If selections are made in the phylogenetic tree, * this method will visualize/highlight them specifically. * * @param s a List of selected strains. */ public void strainSelection(List<String> s) { //ToDo: add function to visualize only the selected strains. System.out.println("Show: " + s.toString()); graphController.getGraph().phyloSelection(s); try { graphController.init(null, currentView); } catch (IOException e) { e.printStackTrace(); } screen = graphController.getRoot(); this.getRoot().setCenter(screen); try { graphController.takeSnapshot(); } catch (IOException e) { e.printStackTrace(); } } /** * Method to fill the phylogenetic tree. */ public void fillTree() { try { PhylogeneticTree pt = new PhylogeneticTree(); pt.setup(); treeController = new TreeController(pt, this, this.getClass().getResourceAsStream("/metadata.xlsx")); screen = treeController.getRoot(); this.getRoot().setCenter(screen); this.getRoot().setBottom(null); } catch (IOException e) { e.printStackTrace(); } hideListVBox(); } /** * Method to create the menu bar. */ public void createMenu() { MenuFactory menuFactory = new MenuFactory(this); menuBar = menuFactory.createMenu(menuBar); this.getRoot().setTop(menuBar); } /** * Switches the scene to the graph view. * * @param delta the diff in view to apply. */ public void switchScene(int delta) { currentView += delta; currentView = Math.max(0, currentView); currentView = Math.min(9, currentView); fillGraph(null); } /** * Switches the scene to the phylogenetic tree view. */ public void switchTreeScene() { fillTree(); } /** * Show the info panel. */ private void showListVBox() { this.getRoot().setRight(listVBox); } /** * Hide the info panel. */ private void hideListVBox() { this.getRoot().getChildren().remove(listVBox); } /** * Getter method for the graphController. * * @return the graphController. */ public GraphController getGraphController() { return graphController; } /** * Getter method for the treeController. * * @return the treeController. */ public TreeController getTreeController() { return treeController; } /** * Getter method for the MenuBar. * * @return the MenuBar. */ public MenuBar getMenuBar() { return menuBar; } }
package asa.service.impl; import asa.service.ConstantsInterface; import asa.service.AttendanceService; //import asa.dao.ScheduleDAO ; import asa.bean.Attendance; //import asa.model.Schedule; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.BeanUtils; import java.util.*; @Service("attendanceService") public class AttendanceServiceMock implements ConstantsInterface,AttendanceService{ public boolean add(Attendance attendance){ return true; } public Attendance get(String group,String date){ Map<String,Boolean> members= new HashMap<>(); members.put('Ker',Boolean.TRUE); members.put('Ver',Boolean.TRUE); members.put('Ber',Boolean.FALSE); return new Attendance("1","30/06/17",members); } }
package ch.squix.extraleague.model.match; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.googlecode.objectify.annotation.Cache; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; @Entity @Cache public class Match { @Id private Long id; @Index private Long gameId; private String [] teamA = {}; private String [] teamB = {}; private Integer teamAScore; private Integer teamBScore; @Index private Date startDate; private Date endDate; private String table; private Integer matchIndex; @Index private List<String> players = new ArrayList<>(); public Long getId() { return id; } public Long getGameId() { return gameId; } public String[] getTeamA() { return teamA; } public String[] getTeamB() { return teamB; } public Integer getTeamAScore() { return teamAScore; } public Integer getTeamBScore() { return teamBScore; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public void setId(Long id) { this.id = id; } public void setGameId(Long gameId) { this.gameId = gameId; } public void setTeamA(String[] teamA) { this.teamA = teamA; } public void setTeamB(String[] teamB) { this.teamB = teamB; } public void setTeamAScore(Integer teamAScore) { this.teamAScore = teamAScore; } public void setTeamBScore(Integer teamBScore) { this.teamBScore = teamBScore; } public void setStartDate(Date startDate) { this.startDate = startDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } /** * @return the table */ public String getTable() { return table; } /** * @param table the table to set */ public void setTable(String table) { this.table = table; } /** * @return the matchIndex */ public Integer getMatchIndex() { return matchIndex; } /** * @param matchIndex the matchIndex to set */ public void setMatchIndex(Integer matchIndex) { this.matchIndex = matchIndex; } /** * @return the players */ public List<String> getPlayers() { return players; } /** * @param players the players to set */ public void setPlayers(List<String> players) { this.players = players; } }
package com.avegao.tuenti.imagedownloader; import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; public class Main extends JFrame { private JLabel emailLabel; private JTextField emailInput; private JLabel passwordLabel; private JPasswordField passwordInput; private JLabel downloadDirLabel; private JTextField downloadDirInput; private JButton downloadDirButton; private JFileChooser downloadDirChooser; private JButton startButton; public Main() { this.setLayout(null); emailLabel = new JLabel("Email"); emailLabel.setBounds(50, 12, 150, 25); this.add(emailLabel); emailInput = new JTextField(); emailInput.setBounds(120, 12, 250, 25); this.add(emailInput); passwordLabel = new JLabel("Contraseña"); passwordLabel.setBounds(50, 50, 150, 25); this.add(passwordLabel); passwordInput = new JPasswordField(); passwordInput.setBounds(120, 50, 250, 25); this.add(passwordInput); downloadDirLabel = new JLabel("Carpeta de descarga"); downloadDirLabel.setBounds(50, 88, 150, 25); this.add(downloadDirLabel); downloadDirInput = new JTextField(); downloadDirInput.setBounds(120, 88, 250, 25); this.add(downloadDirInput); downloadDirButton = new JButton("Descargar"); downloadDirButton.setBounds(400, 88, 250, 25); this.add(downloadDirButton); downloadDirButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String email = emailInput.getText(); String password = String.copyValueOf(passwordInput.getPassword()); //TODO: Empezar Selenium FirefoxDriver driver = new FirefoxDriver(); driver.get("http: try { Thread.sleep(5000); } catch (Exception e1) {} driver.findElement(By.id("email")).sendKeys(email); driver.findElement(By.id("input_password")).sendKeys(password); driver.findElement(By.id("submit_button")).click(); String userId = driver.findElement(By.xpath( "//div[contains(concat(' ', @class, ' '), ' js-avatar h-pr')]")).getAttribute("data-entity-id"); driver.navigate().to("http://www.tuenti.com/#m=Albums&func=index&collection_key=1-" + userId); driver.navigate().refresh(); int numImages = Integer.parseInt(driver.findElement(By.xpath( "//a[@id=\"albumSelectorTrigger\"]/span")).getText().replace("(", "").replace(")", "").replace(".", "")); driver.findElement(By.xpath("//ul[@id='albumBody']/li/a")).click(); try { Thread.sleep(2000); } catch (Exception e1) {} ArrayList<String> urlImages = new ArrayList<String>(); urlImages.add(driver.findElement(By.id("photo_image")).getAttribute("src")); System.out.println(numImages); for (int i = 0; i < numImages; i++) { try { Thread.sleep(2000); } catch (Exception e1) {} urlImages.add(driver.findElement(By.id("photo_image")).getAttribute("src")); System.out.println(i); try { downloadImage(driver.findElement(By.id("photo_image")).getAttribute("src"), i); } catch (IOException e1) { e1.printStackTrace(); } driver.findElement(By.id("photo_nav_next")).click(); } System.out.println(urlImages.size()); } }); } public static void main(String[] args) { JFrame window = new Main(); window.setBounds(80, 80, 500, 250); window.setVisible(true); window.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } private void downloadImage(String url, int number) throws IOException { BufferedImage image = null; String downloadDir = null; if (null != downloadDirInput.getText()) { downloadDir = downloadDirInput.getText(); } else { downloadDir = "./"; } try { URL urlImage = new URL(url); image = ImageIO.read(urlImage); if (image != null) { File file = new File(downloadDir + "/" + number + ".jpg"); ImageIO.write(image, "JPG", file); } } catch (Exception e) { e.printStackTrace(); } } }
package com.codeborne.selenide; import com.codeborne.selenide.impl.WebDriverThreadLocalContainer; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.events.WebDriverEventListener; import static com.codeborne.selenide.Configuration.browser; public class WebDriverRunner { public static WebDriverThreadLocalContainer webdriverContainer = new WebDriverThreadLocalContainer(); public static final String CHROME = "chrome"; public static final String INTERNET_EXPLORER = "ie"; public static final String FIREFOX = "firefox"; /** * To use Safari webdriver, you need to include extra dependency to your project: * &lt;dependency org="org.seleniumhq.selenium" name="selenium-safari-driver" rev="2.+" conf="test-&gt;default"/&gt; */ public static final String SAFARI = "safari"; /** * To use HtmlUnitDriver, you need to include extra dependency to your project: * <dependency org="org.seleniumhq.selenium" name="selenium-htmlunit-driver" rev="2.+" conf="test->default"/> * * It's also possible to run HtmlUnit driver emulating different browsers: * <p> * java -Dbrowser=htmlunit:firefox * </p> * <p> * java -Dbrowser=htmlunit:chrome * </p> * <p> * java -Dbrowser=htmlunit:internet explorer (default) * </p> * etc. */ public static final String HTMLUNIT = "htmlunit"; /** * To use PhantomJS, you need to include extra dependency to your project: * &lt;dependency org="com.github.detro" name="phantomjsdriver" rev="1.2.0" conf="test-&gt;default"/&gt; */ public static final String PHANTOMJS = "phantomjs"; /** * To use OperaDriver, you need to include extra dependency to your project: * &lt;dependency org="com.opera" name="operadriver" rev="1.5" conf="test-&gt;default"/&gt; */ public static final String OPERA = "opera"; /** * Use this method BEFORE opening a browser to add custom event listeners to webdriver. * @param listener your listener of webdriver events */ public static void addListener(WebDriverEventListener listener) { webdriverContainer.addListener(listener); } /** * Tell Selenide use your provided WebDriver instance. * Use it if you need a custom logic for creating WebDriver. * * It's recommended not to use implicit wait with this driver, because Selenide handles timing issues explicitly. * * <p/> * <p/> * * NB! Be sure to call this method before calling <code>open(url)</code>. * Otherwise Selenide will create its own WebDriver instance and would not close it. * * <p> * NB! When using your custom webdriver, you are responsible for closing it. * Selenide will not take care of it. * </p> * * <p> * NB! Webdriver instance should be created and used in the same thread. * A typical error is to create webdriver instance in one thread and use it in another. Selenide does not support it. * If you really need using multiple threads, please use #com.codeborne.selenide.WebDriverProvider * </p> * * <p> * P.S. Alternatively, you can run tests with system property * <pre> -Dbrowser=com.my.WebDriverFactory</pre> * * which should implement interface #com.codeborne.selenide.WebDriverProvider * </p> */ public static void setWebDriver(WebDriver webDriver) { webdriverContainer.setWebDriver(webDriver); } /** * Get the underlying instance of Selenium WebDriver. * This can be used for any operations directly with WebDriver. */ public static WebDriver getWebDriver() { return webdriverContainer.getWebDriver(); } /** * Get the underlying instance of Selenium WebDriver, and assert that it's still alive. * @return new instance of WebDriver if the previous one has been closed meanwhile. */ public static WebDriver getAndCheckWebDriver() { return webdriverContainer.getAndCheckWebDriver(); } /** * Close the browser if it's open */ public static void closeWebDriver() { webdriverContainer.closeWebDriver(); } /** * Is Selenide configured to use Firefox browser */ public static boolean isFirefox() { return FIREFOX.equalsIgnoreCase(browser); } /** * Is Selenide configured to use Chrome browser */ public static boolean isChrome() { return CHROME.equalsIgnoreCase(browser); } /** * Is Selenide configured to use Internet Explorer browser */ public static boolean isIE() { return INTERNET_EXPLORER.equalsIgnoreCase(browser); } @Deprecated public static boolean ie() { return isIE(); } public static boolean isSafari() { return SAFARI.equalsIgnoreCase(browser); } /** * Is Selenide configured to use headless browser (HtmlUnit or PhantomJS) */ public static boolean isHeadless() { return isHtmlUnit() || isPhantomjs(); } /** * Does this browser support "alert" and "confirm" dialogs. */ public static boolean supportsModalDialogs() { return !isHeadless() && !isSafari(); } /** * Is Selenide configured to use HtmlUnit browser */ public static boolean isHtmlUnit() { return browser != null && browser.startsWith(HTMLUNIT); } @Deprecated public static boolean htmlUnit() { return isHtmlUnit(); } /** * Is Selenide configured to use PhantomJS browser */ public static boolean isPhantomjs() { return PHANTOMJS.equalsIgnoreCase(browser); } @Deprecated public static boolean phantomjs() { return isPhantomjs(); } /** * Is Selenide configured to use Opera browser */ public static boolean isOpera() { return OPERA.equalsIgnoreCase(browser); } /** * Delete all the browser cookies */ public static void clearBrowserCache() { webdriverContainer.clearBrowserCache(); } /** * @return the source (HTML) of current page */ public static String source() { return webdriverContainer.getPageSource(); } /** * @return the URL of current page */ public static String url() { return webdriverContainer.getCurrentUrl(); } /** * @deprecated Use com.codeborne.selenide.Screenshots#takeScreenShot(java.lang.String, java.lang.String) */ @Deprecated public static String takeScreenShot(String className, String methodName) { return Screenshots.takeScreenShot(className, methodName); } /** * @deprecated Use com.codeborne.selenide.Screenshots#takeScreenShot(java.lang.String) */ @Deprecated public static String takeScreenShot(String fileName) { return Screenshots.takeScreenShot(fileName); } }
package com.example.filelist; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List; import static java.util.Arrays.asList; /** * @author innokenty */ public class NewFileListDialog extends JDialog { private static final List<? extends FileListFactory> FACTORIES = asList( new NewLocalFileListPanel(), new NewFtpFileListPanel() ); private FileListFactory factory; public NewFileListDialog(Component owner) { super(JOptionPane.getFrameForComponent(owner)); initUIOptions(); final JTabbedPane tabbedPane = listSelectionPane(); add(tabbedPane, BorderLayout.NORTH); add(bottomPanel(tabbedPane), BorderLayout.SOUTH); } private void initUIOptions() { setPreferredSize(new Dimension(300, 300)); setMinimumSize(getPreferredSize()); setMaximumSize(new Dimension(400, 300)); setTitle("Please select new tab type"); setModal(true); setLayout(new BorderLayout()); } private JTabbedPane listSelectionPane() { final JTabbedPane tabbedPane = new JTabbedPane(); for (FileListFactory factory : FACTORIES) { tabbedPane.add(factory); } return tabbedPane; } private JPanel bottomPanel(JTabbedPane tabbedPane) { JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); bottomPanel.add(cancelButton()); bottomPanel.add(okButton(tabbedPane)); return bottomPanel; } private JButton okButton(final JTabbedPane tabbedPane) { return new JButton(new AbstractAction("OK") { @Override public void actionPerformed(ActionEvent e) { NewFileListDialog.this.dispose(); factory = ((FileListFactory) tabbedPane.getSelectedComponent()); } }); } private JButton cancelButton() { return new JButton(new AbstractAction("Cancel") { @Override public void actionPerformed(ActionEvent e) { NewFileListDialog.this.dispose(); } }); } public FileList getFileList() throws Exception { pack(); setLocationRelativeTo(getOwner()); setVisible(true); return factory == null ? null : factory.buildFileList(); } }
package com.fitbit.bluetooth.fbgatt; import com.fitbit.bluetooth.fbgatt.exception.AddingServiceOnStartException; import com.fitbit.bluetooth.fbgatt.exception.AlreadyStartedException; import com.fitbit.bluetooth.fbgatt.exception.BitGattStartException; import com.fitbit.bluetooth.fbgatt.exception.BluetoothNotEnabledException; import com.fitbit.bluetooth.fbgatt.exception.MissingGattServerErrorException; import com.fitbit.bluetooth.fbgatt.exception.NoFiltersSetException; import com.fitbit.bluetooth.fbgatt.logging.BitgattDebugTree; import com.fitbit.bluetooth.fbgatt.logging.BitgattReleaseTree; import com.fitbit.bluetooth.fbgatt.strategies.BluetoothOffClearGattServerStrategy; import com.fitbit.bluetooth.fbgatt.strategies.Strategy; import com.fitbit.bluetooth.fbgatt.tx.AddGattServerServiceTransaction; import com.fitbit.bluetooth.fbgatt.tx.GattConnectTransaction; import com.fitbit.bluetooth.fbgatt.util.BluetoothManagerFacade; import com.fitbit.bluetooth.fbgatt.util.LooperWatchdog; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattServer; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothProfile; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanRecord; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.ParcelUuid; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.VisibleForTesting; import androidx.annotation.WorkerThread; import timber.log.Timber; public class FitbitGatt implements PeripheralScanner.TrackerScannerListener, BluetoothRadioStatusListener.BluetoothOnListener { static final long MAX_TTL = TimeUnit.HOURS.toMillis(1); private static final long GATT_SERVER_START_FAILURE_RETRY_INTERVAL = 500; /* * The Fitbit gatt instance, this holds the context, lint is rightfully complaining about * leaking the context. */ @SuppressLint("StaticFieldLeak") private static volatile FitbitGatt ourInstance; private static final int OPEN_GATT_SERVER_RETRY_COUNT = 3; private final ConcurrentHashMap<FitbitBluetoothDevice, GattConnection> connectionMap = new ConcurrentHashMap<>(); private static final long CLEANUP_INTERVAL = TimeUnit.MINUTES.toMillis(5); // this is only used on init private CopyOnWriteArrayList<FitbitGattCallback> overallGattEventListeners; private BluetoothGattServer gattServer; // this is only used on init private final CopyOnWriteArrayList<BluetoothGattService> servicesToAdd = new CopyOnWriteArrayList<>(); @Nullable private GattServerConnection serverConnection; private GattServerCallback serverCallback; private GattClientCallback clientCallback; private @Nullable PeripheralScanner peripheralScanner; private @NonNull AlwaysConnectedScanner alwaysConnectedScanner; @VisibleForTesting LowEnergyAclListener aclListener; private @Nullable Context appContext; @VisibleForTesting AtomicBoolean isInitialized = new AtomicBoolean(false); //Tracks that we initialized gatt server and should be turned back on automatically on bluetooth toggle private AtomicBoolean isGattServerStarted = new AtomicBoolean(false); //used to track if we are starting the server already private AtomicBoolean isGattServerStarting = new AtomicBoolean(false); //Tracks that we initialized gatt client and we should run anything in cases where bluetooth gets toggled on/off private AtomicBoolean isGattClientStarted = new AtomicBoolean(false); private Handler connectionCleanup; @Nullable private LooperWatchdog asyncOperationThreadWatchdog; // this should be max priority so as to not affect performance private HandlerThread fitbitGattAsyncOperationThread = new HandlerThread("FitbitGatt Async Operation Thread", Thread.MAX_PRIORITY); private Handler fitbitGattAsyncOperationHandler; private BluetoothRadioStatusListener radioStatusListener; @VisibleForTesting volatile boolean isBluetoothOn; private volatile boolean slowLoggingEnabled = false; private BitGattDependencyProvider dependencyProvider = new BitGattDependencyProvider(); /** * Will get the instance of the singleton FitbitGatt manager class * @return The instance of FitbitGatt */ public static FitbitGatt getInstance() { if(ourInstance == null) { synchronized (FitbitGatt.class) { if (ourInstance == null) { ourInstance = new FitbitGatt(); ourInstance.setup(); } } } return ourInstance; } @RestrictTo(RestrictTo.Scope.TESTS) public static void setInstance(@Nullable FitbitGatt gatt) { ourInstance = gatt; } private void setup(){ // only add a custom logger if the implementer isn't using Timber, if they are using Timber // let them deal with it, just make sure your variants set BuildConfig.DEBUG correctly if (Timber.treeCount() == 0) { if (BuildConfig.DEBUG) { Timber.plant(new BitgattDebugTree()); } else { Timber.plant(new BitgattReleaseTree()); } } ourInstance.overallGattEventListeners = new CopyOnWriteArrayList<>(); // we will default to one expected device and that it should not looking ourInstance.alwaysConnectedScanner = new AlwaysConnectedScanner(1, false, Looper.getMainLooper()); ourInstance.fitbitGattAsyncOperationThread.start(); ourInstance.fitbitGattAsyncOperationHandler = new Handler(ourInstance.fitbitGattAsyncOperationThread.getLooper()); // we need to make sure that this thread is alive and responsive or our gatt // flow will stop and we won't be able to tell ourInstance.asyncOperationThreadWatchdog = new LooperWatchdog(ourInstance.fitbitGattAsyncOperationThread.getLooper()); } @VisibleForTesting @SuppressWarnings("WeakerAccess") // API Method public synchronized void setGattServerConnection(GattServerConnection gattServer) { this.serverConnection = gattServer; for (FitbitGattCallback callback : overallGattEventListeners) { callback.onGattServerStarted(serverConnection); } } @SuppressWarnings("WeakerAccess") // API Method public synchronized boolean isBluetoothOn() { if (appContext == null) { Timber.w("Bitgatt must not be started yet, so as far as we know BT is off."); return false; } if (!dependencyProvider.getBluetoothUtils().isBluetoothEnabled(appContext)) { if (isBluetoothOn) { isBluetoothOn = false; } } else { if (!isBluetoothOn) { isBluetoothOn = true; } } return isBluetoothOn; } /** * Will allow access to the gatt server callback handler thread * @return The gatt server handler thread */ public HandlerThread getFitbitGattAsyncOperationThread() { return fitbitGattAsyncOperationThread; } /** * Interface for use in opening gatt server */ @VisibleForTesting interface OpenGattServerCallback { /** * The gatt server status is resolved to started or not * * @param started true if the gatt server started, false if not */ void onGattServerStatus(boolean started); } /** * Used to communicate async errors */ private interface StartErrorCallback { public void onError(BitGattStartException error); } /** * Used to communicate to subscribers about changes in the global state of the gatt library * as well as when peripherals are ready to be used. */ public interface FitbitGattCallback { /** * An recently discovered bluetooth peripheral has been detected as the result of a scan, to prevent errors * you should check the peripheral's connection state because this could reuse the connection * * @param connection The connection that we have created as the result of a scan result */ void onBluetoothPeripheralDiscovered(GattConnection connection); /** * A bluetooth peripheral has disconnected with the given connection * * @param connection The connection in the map of the disconnected peripheral */ void onBluetoothPeripheralDisconnected(GattConnection connection); /** * Will notify if a scan has been started */ void onScanStarted(); /** * Will notify of scanner stop */ void onScanStopped(); /** * This will get called when we call {@link FitbitGatt#initializeScanner(Context)}, {@link FitbitGatt#startPeriodicalScannerWithFilters(Context, List)} ()} and * an error occurs * * @param error */ void onScannerInitError(BitGattStartException error); /** * Will notify of pending intent scan stop */ void onPendingIntentScanStopped(); /** * Will notify of pending intent scan started */ void onPendingIntentScanStarted(); /** * In order to make sure that consumers of the bitgatt library only react to BT off * we will want for them to utilize the bt off / on as tracked by bitgatt and not * implement their own broadcast receiver. */ @MainThread void onBluetoothOff(); /** * In order to make sure that consumers of the bitgatt library only react to BT off * we will want for them to utilize the bt off / on as tracked by bitgatt and not * implement their own broadcast receiver. */ @MainThread void onBluetoothOn(); /** * Some phones may not deliver this, older ones especially may not, be aware that the code * in here may not be executed, however you can execute code that you want to have happen * before the radio turns on. */ @MainThread void onBluetoothTurningOn(); /** * Some phones deliver this, older ones may not, be aware that code inside of here may not * be executed, however you can execute code that you want to have happen * before the radio turns off */ @MainThread void onBluetoothTurningOff(); /** * Called when gatt server has started successfully * * @param serverConnection the {@link GattServerTransaction} that has been created */ void onGattServerStarted(GattServerConnection serverConnection); /** * Called when gatt server has not been able to start * * @param error the error encountered */ void onGattServerStartError(BitGattStartException error); /** * Called when client started */ void onGattClientStarted(); /** * Called when gatt client has not been able to start * * @param error the error encountered */ void onGattClientStartError(BitGattStartException error); } @VisibleForTesting FitbitGatt() { // empty so that this class can be mocked // setup is done internal to getInstance } //Allows us to inject in FitbitGatt dependencies for testing @VisibleForTesting(otherwise = VisibleForTesting.NONE) FitbitGatt(AlwaysConnectedScanner alwaysConnectedScanner, Handler fitbitGattAsyncOperationHandler, Handler connectionCleanup, LooperWatchdog watchDog) { this.overallGattEventListeners = new CopyOnWriteArrayList<>(); this.alwaysConnectedScanner = alwaysConnectedScanner; this.fitbitGattAsyncOperationHandler = fitbitGattAsyncOperationHandler; this.connectionCleanup = connectionCleanup; this.asyncOperationThreadWatchdog = watchDog; } public void registerGattEventListener(FitbitGattCallback callback) { if (!overallGattEventListeners.contains(callback)) { overallGattEventListeners.add(callback); } } public void unregisterGattEventListener(FitbitGattCallback callback) { overallGattEventListeners.remove(callback); } @VisibleForTesting(otherwise = VisibleForTesting.NONE) @SuppressWarnings({"unused", "WeakerAccess"}) // API Method List<GattClientListener> getAllGattClientListeners() { return getClientCallback().getGattClientListeners(); } @VisibleForTesting(otherwise = VisibleForTesting.NONE) void unregisterAllGattEventListeners() { overallGattEventListeners.clear(); } @RestrictTo(RestrictTo.Scope.TESTS) void setStarted() { Timber.i("Initalization complete, internalInitialize finished"); boolean success = isInitialized.compareAndSet(false, true); if (!success) { Timber.w("There was a problem updating the started state, are you starting from two threads?"); } } /** * Will start a high-priority scan, if there is already a scan in progress this call will cancel * the in-progress scan and start a new one at a high-duty cycle, please use this sparingly for * a couple of reasons: * 1) The concept of bitgatt is that you can rely on the system to find devices that match the * filter criteria. This type of scan should only be necessary if you know that the device * is disconnected, and you suspect that a connection is not already in the cache. Please use * the various background scanning APIs instead if your goal is to remain connected. * 2) This type of scan is very expensive power-wise for the phone and should not be used * constantly, please use the {@link FitbitGatt#startPeriodicScan(Context)} or {@link FitbitGatt#startBackgroundScan(Context, Intent, List)} * to find devices and rely on the device discovery callbacks or polling the connection cache * {@link FitbitGatt#getMatchingConnectionsForDeviceNames(List)} or {@link FitbitGatt#getMatchingConnectionsForServices(List)} * * This will copy report delay, callback type, legacy * and will run using scan mode low latency as scan scan settings * * @param context The android context for providing to the scanner * @return True if the scan started, false if it did not */ public boolean startHighPriorityScan(Context context) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return false; } if (peripheralScanner == null) { Timber.w("You are trying to start a high-priority scan, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return false; } return peripheralScanner.startHighPriorityScan(context); } /** * Upon setting up your scan filters, this call will start to periodically scan for matching devices, it will notify via the {@link FitbitGattCallback} * interface if a device is discovered and will provide the {@link GattConnection} to you * * @param context The android context for the scanner * @return True if the scan started, false if it did not */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public boolean startPeriodicScan(Context context) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return false; } if (peripheralScanner == null) { Timber.w("You are trying to start a periodical scan, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return false; } return peripheralScanner.startPeriodicScan(context); } /** * Will cancel high priority and periodical scans that are currently running, but will not have any effect if using the * background PendingIntent based scanner, and will not un-schedule periodical scans. Use {@link PeripheralScanner#cancelPeriodicalScan(Context)} * to stop periodical scans. * * @param context The android context for the scanner */ public void cancelScan(@Nullable Context context) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return; } if (peripheralScanner == null) { Timber.w("You are trying to cancel a scan, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.cancelScan(context); } /** * Will cancel a periodical scan, but will not have any effect if using the background PendingIntent * based scanner. Will not cancel an in progress high priority scan * * @param context The android context for the scanner */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void cancelPeriodicalScan(@Nullable Context context) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return; } if (peripheralScanner == null) { Timber.w("You are trying to cancel a scan, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.cancelPeriodicalScan(context); } /** * Will cancel a high-priority scan, but will not have any effect if using the background PendingIntent * based scanner. Will not cancel an enabled periodical scan * * @param context The android context for the scanner */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void cancelHighPriorityScan(@Nullable Context context) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return; } if (peripheralScanner == null) { Timber.w("You are trying to cancel a scan, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.cancelHighPriorityScan(context); } /** * Will put the scanner into mock mode which is useful for testing * * @param mockMode true to set mock mode, false to disable it. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void setScannerMockMode(boolean mockMode) { if (peripheralScanner == null) { Timber.w("You are trying to put the scanner into mock mode, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } alwaysConnectedScanner.setTestMode(mockMode); } /** * Will set filters on bluetooth device name, it is important to remember that these filters can * be rendered obsolete if the peripheral changes it's advertising device name. * * @param deviceNameFilters A list of device bluetooth names */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method// API Method public void setDeviceNameScanFilters(List<String> deviceNameFilters) { if (peripheralScanner == null) { Timber.w("You are trying to set device name filters on the scanner, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.setDeviceNameFilters(deviceNameFilters); } /** * Will add a name onto the bluetooth device name filters, it is important to remember that these filters can * be rendered obsolete if the peripheral changes it's advertising device name. Also, this function * will add a new name that will only take effect after the currently running scan. * * @param deviceName A device bluetooth names */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void addDeviceNameScanFilter(String deviceName) { if (peripheralScanner == null) { Timber.w("You are trying to add a device name filter onto the scanner, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.addDeviceNameFilter(deviceName); } /** * Will set service uuid filters on the scanner, this works with adding proper service records * within the adv packet for the peripheral, but may not work with service records added as part * of the service data. Please use the service data filter for these records to be certain as this * is dependent upon the HW implementation on the particular Android device. * * @param uuidFilters The service UUIDs upon which to filter advertising peripherals */ public void setScanServiceUuidFilters(List<ParcelUuid> uuidFilters) { if (peripheralScanner == null) { Timber.w("You are trying to set service uuid filters on the scanner, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.setServiceUuidFilters(uuidFilters); } /** * Will add the service UUID with a given mask to find multiple devices that conform to a uuid * service pattern in the advertisement. Will only take effect after the current scan has ended * in the next scan. * * @param service The service parceluuid * @param mask The parceluuid service mask */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void addScanServiceUUIDWithMaskFilter(ParcelUuid service, ParcelUuid mask) { if (peripheralScanner == null) { Timber.w("You are trying to set service uuid with mask filters on the scanner, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.addServiceUUIDWithMask(service, mask); } /** * Add a filter for the scanner based on the service data. Will only take effect after the current * scan has ended if one is running. * * @param serviceUUID The parcel uuid for the service * @param serviceData The actual service data * @param serviceDataMask The service data mask */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void addFilterUsingServiceData(ParcelUuid serviceUUID, byte[] serviceData, byte[] serviceDataMask) { if (peripheralScanner == null) { Timber.w("You are trying to add a filter using service data to the scanner, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.addFilterUsingServiceData(serviceUUID, serviceData, serviceDataMask); } /** * Will filter scan results for a min rssi, not the most reliable way to determine nearby devices * since the RSSI values vary from phone to phone, but it is possible to build a model for this * and do this effectively. * * @param minRssi The minimum RSSI value to accept for a callback upon a found device */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void addScanRssiFilter(int minRssi) { if (peripheralScanner == null) { Timber.w("You are trying to set rssi filters on the scanner, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.addRssiFilter(minRssi); } /** * Add scanner filter on device address. Will only take effect after the current scan has ended * if one is running. * <p> * Note: This filter is known to not be supported on some hardware like "HTC One" and some Huawei phones * * @param deviceAddress he device Bluetooth address for the filter. It needs to be in the * format of "01:02:03:AB:CD:EF". The device address can be validated using * {@link BluetoothAdapter#checkBluetoothAddress}. */ @SuppressWarnings("WeakerAccess") // API Method public void addDeviceAddressFilter(String deviceAddress) { if (peripheralScanner == null) { Timber.w("You are trying to add a device address filter onto the scanner, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.addDeviceAddressFilter(deviceAddress); } /** * Will return a shallow copy of the current scan filters held by the scanner * * @return Shallow copy of the current scan filters */ @SuppressWarnings("WeakerAccess") // API Method public List<ScanFilter> getScanFilters() { if (peripheralScanner == null) { Timber.w("You are trying to get scan filters, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return Collections.emptyList(); } return peripheralScanner.getScanFilters(); } /** * Will clear the scan filters currently applied, will not apply to the current scan if one is running. */ @SuppressWarnings("WeakerAccess") // API Method public void resetScanFilters() { if (peripheralScanner == null) { Timber.w("You are trying to reset the scan filters on the scanner, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return; } peripheralScanner.resetFilters(); } /** * To determine if the scanner is presently scanning or not * * @return true if a scan is currently happening, false if not */ public boolean isScanning() { if (peripheralScanner == null) { Timber.w("You are trying to determine the scan state, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return false; } return peripheralScanner.isScanning(); } /** * To determine if there is a pending intent scan going right now * * @return True if there is a pending intent scan occurring */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public boolean isPendingIntentScanning() { if (peripheralScanner == null) { Timber.w("You are trying to determine the scan state, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return false; } return peripheralScanner.isPendingIntentScanning(); } /** * To determine if there is a periodical scan enabled, should not be confused with whether a low priority scan is currently happening. * * @return True if there is a periodical scan enabled */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public boolean isPeriodicalScanEnabled() { if (peripheralScanner == null) { Timber.w("You are trying to determine the scan state, but the scanner isn't set-up, did you call FitbitGatt#initializeScanner?"); return false; } return peripheralScanner.isPeriodicalScanEnabled(); } /** * Convenience method that attempts to start all the components * * @param context */ @WorkerThread public synchronized void start(Context context) { startGattClient(context); startGattServer(context); initializeScanner(context); } /** * Initializes the scanner component */ public synchronized boolean initializeScanner(@NonNull Context context) { boolean started = startSimple(context, (error -> { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onScannerInitError(error); } })); if (!isBluetoothOn()) { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onScannerInitError(new BluetoothNotEnabledException()); } return false; } return started; } /** * Initializes the scanner with a a set of filters. * <p> * In this case it also starts a periodical scanner with it * * @param filters scan filters */ @SuppressWarnings({"unused", "WeakerAccess"}) // API method public synchronized void startPeriodicalScannerWithFilters(@NonNull Context context, List<ScanFilter> filters) { if (!initializeScanner(context)) { return; } if (isScanning()) { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onScannerInitError(new AlreadyStartedException()); } // we cannot start what has been already started. return; } if (filters != null && !filters.isEmpty()) { peripheralScanner.setScanFilters(filters); alwaysConnectedScanner.setScanFilters(filters); peripheralScanner.startPeriodicScan(this.appContext); } else { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onScannerInitError(new NoFiltersSetException()); } } } /** * Initialize bitgatt client dependencies. * Without calling this method we are not allowed to execute {@link GattTransaction} for client devices * * If bluetooth is on it adds as well the list of known devices to bitgatt. These include devices that * have are already connected or bonded. * * Does not automatically start scanning for other devices * */ public synchronized void startGattClient(@NonNull Context context) { isGattClientStarted.set(true); if (!startSimple(context, (error -> { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onGattClientStartError(error); } }))) { return; } if (!isBluetoothOn()) { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onGattClientStartError(new BluetoothNotEnabledException()); } return; } if (this.aclListener == null) { this.aclListener = dependencyProvider.getNewLowEnergyAclListener(); this.aclListener.register(this.appContext); for (FitbitGattCallback cb : overallGattEventListeners) { cb.onGattClientStarted(); } if (isBluetoothOn()) { addConnectedDevices(this.appContext); } } } synchronized void addConnectedDevice(BluetoothDevice device) { fitbitGattAsyncOperationHandler.post(() -> { FitbitBluetoothDevice fitbitBluetoothDevice = new FitbitBluetoothDevice(device); fitbitBluetoothDevice.origin = FitbitBluetoothDevice.DeviceOrigin.CONNECTED; addConnectedDeviceToConnectionMap(this.appContext, fitbitBluetoothDevice); }); } @VisibleForTesting void addConnectedDeviceToConnectionMap(Context context, FitbitBluetoothDevice device) { Timber.v("Adding the new connected device"); BluetoothAdapter adapter = dependencyProvider.getBluetoothUtils().getBluetoothAdapter(context); if (adapter != null) { if (null == connectionMap.get(device)) { Timber.v("Adding connected device named %s, with address %s", device.getName(), device.getAddress()); if (context != null) { GattConnection conn = new GattConnection(device, context.getMainLooper()); conn.setState(GattState.CONNECTED); connectionMap.put(device, conn); FitbitGatt.getInstance().notifyListenersOfConnectionAdded(conn); } else { Timber.w("Tried to add the connected device, but the cached context was null"); } } } Timber.v("Added the new connected device"); } /** * Starts the gatt server and allows the execution of {@link GattTransaction} on it * */ public synchronized void startGattServer(@NonNull Context context) { startGattServerWithServices(context, null); } /** * Starts the gatt server and allows the execution of {@link GattTransaction} on it * Also adds the given service list on the gatt server. In the case that * * @param context Context * @param services The services desired */ @WorkerThread @SuppressWarnings("WeakerAccess") // API Method public synchronized void startGattServerWithServices(@NonNull Context context, @Nullable List<BluetoothGattService> services) { isGattServerStarted.set(true); if (!startSimple(context, (error -> { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onGattServerStartError(error); } }))) { return; } if (!isBluetoothOn()) { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onGattServerStartError(new BluetoothNotEnabledException()); } return; } if (serverConnection != null && gattServer != null && serverConnection.getGattState() != GattState.CLOSED) { //server already started and running for (FitbitGattCallback cb : overallGattEventListeners) { cb.onGattServerStartError(new AlreadyStartedException()); } return; } if (isGattServerStarting.getAndSet(true)) { Timber.tag("FitbitGattServer").d("Server is already trying to start"); return; } startServer(getOpenGattServerCallback(services)); } public void setScanSettings(ScanSettings scanSettings) { if(this.peripheralScanner != null) { this.peripheralScanner.setScanSettings(scanSettings); } else { Timber.w("Scanner was not initialized so we are not updating settings"); } } @NonNull @VisibleForTesting OpenGattServerCallback getOpenGattServerCallback(@Nullable List<BluetoothGattService> services) { return started -> { if (!started) { Timber.w("Could not get an instance of a gatt server, if you keep trying without fixing the issue, you might end up with too many server_if"); for (FitbitGattCallback readCallback : overallGattEventListeners) { readCallback.onGattServerStartError(new MissingGattServerErrorException()); } return; } if (services != null) { Timber.v("Starting to add services, will set to started after complete"); // usually the android stack will add the service setup to the bt stack, if this stack // is busy, this can take a while, so we'll need to wait until we get the callbacks // for all of the expected services. if (!services.isEmpty()) { servicesToAdd.clear(); servicesToAdd.addAll(services); addServicesToGattServerOnStart(); } } }; } private synchronized void initialize(Context context) { if (!isInitialized.get()) { Timber.v("Starting fitbit gatt"); appContext = context.getApplicationContext(); peripheralScanner = dependencyProvider.getNewPeripheralScanner(this, this); connectionCleanup = new Handler(context.getMainLooper()); Timber.v("Initializing the always connected scanner for one device, and that it should stop scanning when it finds one, if you wish to change this, please configure it."); if (radioStatusListener == null) { radioStatusListener = dependencyProvider.getNewBluetoothRadioStatusListener(this.appContext, false); radioStatusListener.startListening(); radioStatusListener.setListener(this); } if (asyncOperationThreadWatchdog != null) { asyncOperationThreadWatchdog.startProbing(); } clientCallback = new GattClientCallback(); serverCallback = new GattServerCallback(); isInitialized.set(true); } } private synchronized boolean startSimple(@NonNull Context context, StartErrorCallback errorHandler) { initialize(context); if (!isBluetoothOn()) { errorHandler.onError(new BluetoothNotEnabledException()); return false; } // will start the cleanup process decrementAndInvalidateClosedConnections(); return true; } /** * Will fetch the always connected scanner for configuration and starting. The always connected * scanner is designed for you to delegate all of the scanning to bitgatt where you want to * always connect to a peripheral when in range, once started, no ad-hoc scanning can be * accomplished. * * @return the always connected scanner */ @SuppressWarnings({"unused", "WeakerAccess"}) // API method public @NonNull AlwaysConnectedScanner getAlwaysConnectedScanner() { return this.alwaysConnectedScanner; } /** * Do not do this unless you truly know what you are doing, there are very, very few reasons * to perform this operation. */ @VisibleForTesting(otherwise = VisibleForTesting.NONE) @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void shutdown() { Timber.v("Someone wants to shutdown the gatt"); this.overallGattEventListeners.clear(); this.servicesToAdd.clear(); this.connectionMap.clear(); if (asyncOperationThreadWatchdog != null) { this.asyncOperationThreadWatchdog.stopProbing(); } //clean up callbacks and listeners; if (serverCallback != null) { serverCallback.unregisterAll(); } if (this.appContext != null && this.aclListener != null) { this.aclListener.unregister(this.appContext); } if (this.peripheralScanner != null) { this.peripheralScanner.onDestroy(this.appContext); } if (this.aclListener != null) { this.aclListener.unregister(this.appContext); } if (radioStatusListener != null) { try { radioStatusListener.stopListening(); radioStatusListener.removeListener(); } catch (IllegalArgumentException e) { //no-op can happen during test runs } } if(serverConnection != null) { List<ServerConnectionEventListener> serverConnectionEventListeners = serverConnection.getConnectionEventListeners(); for (ServerConnectionEventListener serverConnectionEventListener : serverConnectionEventListeners) { serverConnection.unregisterConnectionEventListener(serverConnectionEventListener); } serverConnection.close(); serverConnection = null; if(gattServer != null) { gattServer.close(); } } //clear up all references this.gattServer = null; this.serverConnection = null; this.connectionCleanup = null; this.isInitialized.set(false); this.isGattClientStarted.set(false); this.isGattServerStarted.set(false); this.appContext = null; this.serverCallback = null; this.clientCallback = null; this.radioStatusListener = null; this.aclListener = null; this.peripheralScanner = null; this.asyncOperationThreadWatchdog = null; } @VisibleForTesting void setBluetoothListener(BluetoothRadioStatusListener listener) { this.radioStatusListener = listener; } @RestrictTo(RestrictTo.Scope.LIBRARY) boolean isInitialized() { return isInitialized.get(); } public @Nullable Context getAppContext() { return appContext; } @RestrictTo(RestrictTo.Scope.TESTS) void setStarted(boolean isStarted) { this.isInitialized.set(isStarted); } @RestrictTo(RestrictTo.Scope.TESTS) void setAppContext(Context context) { this.appContext = context; } @RestrictTo(RestrictTo.Scope.TESTS) void setGattServerStarted(boolean isStarted) { this.isGattServerStarted.set(isStarted); } @RestrictTo(RestrictTo.Scope.TESTS) void setGattClientStarted(boolean isStarted) { this.isGattClientStarted.set(isStarted); } @RestrictTo(RestrictTo.Scope.TESTS) void setConnectionMap(ConcurrentHashMap<FitbitBluetoothDevice, GattConnection> map) { this.connectionMap.clear(); this.connectionMap.putAll(map); } @RestrictTo(RestrictTo.Scope.TESTS) void setPeripheralScanner(PeripheralScanner scanner) { this.peripheralScanner = scanner; } @RestrictTo(RestrictTo.Scope.TESTS) void setAlwaysConnectedScanner(AlwaysConnectedScanner scanner) { this.alwaysConnectedScanner = scanner; } @RestrictTo(RestrictTo.Scope.TESTS) void setClientCallback(GattClientCallback callback) { this.clientCallback = callback; } @RestrictTo(RestrictTo.Scope.TESTS) void setDependencyProvider(BitGattDependencyProvider provider) { this.dependencyProvider = provider; } @RestrictTo(RestrictTo.Scope.TESTS) void setConnectionCleanup(Handler handler) { this.connectionCleanup = handler; } @RestrictTo(RestrictTo.Scope.TESTS) void setAsyncOperationThreadWatchdog(LooperWatchdog watchdog) { this.asyncOperationThreadWatchdog = watchdog; } @SuppressWarnings("WeakerAccess") // API Method @Nullable public GattServerCallback getServerCallback() { return this.serverCallback; } @Nullable public GattClientCallback getClientCallback() { return this.clientCallback; } @Nullable PeripheralScanner getPeripheralScanner() { if (this.peripheralScanner == null) { Timber.w("The scanner is null, did you call FitbitGatt#initializeScanner?"); } return this.peripheralScanner; } @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) public synchronized void putConnectionIntoDevices(FitbitBluetoothDevice device, GattConnection conn) { // we don't want duplicate connections in the map if (!connectionMap.containsKey(device)) { connectionMap.put(device, conn); // since this directly calls notify listeners of connection added // we will need to synchronize around those listeners since // someone could be adding or removing a listener while this asynchronous // call happens. To do this easily, we will use a // CopyOnWriteArrayList for the {@link FitbitGattCallback} FitbitGatt.getInstance().notifyListenersOfConnectionAdded(conn); } } /** * Will check to determine if the provided {@link FitbitBluetoothDevice} is actually in the map * * @param device The {@link FitbitBluetoothDevice} for which to search * @return true if the device is present, false otherwise */ @SuppressWarnings("WeakerAccess") // API Method public synchronized boolean isDeviceInConnections(FitbitBluetoothDevice device) { return connectionMap.containsKey(device); } private void notifyListenersOfConnectionAdded(GattConnection connection) { for (FitbitGattCallback callback : this.overallGattEventListeners) { callback.onBluetoothPeripheralDiscovered(connection); } } void notifyListenersOfConnectionDisconnected(GattConnection connection) { for (FitbitGattCallback callback : this.overallGattEventListeners) { callback.onBluetoothPeripheralDisconnected(connection); } } void registerGattServerListener(GattServerListener listener) { serverCallback.addListener(listener); } void unregisterGattServerListener(GattServerListener listener) { serverCallback.removeListener(listener); } @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void connectToScannedDevice(BluetoothDevice device, GattTransactionCallback callback) { FitbitBluetoothDevice fitDevice = new FitbitBluetoothDevice(device); connectToScannedDevice(fitDevice, false, callback); } @VisibleForTesting void connectToScannedDevice(FitbitBluetoothDevice fitDevice, boolean shouldMock, GattTransactionCallback callback) { GattConnection conn = connectionMap.get(fitDevice); if (conn == null) { if (appContext == null) { Timber.w("[%s] Bitgatt client must not be started, please start bitgatt client", fitDevice); return; } conn = new GattConnection(fitDevice, appContext.getMainLooper()); connectionMap.put(fitDevice, conn); notifyListenersOfConnectionAdded(conn); } conn.setMockMode(shouldMock); if (!conn.isConnected()) { GattConnectTransaction tx = new GattConnectTransaction(conn, GattState.CONNECTED); conn.runTx(tx, callback); } else { TransactionResult.Builder builder = new TransactionResult.Builder(); builder.resultStatus(TransactionResult.TransactionResultStatus.SUCCESS) .gattState(conn.getGattState()); callback.onTransactionComplete(builder.build()); } } ConcurrentHashMap<FitbitBluetoothDevice, GattConnection> getConnectionMap() { return connectionMap; } @VisibleForTesting(otherwise = VisibleForTesting.NONE) List<FitbitBluetoothDevice> getNewlyScannedDevicesOnly() { ArrayList<FitbitBluetoothDevice> devices = new ArrayList<>(); for (FitbitBluetoothDevice iteratedDevice : getConnectionMap().keySet()) { if (iteratedDevice.origin.equals(FitbitBluetoothDevice.DeviceOrigin.SCANNED)) { devices.add(iteratedDevice); } } return devices; } @RestrictTo(RestrictTo.Scope.TESTS) void clearConnectionsMap() { connectionMap.clear(); } /** * Will iterate through connections in the map to decrement those that need decrementing, and * will evict those that need to be evicted. This should run for as long as the singleton * exists. */ private void decrementAndInvalidateClosedConnections() { connectionCleanup.postDelayed(this::doDecrementAndInvalidateClosedConnections, CLEANUP_INTERVAL); } @VisibleForTesting void doDecrementAndInvalidateClosedConnections() { if (this.appContext == null) { Timber.w("[%s] Bitgatt must not be started, please start bitgatt client.", Build.DEVICE); return; } addConnectedDevices(this.appContext); for (FitbitBluetoothDevice fitbitBluetoothDevice : getConnectionMap().keySet()) { GattConnection conn = getConnectionMap().get(fitbitBluetoothDevice); if (conn != null) { // we only want to try to prune disconnected peripherals, there may be some // peripherals that are connected that we want to get rid of, but the caller // will need to disconnect them first, eventually we will clean up the // connection if (!conn.isConnected()) { long currentTtl = conn.getDisconnectedTTL(); if (currentTtl <= 0) { conn.close(); GattConnection connection = getConnectionMap().remove(fitbitBluetoothDevice); if (connection != null) { notifyListenersOfConnectionDisconnected(connection); Timber.v("Connection for %s is disconnected and pruned", connection.getDevice()); } } else { conn.setDisconnectedTTL(currentTtl - CLEANUP_INTERVAL); } } } } decrementAndInvalidateClosedConnections(); } @VisibleForTesting synchronized void addScannedDevice(FitbitBluetoothDevice device) { // we need to deal with the scenario where the peripheral was connected, but now // it is disconnected, then it is picked up in the background with the scan // the listener could potentially be called back twice for the same connection // if the user has a background scan running while an active scan is running GattConnection conn = connectionMap.get(device); if (null == conn) { if (appContext == null) { Timber.w("[%s] Bitgatt must not be started, please start bitgatt client", device); return; } Timber.v("Adding scanned device %s", device.toString()); conn = new GattConnection(device, appContext.getMainLooper()); device.origin = FitbitBluetoothDevice.DeviceOrigin.SCANNED; connectionMap.put(device, conn); notifyListenersOfConnectionAdded(conn); } else { FitbitBluetoothDevice oldDevice = conn.getDevice(); String previousDeviceName = oldDevice.getName(); ScanRecord previousScanRecord = oldDevice.getScanRecord(); int previousRssi = oldDevice.getRssi(); if (!previousDeviceName.equals(device.getName())) { Timber.w("This device has the same mac (bluetooth ID) as a known device, but has changed it's BT name, IRL be careful this can break upstream logic, or have security implications."); } oldDevice.origin = FitbitBluetoothDevice.DeviceOrigin.SCANNED; if (!previousDeviceName.equals(device.getName()) || previousRssi != device.getRssi() || (previousScanRecord != null && device.getScanRecord() != null && !Arrays.equals(previousScanRecord.getBytes(), device.getScanRecord().getBytes()))) { //Timber.v("Found device may have changed was %s, and now is %s", oldDevice, device); oldDevice.setName(device.getName()); oldDevice.setScanRecord(device.getScanRecord()); oldDevice.setRssi(device.getRssi()); } notifyListenersOfConnectionAdded(conn); } } /** * Will create connection objects representing all of the BTLE devices connected presently * or bonded to this phone */ private void addConnectedDevices(Context context) { fitbitGattAsyncOperationHandler.post(() -> { Timber.v("Adding connected or bonded devices"); BluetoothManagerFacade manager = dependencyProvider.getBluetoothManagerFacade(appContext); if (manager != null) { BluetoothAdapter adapter = manager.getAdapter(); if (adapter != null) { List<BluetoothDevice> connectedDevices = manager.getConnectedDevices(BluetoothProfile.GATT); for (BluetoothDevice connectedDevice : connectedDevices) { FitbitBluetoothDevice fitbitBluetoothDevice = new FitbitBluetoothDevice(connectedDevice); fitbitBluetoothDevice.origin = FitbitBluetoothDevice.DeviceOrigin.CONNECTED; GattConnection connection = connectionMap.get(fitbitBluetoothDevice); if (null == connection) { Timber.v("Adding connected device named %s, with address %s", connectedDevice.getName(), connectedDevice.getAddress()); if (appContext != null) { GattConnection conn = new GattConnection(fitbitBluetoothDevice, appContext.getMainLooper()); connectionMap.put(fitbitBluetoothDevice, conn); conn.initGattForConnectedDevice(); FitbitGatt.getInstance().notifyListenersOfConnectionAdded(conn); } else { Timber.w("Tried to add a discovered device, but the cached context was null"); } } else { connection.initGattForConnectedDevice(); } } Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices(); for (BluetoothDevice bondedDevice : bondedDevices) { FitbitBluetoothDevice fitBluetoothDevice = new FitbitBluetoothDevice(bondedDevice); fitBluetoothDevice.origin = FitbitBluetoothDevice.DeviceOrigin.BONDED; if (null == connectionMap.get(fitBluetoothDevice)) { if (appContext == null) { Timber.w("[%s] Bitgatt must not be started, please start bitgatt", fitBluetoothDevice); return; } GattConnection conn = new GattConnection(fitBluetoothDevice, appContext.getMainLooper()); Timber.v("Adding bonded device named %s, with address %s", bondedDevice.getName(), bondedDevice.getAddress()); connectionMap.put(fitBluetoothDevice, conn); FitbitGatt.getInstance().notifyListenersOfConnectionAdded(conn); } } } } Timber.v("Added all connected or bonded devices"); }); } /** * Will return a list of {@link GattConnection} objects that match the provided bluetooth device * names, providing a null list returns all connections * * @param names The list of bluetooth device names by which to filter the list * @return The list of connections matching these names */ public List<GattConnection> getMatchingConnectionsForDeviceNames(@Nullable List<String> names) { ArrayList<GattConnection> connections = new ArrayList<>(2); if (names == null) { connections.addAll(connectionMap.values()); return connections; } for (String name : names) { Enumeration<FitbitBluetoothDevice> fitbitDeviceEnumeration = connectionMap.keys(); while (fitbitDeviceEnumeration.hasMoreElements()) { FitbitBluetoothDevice device = fitbitDeviceEnumeration.nextElement(); if (device.getName().equals(name)) { connections.add(connectionMap.get(device)); } } } return connections; } /** * Will return a list of connections that match a series of service UUIDs, will return if any * of the services provided matches a hosted service. If discovery has not been performed * on the connected device, or if it is not connected, it will not be returned. * * @param services A list of services to filter * @return The connections that match any of the items in the list */ @SuppressWarnings("WeakerAccess") // API Method public List<GattConnection> getMatchingConnectionsForServices(@Nullable List<UUID> services) { ArrayList<GattConnection> connections = new ArrayList<>(2); if (services == null) { connections.addAll(connectionMap.values()); return connections; } Enumeration<FitbitBluetoothDevice> fitbitDeviceEnumeration = connectionMap.keys(); while (fitbitDeviceEnumeration.hasMoreElements()) { FitbitBluetoothDevice device = fitbitDeviceEnumeration.nextElement(); GattConnection conn = connectionMap.get(device); if (conn != null) { BluetoothGatt gatt = conn.getGatt(); if ((conn.getMockMode() || gatt != null) && conn.isConnected()) { for (UUID serviceUuid : services) { if (conn.connectedDeviceHostsService(serviceUuid)) { connections.add(conn); } } } } } return connections; } /** * Will retrieve a connection from the map if one exists using the bluetooth mac address * of the device, or will return null if it does not. * * @param bluetoothAddress The bluetooth mac address * @return NULL if error creating creating connection, the connection if it does */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public @Nullable GattConnection getConnectionForBluetoothAddress(String bluetoothAddress) { if (appContext != null) { return getConnectionForAddress(bluetoothAddress); } else { Timber.w("Error getting connection FitbitGatt state %s", isInitialized()); return null; } } /** * Will retrieve a connection from the map if one exists using the bluetooth mac address * of the device, or will create one if it does not. * * @param context The Android context * @param bluetoothAddress The bluetooth mac address * @return NULL if error creating creating connection, the connection if it does * @deprecated Using this method is discouraged as it will soon become private */ @Deprecated public @Nullable GattConnection getConnectionForBluetoothAddress(Context context, String bluetoothAddress) { BluetoothManager mgr = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); if (mgr != null) { BluetoothAdapter adp = mgr.getAdapter(); if (adp != null) { BluetoothDevice bluetoothDevice = adp.getRemoteDevice(bluetoothAddress); return getConnection(bluetoothDevice); } else { Timber.e("Couldn't fetch the connection because we couldn't initialize the adapter"); return null; } } else { Timber.e("Couldn't fetch the connection because we couldn't initialize the manager"); return null; } } /** * Synchronized because this can be called in effect from bluetooth on and startGattServer, there could * be some odd behavior if this were called concurrently * * @param callback The async callback for resolving the gatt server open */ private synchronized void startServer(OpenGattServerCallback callback) { BluetoothManagerFacade manager = dependencyProvider.getBluetoothManagerFacade(appContext); if (manager != null && manager.getAdapter() != null) { /* * We've observed that the registration of the callback inside of the android * source for the gatt_if can lead to a hang for up to 13 seconds, but the * ANR time is 5 seconds currently (Summer 2019) * * If this occurs, then you probably should tell the user to clear their bluetooth * application's data in the application list with system apps shown. The gatt * cache is probably corrupt */ fitbitGattAsyncOperationHandler.post(tryAndStartGattServer(this.appContext, callback, manager)); } else { Timber.w("No bluetooth manager, we must be simulating, or BT is off!!!"); callback.onGattServerStatus(false); } } @NonNull Runnable tryAndStartGattServer(Context context, OpenGattServerCallback callback, BluetoothManagerFacade manager) { return tryAndStartGattServer(context, callback, manager, serverCallback); } @VisibleForTesting Runnable tryAndStartGattServer(Context context, OpenGattServerCallback callback, BluetoothManagerFacade manager, GattServerCallback serverCallback) { return () -> { synchronized (FitbitGatt.this) { //may have been started already in another thread in parallel trough another post //We observed this behaviour inside the FitbitGattTest instrumentation test //when trying to start the gatt server multiple times Timber.tag("FitbitGattServer").d("Trying to start the gatt server"); if (gattServer != null) { gattServer.close(); } for (int openServerRetryCount = 0; openServerRetryCount < OPEN_GATT_SERVER_RETRY_COUNT; openServerRetryCount++) { gattServer = manager.openGattServer(context, serverCallback); if (gattServer != null) { if(gattServer.getServices().size() != 0) { Timber.w("We have services on a fresh gatt server instance"); gattServer.clearServices(); } if (serverConnection != null) { // We have a new server instance we need to replace it in the GattServerConnection serverConnection.close(); serverConnection.setState(GattState.IDLE); } setGattServerConnection(new GattServerConnection(gattServer, context.getMainLooper())); serverConnection.setState(GattState.IDLE); callback.onGattServerStatus(true); isGattServerStarting.set(false); Timber.tag("FitbitGattServer").v("Gatt server successfully opened"); return; } } isGattServerStarting.set(false); Timber.tag("FitbitGattServer").w("Exhausted retries to open gatt server, recommend that you tell your user to clear bluetooth share in the apps list, the GATT db is probably corrupt"); callback.onGattServerStatus(false); } }; } /** * Will add a device that was discovered via the background scan in a provided scan result to * the connected devices map and will notify listeners of the availability of the new connection. This will allow * an API user to add devices from scans that occur outside of the context of the periodical scanner. * * @param device The scan result from the background system scan */ synchronized void addBackgroundScannedDeviceConnection(@Nullable FitbitBluetoothDevice device) { if (device != null) { device.origin = FitbitBluetoothDevice.DeviceOrigin.SCANNED; addScannedDevice(device); } else { Timber.w("No result provided."); } } /** * Will add a device that was discovered via the background scan in a provided scan result to * the connected devices map and will notify listeners of the availability of the new connection. This will allow * an API user to add devices from scans that occur outside of the context of the periodical scanner. * * @param result The scan result from the background system scan */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public synchronized void addBackgroundScannedDeviceConnection(@Nullable ScanResult result) { if (result != null) { BluetoothDevice bluetoothDevice = result.getDevice(); FitbitBluetoothDevice device = new FitbitBluetoothDevice(bluetoothDevice); device.origin = FitbitBluetoothDevice.DeviceOrigin.SCANNED; device.setRssi(result.getRssi()); addScannedDevice(device); } else { Timber.w("No result provided."); } } /** * To provide an API to attempt to always find a bluetooth device that the caller wants to know * is in close proximity. If this is attempted on a version prior to Android Oreo, * the result will be a no-op and will return false. This API can be used to remain connected * to a particular set of devices. The type of scan that occurs via this API is a privileged * scan that can run generally forever, but is not entirely under our control. * This scan is run by the system, so the resulting broadcast intent's content RE the bluetooth * device may change with the Android version. Be advised that this scan will be automatically * cancelled if the user turns bluetooth off. * * @param context The Android context for creating the pending intent * @param broadcastIntent The broadcast intent to be sent when the device is found. * Will wake up application if process is dead. * @param macAddresses The specific mac addresses for which to be called back * @return The pending intent that should be used to cancel the scan if desired, or null * if the scan wasn't started. */ @SuppressWarnings({"WeakerAccess", "unused"}) // API Method public PendingIntent startBackgroundScan(@NonNull Context context, @NonNull Intent broadcastIntent, @NonNull List<String> macAddresses) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return null; } if (isInitialized() && peripheralScanner != null) { return peripheralScanner.startBackgroundScan(macAddresses, broadcastIntent, context); } else { Timber.w("The FitbitGatt must have been started in order to use the background scanner."); return null; } } /** * Will start a background scan that will continue to run even if our process is killed. This * will internally handle the result of particular intent based scan results and deliver * connection callbacks when items are found. In order to start a pending intent based scan you will * need to stop any existing high-priority scan in order to enable the pending intent based scan, the intended * use of this API is for scanning while your application is in the background. When you * come into the foreground, you should cancel the background scan * with {@link FitbitGatt#stopSystemManagedPendingIntentScan()} unless you want for * the background scan to continue. Be advised that this might result in multiple callbacks to * {@link FitbitGattCallback#onBluetoothPeripheralDiscovered(GattConnection)}. * <p> * This background scan will be auto cancelled by the Android operating system in a way that we * can not control if BT is turned off or if the phone is rebooted. This is a function of the * pending intent scan Android API. * <p> * WARNING!!!! Using this with scan filters that are empty is extremely dangerous and is frowned upon * your application will potentially get hundreds of intent callbacks every second. Please do * not use this to get around the scanfilter empty check. * * @param context The Android context for creating the pending intent * @param scanFilters The specific scan filters for which to be called back * @return true if the scan was able to be started, false if not */ public boolean startSystemManagedPendingIntentScan(@NonNull Context context, @NonNull List<ScanFilter> scanFilters) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return false; } if (isInitialized() && peripheralScanner != null) { return peripheralScanner.startPendingIntentBasedBackgroundScan(scanFilters, context); } else { Timber.i("Can't start because scanner has not been initialized"); return false; } } /** * Will stop the currently running pending intent based scan */ public void stopSystemManagedPendingIntentScan() { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return; } if (isInitialized() && peripheralScanner != null) { try { peripheralScanner.cancelPendingIntentBasedBackgroundScan(); } catch (NoSuchMethodError error) { Timber.i(error, "There was a no such method error stopping the pending intent scan, assuming stopped."); } } else { Timber.i("Can't stop because we aren't started, or the scanner is null"); } } /** * Will stop the background scan started earlier by {@link FitbitGatt#startBackgroundScan(Context, Intent, List)} * * @param pendingIntent The pending intent returned by {@link FitbitGatt#startBackgroundScan(Context, Intent, List)} */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void stopBackgroundScan(@Nullable PendingIntent pendingIntent) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return; } if (pendingIntent == null) { Timber.v("No pending intent."); } else { if (peripheralScanner != null) { peripheralScanner.stopBackgroundScan(pendingIntent); } else { Timber.w("Peripheral scanner was null, did you forget to call FitbitGatt#initializeScanner?"); } } } /** * Will stop the background scan with a regular intent * * @param context The android context * @param regularIntent The regular intent */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public void stopBackgroundScanWithRegularIntent(Context context, @Nullable Intent regularIntent) { if (alwaysConnectedScanner.isAlwaysConnectedScannerEnabled()) { Timber.i("You are using the always connected scanner, stop it first before ad-hoc scanning"); return; } if (regularIntent == null) { Timber.v("No intent."); } else { PendingIntent pending; try { pending = dependencyProvider.getNewScanPendingIntent(context, regularIntent); } catch (NoSuchMethodError error) { Timber.i(error, "There was a no such method error stopping the pending intent scan, assuming stopped"); return; } if (peripheralScanner != null && pending != null) { peripheralScanner.stopBackgroundScan(pending); } else { Timber.w("Peripheral scanner was null, did you forget to call FitbitGatt#initializeScanner?"); } } } public GattServerConnection getServer() { return serverConnection; } public @Nullable GattConnection getConnection(@Nullable BluetoothDevice device) { if (device == null || device.getAddress() == null) { return null; } return getConnectionForAddress(device.getAddress()); } /** * Will fetch a connection object if one is present for a given bluetooth address * * @param bluetoothAddress The bluetooth MAC address * @return The GattConnection object */ @SuppressWarnings({"unused", "WeakerAccess"}) // API Method public @Nullable GattConnection getConnectionForAddress(@Nullable String bluetoothAddress) { if (bluetoothAddress == null) { return null; } for (FitbitBluetoothDevice device : connectionMap.keySet()) { if (device.getAddress().equals(bluetoothAddress)) { return connectionMap.get(device); } } return null; } /** * This method will create a new connection if one does not already exist for the provided * device and add it to the connection map * * @param device The fitbit bluetooth device * @return The connection, it can be null if no connection is in the map, this is necessary to prevent too many client_ifs from races */ public @Nullable GattConnection getConnection(FitbitBluetoothDevice device) { return connectionMap.get(device); } @TargetApi(24) @SuppressWarnings("WeakerAccess") // API Method protected BluetoothAdapter getAdapter(Context context) { if (atLeastSDK(Build.VERSION_CODES.M)) { BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); assert manager != null; return manager.getAdapter(); } else { return BluetoothAdapter.getDefaultAdapter(); } } /** * Returns the BluetoothDevice Object for a remote Device that has the mac Address specified * <p> The mac Address should be a valid, such as "00:43:A8:23:10:F0" * Alphabetic characters must be uppercase to be valid. * * @param macAddress the mac address of the bluetooth device in question * @return The bluetooth device or null if not connected */ public BluetoothDevice getBluetoothDevice(String macAddress) { BluetoothAdapter adapter = getAdapter(appContext); if (adapter != null && BluetoothAdapter.checkBluetoothAddress(macAddress)) { return adapter.getRemoteDevice(macAddress); } return null; } /** * Simple function to return true if the current device is running the given API Level or higher. * Recommended to use as a static import when comparing api levels * * @param buildVersion the buildVersion or API Level as defined by android.os.Build.VERSION_CODES. * @return true if the current device's API level is equal to or greater than the given API Level code */ public static boolean atLeastSDK(int buildVersion) { return Build.VERSION.SDK_INT >= buildVersion; } @Override public void onScanStatusChanged(boolean isScanning) { Timber.i("On scan status changed %b", isScanning); if (isScanning) { for (FitbitGattCallback callback : this.overallGattEventListeners) { callback.onScanStarted(); } } else { for (FitbitGattCallback callback : this.overallGattEventListeners) { callback.onScanStopped(); } } } @Override public void onPendingIntentScanStatusChanged(boolean isScanning) { if (isScanning) { for (FitbitGattCallback callback : this.overallGattEventListeners) { callback.onPendingIntentScanStarted(); } } else { for (FitbitGattCallback callback : this.overallGattEventListeners) { callback.onPendingIntentScanStopped(); } } } @Override public void onFitbitDeviceFound(FitbitBluetoothDevice device) { addScannedDevice(device); } private void addServicesToGattServerOnStart() { GattServerConnection server = getServer(); if (server != null) { CompositeServerTransaction addServicesTransaction = new CompositeServerTransaction(server, getGattAddServerServiceTransactions(servicesToAdd)); server.runTx(addServicesTransaction, getGattAddServicesOnTransactionCallback()); } else { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onGattServerStartError(new MissingGattServerErrorException()); } } } @NonNull private List<GattServerTransaction> getGattAddServerServiceTransactions(List<BluetoothGattService> services) { List<GattServerTransaction> transactions = new ArrayList<>(); for (BluetoothGattService service : services) { transactions.add(new AddGattServerServiceTransaction(getServer(), GattState.ADD_SERVICE_SUCCESS, service)); } return transactions; } @NonNull private GattTransactionCallback getGattAddServicesOnTransactionCallback() { return result -> { Timber.d("Gatt server init add service result: %s", result); processAddServiceOnStartResult(result); }; } private void processAddServiceOnStartResult(TransactionResult result) { if (!result.resultStatus.equals(TransactionResult.TransactionResultStatus.SUCCESS)) { List<TransactionResult> results = result.getTransactionResults(); for (TransactionResult tr : results) { if (!tr.resultStatus.equals(TransactionResult.TransactionResultStatus.SUCCESS)) { for (FitbitGattCallback cb : overallGattEventListeners) { cb.onGattServerStartError(new AddingServiceOnStartException(tr.getServiceUuid())); } } } } } /** * Clean up the states of the devices, the bluetooth adapter is turning off so we will have to * mark them all as disconnected and start the TTL */ private void cleanUpBecauseBluetoothIsTurningOff() { for (Map.Entry<FitbitBluetoothDevice, GattConnection> entry : getConnectionMap().entrySet()) { cleanUpConnection(entry.getValue()); } // need to clean up scanner also, if BT turns off then we can no longer be scanning if (getPeripheralScanner() != null) { if (getPeripheralScanner().isPendingIntentScanning() || getPeripheralScanner().isScanning()) { // we will try to clean up the normal way getPeripheralScanner().cancelPendingIntentBasedBackgroundScan(); getPeripheralScanner().cancelScan(appContext); } } } private void cleanUpConnection(GattConnection conn) { // by setting the state to bt_off no additional transactions can run except for // connect. The existing transaction might timeout in this case, but this seems to be // the best way. conn.cleanUpConnection(); conn.justClearGatt(); conn.setState(GattState.BT_OFF); } private void switchAllConnectionsToDisconnectedBecauseBtIsOn() { for (Map.Entry<FitbitBluetoothDevice, GattConnection> entry : getConnectionMap().entrySet()) { entry.getValue().setState(GattState.DISCONNECTED); } } @Override public void bluetoothOff() { isBluetoothOn = false; Timber.v("Bluetooth is off"); cleanUpBecauseBluetoothIsTurningOff(); for (FitbitGattCallback callback : overallGattEventListeners) { callback.onBluetoothOff(); } } @Override public void bluetoothOn() { isBluetoothOn = true; /* * In testing we see that sometimes there will be a dead object exception from the stack * after bluetooth is turned off and then on again. It seems that the IBluetoothGatt is * no longer connected to any process, to make sure that we don't have this situation, let's * replace the instance. * */ if (!isInitialized() || this.appContext == null) { Timber.e("Refreshing the gatt server after BT was enabled failed. Bitgatt has not been started"); return; } if (isGattServerStarted.get()) { startServer(getOpenGattServerCallbackOnBluetoothOn()); } if (isGattClientStarted.get()) { switchAllConnectionsToDisconnectedBecauseBtIsOn(); } for (FitbitGattCallback callback : overallGattEventListeners) { callback.onBluetoothOn(); } } @NonNull @VisibleForTesting OpenGattServerCallback getOpenGattServerCallbackOnBluetoothOn() { return started -> { if (started) { Timber.v("Gatt server up and ready"); } else { Timber.w("After several attempts the gatt server could not be re-opened, tread lightly"); } if (servicesToAdd != null && !servicesToAdd.isEmpty()) { addServicesToGattServerOnStart(); } Timber.v("Bluetooth is on"); }; } @Override public void bluetoothTurningOff() { isBluetoothOn = false; // let's try to clean up the gatt server on devices that are likely to duplicate or host // no services after add on startup due to queueing issues, almost all Samsung devices // seem to behave in this way AndroidDevice strategyDevice = new AndroidDevice.Builder().manufacturerName("Samsung").build(); Strategy executableStrategy = new StrategyProvider() .getStrategyForPhoneAndGattConnection(strategyDevice, null, Situation.CLEAR_GATT_SERVER_SERVICES_DEVICE_FUNKY_BT_IMPL); if(executableStrategy != null) { // we don't want to run any other strategies that may end up // with this situation if(executableStrategy instanceof BluetoothOffClearGattServerStrategy) { executableStrategy.applyStrategy(); } } Timber.v("Bluetooth is turning off"); for (FitbitGattCallback callback : overallGattEventListeners) { callback.onBluetoothTurningOff(); } // you can not cancel the scan here because if you do, there is a chance that the actual // scanner implementation inside of the adapter could become null, even if you cache // the reference, like in IPD-103133 where we set it and in the next call it's null cleanUpBecauseBluetoothIsTurningOff(); } @Override public void bluetoothTurningOn() { // still can't use it until it's on isBluetoothOn = false; Timber.v("Bluetooth is turning on"); for (FitbitGattCallback callback : overallGattEventListeners) { callback.onBluetoothTurningOn(); } } /** * @return true if log statements that may slow down data transfer speeds should be executed */ @RestrictTo(RestrictTo.Scope.LIBRARY) public boolean isSlowLoggingEnabled() { return slowLoggingEnabled; } /** * Use this method to enable or disable (default) log statements that may slow down data transfer speeds * @param newValue true to enable these logs, false to disable. */ @SuppressWarnings({"unused"}) // API Method public void setSlowLoggingEnabled(boolean newValue) { slowLoggingEnabled = newValue; } }
package com.fredhopper.environment; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Formatter; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.function.Supplier; import com.google.common.base.StandardSystemProperty; /** * A general abstract presentation of an environment of an * application's runtime in JVM. The environment is a read-only * source of key-value pairs in the environment. */ public interface Environment { /** * A unique ID that is initialized for an {@link Environment} * the first time the environment is initialized. If multiple * {@link Environment} instances are used in the same JVM, * this is not reliable and should not be used. */ String ID = UUID.randomUUID().toString(); /** * A Java {@link Properties} file that can be used to define * an {@link Environment} instance with system property * {@value}. */ String ENVIRONMENT_FILE = "environment.file"; /** * The name that is given to the environment instance; e.g. * <code>development</code>, <code>test</code>, * <code>production</code>. */ String ENVIRONMENT_NAME = "environment.name"; /** * Key of the name of the application: {@value}. */ String APPLICATION_NAME = "application.name"; /** * The application's root directory suffix: {@value}. */ String ROOT_SUFFIX = ".root"; /** * The application's root directory for logs suffix: {@value}. */ String LOG_ROOT_SUFFIX = ".logs.root"; /** * The default log files extension: {@value}. */ String LOG_FILE_SUFFIX = ".log"; /** * The default access log files extension: {@value}. */ String ACCESS_LOG_FILE_SUFFIX = "-access.log"; /** * The pattern suffix to use for Apache Log4j for rolling log * files: {@value}. */ String LOG_FILE_ROTATE_PATTERN_SUFFIX = ".%d{yyyy-MM-dd}"; /** * The default suffix for access log files rolling: {@value}. */ String ACCESS_LOG_FILE_ROTATE_PATTERN = ".yyyy-MM-dd"; /** * The default log pattern: {@value}. */ String LOG_PATTERN = "[%d] [%level] [%thread] %msg (%logger{1}:%L)%n%throwable"; /** * The default value: {@value} */ String AUDIT_LOG_PATTERN = "%d{ISO8601} %level %msg%n"; String SERVER_HOST_SUFFIX = ".server.host"; String SERVER_PORT_SUFFIX = ".server.port"; /** * The environment or system property key to hold the shutdown * password token for Jetty (HTTP server). */ String SERVER_SHUTDOWN_TOKEN_KEY = "server.shutdown.token"; /** * The ID of the environment. * * @return the id of the environment */ default String getId() { return ID; } /** * The name of the environment. The default value is * <code>development</code> * * @see RuntimeMode * @return the name of the environment */ default String getEnvironmentName() { return "development"; } /** * The application name. * * @return the name of the application configured as * <code>application.name</code>. */ String getApplicationName(); /** * The path to application root. * * @return the root of the application configured as * <code>${application.name}.root</code>. Can be * <code>null</code>. */ Path getApplicationRoot(); /** * The path to application logs root. By default, the * implementations might choose to fall back to * <code>${application.name}.root/logs</code>. * * @return the root of the application logs. Can be * <code>null</code>. */ Path getApplicationLogsRoot(); /** * The log file name. By default, the implementations might * choose to fall back to <code>${application.name}.log</code> * * @return the name of the log files for the application. */ String getLogFileName(); /** * The rotating log file pattern. * * @return the rotating log file pattern potentially include a * date/time pattern. */ String getRotatingLogFilePattern(); /** * The access log file name. By default, implementations might * choose to use {@link #getLogFileName()}- * <code>access.log</code> * * @return the log file name for access logs of the * application. */ String getAccessLogFileName(); /** * The rotating access log file name. * * @return the name pattern for rotating access log files. */ String getRotatingAccessLogFileName(); /** * The context path. By default, it falls back to * <code>/${application.name}</code>. * * @return the context path at which the application is * accessible through HTTP. */ String getContextPath(); /** * The host name of the server. * * @return the host name of the server running the * application. */ String getServerHost(); /** * The port number of the server. * * @return the port number of the server running the * application. */ int getServerPort(); /** * The value of a key. * * @param key the environment key * @return the value for the key or <code>null</code> */ default String getValue(String key) { return getValue(key, () -> null); } /** * The value of a key with a supplier. * * @param key the environment key * @param supplier a {@link Supplier} for the key in case * there is no value available * @return the value for the key or delegates to the supplier */ String getValue(String key, Supplier<String> supplier); /** * The value of {@link #SERVER_SHUTDOWN_TOKEN_KEY} in the * created environment. * * @return the server shutdown token or <code>null</code> if * none is specified. */ default String getServerShutdownToken() { return getValue(SERVER_SHUTDOWN_TOKEN_KEY); } /** * The description of the environment. * * @return a formatted {@link StringBuilder} to describe the * environment instance. */ default StringBuilder getDescription() { final String newLine = StandardSystemProperty.LINE_SEPARATOR.value(); final StringBuilder sb = new StringBuilder(""); sb.append(newLine); try (final Formatter f = new Formatter(sb)) { final String format = "%1$24s %2$s" + newLine; sb.append(newLine); f.format(format, "OS", StandardSystemProperty.OS_NAME.value() + " " + StandardSystemProperty.OS_ARCH.value() + " " + StandardSystemProperty.OS_VERSION.value()); f.format(format, "Java Runtime", System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version")); f.format(format, "Java VM", StandardSystemProperty.JAVA_VM_NAME.value() + " " + StandardSystemProperty.JAVA_VM_VENDOR.value() + " " + StandardSystemProperty.JAVA_VM_VERSION.value()); f.format(format, "Java Class Ver.", StandardSystemProperty.JAVA_CLASS_VERSION.value()); f.format(format, "Environment ID", getId()); f.format(format, "Environment Ver.", Environment.class.getPackage().getImplementationVersion()); f.format(format, "Environment Name", getEnvironmentName()); f.format(format, "Runtime Mode", RuntimeMode.fromEnvironment(this)); f.format(format, "Application", getApplicationName()); f.format(format, "Application Root", getApplicationRoot()); f.format(format, "Application Logs", getApplicationLogsRoot()); f.format(format, "Server Host", getServerHost()); f.format(format, "Server Port", getServerPort()); sb.append(newLine); } catch (Exception e) { // Ignore } return sb; } static Environment createEnvironment() { return createEnvironment(new HashMap<>()); } /** * Create an environment. * * @param environment the base environment to use. Values will * be over-written first by {@link System#getenv()}, * then {@link System#getProperties()}, and then * finally if {@link #ENVIRONMENT_FILE} provides any. * @return the created {@link Environment} instance. */ static Environment createEnvironment(Map<String, String> environment) { final Map<String, String> env = new HashMap<>(); env.putAll(environment); env.putAll(new HashMap<String, String>(System.getenv())); final Properties systemProperties = System.getProperties(); systemProperties.stringPropertyNames() .forEach(p -> env.put(p, systemProperties.getProperty(p))); final String environmentFilePath = systemProperties.getProperty(ENVIRONMENT_FILE, null); final Properties environmentFileProperties = new Properties(); if (environmentFilePath != null && Files.isReadable(Paths.get(environmentFilePath))) { try (InputStream is = Files.newInputStream(Paths.get(environmentFilePath))) { environmentFileProperties.load(is); } catch (IOException e) { throw new IllegalArgumentException("Cannot load environment from " + environmentFilePath, e); } } environmentFileProperties.stringPropertyNames() .forEach(p -> env.put(p, environmentFileProperties.getProperty(p))); return new KeyValueEnvironment(env); } }
package com.github.davidmoten.rx.jdbc; import static com.github.davidmoten.rx.RxUtil.constant; import static com.github.davidmoten.rx.RxUtil.greaterThanZero; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Connection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.Operator; import rx.Scheduler; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func2; import rx.observables.StringObservable; import rx.schedulers.Schedulers; import com.github.davidmoten.rx.RxUtil; import com.github.davidmoten.rx.RxUtil.CounterAction; /** * Main entry point for manipulations of a database using rx-java-jdbc style * queries. */ final public class Database { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(Database.class); /** * Provides access for queries to a limited subset of {@link Database} * methods. */ private final QueryContext context; /** * ThreadLocal storage of the current {@link Scheduler} factory to use with * queries. */ private final ThreadLocal<Func0<Scheduler>> currentSchedulerFactory = new ThreadLocal<Func0<Scheduler>>(); /** * ThreadLocal storage of the current {@link ConnectionProvider} to use with * queries. */ private final ThreadLocal<ConnectionProvider> currentConnectionProvider = new ThreadLocal<ConnectionProvider>(); private final ThreadLocal<Boolean> isTransactionOpen = new ThreadLocal<Boolean>(); /** * Records the result of the last finished transaction (committed = * <code>true</code> or rolled back = <code>false</code>). */ private final ThreadLocal<Observable<Boolean>> lastTransactionResult = new ThreadLocal<Observable<Boolean>>(); /** * Connection provider. */ private final ConnectionProvider cp; /** * Schedules non transactional queries. */ private final Func0<Scheduler> nonTransactionalSchedulerFactory; /** * Constructor. * * @param cp * provides connections * @param nonTransactionalSchedulerFactory * schedules non transactional queries */ public Database(final ConnectionProvider cp, Func0<Scheduler> nonTransactionalSchedulerFactory) { Conditions.checkNotNull(cp); this.cp = cp; currentConnectionProvider.set(cp); if (nonTransactionalSchedulerFactory != null) this.nonTransactionalSchedulerFactory = nonTransactionalSchedulerFactory; else this.nonTransactionalSchedulerFactory = IO_SCHEDULER_FACTORY; this.context = new QueryContext(this); } /** * Returns the {@link ConnectionProvider}. * * @return */ public ConnectionProvider getConnectionProvider() { return cp; } /** * Schedules on {@link Schedulers#io()}. */ private final Func0<Scheduler> IO_SCHEDULER_FACTORY = new Func0<Scheduler>() { @Override public Scheduler call() { return Schedulers.io(); } }; /** * Schedules using {@link Schedulers}.trampoline(). */ private static final Func0<Scheduler> CURRENT_THREAD_SCHEDULER_FACTORY = new Func0<Scheduler>() { @Override public Scheduler call() { return Schedulers.trampoline(); } }; /** * Constructor. Thread pool size defaults to * <code>{@link Runtime#getRuntime()}.availableProcessors()+1</code>. This * may be too conservative if the database is on another server. If that is * the case then you may want to use a thread pool size equal to the * available processors + 1 on the database server. * * @param cp * provides connections */ public Database(ConnectionProvider cp) { this(cp, null); } /** * Constructor. Uses a {@link ConnectionProviderFromUrl} based on the given * url. * * @param url * jdbc connection url */ public Database(String url) { this(new ConnectionProviderFromUrl(url)); } /** * Returns a new {@link Builder}. * * @return */ public static Builder builder() { return new Builder(); } /** * Builds a {@link Database}. */ public final static class Builder { private ConnectionProvider cp; private Func0<Scheduler> nonTransactionalSchedulerFactory = null; /** * Constructor. */ private Builder() { } /** * Sets the connection provider. * * @param cp * @return */ public Builder connectionProvider(ConnectionProvider cp) { this.cp = cp; return this; } /** * Sets the jdbc url. * * @param url * @return */ public Builder url(String url) { this.cp = new ConnectionProviderFromUrl(url); return this; } /** * Sets the {@link ConnectionProvider} to use a connection pool with the * given jdbc url and pool size. * * @param url * @param minPoolSize * @param maxPoolSize * @return */ public Builder pooled(String url, int minPoolSize, int maxPoolSize) { this.cp = new ConnectionProviderPooled(url, minPoolSize, maxPoolSize); return this; } /** * Sets the {@link ConnectionProvider} to use a connection pool with the * given jdbc url and min pool size of 0, max pool size of 10. * * @param url * @return */ public Builder pooled(String url) { this.cp = new ConnectionProviderPooled(url, 0, 10); return this; } /** * Sets the non transactional scheduler. * * @param factory * @return */ public Builder nonTransactionalScheduler(Func0<Scheduler> factory) { nonTransactionalSchedulerFactory = factory; return this; } /** * Requests that the non transactional queries are run using * {@link Schedulers#trampoline()}. * * @return */ public Builder nonTransactionalSchedulerOnCurrentThread() { nonTransactionalSchedulerFactory = CURRENT_THREAD_SCHEDULER_FACTORY; return this; } /** * Returns a {@link Database}. * * @return */ public Database build() { return new Database(cp, nonTransactionalSchedulerFactory); } } /** * Returns the thread local current query context (will not return null). * Will return overriden context (for example using Database returned from * {@link Database#beginTransaction()} if set. * * @return */ public QueryContext queryContext() { return context; } /** * Returns a {@link QuerySelect.Builder} builder based on the given select * statement sql. * * @param sql * a select statement. * @return select query builder */ public QuerySelect.Builder select(String sql) { return new QuerySelect.Builder(sql, this); } /** * Returns a {@link QueryUpdate.Builder} builder based on the given * update/insert/delete/DDL statement sql. * * @param sql * an update/insert/delete/DDL statement. * @return update/insert query builder */ public QueryUpdate.Builder update(String sql) { return new QueryUpdate.Builder(sql, this); } /** * Starts a transaction. Until commit() or rollback() is called on the * source this will set the query context for all created queries to be a * single threaded executor with one (new) connection. * * @param dependency * @return */ public Observable<Boolean> beginTransaction(Observable<?> dependency) { return update("begin").dependsOn(dependency).count().map(constant(true)); } /** * Starts a transaction. Until commit() or rollback() is called on the * source this will set the query context for all created queries to be a * single threaded executor with one (new) connection. * * @return */ public Observable<Boolean> beginTransaction() { return beginTransaction(Observable.empty()); } /** * Returns true if and only if integer is non-zero. */ private static final Func1<Integer, Boolean> IS_NON_ZERO = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer i) { return i != 0; } }; /** * Commits a transaction and resets the current query context so that * further queries will use the asynchronous version by default. All * Observable dependencies must be complete before commit is called. * * @param depends * depdencies that must complete before commit occurs. * @return */ public Observable<Boolean> commit(Observable<?>... depends) { return commitOrRollback(true, depends); } /** * Waits for the source to complete before returning the result of * db.commit(); * * @return commit operator */ public <T> Operator<Boolean, T> commitOperator() { return commitOrRollbackOperator(true); } /** * Waits for the source to complete before returning the result of * db.rollback(); * * @return rollback operator */ public <T> Operator<Boolean, T> rollbackOperator() { return commitOrRollbackOperator(false); } private <T> Operator<Boolean, T> commitOrRollbackOperator(final boolean commit) { final QueryUpdate.Builder updateBuilder = createCommitOrRollbackQuery(commit); return RxUtil.toOperator(new Func1<Observable<T>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<T> source) { return updateBuilder.dependsOn(source).count().map(IS_NON_ZERO); } }); } /** * Commits or rolls back a transaction depending on the <code>commit</code> * parameter and resets the current query context so that further queries * will use the asynchronous version by default. All Observable dependencies * must be complete before commit/rollback is called. * * @param commit * @param depends * @return */ private Observable<Boolean> commitOrRollback(boolean commit, Observable<?>... depends) { QueryUpdate.Builder u = createCommitOrRollbackQuery(commit); for (Observable<?> dep : depends) u = u.dependsOn(dep); Observable<Boolean> result = u.count().map(IS_NON_ZERO); lastTransactionResult.set(result); return result; } private QueryUpdate.Builder createCommitOrRollbackQuery(boolean commit) { String action; if (commit) action = "commit"; else action = "rollback"; QueryUpdate.Builder u = update(action); return u; } /** * Rolls back a transaction and resets the current query context so that * further queries will use the asynchronous version by default. All * Observable dependencies must be complete before rollback is called. * * @param depends * depdencies that must complete before commit occurs. * @return * **/ public Observable<Boolean> rollback(Observable<?>... depends) { return commitOrRollback(false, depends); } /** * Returns observable that emits true when last transaction committed or * false when last transaction is rolled back. * * @return */ public Observable<Boolean> lastTransactionResult() { Observable<Boolean> o = lastTransactionResult.get(); if (o == null) return Observable.empty(); else return o; } /** * Close the database in particular closes the {@link ConnectionProvider} * for the database. For a {@link ConnectionProviderPooled} this will be a * required call for cleanup. * * @return */ public Database close() { log.debug("closing connection provider"); cp.close(); log.debug("closed connection provider"); return this; } /** * Returns the current thread local {@link Scheduler}. * * @return */ Scheduler currentScheduler() { if (currentSchedulerFactory.get() == null) return nonTransactionalSchedulerFactory.call(); else return currentSchedulerFactory.get().call(); } /** * Returns the current thread local {@link ConnectionProvider}. * * @return */ ConnectionProvider connectionProvider() { if (currentConnectionProvider.get() == null) return cp; else return currentConnectionProvider.get(); } /** * Sets the current thread local {@link ConnectionProvider} to a singleton * manual commit instance. */ void beginTransactionObserve() { log.debug("beginTransactionObserve"); currentConnectionProvider.set(new ConnectionProviderSingletonManualCommit(cp)); if (isTransactionOpen.get() != null && isTransactionOpen.get()) throw new RuntimeException("cannot begin transaction as transaction open already"); isTransactionOpen.set(true); } /** * Sets the current thread local {@link Scheduler} to be * {@link Schedulers#trampoline()}. */ void beginTransactionSubscribe() { log.debug("beginTransactionSubscribe"); currentSchedulerFactory.set(CURRENT_THREAD_SCHEDULER_FACTORY); } /** * Resets the current thread local {@link Scheduler} to default. */ void endTransactionSubscribe() { log.debug("endTransactionSubscribe"); currentSchedulerFactory.set(null); } /** * Resets the current thread local {@link ConnectionProvider} to default. */ void endTransactionObserve() { log.debug("endTransactionObserve"); currentConnectionProvider.set(cp); isTransactionOpen.set(false); } /** * Returns an {@link Operator} that performs commit or rollback of a * transaction. * * @param isCommit * @return */ private <T> Operator<Boolean, T> commitOrRollbackOnCompleteOperator(final boolean isCommit) { return RxUtil.toOperator(new Func1<Observable<T>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<T> source) { return commitOrRollbackOnCompleteOperatorIfAtLeastOneValue(isCommit, Database.this, source); } }); } /** * Commits current transaction on the completion of source if and only if * the source sequence is non-empty. * * @return operator that commits on completion of source. */ public <T> Operator<Boolean, T> commitOnCompleteOperator() { return commitOrRollbackOnCompleteOperator(true); } /** * Rolls back current transaction on the completion of source if and only if * the source sequence is non-empty. * * @return operator that rolls back on completion of source. */ public <T> Operator<Boolean, T> rollbackOnCompleteOperator() { return commitOrRollbackOnCompleteOperator(false); } /** * Starts a database transaction for each onNext call. Following database * calls will be subscribed on current thread (Schedulers.trampoline()) and * share the same {@link Connection} until transaction is rolled back or * committed. * * @return begin transaction operator */ public <T> Operator<T, T> beginTransactionOnNextOperator() { return RxUtil.toOperator(new Func1<Observable<T>, Observable<T>>() { @Override public Observable<T> call(Observable<T> source) { return beginTransactionOnNext(Database.this, source); } }); } /** * Commits the currently open transaction. Emits true. * * @return */ public Operator<Boolean, Object> commitOnNextOperator() { return commitOrRollbackOnNextOperator(true); } public Operator<Boolean, Observable<?>> commitOnNextListOperator() { return commitOrRollbackOnNextListOperator(true); } public Operator<Boolean, Observable<?>> rollbackOnNextListOperator() { return commitOrRollbackOnNextListOperator(false); } private Operator<Boolean, Observable<?>> commitOrRollbackOnNextListOperator(final boolean isCommit) { return RxUtil.toOperator(new Func1<Observable<Observable<?>>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<Observable<?>> source) { return source.flatMap(new Func1<Observable<?>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<?> source) { if (isCommit) return commit(source); else return rollback(source); } }); } }); } /** * Rolls back the current transaction. Emits false. * * @return */ public Operator<Boolean, ?> rollbackOnNextOperator() { return commitOrRollbackOnNextOperator(false); } private Operator<Boolean, Object> commitOrRollbackOnNextOperator(final boolean isCommit) { return RxUtil.toOperator(new Func1<Observable<Object>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<Object> source) { return commitOrRollbackOnNext(isCommit, Database.this, source); } }); } private static final <T> Observable<Boolean> commitOrRollbackOnCompleteOperatorIfAtLeastOneValue( final boolean isCommit, final Database db, Observable<T> source) { CounterAction<T> counter = RxUtil.counter(); Observable<Boolean> commit = counter // get count .count() // greater than zero or empty .filter(greaterThanZero()) // commit if at least one value .lift(db.commitOrRollbackOperator(isCommit)); return Observable // concatenate .concat(source // count emissions .doOnNext(counter) // ignore emissions .ignoreElements() // cast the empty sequence to type Boolean .cast(Boolean.class), // concat with commit commit); } /** * Emits true for commit and false for rollback. * * @param isCommit * @param db * @param source * @return */ private static final <T> Observable<Boolean> commitOrRollbackOnNext(final boolean isCommit, final Database db, Observable<T> source) { return source.flatMap(new Func1<T, Observable<Boolean>>() { @Override public Observable<Boolean> call(T t) { if (isCommit) return db.commit(); else return db.rollback(); } }); } private static <T> Observable<T> beginTransactionOnNext(final Database db, Observable<T> source) { return source.flatMap(new Func1<T, Observable<T>>() { @Override public Observable<T> call(T t) { return db.beginTransaction().map(constant(t)); } }); } /** * Returns an {@link Observable} that is the result of running a sequence of * update commands (insert/update/delete, ddl) read from the given * {@link Observable} sequence. * * @param commands * @return */ public Observable<Integer> run(Observable<String> commands) { return commands.reduce(Observable.<Integer> empty(), new Func2<Observable<Integer>, String, Observable<Integer>>() { @Override public Observable<Integer> call(Observable<Integer> dep, String command) { return update(command).dependsOn(dep).count(); } }).lift(RxUtil.<Integer> flatten()); } /** * Returns an {@link Operator} version of {@link #run(Observable)}. * * @return */ public Operator<Integer, String> run() { return RxUtil.toOperator(new Func1<Observable<String>, Observable<Integer>>() { @Override public Observable<Integer> call(Observable<String> commands) { return run(commands); } }); } /** * Returns an {@link Observable} that is the result of running a sequence of * update commands (insert/update/delete, ddl) commands read from an * InputStream using the given delimiter as the statement delimiter (for * example semicolon). * * @param is * @param delimiter * @return */ public Observable<Integer> run(InputStream is, String delimiter) { return StringObservable.split(StringObservable.from(new InputStreamReader(is)), ";").lift(run()); } }
package com.google.sps.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Given a tweet or sentence, the servlet will extract salient terms * and store them in a list. */ @WebServlet("/keyword") public class KeywordServlet extends HttpServlet { private static final List<String> tweets = new ArrayList<>(); private static final List<String> terms = Arrays.asList("Black Lives Matter", "COVID-19"); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // TODO: Extract saliency. String json = jsonBuilder(terms); response.getWriter().println(json); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { final String tweet = request.getParameter("keyword-sentence"); if (tweet != null && !tweet.equals("")) { tweets.add(request.getParameter("keyword-sentence")); } response.sendRedirect("/index.html"); } /** * Generates and returns a JSON usable by Mustache. */ private String jsonBuilder(Collection<String> toJson) { List<String> terms = new ArrayList<>(); for (String term : toJson) { terms.add(keyValueJson("term", term)); } return String.format("{\"keywords\": [%s]}", String.join(",", terms)); } /** * Given a key-value pair, this function returns "{key: value}". */ private String keyValueJson(String key, String value) { return String.format("{\"%s\": \"%s\"}", key, value); } }
package com.googlecode.jsonrpc4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; /** * A JSON-RPC request server reads JSON-RPC requests from an input stream and writes responses to an output stream. * Supports handler and servlet requests. */ @SuppressWarnings("unused") public class JsonRpcServer extends JsonRpcBasicServer { private static final Logger logger = LoggerFactory.getLogger(JsonRpcServer.class); /** * Creates the server with the given {@link ObjectMapper} delegating * all calls to the given {@code handler} {@link Object} but only * methods available on the {@code remoteInterface}. * * @param mapper the {@link ObjectMapper} * @param handler the {@code handler} * @param remoteInterface the interface */ public JsonRpcServer(ObjectMapper mapper, Object handler, Class<?> remoteInterface) { super(mapper, handler, remoteInterface); } /** * Creates the server with the given {@link ObjectMapper} delegating * all calls to the given {@code handler}. * * @param mapper the {@link ObjectMapper} * @param handler the {@code handler} */ public JsonRpcServer(ObjectMapper mapper, Object handler) { super(mapper, handler, null); } /** * Creates the server with a default {@link ObjectMapper} delegating * all calls to the given {@code handler} {@link Object} but only * methods available on the {@code remoteInterface}. * * @param handler the {@code handler} * @param remoteInterface the interface */ private JsonRpcServer(Object handler, Class<?> remoteInterface) { super(new ObjectMapper(), handler, remoteInterface); } /** * Creates the server with a default {@link ObjectMapper} delegating * all calls to the given {@code handler}. * * @param handler the {@code handler} */ public JsonRpcServer(Object handler) { super(new ObjectMapper(), handler, null); } /** * Handles a portlet request. * * @param request the {@link ResourceRequest} * @param response the {@link ResourceResponse} * @throws IOException on error */ public void handle(ResourceRequest request, ResourceResponse response) throws IOException { logger.debug("Handing ResourceRequest {}", request.getMethod()); response.setContentType(JSONRPC_CONTENT_TYPE); InputStream input = getRequestStream(request); OutputStream output = response.getPortletOutputStream(); handleRequest(input, output); // fix to not flush within handleRequest() but outside so http status code can be set output.flush(); } private InputStream getRequestStream(ResourceRequest request) throws IOException { if (request.getMethod().equals("POST")) { return request.getPortletInputStream(); } else if (request.getMethod().equals("GET")) { return createInputStream(request); } else { throw new IOException("Invalid request method, only POST and GET is supported"); } } private static InputStream createInputStream(ResourceRequest request) throws IOException { return createInputStream(request.getParameter(METHOD), request.getParameter(ID), request.getParameter(PARAMS)); } /** * Handles a servlet request. * * @param request the {@link HttpServletRequest} * @param response the {@link HttpServletResponse} * @throws IOException on error */ public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { logger.debug("Handling HttpServletRequest {}", request); response.setContentType(JSONRPC_CONTENT_TYPE); OutputStream output = response.getOutputStream(); InputStream input = getRequestStream(request); int result = handleRequest(input, output); int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result) : httpStatusCodeProvider.getHttpStatusCode(result); response.setStatus(httpStatusCode); output.flush(); } private InputStream getRequestStream(HttpServletRequest request) throws IOException { InputStream input; if (request.getMethod().equals("POST")) { input = request.getInputStream(); } else if (request.getMethod().equals("GET")) { input = createInputStream(request); } else { throw new IOException("Invalid request method, only POST and GET is supported"); } return input; } private static InputStream createInputStream(HttpServletRequest request) throws IOException { return createInputStream(request.getParameter(METHOD), request.getParameter(ID), request.getParameter(PARAMS)); } }
package com.jakduk.batch.service; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.jakduk.batch.common.Constants; import com.jakduk.batch.common.JakdukUtils; import com.jakduk.batch.common.ObjectMapperUtils; import com.jakduk.batch.configuration.JakdukProperties; import com.jakduk.batch.model.db.Article; import com.jakduk.batch.model.db.ArticleComment; import com.jakduk.batch.model.db.Gallery; import com.jakduk.batch.model.elasticsearch.EsArticle; import com.jakduk.batch.model.elasticsearch.EsComment; import com.jakduk.batch.model.elasticsearch.EsGallery; import com.jakduk.batch.repository.ArticleCommentRepository; import com.jakduk.batch.repository.ArticleRepository; import com.jakduk.batch.repository.GalleryRepository; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class SearchService { @Resource private JakdukProperties.Elasticsearch elasticsearchProperties; @Autowired private RestHighLevelClient highLevelClient; @Autowired private ArticleRepository articleRepository; @Autowired private GalleryRepository galleryRepository; @Autowired private ArticleCommentRepository articleCommentRepository; public void createIndexBoard() throws IOException { String index = elasticsearchProperties.getIndexBoard(); CreateIndexRequest createIndexRequest = new CreateIndexRequest(index); createIndexRequest.settings(this.getIndexSettings()); createIndexRequest.mapping(this.getBoardMappings()); CreateIndexResponse createIndexResponse = highLevelClient.indices() .create(createIndexRequest, RequestOptions.DEFAULT); if (createIndexResponse.isAcknowledged()) { log.debug("Index " + index + " created"); } else { throw new RuntimeException("Index " + index + " not created"); } } public void createIndexGallery() throws IOException { String index = elasticsearchProperties.getIndexGallery(); CreateIndexRequest createIndexRequest = new CreateIndexRequest(index); createIndexRequest.settings(this.getIndexSettings()); createIndexRequest.mapping(this.getGalleryMappings()); CreateIndexResponse createIndexResponse = highLevelClient.indices() .create(createIndexRequest, RequestOptions.DEFAULT); if (createIndexResponse.isAcknowledged()) { log.debug("Index " + index + " created"); } else { throw new RuntimeException("Index " + index + " not created"); } } public void createIndexSearchWord() throws IOException { String index = elasticsearchProperties.getIndexSearchWord(); CreateIndexRequest createIndexRequest = new CreateIndexRequest(index); createIndexRequest.settings(this.getIndexSettings()); createIndexRequest.mapping(this.getSearchWordMappings()); CreateIndexResponse createIndexResponse = highLevelClient.indices() .create(createIndexRequest, RequestOptions.DEFAULT); if (createIndexResponse.isAcknowledged()) { log.debug("Index " + index + " created"); } else { throw new RuntimeException("Index " + index + " not created"); } } public void processBulkInsertArticle() throws InterruptedException { BulkProcessor bulkProcessor = getBulkProcessor(); Boolean hasPost = true; ObjectId lastPostId = null; do { List<Article> articles = articleRepository.findPostsGreaterThanId(lastPostId, Constants.ES_BULK_LIMIT); List<EsArticle> esArticles = articles.stream() .filter(Objects::nonNull) .map(post -> { List<String> galleryIds = null; if (post.getLinkedGallery()) { List<Gallery> galleries = galleryRepository.findByItemIdAndFromType( new ObjectId(post.getId()), Constants.GALLERY_FROM_TYPE.ARTICLE.name(), 1); galleryIds = galleries.stream() .filter(Objects::nonNull) .map(Gallery::getId) .collect(Collectors.toList()); } return EsArticle.builder() .id(post.getId()) .seq(post.getSeq()) .board(post.getBoard()) .writer(post.getWriter()) .subject(JakdukUtils.stripHtmlTag(post.getSubject())) .content(JakdukUtils.stripHtmlTag(post.getContent())) .category(StringUtils.defaultIfBlank(post.getCategory(), null)) .galleries(galleryIds) .boardJoinField(Constants.ES_TYPE_ARTICLE) .build(); }) .collect(Collectors.toList()); if (esArticles.isEmpty()) { hasPost = false; } else { EsArticle lastPost = esArticles.get(esArticles.size() - 1); lastPostId = new ObjectId(lastPost.getId()); } esArticles.forEach(post -> { try { IndexRequest indexRequest = new IndexRequest(elasticsearchProperties.getIndexBoard()); indexRequest.id(post.getId()); indexRequest.source(ObjectMapperUtils.writeValueAsString(post), XContentType.JSON); bulkProcessor.add(indexRequest); } catch (JsonProcessingException e) { log.error(e.getLocalizedMessage()); } }); } while (hasPost); bulkProcessor.awaitClose(Constants.ES_AWAIT_CLOSE_TIMEOUT_MINUTES, TimeUnit.MINUTES); } public void processBulkInsertArticleComment() throws InterruptedException { BulkProcessor bulkProcessor = getBulkProcessor(); Boolean hasComment = true; ObjectId lastCommentId = null; do { List<ArticleComment> comments = articleCommentRepository.findCommentsGreaterThanId(lastCommentId, Constants.ES_BULK_LIMIT); List<EsComment> esComments = comments.stream() .filter(Objects::nonNull) .map(comment -> { List<String> galleryIds = null; if (comment.getLinkedGallery()) { List<Gallery> galleries = galleryRepository.findByItemIdAndFromType( new ObjectId(comment.getId()), Constants.GALLERY_FROM_TYPE.ARTICLE_COMMENT.name(), 1); galleryIds = galleries.stream() .filter(Objects::nonNull) .map(Gallery::getId) .collect(Collectors.toList()); } return EsComment.builder() .id(comment.getId()) .article(comment.getArticle()) .writer(comment.getWriter()) .content(JakdukUtils.stripHtmlTag(comment.getContent())) .galleries(galleryIds) .boardJoinField( new HashMap<String, Object>() {{ put("name", Constants.ES_TYPE_COMMENT); put("parent", comment.getArticle().getId()); }} ) .build(); }) .collect(Collectors.toList()); if (esComments.isEmpty()) { hasComment = false; } else { EsComment lastComment = esComments.get(esComments.size() - 1); lastCommentId = new ObjectId(lastComment.getId()); } esComments.forEach(comment -> { try { IndexRequest indexRequest = new IndexRequest(elasticsearchProperties.getIndexBoard()); indexRequest.id(comment.getId()); indexRequest.source(ObjectMapperUtils.writeValueAsString(comment), XContentType.JSON); bulkProcessor.add(indexRequest); } catch (JsonProcessingException e) { log.error(e.getLocalizedMessage()); } }); } while (hasComment); bulkProcessor.awaitClose(Constants.ES_AWAIT_CLOSE_TIMEOUT_MINUTES, TimeUnit.MINUTES); } public void processBulkInsertGallery() throws InterruptedException { BulkProcessor bulkProcessor = getBulkProcessor(); Boolean hasGallery = true; ObjectId lastGalleryId = null; do { List<EsGallery> comments = galleryRepository.findGalleriesGreaterThanId(lastGalleryId, Constants.ES_BULK_LIMIT); if (comments.isEmpty()) { hasGallery = false; } else { EsGallery lastGallery = comments.get(comments.size() - 1); lastGalleryId = new ObjectId(lastGallery.getId()); } comments.forEach(comment -> { try { IndexRequest indexRequest = new IndexRequest(elasticsearchProperties.getIndexGallery(), Constants.ES_TYPE_GALLERY, comment.getId()); indexRequest.source(ObjectMapperUtils.writeValueAsString(comment), XContentType.JSON); bulkProcessor.add(indexRequest); } catch (JsonProcessingException e) { log.error(e.getLocalizedMessage()); } }); } while (hasGallery); bulkProcessor.awaitClose(Constants.ES_AWAIT_CLOSE_TIMEOUT_MINUTES, TimeUnit.MINUTES); } public void deleteIndexBoard() throws IOException { String index = elasticsearchProperties.getIndexBoard(); AcknowledgedResponse response = highLevelClient.indices() .delete(new DeleteIndexRequest(index), RequestOptions.DEFAULT); if (response.isAcknowledged()) { log.debug("Index {} deleted." + index); } else { throw new RuntimeException("Index " + index + " not deleted"); } } public void deleteIndexGallery() throws IOException { String index = elasticsearchProperties.getIndexGallery(); AcknowledgedResponse response = highLevelClient.indices() .delete(new DeleteIndexRequest(index), RequestOptions.DEFAULT); if (response.isAcknowledged()) { log.debug("Index {} deleted." + index); } else { throw new RuntimeException("Index " + index + " not deleted"); } } public void deleteIndexSearchWord() throws IOException { String index = elasticsearchProperties.getIndexSearchWord(); AcknowledgedResponse response = highLevelClient.indices() .delete(new DeleteIndexRequest(index), RequestOptions.DEFAULT); if (response.isAcknowledged()) { log.debug("Index {} deleted." + index); } else { throw new RuntimeException("Index " + index + " not deleted"); } } private BulkProcessor getBulkProcessor() { BulkProcessor.Listener bulkProcessorListener = new BulkProcessor.Listener() { @Override public void beforeBulk(long l, BulkRequest bulkRequest) { } @Override public void afterBulk(long l, BulkRequest bulkRequest, BulkResponse bulkResponse) { log.debug("bulk took: {}", bulkResponse.getTook()); if (bulkResponse.hasFailures()) log.error(bulkResponse.buildFailureMessage()); } @Override public void afterBulk(long l, BulkRequest bulkRequest, Throwable throwable) { log.error(throwable.getLocalizedMessage()); } }; return BulkProcessor.builder( (bulkRequest, bulkResponseActionListener) -> highLevelClient.bulkAsync(bulkRequest, RequestOptions.DEFAULT, bulkResponseActionListener), bulkProcessorListener) .setBulkActions(elasticsearchProperties.getBulkActions()) .setBulkSize(new ByteSizeValue(elasticsearchProperties.getBulkSizeMb(), ByteSizeUnit.MB)) .setFlushInterval(TimeValue.timeValueSeconds(elasticsearchProperties.getBulkFlushIntervalSeconds())) .setConcurrentRequests(elasticsearchProperties.getBulkConcurrentRequests()) .build(); } private Settings.Builder getIndexSettings() { String[] userWords = new String[] { "k", "k1", "k2", "k3", "k4", "fc", "fc", "utd", "", "fc", "fc", "fc", "fc", "fc", "fc", "fc", "utd", "", "e" }; return Settings.builder() .put("analysis.tokenizer.korean.type", "nori_tokenizer") .putList("analysis.tokenizer.korean.user_dictionary_rules", userWords) .put("analysis.tokenizer.korean.decompound_mode", "none"); } private Map getBoardMappings() { return new HashMap<String, Object>() {{ put("properties", new HashMap<String, Object>() {{ put("id", new HashMap<String, String>() {{ put("type", "string"); }}); put("seq", new HashMap<String, String>() {{ put("type", "integer"); put("index", "no"); }}); put("board", new HashMap<String, String>() {{ put("type", "string"); put("index", "not_analyzed"); }}); put("category", new HashMap<String, String>() {{ put("type", "string"); put("index", "not_analyzed"); }}); put("subject", new HashMap<String, String>() {{ put("type", "string"); put("analyzer", "korean"); }}); put("content", new HashMap<String, String>() {{ put("type", "string"); put("analyzer", "korean"); }}); put("galleries", new HashMap<String, String>() {{ put("type", "string"); put("index", "no"); }}); put("writer", new HashMap<String, Object>() {{ put("properties", new HashMap<String, Object>() {{ put("providerId", new HashMap<String, String>() {{ put("type", "string"); put("index", "no"); }}); put("userId", new HashMap<String, String>() {{ put("type", "string"); put("index", "no"); }}); put("username", new HashMap<String, String>() {{ put("type", "string"); put("index", "no"); }}); }}); }}); put("registerDate", new HashMap<String, String>() {{ put("type", "date"); }}); // for Comment Index put("article", new HashMap<String, Object>() {{ put("properties", new HashMap<String, Object>() {{ put("id", new HashMap<String, String>() {{ put("type", "string"); put("index", "no"); }}); put("seq", new HashMap<String, String>() {{ put("type", "integer"); put("index", "no"); }}); put("board", new HashMap<String, String>() {{ put("type", "string"); put("index", "no"); }}); }}); }}); // for Join field type put("boardJoinField", new HashMap<String, Object>() {{ put("type", "join"); put("relations", new HashMap<String, String>() {{ put(Constants.ES_TYPE_ARTICLE, Constants.ES_TYPE_COMMENT); }}); }}); }}); }}; } private Map<String, Object> getGalleryMappings() { ObjectMapper objectMapper = ObjectMapperUtils.getObjectMapper(); ObjectNode idNode = objectMapper.createObjectNode(); idNode.put("type", "string"); ObjectNode nameNode = objectMapper.createObjectNode(); nameNode.put("type", "string"); nameNode.put("analyzer", "korean"); // writer ObjectNode writerProviderIdNode = objectMapper.createObjectNode(); writerProviderIdNode.put("type", "string"); writerProviderIdNode.put("index", "no"); ObjectNode writerUserIdNode = objectMapper.createObjectNode(); writerUserIdNode.put("type", "string"); writerUserIdNode.put("index", "no"); ObjectNode writerUsernameNode = objectMapper.createObjectNode(); writerUsernameNode.put("type", "string"); writerUsernameNode.put("index", "no"); ObjectNode writerPropertiesNode = objectMapper.createObjectNode(); writerPropertiesNode.set("providerId", writerProviderIdNode); writerPropertiesNode.set("userId", writerUserIdNode); writerPropertiesNode.set("username", writerUsernameNode); ObjectNode writerNode = objectMapper.createObjectNode(); writerNode.set("properties", writerPropertiesNode); // properties ObjectNode propertiesNode = objectMapper.createObjectNode(); propertiesNode.set("id", idNode); propertiesNode.set("name", nameNode); propertiesNode.set("writer", writerNode); ObjectNode mappings = objectMapper.createObjectNode(); mappings.set("properties", propertiesNode); return objectMapper.convertValue(mappings, Map.class); } private Map<String, Object> getSearchWordMappings() { ObjectMapper objectMapper = ObjectMapperUtils.getObjectMapper(); JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance; ObjectNode propertiesNode = jsonNodeFactory.objectNode(); propertiesNode.set("id", jsonNodeFactory.objectNode() .put("type", "string")); propertiesNode.set("word", jsonNodeFactory.objectNode() .put("type", "string") .put("index", "not_analyzed") ); ObjectNode writerNode = jsonNodeFactory.objectNode(); writerNode.set("providerId", jsonNodeFactory.objectNode().put("type", "string").put("index", "no")); writerNode.set("userId", jsonNodeFactory.objectNode().put("type", "string").put("index", "no")); writerNode.set("username", jsonNodeFactory.objectNode().put("type", "string").put("index", "no")); propertiesNode.set("writer", jsonNodeFactory.objectNode().set("properties", writerNode)); propertiesNode.set("registerDate", jsonNodeFactory.objectNode() .put("type", "date") ); ObjectNode mappings = jsonNodeFactory.objectNode(); mappings.set("properties", propertiesNode); return objectMapper.convertValue(mappings, Map.class); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.malhartech.netlet; import com.malhartech.netlet.Listener.ClientListener; import com.malhartech.netlet.Listener.ServerListener; import com.malhartech.util.CircularBuffer; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.*; import java.nio.channels.spi.AbstractSelectableChannel; import java.util.Iterator; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Chetan Narsude <chetan@malhar-inc.com> */ public class DefaultEventLoop implements Runnable, EventLoop { public final String id; private boolean alive; private int refCount; private Selector selector; private Thread eventThread; private final CircularBuffer<Runnable> tasks = new CircularBuffer<Runnable>(1024, 5); public DefaultEventLoop(String id) throws IOException { this.id = id; selector = Selector.open(); } public synchronized void start() { if (++refCount == 1) { new Thread(this, id).start(); } } public void stop() { submit(new Runnable() { @Override public void run() { synchronized (DefaultEventLoop.this) { if (--refCount == 0) { alive = false; } } } }); } @Override @SuppressWarnings({"SleepWhileInLoop", "null", "ConstantConditions"}) public void run() { logger.info("Starting event loop {}", this); alive = true; eventThread = Thread.currentThread(); boolean wait = true; SelectionKey sk = null; Set<SelectionKey> selectedKeys = null; Iterator<SelectionKey> iterator = null; do { try { do { if (wait) { if (selector.selectNow() > 0) { selectedKeys = selector.selectedKeys(); iterator = selectedKeys.iterator(); } else { iterator = null; } } if (iterator != null) { wait = false; while (iterator.hasNext()) { if (!(sk = iterator.next()).isValid()) { continue; } ClientListener l; switch (sk.readyOps()) { case SelectionKey.OP_ACCEPT: ServerSocketChannel ssc = (ServerSocketChannel)sk.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); ServerListener sl = (ServerListener)sk.attachment(); l = sl.getClientConnection(sc, (ServerSocketChannel)sk.channel()); register(sc, SelectionKey.OP_READ | SelectionKey.OP_WRITE, l); break; case SelectionKey.OP_CONNECT: ((SocketChannel)sk.channel()).finishConnect(); sk.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); break; case SelectionKey.OP_READ: ((ClientListener)sk.attachment()).read(); break; case SelectionKey.OP_WRITE: ((ClientListener)sk.attachment()).write(); break; case SelectionKey.OP_READ | SelectionKey.OP_WRITE: (l = (ClientListener)sk.attachment()).write(); l.read(); break; case SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT: case SelectionKey.OP_READ | SelectionKey.OP_CONNECT: case SelectionKey.OP_READ | SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT: logger.debug("!!!!!! connect interest was ready along with read or write = {} !!!!!!!", Integer.toBinaryString(sk.readyOps())); ((SocketChannel)sk.channel()).finishConnect(); sk.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); if (sk.isWritable()) { ((ClientListener)sk.attachment()).write(); } if (sk.isReadable()) { ((ClientListener)sk.attachment()).read(); } break; default: logger.debug("!!!!!! not sure what interest this is {} !!!!!!", Integer.toBinaryString(sk.readyOps())); break; } } selectedKeys.clear(); } int size = tasks.size(); if (size > 0) { wait = false; do { tasks.pollUnsafe().run(); } while (--size > 0); } if (wait) { Thread.sleep(5); } else { wait = true; } } while (alive); } catch (InterruptedException ie) { throw new RuntimeException("Interrupted!", ie); } catch (Exception io) { if (sk == null) { logger.warn("Unexpected exception not related to SelectionKey", io); } else { Listener l = (Listener)sk.attachment(); if (l == null) { logger.warn("Exception on unregistered SelectionKey", io); } else { l.handleException(io, this); } } if (selectedKeys.isEmpty()) { wait = true; } } } while (alive); logger.info("Terminated event loop {}", this); } @Override public void submit(Runnable r) { if (tasks.isEmpty() && eventThread == Thread.currentThread()) { r.run(); } else { synchronized (tasks) { tasks.add(r); } } } private void register(final SelectableChannel c, final int ops, final Listener l) { submit(new Runnable() { @Override public void run() { try { l.registered(c.register(selector, ops, l)); } catch (ClosedChannelException cce) { l.handleException(cce, DefaultEventLoop.this); } } }); } @Override public void unregister(final SelectableChannel c) { submit(new Runnable() { @Override public void run() { for (SelectionKey key: selector.keys()) { if (key.channel() == c) { ((Listener)key.attachment()).unregistered(key); key.interestOps(0); key.attach(Listener.NOOP_LISTENER); } } } }); } @Override public void register(ServerSocketChannel channel, Listener l) { register(channel, SelectionKey.OP_ACCEPT, l); } @Override public void register(SocketChannel channel, int ops, Listener l) { register((AbstractSelectableChannel)channel, ops, l); } @Override public final void connect(final InetSocketAddress address, final Listener l) { submit(new Runnable() { @Override public void run() { SocketChannel channel = null; try { channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(address); register(channel, SelectionKey.OP_CONNECT, l); } catch (IOException ie) { l.handleException(ie, DefaultEventLoop.this); if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException io) { l.handleException(io, DefaultEventLoop.this); } } } } }); } @Override public final void disconnect(final ClientListener l) { submit(new Runnable() { @Override public void run() { for (SelectionKey key: selector.keys()) { if (key.attachment() == l) { if (key.isValid()) { l.unregistered(key); if ((key.interestOps() & SelectionKey.OP_WRITE) != 0) { key.attach(new Listener.DisconnectingListener(key)); return; } } try { key.attach(Listener.NOOP_CLIENT_LISTENER); key.channel().close(); } catch (IOException io) { l.handleException(io, DefaultEventLoop.this); } } } } }); } @Override public final void start(final String host, final int port, final ServerListener l) { submit(new Runnable() { @Override public void run() { ServerSocketChannel channel = null; try { channel = ServerSocketChannel.open(); channel.configureBlocking(false); channel.socket().bind(host == null ? new InetSocketAddress(port) : new InetSocketAddress(host, port), 128); register(channel, SelectionKey.OP_ACCEPT, l); } catch (IOException io) { l.handleException(io, DefaultEventLoop.this); if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException ie) { l.handleException(ie, DefaultEventLoop.this); } } } } }); } @Override public final void stop(final ServerListener l) { submit(new Runnable() { @Override public void run() { for (SelectionKey key: selector.keys()) { if (key.attachment() == l) { if (key.isValid()) { l.unregistered(key); key.cancel(); } key.attach(Listener.NOOP_LISTENER); try { key.channel().close(); } catch (IOException io) { l.handleException(io, DefaultEventLoop.this); } } } } }); } public boolean isActive() { return eventThread != null && eventThread.isAlive(); } private static final Logger logger = LoggerFactory.getLogger(DefaultEventLoop.class); }
package com.meiziaccess; import com.meiziaccess.CommandTool.MyHttpUtil; import com.meiziaccess.model.ItemMedia; import com.meiziaccess.model.ItemMediaRepository; import com.meiziaccess.model.UploadItem; import com.meiziaccess.model.UploadRepository; import com.meiziaccess.upload.UploadTool; import com.meiziaccess.upload.UploadToolInterface; import com.meiziaccess.uploadModel.UploadLogRepository; import net.sf.json.JSONObject; import org.apache.commons.collections.map.HashedMap; import org.apache.poi.ss.usermodel.Workbook; import org.jeecgframework.poi.excel.ExcelExportUtil; import org.jeecgframework.poi.excel.entity.ExportParams; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; @SpringBootApplication @RestController @EnableRedisHttpSession //@EnableScheduling public class MeiziaccessApplication { @Autowired UploadRepository uploadRepository; // private int vendor_type = 1; @RequestMapping(value = "/authenticate") public Map<String, Object> authenticate(HttpServletRequest request){ Map<String, Object> model = new HashMap<String, Object>(); if(request.getSession().getAttribute("username") != null){ System.out.println("session-get-username=" + request.getSession().getAttribute("username").toString()); model.put("status", true); return model; } String username = request.getParameter("username"); String password = request.getParameter("password"); JSONObject objData = MyHttpUtil.post(username, password); if(objData == null){ model.put("status", false); }else{ if(objData.getInt("code") == 200){ model.put("status", true); int vendor_type = objData.getInt("data"); System.out.println("session-set-username=" + username); request.getSession().setAttribute("username", username); request.getSession().setAttribute("vendor_type", vendor_type); System.out.println(objData.toString()); }else{ model.put("status", false); } } return model; } @RequestMapping(value = "/logout") public Map<String, Object> logout(HttpServletRequest request){ Map<String, Object> model = new HashMap<String, Object>(); if(request.getSession().getAttribute("username") != null){ System.out.println("session-delete-username=" + request.getSession().getAttribute("username").toString()); request.getSession().removeAttribute("username"); request.getSession().removeAttribute("vendor_type"); return model; } model.put("status", false); return model; } @Value("${configure.upload.local_path}") private String upload_local_path; //xml,home @RequestMapping("/data-source-association") @ResponseBody public Map<String, Object> getItemsAssociation(HttpServletRequest request) { Object name = request.getSession().getAttribute("username"); Map<String, Object> map = new HashMap<>(); if (name == null){ List<UploadItem> uploadItems = new ArrayList<>(); map.put("data",uploadItems); }else{ Object type = request.getSession().getAttribute("vendor_type"); int vendor_type = Integer.parseInt(type.toString()); List<UploadItem> uploadItems = uploadRepository.findByStatusAndVendor_typeAndToken(0,vendor_type,0); map.put("data",uploadItems); } return map; } /** * * 1 * 2 BTV * 3 * 4 * 5 */ //xml,home @RequestMapping("/data-refresh-association") @ResponseBody public boolean refreshItemsAssociation(HttpServletRequest request) { System.out.println(" " + upload_local_path); Object o = request.getSession().getAttribute("vendor_type"); if (o == null) { return false; } int vendor_type = Integer.parseInt(o.toString()); List<UploadItem> list = UploadTool.getUploadItemsAssociation(upload_local_path, vendor_type); /* search in database*/ // System.out.println(" "); // List<UploadItem> uploadList = uploadRepository.findAll(); // list.removeAll(uploadList); // map.put("data", list); System.out.println("list"); System.out.println(list.get(0).getPath()); if (list.isEmpty()) { System.out.println(""); } else{ for (int i = 0; i < list.size(); i++) { if (uploadRepository.findByTitle(list.get(i).getTitle()).isEmpty()) { list.get(i).setUpload_time(new Date()); list.get(i).setUpload(true); list.get(i).setVendor_type(vendor_type); uploadRepository.save(list.get(i)); } else { System.out.println(list.get(i).getTitle()+""); } } } return true; } @Value("${configure.upload.remote_path}") String upload_remote_path; @Autowired UploadLogRepository uploadLogRepository; @Value("${configure.upload.vendor_name}") String vendor_name; @Value("${configure.local.vendor_path}") String vendor_path; @Value("${configure.upload.uploader_name}") String uploader_name; @Value("${configure.upload.trans_path}") String trans_path; @Value("${configure.upload.play_path}") String play_path; public boolean updateDatabase(List<UploadItem> list){ for(UploadItem item : list){ item.setUpload_time(new Date()); item.setUpload(true); uploadRepository.save(item); } return true; } // public boolean upField(List<UploadItem> li){ // for (UploadItem item : li){ // item.setUpload_time(new Date()); // item.setStatus(1); // return true; @RequestMapping(value = "/upload-association", produces = "application/json;charset=UTF-8", method = RequestMethod.POST) @ResponseBody public Map<String, Object> uploadItemsAssociation(@RequestBody UploadItem item, HttpServletRequest request) { Map<String, Object> map = new HashMap<>(); if (item == null){ map.put("status", false); return map; } List<UploadItem> list = new ArrayList<>(); list.add(item); UploadToolInterface tool = new UploadTool(); Object o = request.getSession().getAttribute("vendor_type"); if(o == null){ map.put("status", false); return map; } item.setStatus(1); updateDatabase(list); int vendor_type = Integer.parseInt(o.toString()); tool.uploadItemDirsAssociation(upload_remote_path, list, uploadLogRepository, ""+vendor_type, vendor_path, uploader_name, trans_path, play_path); map.put("status", true); return map; } public static void main(String[] args) { SpringApplication.run(MeiziaccessApplication.class, args); } @RequestMapping(value = "/delete-association", produces = "application/json;charset=UTF-8", method = RequestMethod.POST) @ResponseBody public Map<String, Object> deleteItemsAssociation(@RequestBody UploadItem item, HttpServletRequest request) { Map<String , Object> map = new HashedMap(); if (item == null){ map.put("status", false); return map; } List<UploadItem> list = new ArrayList<>(); list.add(item); for (int i=0;i<list.size();i++){ uploadRepository.delete(list.get(i).getId()); } UploadToolInterface tool = new UploadTool(); tool.deleteItemDirsAssociation(item); map.put("status", true); return map; } @RequestMapping( "/upload_audit_data" ) public Map<String, Object> upload_audit(HttpServletRequest request){ Object name = request.getSession().getAttribute("username"); Map<String, Object> map = new HashMap<>(); if(name == null){ List<UploadItem> uploadItems = new ArrayList<>(); map.put("data",uploadItems); }else { Object o = request.getSession().getAttribute("vendor_type"); int vendor_type = Integer.parseInt(o.toString()); List<UploadItem> uploadItems = uploadRepository.findByStatusAndVendor_typeAndToken(1, vendor_type, 0); //Map<String, Object> map = new HashMap<>(); map.put("data", uploadItems); } return map; } @RequestMapping("/upload_pass_data") public Map<String, Object> upload_pass(HttpServletRequest request){ Object name = request.getSession().getAttribute("username"); Map<String, Object> map = new HashedMap(); if (name == null){ List<UploadItem> uploadItems = new ArrayList<>(); map.put("data",uploadItems); }else { Object o =request.getSession().getAttribute("vendor_type"); int vendor_type = Integer.parseInt(o.toString()); List<UploadItem> uploadItems = uploadRepository.findByStatusAndVendor_typeAndToken(1, vendor_type, 99); map.put("data", uploadItems); } return map; } @RequestMapping("/upload_not_pass_data") public Map<String, Object> upload_not_pass(HttpServletRequest request){ Object name = request.getSession().getAttribute("username"); Map<String, Object> map = new HashedMap(); if (name == null){ List<UploadItem> uploadItems = new ArrayList<>(); map.put("data",uploadItems); }else { Object o =request.getSession().getAttribute("vendor_type"); int vendor_type = Integer.parseInt(o.toString()); List<UploadItem> uploadItems = uploadRepository.findByStatusAndVendor_typeAndToken(1, vendor_type, 2); map.put("data", uploadItems); } return map; } @Autowired ItemMediaRepository itemMediaRepository; @RequestMapping("/indent_data") public Map<String, Object> indent(){ List<ItemMedia> itemMedias = itemMediaRepository.findAll(); Map<String, Object> map = new HashMap<>(); map.put("data",itemMedias); return map; } @RequestMapping(value = "/export", method = RequestMethod.GET) public void export(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename="+new Date().toLocaleString()+".xls"); List<ItemMedia> list = itemMediaRepository.findAll(); Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ItemMedia.class, list); workbook.write(response.getOutputStream()); } @RequestMapping(value = "/sold_out_del", produces = "application/json;charset=UTF-8", method = RequestMethod.POST) @ResponseBody public Map<String, Object> soldDel(@RequestBody UploadItem item){ Map<String, Object> map = new HashedMap(); List<UploadItem> list = new ArrayList<>(); list.add(item); for (int i=0;i<list.size();i++){ uploadRepository.delMd5(list.get(i).getMd5()); } UploadToolInterface tool = new UploadTool(); tool.deleteItemDirsAssociation(item); map.put("status", true); return map; } @RequestMapping(value = "/sold_out_return", produces = "application/json;charset=UTF-8", method = RequestMethod.POST) @ResponseBody public Map<String, Object> soldReturn(@RequestBody UploadItem item){ Map<String, Object> map = new HashedMap(); //informpriceprice_typestatustoken List<UploadItem> list = new ArrayList<>(); list.add(item); for (int i=0;i<list.size();i++){ uploadRepository.updataBymd5(list.get(i).getMd5()); } map.put("status",true); return map; } }
package com.molina.cvmfs.common; import org.sqlite.SQLiteConfig; import java.io.File; import java.sql.*; import java.util.HashMap; import java.util.Map; /** * @author Jose Molina Colmenero */ public class DatabaseObject { protected File databaseFile; private Connection connection; public DatabaseObject(File databaseFile) throws IllegalStateException, SQLException { this.databaseFile = databaseFile; if (this.databaseFile != null && this.databaseFile.exists()) { openDatabase(); } else { throw new IllegalStateException("Database file is null or doesn't exist"); } } /** * Create and configure a database handle to the Catalog */ protected void openDatabase() throws SQLException { try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { connection = null; return; } SQLiteConfig config = new SQLiteConfig(); config.setReadOnly(true); connection = config.createConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath()); connection.setAutoCommit(false); } public boolean open() { try { openDatabase(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public boolean recycle() { return isOpenned() && close() && open(); } public boolean isOpenned() { try { return connection != null && !connection.isClosed(); } catch (SQLException e) { e.printStackTrace(); return false; } } public boolean close() { try { connection.close(); connection = null; return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public long databaseSize() { return databaseFile.length(); } /** * Retrieve all properties stored in the 'properties' table */ public Map<String, Object> readPropertiesTable() throws SQLException { ResultSet rs = runSQL("SELECT key, value FROM properties;"); Map<String, Object> result = new HashMap<String, Object>(); while (rs.next()) { result.put(rs.getString(1), rs.getObject(2)); } rs.close(); rs.getStatement().close(); return result; } /** * Run an arbitrary SQL query on the catalog database * * @param sqlQuery query to run in the database * @return the ResultSet obtained after executing the query */ public ResultSet runSQL(String sqlQuery) throws SQLException { Statement statement = connection.createStatement(); return statement.executeQuery(sqlQuery); } }
package com.mossle.bpm.parser; import org.activiti.engine.impl.bpmn.parser.BpmnParser; import org.activiti.engine.impl.bpmn.parser.factory.ActivityBehaviorFactory; import org.activiti.engine.impl.bpmn.parser.factory.DefaultActivityBehaviorFactory; public class CustomBpmnParser extends BpmnParser{ public void setActivityBehaviorFactory(ActivityBehaviorFactory activityBehaviorFactory) { // TODO .serviceTask ((DefaultActivityBehaviorFactory)activityBehaviorFactory).setExpressionManager(expressionManager); super.setActivityBehaviorFactory(activityBehaviorFactory); } }
package com.oneliang.tools.autodex; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.oneliang.Constant; import com.oneliang.thirdparty.asm.util.AsmUtil; import com.oneliang.thirdparty.asm.util.AsmUtil.FieldProcessor; import com.oneliang.thirdparty.asm.util.ClassDescription; import com.oneliang.tools.dex.DexUtil; import com.oneliang.tools.linearalloc.AllocClassVisitor.MethodReference; import com.oneliang.tools.linearalloc.LinearAllocUtil; import com.oneliang.tools.linearalloc.LinearAllocUtil.AllocStat; import com.oneliang.util.common.Generator; import com.oneliang.util.common.JavaXmlUtil; import com.oneliang.util.common.ObjectUtil; import com.oneliang.util.common.StringUtil; import com.oneliang.util.file.FileUtil; import com.oneliang.util.logging.Logger; import com.oneliang.util.logging.LoggerManager; public final class AutoDexUtil { private static final Logger logger = LoggerManager.getLogger(AutoDexUtil.class); private static final String CLASSES="classes"; private static final String DEX="dex"; private static final String AUTO_DEX_DEX_CLASSES_PREFIX="dexClasses"; /** * find main class list from android manifest * @return List<String> */ public static List<String> findMainDexClassListFromAndroidManifest(String androidManifestFullFilename,boolean attachBaseContextMultiDex){ List<String> mainDexClassList=new ArrayList<String>(); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); try{ Document document = JavaXmlUtil.parse(new FileInputStream(androidManifestFullFilename)); String applicationName=findApplication(xPath, document); if(StringUtil.isNotBlank(applicationName)){ mainDexClassList.add(applicationName); } if(!attachBaseContextMultiDex){ mainDexClassList.addAll(findActivity(xPath, document)); mainDexClassList.addAll(findProvider(xPath, document)); mainDexClassList.addAll(findReceiver(xPath, document)); mainDexClassList.addAll(findService(xPath, document)); } }catch(Exception e){ throw new AutoDexUtilException(e); } return mainDexClassList; } /** * find application * @param xPath * @param document * @return String * @throws Exception */ private static String findApplication(XPath xPath,Document document) throws Exception{ String applicationName=null; //application NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application[@*]", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); Node nameNode=node.getAttributes().getNamedItem("android:name"); if(nameNode!=null){ applicationName=nameNode.getTextContent(); logger.verbose(applicationName); } } } return applicationName; } /** * find activity * @param xPath * @param document * @return List<String> * @throws Exception */ private static List<String> findActivity(XPath xPath,Document document) throws Exception{ List<String> mainActivityList=new ArrayList<String>(); NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application/activity", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); String activityName=node.getAttributes().getNamedItem("android:name").getTextContent(); Node activityExportedNode=node.getAttributes().getNamedItem("android:exported"); if(activityExportedNode!=null){ boolean exported=Boolean.parseBoolean(activityExportedNode.getTextContent()); if(exported){ logger.verbose(activityName); mainActivityList.add(activityName); } }else{ Element element=(Element)node; NodeList actionNodeList=element.getElementsByTagName("action"); if(actionNodeList.getLength()>0){ // logger.verbose(activityName); // mainActivityList.add(activityName); } for(int j=0;j<actionNodeList.getLength();j++){ Node activityActionNode=actionNodeList.item(j).getAttributes().getNamedItem("android:name"); if(activityActionNode!=null){ String activityActionName=activityActionNode.getTextContent(); if(activityActionName.equals("android.intent.action.MAIN")){ logger.verbose(activityName); mainActivityList.add(activityName); } } } } } } return mainActivityList; } /** * find provider * @param xPath * @param document * @return List<String> * @throws Exception */ private static List<String> findProvider(XPath xPath,Document document) throws Exception{ List<String> providerList=new ArrayList<String>(); NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application/provider", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); Node nameNode=node.getAttributes().getNamedItem("android:name"); if(nameNode!=null){ // Node providerExportedNode=node.getAttributes().getNamedItem("android:exported"); // if(providerExportedNode!=null){ // boolean exported=Boolean.parseBoolean(providerExportedNode.getTextContent()); // if(exported){ String providerName=nameNode.getTextContent(); logger.verbose(providerName); providerList.add(providerName); } } } return providerList; } /** * find receiver * @param xPath * @param document * @return List<String> * @throws Exception */ private static List<String> findReceiver(XPath xPath,Document document) throws Exception{ List<String> receiverList=new ArrayList<String>(); NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application/receiver", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); Node nameNode=node.getAttributes().getNamedItem("android:name"); if(nameNode!=null){ Node receiverExportedNode=node.getAttributes().getNamedItem("android:exported"); String receiverName=nameNode.getTextContent(); boolean needToCheckAgain=false; if(receiverExportedNode!=null){ boolean exported=Boolean.parseBoolean(receiverExportedNode.getTextContent()); if(exported){ logger.verbose(receiverName); receiverList.add(receiverName); }else{ needToCheckAgain=true; } }else{ needToCheckAgain=true; } if(needToCheckAgain){ Element element=(Element)node; NodeList actionNodeList=element.getElementsByTagName("action"); if(actionNodeList.getLength()>0){ logger.verbose(receiverName); receiverList.add(receiverName); } } } } } return receiverList; } /** * find service * @param xPath * @param document * @return List<String> * @throws Exception */ private static List<String> findService(XPath xPath,Document document) throws Exception{ List<String> serviceList=new ArrayList<String>(); NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application/service", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); Node nameNode=node.getAttributes().getNamedItem("android:name"); if(nameNode!=null){ String serviceName=nameNode.getTextContent(); Node serviceExportedNode=node.getAttributes().getNamedItem("android:exported"); boolean needToCheckAgain=false; if(serviceExportedNode!=null){ boolean exported=Boolean.parseBoolean(serviceExportedNode.getTextContent()); if(exported){ logger.verbose(serviceName); serviceList.add(serviceName); }else{ needToCheckAgain=true; } }else{ needToCheckAgain=true; } if(needToCheckAgain){ Element element=(Element)node; NodeList actionNodeList=element.getElementsByTagName("action"); if(actionNodeList.getLength()>0){ logger.verbose(serviceName); serviceList.add(serviceName); } } } } } return serviceList; } /** * auto dex * * @param option */ public static void autoDex(Option option) { autoDex(option, null); } /** * auto dex * @param option * @param result */ public static void autoDex(Option option, Result result) { if (result == null) { result = new Result(); } String outputDirectory=new File(option.outputDirectory).getAbsolutePath(); FileUtil.createDirectory(outputDirectory); long outerBegin=System.currentTimeMillis(); long innerBegin=outerBegin; List<String> classNameList=new ArrayList<String>(); //parse android manifest and package name String packageName=null; if(option.androidManifestFullFilename!=null&&FileUtil.isExist(option.androidManifestFullFilename)){ classNameList.addAll(findMainDexClassListFromAndroidManifest(option.androidManifestFullFilename,option.attachBaseContext)); packageName=parsePackageName(option.androidManifestFullFilename); } //read all combined class String cacheFullFilename=outputDirectory+Constant.Symbol.SLASH_LEFT+"cache.txt"; Cache cache=readAllCombinedClassWithCacheFile(option.combinedClassList, cacheFullFilename); //find main root class if(option.mainDexOtherClassList!=null){ classNameList.addAll(option.mainDexOtherClassList); } Set<String> mainDexRootClassNameSet=new HashSet<String>(); if(option.combinedClassList!=null){ mainDexRootClassNameSet.addAll(findMainRootClassSet(cache.classNameByteArrayMap.keySet(), packageName, classNameList)); } for(String className:mainDexRootClassNameSet){ logger.verbose("Main root class:"+className); } Map<Integer,Map<String,String>> dexIdClassNameMap=null; //find all dex class if(cache.dexIdClassNameMap!=null&&!cache.dexIdClassNameMap.isEmpty()){ dexIdClassNameMap=cache.dexIdClassNameMap; result.dexIdClassNameMap = dexIdClassNameMap; String incrementalDirectory=outputDirectory+Constant.Symbol.SLASH_LEFT+"incremental"; FileUtil.deleteAllFile(incrementalDirectory); FileUtil.createDirectory(incrementalDirectory); Map<Integer, Map<String, String>> changedDexIdClassNameMap=new HashMap<Integer, Map<String,String>>(); Map<Integer,Map<String,byte[]>> dexIdClassNameByteArrayMap=new HashMap<Integer,Map<String,byte[]>>(); if(cache.incrementalClassNameByteArrayMap!=null&&!cache.incrementalClassNameByteArrayMap.isEmpty()){ Iterator<Entry<String,byte[]>> incrementalClassNameIterator=cache.incrementalClassNameByteArrayMap.entrySet().iterator(); int dexId=0; while(incrementalClassNameIterator.hasNext()){ Entry<String,byte[]> incrementalEntry=incrementalClassNameIterator.next(); String className=incrementalEntry.getKey(); Map<String, String> changedClassNameMap=null; if(changedDexIdClassNameMap.containsKey(dexId)){ changedClassNameMap=changedDexIdClassNameMap.get(dexId); }else{ changedClassNameMap=new HashMap<String,String>(); changedDexIdClassNameMap.put(dexId, changedClassNameMap); } changedClassNameMap.put(className, className); Map<String, byte[]> classNameByteArrayMap=null; if(dexIdClassNameByteArrayMap.containsKey(dexId)){ classNameByteArrayMap=dexIdClassNameByteArrayMap.get(dexId); }else{ classNameByteArrayMap=new HashMap<String, byte[]>(); dexIdClassNameByteArrayMap.put(dexId, classNameByteArrayMap); } classNameByteArrayMap.put(className, incrementalEntry.getValue()); } } if(cache.modifiedClassNameByteArrayMap!=null&&!cache.modifiedClassNameByteArrayMap.isEmpty()){ Iterator<Entry<String,byte[]>> modifiedClassNameIterator=cache.modifiedClassNameByteArrayMap.entrySet().iterator(); while(modifiedClassNameIterator.hasNext()){ Entry<String,byte[]> modifiedEntry=modifiedClassNameIterator.next(); String className=modifiedEntry.getKey(); Iterator<Entry<Integer, Map<String, String>>> dexIdClassNameIterator=cache.dexIdClassNameMap.entrySet().iterator(); while(dexIdClassNameIterator.hasNext()){ Entry<Integer, Map<String, String>> dexIdClassNameEntry=dexIdClassNameIterator.next(); int dexId=dexIdClassNameEntry.getKey(); Map<String, String> classNameMap=dexIdClassNameEntry.getValue(); if(classNameMap.containsKey(className)){ // FileUtil.writeFile(incrementalDirectory+Constant.Symbol.SLASH_LEFT+dexId+Constant.Symbol.SLASH_LEFT+modifiedEntry.getKey(), modifiedEntry.getValue()); Map<String, String> changedClassNameMap=null; if(changedDexIdClassNameMap.containsKey(dexId)){ changedClassNameMap=changedDexIdClassNameMap.get(dexId); }else{ changedClassNameMap=new HashMap<String,String>(); changedDexIdClassNameMap.put(dexId, changedClassNameMap); } changedClassNameMap.put(className, className); Map<String, byte[]> classNameByteArrayMap=null; if(dexIdClassNameByteArrayMap.containsKey(dexId)){ classNameByteArrayMap=dexIdClassNameByteArrayMap.get(dexId); }else{ classNameByteArrayMap=new HashMap<String, byte[]>(); dexIdClassNameByteArrayMap.put(dexId, classNameByteArrayMap); } classNameByteArrayMap.put(className, modifiedEntry.getValue()); } } } } //write changed class to jar Iterator<Entry<Integer, Map<String, byte[]>>> dexIdIterator=dexIdClassNameByteArrayMap.entrySet().iterator(); while(dexIdIterator.hasNext()){ Entry<Integer, Map<String, byte[]>> dexIdEntry=dexIdIterator.next(); int dexId=dexIdEntry.getKey(); Map<String, byte[]> classNameByteArrayMap=dexIdEntry.getValue(); String incrementalJarFullFilename=incrementalDirectory+Constant.Symbol.SLASH_LEFT+dexId+Constant.Symbol.DOT+Constant.File.JAR; FileUtil.createFile(incrementalJarFullFilename); ZipOutputStream zipOutputStream=null; try{ zipOutputStream=new ZipOutputStream(new FileOutputStream(incrementalJarFullFilename)); Iterator<Entry<String, byte[]>> classNameByteArrayIterator=classNameByteArrayMap.entrySet().iterator(); while(classNameByteArrayIterator.hasNext()){ Entry<String, byte[]> classNameByteArrayEntry=classNameByteArrayIterator.next(); String className=classNameByteArrayEntry.getKey(); FileUtil.addZipEntry(zipOutputStream, new ZipEntry(className), new ByteArrayInputStream(classNameByteArrayEntry.getValue())); } }catch(Exception e){ logger.error("Zip output exception dexId:"+dexId, e); }finally{ if(zipOutputStream!=null){ try { zipOutputStream.close(); } catch (IOException e) { logger.error("Zip close exception dexId:"+dexId, e); } } } } for(int dexId:changedDexIdClassNameMap.keySet()){ String incrementalJarFullFilename=incrementalDirectory+Constant.Symbol.SLASH_LEFT+dexId+Constant.Symbol.DOT+Constant.File.JAR; String incrementalDexFullFilename=incrementalDirectory+Constant.Symbol.SLASH_LEFT+CLASSES+(dexId==0?StringUtil.BLANK:(dexId+1))+Constant.Symbol.DOT+DEX; DexUtil.androidDx(incrementalDexFullFilename, Arrays.asList(incrementalJarFullFilename), option.debug); String dexFullFilename=outputDirectory+Constant.Symbol.SLASH_LEFT+CLASSES+(dexId==0?StringUtil.BLANK:(dexId+1))+Constant.Symbol.DOT+DEX; DexUtil.androidMergeDex(dexFullFilename, Arrays.asList(incrementalDexFullFilename, dexFullFilename)); } //update cache for(int dexId:changedDexIdClassNameMap.keySet()){ if(cache.dexIdClassNameMap.containsKey(dexId)){ Map<String,String> cacheDexIdClassNameMap=cache.dexIdClassNameMap.get(dexId); cacheDexIdClassNameMap.putAll(changedDexIdClassNameMap.get(dexId)); }else{ logger.error("DexId:"+dexId+" is not exist? impossible...", null); } } if(cache.changedClassNameByteArrayMd5Map!=null){ cache.classNameByteArrayMd5Map.putAll(cache.changedClassNameByteArrayMd5Map); } if(cache.incrementalClassNameByteArrayMap!=null){ cache.classNameByteArrayMap.putAll(cache.incrementalClassNameByteArrayMap); } if(cache.modifiedClassNameByteArrayMap!=null){ cache.classNameByteArrayMap.putAll(cache.modifiedClassNameByteArrayMap); } }else{ dexIdClassNameMap=autoDex(option, result, cache.classNameByteArrayMap, mainDexRootClassNameSet, null); cache.dexIdClassNameMap.putAll(dexIdClassNameMap); result.dexIdClassNameMap = dexIdClassNameMap; logger.info("Caculate total cost:"+(System.currentTimeMillis()-innerBegin)); try{ String splitAndDxTempDirectory=outputDirectory+Constant.Symbol.SLASH_LEFT+"temp"; final Map<Integer,List<String>> subDexListMap=splitAndDx(cache.classNameByteArrayMap, splitAndDxTempDirectory, dexIdClassNameMap, option.debug); //concurrent merge dex innerBegin=System.currentTimeMillis(); final CountDownLatch countDownLatch=new CountDownLatch(subDexListMap.size()); Set<Integer> dexIdSet=subDexListMap.keySet(); final Map<Integer, Exception> mergeDexExceptionMap = new HashMap<Integer, Exception>(); for(final int dexId:dexIdSet){ String dexOutputDirectory=outputDirectory; String dexFullFilename=null; if(dexId==0){ dexFullFilename=dexOutputDirectory+"/"+CLASSES+Constant.Symbol.DOT+DEX; }else{ dexFullFilename=dexOutputDirectory+"/"+CLASSES+(dexId+1)+Constant.Symbol.DOT+DEX; } final String finalDexFullFilename=dexFullFilename; Thread thread=new Thread(new Runnable(){ public void run() { try{ DexUtil.androidMergeDex(finalDexFullFilename, subDexListMap.get(dexId)); }catch(Exception e){ mergeDexExceptionMap.put(dexId, e); logger.error(Constant.Base.EXCEPTION+",dexId:"+dexId+","+e.getMessage(), e); } countDownLatch.countDown(); } }); thread.start(); } countDownLatch.await(); logger.info("Merge dex cost:"+(System.currentTimeMillis()-innerBegin)); FileUtil.deleteAllFile(splitAndDxTempDirectory); if(!mergeDexExceptionMap.isEmpty()){ Iterator<Entry<Integer, Exception>> iterator=mergeDexExceptionMap.entrySet().iterator(); while(iterator.hasNext()){ Entry<Integer, Exception> entry=iterator.next(); int dexId=entry.getKey(); Exception e=entry.getValue(); throw new AutoDexUtilException(Constant.Base.EXCEPTION+",dexId:"+dexId+","+e.getMessage(), e); } } }catch(Exception e){ throw new AutoDexUtilException(Constant.Base.EXCEPTION, e); } } try { ObjectUtil.writeObject(cache, new FileOutputStream(cacheFullFilename)); } catch (Exception e) { logger.error("Write cache exception.", e); } logger.info("Auto dex cost:"+(System.currentTimeMillis()-outerBegin)); } /** * auto dex * @param option * @param result * @param classNameByteArrayMap * @param mainDexRootClassNameSet * @param fieldProcessor * @return Map<Integer, Map<String,String>>, <dexId,classNameMap> */ private static Map<Integer,Map<String,String>> autoDex(Option option, Result result, Map<String, byte[]> classNameByteArrayMap, Set<String> mainDexRootClassNameSet, final FieldProcessor fieldProcessor){ final Map<Integer,Map<String,String>> dexIdClassNameMap=new HashMap<Integer, Map<String,String>>(); try{ long begin=System.currentTimeMillis(); //all class description Map<String,List<ClassDescription>> referencedClassDescriptionListMap=new HashMap<String,List<ClassDescription>>(); Map<String,ClassDescription> classDescriptionMap=new HashMap<String,ClassDescription>(); if(classNameByteArrayMap!=null){ classDescriptionMap.putAll(AsmUtil.findClassDescriptionMap(classNameByteArrayMap, referencedClassDescriptionListMap)); } result.classDescriptionMap = classDescriptionMap; result.referencedClassDescriptionListMap = referencedClassDescriptionListMap; logger.info("classDescriptionMap:"+classDescriptionMap.size()+",referencedClassDescriptionListMap:"+referencedClassDescriptionListMap.size()); //all class map Map<String,String> allClassNameMap=new HashMap<String,String>(); Set<String> classNameKeySet=classDescriptionMap.keySet(); for(String className:classNameKeySet){ allClassNameMap.put(className, className); } logger.info("Find all class description cost:"+(System.currentTimeMillis()-begin)); Map<String, List<String>> samePackageClassNameListMap=null; if(option.autoByPackage){ samePackageClassNameListMap=findAllSamePackageClassNameListMap(classDescriptionMap); } //main dex begin=System.currentTimeMillis(); if(mainDexRootClassNameSet!=null){ begin=System.currentTimeMillis(); Map<Integer,Set<String>> dexClassRootSetMap=new HashMap<Integer,Set<String>>(); dexClassRootSetMap.put(0, mainDexRootClassNameSet); Queue<Integer> dexQueue=new ConcurrentLinkedQueue<Integer>(); dexQueue.add(0); final Map<Integer,AllocStat> dexAllocStatMap=new HashMap<Integer,AllocStat>(); int autoDexId=0; boolean mustMainDex=true; while(!dexQueue.isEmpty()){ Integer dexId=dexQueue.poll(); Set<String> rootClassNameSet=dexClassRootSetMap.get(dexId); Map<String,String> dependClassNameMap=null; if(option.autoByPackage){ dependClassNameMap=findAllSamePackageClassNameMap(rootClassNameSet, samePackageClassNameListMap); }else{ if(mustMainDex){ mustMainDex=false; dependClassNameMap=AsmUtil.findAllDependClassNameMap(rootClassNameSet, classDescriptionMap, referencedClassDescriptionListMap, allClassNameMap, true); }else{ dependClassNameMap=AsmUtil.findAllDependClassNameMap(rootClassNameSet, classDescriptionMap, referencedClassDescriptionListMap, allClassNameMap, !option.debug); } } //linear AllocStat thisTimeAllocStat=new AllocStat(); thisTimeAllocStat.setMethodReferenceMap(new HashMap<String,String>()); thisTimeAllocStat.setFieldReferenceMap(new HashMap<String,String>()); Set<String> keySet=dependClassNameMap.keySet(); for(String key:keySet){ AllocStat allocStat = LinearAllocUtil.estimateClass(new ByteArrayInputStream(classNameByteArrayMap.get(key))); thisTimeAllocStat.setTotalAlloc(thisTimeAllocStat.getTotalAlloc()+allocStat.getTotalAlloc()); List<MethodReference> methodReferenceList=allocStat.getMethodReferenceList(); if(methodReferenceList!=null){ for(MethodReference methodReference:methodReferenceList){ thisTimeAllocStat.getMethodReferenceMap().put(methodReference.toString(), methodReference.toString()); } } //field reference map ClassDescription classDescription=classDescriptionMap.get(key); thisTimeAllocStat.getFieldReferenceMap().putAll(classDescription.referenceFieldNameMap); for(String fieldName:classDescription.fieldNameList){ thisTimeAllocStat.getFieldReferenceMap().put(fieldName, fieldName); } allClassNameMap.remove(key); } //dex,dexId=0 AllocStat dexTotalAllocStat=null; if(dexAllocStatMap.containsKey(dexId)){ dexTotalAllocStat=dexAllocStatMap.get(dexId); }else{ dexTotalAllocStat=new AllocStat(); dexTotalAllocStat.setMethodReferenceMap(new HashMap<String,String>()); dexTotalAllocStat.setFieldReferenceMap(new HashMap<String,String>()); dexAllocStatMap.put(dexId, dexTotalAllocStat); } //dexId=0dexId=0dex,,dex int tempFieldLimit=option.fieldLimit; int tempMethodLimit=option.methodLimit; int tempLinearAllocLimit=option.linearAllocLimit; if(dexId==0){ int thisTimeFieldLimit=thisTimeAllocStat.getFieldReferenceMap().size(); int thisTimeMethodLimit=thisTimeAllocStat.getMethodReferenceMap().size(); int thisTimeTotalAlloc=dexTotalAllocStat.getTotalAlloc()+thisTimeAllocStat.getTotalAlloc(); if(thisTimeFieldLimit>tempFieldLimit){ tempFieldLimit=thisTimeFieldLimit; } if(thisTimeMethodLimit>tempMethodLimit){ tempMethodLimit=thisTimeMethodLimit; } if(thisTimeTotalAlloc>tempLinearAllocLimit){ tempLinearAllocLimit=thisTimeTotalAlloc; } } boolean normalCaculate=false; if(option.minMainDex){ if(dexId==0){ dexTotalAllocStat.setTotalAlloc(dexTotalAllocStat.getTotalAlloc()+thisTimeAllocStat.getTotalAlloc()); dexTotalAllocStat.getMethodReferenceMap().putAll(thisTimeAllocStat.getMethodReferenceMap()); //add to current dex class name map if(!dexIdClassNameMap.containsKey(dexId)){ dexIdClassNameMap.put(dexId, dependClassNameMap); } //and put the this time alloc stat to dex all stat map dexAllocStatMap.put(dexId, thisTimeAllocStat); autoDexId++; }else{ normalCaculate=true; } }else{ normalCaculate=true; } if(normalCaculate){//dex //clonemap Map<String,String> oldFieldReferenceMap=dexTotalAllocStat.getFieldReferenceMap(); Map<String,String> oldMethodReferenceMap=dexTotalAllocStat.getMethodReferenceMap(); Map<String,String> tempFieldReferenceMap=(Map<String,String>)((HashMap<String,String>)oldFieldReferenceMap).clone(); Map<String,String> tempMethodReferenceMap=(Map<String,String>)((HashMap<String,String>)oldMethodReferenceMap).clone(); tempFieldReferenceMap.putAll(thisTimeAllocStat.getFieldReferenceMap()); tempMethodReferenceMap.putAll(thisTimeAllocStat.getMethodReferenceMap()); int tempTotalAlloc=dexTotalAllocStat.getTotalAlloc()+thisTimeAllocStat.getTotalAlloc(); //method limitautoDexId if(tempFieldReferenceMap.size()<=tempFieldLimit&&tempMethodReferenceMap.size()<=tempMethodLimit&&tempTotalAlloc<=tempLinearAllocLimit){ dexTotalAllocStat.setTotalAlloc(dexTotalAllocStat.getTotalAlloc()+thisTimeAllocStat.getTotalAlloc()); dexTotalAllocStat.getMethodReferenceMap().putAll(thisTimeAllocStat.getMethodReferenceMap()); dexTotalAllocStat.getFieldReferenceMap().putAll(thisTimeAllocStat.getFieldReferenceMap()); if(!dexIdClassNameMap.containsKey(dexId)){ dexIdClassNameMap.put(dexId, dependClassNameMap); }else{ dexIdClassNameMap.get(dexId).putAll(dependClassNameMap); } }else{ //this dex is full then next one. autoDexId++; //add to new dex class name map if(!dexIdClassNameMap.containsKey(autoDexId)){ dexIdClassNameMap.put(autoDexId, dependClassNameMap); } //and put the this time alloc stat to dex all stat map dexAllocStatMap.put(autoDexId, thisTimeAllocStat); } } //autoDexIddex Set<String> remainKeySet=allClassNameMap.keySet(); for(String key:remainKeySet){ dexQueue.add(autoDexId); Set<String> set=new HashSet<String>(); set.add(key); dexClassRootSetMap.put(autoDexId, set); break; } } logger.info("Caculate class dependency cost:"+(System.currentTimeMillis()-begin)); logger.info("remain classes:"+allClassNameMap.size()); Iterator<Entry<Integer,AllocStat>> iterator=dexAllocStatMap.entrySet().iterator(); while(iterator.hasNext()){ Entry<Integer,AllocStat> entry=iterator.next(); logger.info("\tdexId:"+entry.getKey()+"\tlinearAlloc:"+entry.getValue().getTotalAlloc()+"\tfield:"+entry.getValue().getFieldReferenceMap().size()+"\tmethod:"+entry.getValue().getMethodReferenceMap().size()); } } }catch(Exception e){ throw new AutoDexUtilException(e); } return dexIdClassNameMap; } /** * split and dx * @param classNameByteArrayMap * @param outputDirectory * @param dexIdClassNameMap * @param apkDebug */ public static Map<Integer,List<String>> splitAndDx(final Map<String,byte[]> classNameByteArrayMap,final String outputDirectory,final Map<Integer,Map<String,String>> dexIdClassNameMap,final boolean apkDebug){ final Map<Integer,List<String>> subDexListMap=new HashMap<Integer,List<String>>(); long begin=System.currentTimeMillis(); try{ final String parentOutputDirectory=new File(outputDirectory).getParent(); try{ //copy all classes final CountDownLatch splitJarCountDownLatch=new CountDownLatch(dexIdClassNameMap.size()); Set<Integer> dexIdSet=dexIdClassNameMap.keySet(); final int fileCountPerJar=500; //concurrent split jar for(final int dexId:dexIdSet){ final Set<String> classNameSet=dexIdClassNameMap.get(dexId).keySet(); Thread thread=new Thread(new Runnable(){ public void run() { int total=classNameSet.size(); int subDexCount=0,count=0; ZipOutputStream dexJarOutputStream=null; String classesJar=null; String classNameTxt=null; String jarSubDexNameTxt=null; OutputStream classNameTxtOutputStream=null; OutputStream jarSubDexNameTxtOutputStream=null; try{ classNameTxt=parentOutputDirectory+"/"+dexId+Constant.Symbol.DOT+Constant.File.TXT; jarSubDexNameTxt=outputDirectory+"/"+dexId+Constant.File.JAR+Constant.Symbol.DOT+Constant.File.TXT; FileUtil.createFile(classNameTxt); FileUtil.createFile(jarSubDexNameTxt); Properties classNameProperties=new Properties(); Properties jarSubDexNameProperties=new Properties(); for(String className:classNameSet){ if(count%fileCountPerJar==0){ classesJar=outputDirectory+"/"+AUTO_DEX_DEX_CLASSES_PREFIX+dexId+Constant.Symbol.UNDERLINE+subDexCount+Constant.Symbol.DOT+Constant.File.JAR; classesJar=new File(classesJar).getAbsolutePath(); FileUtil.createFile(classesJar); dexJarOutputStream=new ZipOutputStream(new FileOutputStream(classesJar)); } ZipEntry zipEntry=new ZipEntry(className); byte[] byteArray=classNameByteArrayMap.get(className); FileUtil.addZipEntry(dexJarOutputStream, zipEntry, new ByteArrayInputStream(byteArray)); count++; classNameProperties.put(className, classesJar); if(count%fileCountPerJar==0||count==total){ if(dexJarOutputStream!=null){ dexJarOutputStream.flush(); dexJarOutputStream.close(); } String classesDex=outputDirectory+"/"+AUTO_DEX_DEX_CLASSES_PREFIX+dexId+Constant.Symbol.UNDERLINE+subDexCount+Constant.Symbol.DOT+Constant.File.DEX; classesDex=new File(classesDex).getAbsolutePath(); if(classesJar!=null){ DexUtil.androidDx(classesDex, Arrays.asList(classesJar), apkDebug); if(subDexListMap.containsKey(dexId)){ subDexListMap.get(dexId).add(classesDex); }else{ List<String> subDexList=new ArrayList<String>(); subDexList.add(classesDex); subDexListMap.put(dexId, subDexList); } } jarSubDexNameProperties.put(classesJar, classesDex); subDexCount++; } } classNameTxtOutputStream=new FileOutputStream(classNameTxt); classNameProperties.store(classNameTxtOutputStream, null); jarSubDexNameTxtOutputStream=new FileOutputStream(jarSubDexNameTxt); jarSubDexNameProperties.store(jarSubDexNameTxtOutputStream, null); }catch (Exception e) { throw new AutoDexUtilException(classesJar,e); }finally{ if(dexJarOutputStream!=null){ try { dexJarOutputStream.flush(); dexJarOutputStream.close(); } catch (Exception e) { throw new AutoDexUtilException(classesJar,e); } } if(classNameTxtOutputStream!=null){ try { classNameTxtOutputStream.flush(); classNameTxtOutputStream.close(); } catch (Exception e) { throw new AutoDexUtilException(classNameTxt,e); } } if(jarSubDexNameTxtOutputStream!=null){ try { jarSubDexNameTxtOutputStream.flush(); jarSubDexNameTxtOutputStream.close(); } catch (Exception e) { throw new AutoDexUtilException(jarSubDexNameTxt,e); } } } splitJarCountDownLatch.countDown(); } }); thread.start(); } splitJarCountDownLatch.await(); logger.info("Split multi jar and dx,file count per jar:"+fileCountPerJar+",cost:"+(System.currentTimeMillis()-begin)); }finally{ } }catch (Exception e) { throw new AutoDexUtilException(e); } return subDexListMap; } /** * find all same package class name list map * @param classDescriptionMap * @return Map<String,List<String>> */ private static Map<String,List<String>> findAllSamePackageClassNameListMap(Map<String,ClassDescription> classDescriptionMap){ Map<String, List<String>> samePackageClassNameListMap=new HashMap<String, List<String>>(); if(classDescriptionMap!=null){ Set<String> classNameSet=classDescriptionMap.keySet(); for(String className:classNameSet){ String packageName=className.substring(0, className.lastIndexOf(Constant.Symbol.SLASH_LEFT)); List<String> classNameList=null; if(samePackageClassNameListMap.containsKey(packageName)){ classNameList=samePackageClassNameListMap.get(packageName); }else{ classNameList=new ArrayList<String>(); samePackageClassNameListMap.put(packageName, classNameList); } classNameList.add(className); } } return samePackageClassNameListMap; } /** * find all same package class name map * @param rootClassNameSet * @param samePackageClassNameListMap * @return Map<String,String> */ private static Map<String,String> findAllSamePackageClassNameMap(Set<String> rootClassNameSet,Map<String,List<String>> samePackageClassNameListMap){ Map<String,String> classNameMap=new HashMap<String,String>(); if(rootClassNameSet!=null&&samePackageClassNameListMap!=null){ for(String rootClassName:rootClassNameSet){ String packageName=rootClassName.substring(0,rootClassName.lastIndexOf(Constant.Symbol.SLASH_LEFT)); List<String> samePackageClassNameList=samePackageClassNameListMap.get(packageName); if(samePackageClassNameList!=null){ for(String className:samePackageClassNameList){ classNameMap.put(className, className); } }else{ logger.error("package:"+packageName+" is not exist.", null); } } } return classNameMap; } /** * parse package name * @param androidManifestFullFilename * @return String */ private static String parsePackageName(String androidManifestFullFilename){ String packageName=null; if(FileUtil.isExist(androidManifestFullFilename)){ XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Document document = JavaXmlUtil.parse(androidManifestFullFilename); try{ XPathExpression expression = xpath.compile("/manifest[@package]"); NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET); if(nodeList!=null&&nodeList.getLength()>0){ Node node=nodeList.item(0); packageName=node.getAttributes().getNamedItem("package").getTextContent(); } }catch(Exception e){ e.printStackTrace(); } } return packageName; } /** * read all combined class with cache * @param combinedClassList * @param oldCache * @return AutoDexCache */ private static Cache readAllCombinedClassWithCache(List<String> combinedClassList, Cache oldCache){ final int CACHE_TYPE_DEFAULT=0; final int CACHE_TYPE_NO_CACHE=1; final int CACHE_TYPE_INCREMENTAL=2; final int CACHE_TYPE_MODIFY=3; Map<String, byte[]> classNameByteArrayMap=new HashMap<String,byte[]>();//incremental when old cache exist, full when old cache not exist Map<String, String> classNameByteArrayMd5Map=new HashMap<String,String>();//incremental when old cache exist, full when old cache not exist Map<String, byte[]> incrementalClassNameByteArrayMap=new HashMap<String,byte[]>(); Map<String, byte[]> modifiedClassNameByteArrayMap=new HashMap<String,byte[]>(); if(combinedClassList!=null){ for(String combinedClassFullFilename:combinedClassList){ File combinedClassFile=new File(combinedClassFullFilename); combinedClassFullFilename=combinedClassFile.getAbsolutePath(); if(combinedClassFile.isFile()&&combinedClassFile.getName().endsWith(Constant.Symbol.DOT+Constant.File.JAR)){ logger.debug("Reading jar combined class:"+combinedClassFullFilename); ZipFile zipFile = null; try{ zipFile = new ZipFile(combinedClassFile.getAbsolutePath()); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); String zipEntryName = zipEntry.getName(); if(zipEntryName.endsWith(Constant.Symbol.DOT+Constant.File.CLASS)){ InputStream inputStream=null; try{ int cacheType=CACHE_TYPE_DEFAULT; if(oldCache!=null){ if(oldCache.classNameByteArrayMd5Map.containsKey(zipEntryName)){ inputStream=zipFile.getInputStream(zipEntry); String md5=Generator.MD5(inputStream); if(oldCache.classNameByteArrayMd5Map.get(zipEntryName).equals(md5)){ continue; }else{ logger.debug("It is a modify class:"+zipEntryName); cacheType=CACHE_TYPE_MODIFY; } }else{ logger.debug("It is a new class:"+zipEntryName); cacheType=CACHE_TYPE_INCREMENTAL; } }else{ cacheType=CACHE_TYPE_NO_CACHE; } if(cacheType!=CACHE_TYPE_DEFAULT){ inputStream=zipFile.getInputStream(zipEntry); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); FileUtil.copyStream(inputStream, byteArrayOutputStream); byte[] byteArray=byteArrayOutputStream.toByteArray(); // logger.verbose(zipEntryName+","+byteArray.length); classNameByteArrayMap.put(zipEntryName, byteArray); classNameByteArrayMd5Map.put(zipEntryName, StringUtil.byteArrayToHexString(Generator.MD5ByteArray(byteArray))); switch (cacheType) { case CACHE_TYPE_INCREMENTAL: incrementalClassNameByteArrayMap.put(zipEntryName, byteArray); break; case CACHE_TYPE_MODIFY: modifiedClassNameByteArrayMap.put(zipEntryName, byteArray); break; } } }catch(Exception e){ logger.error("Exception:"+zipEntryName, e); }finally{ if(inputStream!=null){ try{ inputStream.close(); }catch (Exception e) { logger.error("Close exception:"+zipEntryName, e); } } } } } }catch(Exception e){ throw new AutoDexUtilException(e); }finally{ if(zipFile!=null){ try { zipFile.close(); } catch (Exception e) { throw new AutoDexUtilException(e); } } } }else if(combinedClassFile.isDirectory()){ logger.debug("Reading directory combined class:"+combinedClassFullFilename); String combiledClassRootPath=combinedClassFile.getAbsolutePath(); FileUtil.MatchOption matchOption=new FileUtil.MatchOption(combiledClassRootPath); matchOption.fileSuffix=Constant.Symbol.DOT+Constant.File.CLASS; List<String> allClassFullFilenameList=FileUtil.findMatchFile(matchOption); logger.debug("Find class size:"+allClassFullFilenameList.size()); if(allClassFullFilenameList!=null){ combiledClassRootPath=new File(combiledClassRootPath).getAbsolutePath(); for(String classFullFilename:allClassFullFilenameList){ classFullFilename=new File(classFullFilename).getAbsolutePath(); String relativeClassFilename=classFullFilename.substring(combiledClassRootPath.length()+1); relativeClassFilename=relativeClassFilename.replace(Constant.Symbol.SLASH_RIGHT, Constant.Symbol.SLASH_LEFT); int cacheType=CACHE_TYPE_DEFAULT; if(oldCache!=null){ if(oldCache.classNameByteArrayMd5Map.containsKey(relativeClassFilename)){ String md5=Generator.MD5File(classFullFilename); if(oldCache.classNameByteArrayMd5Map.get(relativeClassFilename).equals(md5)){ continue; }else{ logger.debug("It is a modify class:"+relativeClassFilename); cacheType=CACHE_TYPE_MODIFY; } }else{ logger.debug("It is a new class:"+relativeClassFilename); cacheType=CACHE_TYPE_INCREMENTAL; } }else{ cacheType=CACHE_TYPE_NO_CACHE; } if(cacheType!=CACHE_TYPE_DEFAULT){ byte[] byteArray=FileUtil.readFile(classFullFilename); classNameByteArrayMap.put(relativeClassFilename, byteArray); classNameByteArrayMd5Map.put(relativeClassFilename, StringUtil.byteArrayToHexString(Generator.MD5ByteArray(byteArray))); switch (cacheType) { case CACHE_TYPE_INCREMENTAL: incrementalClassNameByteArrayMap.put(relativeClassFilename, byteArray); break; case CACHE_TYPE_MODIFY: modifiedClassNameByteArrayMap.put(relativeClassFilename, byteArray); break; } } } } } } } Cache cache=new Cache(classNameByteArrayMap, classNameByteArrayMd5Map); cache.changedClassNameByteArrayMd5Map=classNameByteArrayMd5Map; cache.incrementalClassNameByteArrayMap=incrementalClassNameByteArrayMap; cache.modifiedClassNameByteArrayMap=modifiedClassNameByteArrayMap; return cache; } /** * read all combined class * @param combinedClassList * @param cacheFullFilename */ public static Cache readAllCombinedClassWithCacheFile(List<String> combinedClassList, String cacheFullFilename){ long begin=System.currentTimeMillis(); Cache cache=null; if(FileUtil.isExist(cacheFullFilename)){ try{ cache=(Cache)ObjectUtil.readObject(new FileInputStream(cacheFullFilename)); }catch(Exception e){ logger.error("Read cache exception.", e); } } if(cache==null){ cache=readAllCombinedClassWithCache(combinedClassList, cache); }else{//has cache //need to update cache Cache newCache=readAllCombinedClassWithCache(combinedClassList, cache); if(newCache!=null){ cache.changedClassNameByteArrayMd5Map=newCache.changedClassNameByteArrayMd5Map; cache.incrementalClassNameByteArrayMap=newCache.incrementalClassNameByteArrayMap; cache.modifiedClassNameByteArrayMap=newCache.modifiedClassNameByteArrayMap; logger.info("Changed class size:"+cache.changedClassNameByteArrayMd5Map.size()); logger.info("Incremental class size:"+cache.incrementalClassNameByteArrayMap.size()); logger.info("Modified class size:"+cache.modifiedClassNameByteArrayMap.size()); } } logger.info("Read all class file cost:"+(System.currentTimeMillis()-begin)); logger.info("Cache dex size:"+cache.dexIdClassNameMap.size()); return cache; } /** * find main root class set * @param combinedClassNameSet * @param classNameList * @return List<String> */ private static Set<String> findMainRootClassSet(Set<String> combinedClassNameSet, String packageName, List<String> classNameList){ List<String> regexList=new ArrayList<String>(); Set<String> allClassSet=new HashSet<String>(); if(classNameList!=null){ for(String className:classNameList){ className=className.trim(); if(StringUtil.isNotBlank(className)){ if(className.startsWith(Constant.Symbol.DOT)){ className=packageName+className; } className=className.replace(Constant.Symbol.DOT, Constant.Symbol.SLASH_LEFT); if(className.indexOf(Constant.Symbol.WILDCARD)>-1||className.indexOf(Constant.Symbol.WILDCARD+Constant.Symbol.WILDCARD)>-1){ String regex=Constant.Symbol.XOR+className.replace(Constant.Symbol.WILDCARD+Constant.Symbol.WILDCARD, "[\\S]+").replace(Constant.Symbol.WILDCARD, "[^/\\s]+")+Constant.Symbol.DOT+Constant.File.CLASS+Constant.Symbol.DOLLAR; regexList.add(regex); }else{ className=className+Constant.Symbol.DOT+Constant.File.CLASS; allClassSet.add(className); } } } } if(combinedClassNameSet!=null){ for(String combinedClassName:combinedClassNameSet){ for(String regex:regexList){ if(StringUtil.isMatchRegex(combinedClassName, regex)){ logger.verbose("match:"+combinedClassName); allClassSet.add(combinedClassName); } } } } return allClassSet; } public static final class Option{ public static final int DEFAULT_FIELD_LIMIT=0xFFD0;//dex field must less than 65536,but field stat always less then in public static final int DEFAULT_METHOD_LIMIT=0xFFFF;//dex must less than 65536,55000 is more safer then 65535 public static final int DEFAULT_LINEAR_ALLOC_LIMIT=Integer.MAX_VALUE; public List<String> combinedClassList=null; public String androidManifestFullFilename=null; public List<String> mainDexOtherClassList=null; public String outputDirectory=null; public boolean debug=true; public boolean attachBaseContext=true; public boolean autoByPackage=false; public boolean minMainDex=true; public int fieldLimit=DEFAULT_FIELD_LIMIT; public int methodLimit=DEFAULT_METHOD_LIMIT; public int linearAllocLimit=DEFAULT_LINEAR_ALLOC_LIMIT; public Result result=new Result(); public Option(List<String> combinedClassList, String androidManifestFullFilename, String outputDirectory, boolean debug) { this.combinedClassList=combinedClassList; this.androidManifestFullFilename=androidManifestFullFilename; this.outputDirectory=outputDirectory; this.debug=debug; this.fieldLimit=this.debug?(DEFAULT_FIELD_LIMIT-0x200):DEFAULT_FIELD_LIMIT; this.methodLimit=this.debug?(DEFAULT_METHOD_LIMIT-0x200):DEFAULT_METHOD_LIMIT; this.attachBaseContext=this.debug?true:false; this.minMainDex=this.debug?true:false; } } public static final class Result { public Map<Integer, Map<String, String>> dexIdClassNameMap = null; public Map<String, ClassDescription> classDescriptionMap = null; public Map<String, List<ClassDescription>> referencedClassDescriptionListMap = null; } public static final class Cache implements Serializable{ private static final long serialVersionUID = 5668038330717176798L; public final Map<String, byte[]> classNameByteArrayMap; private final Map<String, String> classNameByteArrayMd5Map; private final Map<Integer,Map<String,String>> dexIdClassNameMap=new HashMap<Integer, Map<String,String>>(); private transient Map<String,byte[]> incrementalClassNameByteArrayMap=null; private transient Map<String,byte[]> modifiedClassNameByteArrayMap=null; private transient Map<String,String> changedClassNameByteArrayMd5Map=null; private Cache(Map<String,byte[]> classNameByteArrayMap, Map<String,String> classNameByteArrayMd5Map) { this.classNameByteArrayMap=classNameByteArrayMap; this.classNameByteArrayMd5Map=classNameByteArrayMd5Map; } } private static class AutoDexUtilException extends RuntimeException{ private static final long serialVersionUID = -6167451596208904365L; public AutoDexUtilException(String message) { super(message); } public AutoDexUtilException(Throwable cause) { super(cause); } public AutoDexUtilException(String message, Throwable cause) { super(message, cause); } } }
package com.oneliang.tools.autodex; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.oneliang.Constant; import com.oneliang.thirdparty.asm.util.AsmUtil; import com.oneliang.thirdparty.asm.util.AsmUtil.FieldProcessor; import com.oneliang.thirdparty.asm.util.ClassDescription; import com.oneliang.tools.dex.DexUtil; import com.oneliang.tools.linearalloc.AllocClassVisitor.MethodReference; import com.oneliang.tools.linearalloc.LinearAllocUtil; import com.oneliang.tools.linearalloc.LinearAllocUtil.AllocStat; import com.oneliang.util.common.Generator; import com.oneliang.util.common.JavaXmlUtil; import com.oneliang.util.common.ObjectUtil; import com.oneliang.util.common.StringUtil; import com.oneliang.util.file.FileUtil; import com.oneliang.util.logging.Logger; import com.oneliang.util.logging.LoggerManager; public final class AutoDexUtil { private static final Logger logger = LoggerManager.getLogger(AutoDexUtil.class); private static final String CLASSES="classes"; private static final String DEX="dex"; private static final String AUTO_DEX_DEX_CLASSES_PREFIX="dexClasses"; /** * find main class list from android manifest * @return List<String> */ public static List<String> findMainDexClassListFromAndroidManifest(String androidManifestFullFilename,boolean attachBaseContextMultiDex){ List<String> mainDexClassList=new ArrayList<String>(); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); try{ Document document = JavaXmlUtil.parse(new FileInputStream(androidManifestFullFilename)); String applicationName=findApplication(xPath, document); if(StringUtil.isNotBlank(applicationName)){ mainDexClassList.add(applicationName); } if(!attachBaseContextMultiDex){ mainDexClassList.addAll(findActivity(xPath, document)); mainDexClassList.addAll(findProvider(xPath, document)); mainDexClassList.addAll(findReceiver(xPath, document)); mainDexClassList.addAll(findService(xPath, document)); } }catch(Exception e){ throw new AutoDexUtilException(e); } return mainDexClassList; } /** * find application * @param xPath * @param document * @return String * @throws Exception */ private static String findApplication(XPath xPath,Document document) throws Exception{ String applicationName=null; //application NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application[@*]", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); Node nameNode=node.getAttributes().getNamedItem("android:name"); if(nameNode!=null){ applicationName=nameNode.getTextContent(); logger.verbose(applicationName); } } } return applicationName; } /** * find activity * @param xPath * @param document * @return List<String> * @throws Exception */ private static List<String> findActivity(XPath xPath,Document document) throws Exception{ List<String> mainActivityList=new ArrayList<String>(); NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application/activity", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); String activityName=node.getAttributes().getNamedItem("android:name").getTextContent(); Node activityExportedNode=node.getAttributes().getNamedItem("android:exported"); if(activityExportedNode!=null){ boolean exported=Boolean.parseBoolean(activityExportedNode.getTextContent()); if(exported){ logger.verbose(activityName); mainActivityList.add(activityName); } }else{ Element element=(Element)node; NodeList actionNodeList=element.getElementsByTagName("action"); if(actionNodeList.getLength()>0){ // logger.verbose(activityName); // mainActivityList.add(activityName); } for(int j=0;j<actionNodeList.getLength();j++){ Node activityActionNode=actionNodeList.item(j).getAttributes().getNamedItem("android:name"); if(activityActionNode!=null){ String activityActionName=activityActionNode.getTextContent(); if(activityActionName.equals("android.intent.action.MAIN")){ logger.verbose(activityName); mainActivityList.add(activityName); } } } } } } return mainActivityList; } /** * find provider * @param xPath * @param document * @return List<String> * @throws Exception */ private static List<String> findProvider(XPath xPath,Document document) throws Exception{ List<String> providerList=new ArrayList<String>(); NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application/provider", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); Node nameNode=node.getAttributes().getNamedItem("android:name"); if(nameNode!=null){ // Node providerExportedNode=node.getAttributes().getNamedItem("android:exported"); // if(providerExportedNode!=null){ // boolean exported=Boolean.parseBoolean(providerExportedNode.getTextContent()); // if(exported){ String providerName=nameNode.getTextContent(); logger.verbose(providerName); providerList.add(providerName); } } } return providerList; } /** * find receiver * @param xPath * @param document * @return List<String> * @throws Exception */ private static List<String> findReceiver(XPath xPath,Document document) throws Exception{ List<String> receiverList=new ArrayList<String>(); NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application/receiver", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); Node nameNode=node.getAttributes().getNamedItem("android:name"); if(nameNode!=null){ Node receiverExportedNode=node.getAttributes().getNamedItem("android:exported"); String receiverName=nameNode.getTextContent(); boolean needToCheckAgain=false; if(receiverExportedNode!=null){ boolean exported=Boolean.parseBoolean(receiverExportedNode.getTextContent()); if(exported){ logger.verbose(receiverName); receiverList.add(receiverName); }else{ needToCheckAgain=true; } }else{ needToCheckAgain=true; } if(needToCheckAgain){ Element element=(Element)node; NodeList actionNodeList=element.getElementsByTagName("action"); if(actionNodeList.getLength()>0){ logger.verbose(receiverName); receiverList.add(receiverName); } } } } } return receiverList; } /** * find service * @param xPath * @param document * @return List<String> * @throws Exception */ private static List<String> findService(XPath xPath,Document document) throws Exception{ List<String> serviceList=new ArrayList<String>(); NodeList nodeList = (NodeList) xPath.evaluate("/manifest/application/service", document, XPathConstants.NODESET); if(nodeList!=null){ for(int i=0;i<nodeList.getLength();i++){ Node node=nodeList.item(i); Node nameNode=node.getAttributes().getNamedItem("android:name"); if(nameNode!=null){ String serviceName=nameNode.getTextContent(); Node serviceExportedNode=node.getAttributes().getNamedItem("android:exported"); boolean needToCheckAgain=false; if(serviceExportedNode!=null){ boolean exported=Boolean.parseBoolean(serviceExportedNode.getTextContent()); if(exported){ logger.verbose(serviceName); serviceList.add(serviceName); }else{ needToCheckAgain=true; } }else{ needToCheckAgain=true; } if(needToCheckAgain){ Element element=(Element)node; NodeList actionNodeList=element.getElementsByTagName("action"); if(actionNodeList.getLength()>0){ logger.verbose(serviceName); serviceList.add(serviceName); } } } } } return serviceList; } /** * auto dex * @param option */ public static void autoDex(Option option) { String outputDirectory=new File(option.outputDirectory).getAbsolutePath(); FileUtil.createDirectory(outputDirectory); long outerBegin=System.currentTimeMillis(); long innerBegin=outerBegin; List<String> classNameList=new ArrayList<String>(); //parse android manifest and package name String packageName=null; if(option.androidManifestFullFilename!=null&&FileUtil.isExist(option.androidManifestFullFilename)){ classNameList.addAll(findMainDexClassListFromAndroidManifest(option.androidManifestFullFilename,option.attachBaseContext)); packageName=parsePackageName(option.androidManifestFullFilename); } //read all combined class String cacheFullFilename=outputDirectory+Constant.Symbol.SLASH_LEFT+"cache.txt"; Cache cache=readAllCombinedClass(option.combinedClassList, cacheFullFilename); //find main root class if(option.mainDexOtherClassList!=null){ classNameList.addAll(option.mainDexOtherClassList); } Set<String> mainDexRootClassNameSet=new HashSet<String>(); if(option.combinedClassList!=null){ mainDexRootClassNameSet.addAll(findMainRootClassSet(cache.classNameByteArrayMap.keySet(), packageName, classNameList)); } for(String className:mainDexRootClassNameSet){ logger.verbose("Main root class:"+className); } Map<Integer,Map<String,String>> dexIdClassNameMap=null; //find all dex class if(cache.dexIdClassNameMap!=null&&!cache.dexIdClassNameMap.isEmpty()){ dexIdClassNameMap=cache.dexIdClassNameMap; String incrementalDirectory=outputDirectory+Constant.Symbol.SLASH_LEFT+"incremental"; FileUtil.deleteAllFile(incrementalDirectory); FileUtil.createDirectory(incrementalDirectory); Set<Integer> incrementalDexIdSet=new HashSet<Integer>(); Map<Integer, Map<String, String>> changedDexIdClassNameMap=new HashMap<Integer, Map<String,String>>(); if(cache.incrementalClassNameByteArrayMap!=null&&!cache.incrementalClassNameByteArrayMap.isEmpty()){ Iterator<Entry<String,byte[]>> incrementalClassNameIterator=cache.incrementalClassNameByteArrayMap.entrySet().iterator(); int dexId=0; while(incrementalClassNameIterator.hasNext()){ Entry<String,byte[]> incrementalEntry=incrementalClassNameIterator.next(); String className=incrementalEntry.getKey(); FileUtil.writeFile(incrementalDirectory+Constant.Symbol.SLASH_LEFT+dexId+Constant.Symbol.SLASH_LEFT+className, incrementalEntry.getValue()); incrementalDexIdSet.add(dexId); Map<String, String> changedClassNameMap=null; if(changedDexIdClassNameMap.containsKey(dexId)){ changedClassNameMap=changedDexIdClassNameMap.get(dexId); }else{ changedClassNameMap=new HashMap<String,String>(); changedDexIdClassNameMap.put(dexId, changedClassNameMap); } changedClassNameMap.put(className, className); } } if(cache.modifiedClassNameByteArrayMap!=null&&!cache.modifiedClassNameByteArrayMap.isEmpty()){ Iterator<Entry<String,byte[]>> modifiedClassNameIterator=cache.modifiedClassNameByteArrayMap.entrySet().iterator(); while(modifiedClassNameIterator.hasNext()){ Entry<String,byte[]> modifiedEntry=modifiedClassNameIterator.next(); String className=modifiedEntry.getKey(); Iterator<Entry<Integer, Map<String, String>>> dexIdClassNameIterator=cache.dexIdClassNameMap.entrySet().iterator(); while(dexIdClassNameIterator.hasNext()){ Entry<Integer, Map<String, String>> dexIdClassNameEntry=dexIdClassNameIterator.next(); int dexId=dexIdClassNameEntry.getKey(); Map<String, String> classNameMap=dexIdClassNameEntry.getValue(); if(classNameMap.containsKey(className)){ FileUtil.writeFile(incrementalDirectory+Constant.Symbol.SLASH_LEFT+dexId+Constant.Symbol.SLASH_LEFT+modifiedEntry.getKey(), modifiedEntry.getValue()); incrementalDexIdSet.add(dexId); Map<String, String> changedClassNameMap=null; if(changedDexIdClassNameMap.containsKey(dexId)){ changedClassNameMap=changedDexIdClassNameMap.get(dexId); }else{ changedClassNameMap=new HashMap<String,String>(); changedDexIdClassNameMap.put(dexId, changedClassNameMap); } changedClassNameMap.put(className, className); break; } } } } for(int dexId:incrementalDexIdSet){ String incrementalDexFullFilename=incrementalDirectory+Constant.Symbol.SLASH_LEFT+CLASSES+(dexId==0?StringUtil.BLANK:(dexId+1))+Constant.Symbol.DOT+DEX; DexUtil.androidDx(incrementalDexFullFilename, Arrays.asList(incrementalDirectory+Constant.Symbol.SLASH_LEFT+dexId), option.debug); String dexFullFilename=outputDirectory+Constant.Symbol.SLASH_LEFT+CLASSES+(dexId==0?StringUtil.BLANK:(dexId+1))+Constant.Symbol.DOT+DEX; DexUtil.androidMergeDex(dexFullFilename, Arrays.asList(incrementalDexFullFilename, dexFullFilename)); } //update cache cache.dexIdClassNameMap.putAll(changedDexIdClassNameMap); if(cache.incrementalClassNameByteArrayMap!=null){ cache.classNameByteArrayMap.putAll(cache.incrementalClassNameByteArrayMap); } if(cache.modifiedClassNameByteArrayMap!=null){ cache.classNameByteArrayMap.putAll(cache.modifiedClassNameByteArrayMap); } }else{ dexIdClassNameMap=autoDex(option, cache.classNameByteArrayMap, mainDexRootClassNameSet, null); cache.dexIdClassNameMap.putAll(dexIdClassNameMap); logger.info("Caculate total cost:"+(System.currentTimeMillis()-innerBegin)); try{ String splitAndDxTempDirectory=outputDirectory+Constant.Symbol.SLASH_LEFT+"temp"; final Map<Integer,List<String>> subDexListMap=splitAndDx(cache.classNameByteArrayMap, splitAndDxTempDirectory, dexIdClassNameMap, option.debug); //concurrent merge dex innerBegin=System.currentTimeMillis(); final CountDownLatch countDownLatch=new CountDownLatch(subDexListMap.size()); Set<Integer> dexIdSet=subDexListMap.keySet(); for(final int dexId:dexIdSet){ String dexOutputDirectory=outputDirectory; String dexFullFilename=null; if(dexId==0){ dexFullFilename=dexOutputDirectory+"/"+CLASSES+Constant.Symbol.DOT+DEX; }else{ dexFullFilename=dexOutputDirectory+"/"+CLASSES+(dexId+1)+Constant.Symbol.DOT+DEX; } final String finalDexFullFilename=dexFullFilename; Thread thread=new Thread(new Runnable(){ public void run() { try{ DexUtil.androidMergeDex(finalDexFullFilename, subDexListMap.get(dexId)); }catch(Exception e){ logger.error(Constant.Base.EXCEPTION+",dexId:"+dexId+","+e.getMessage(), e); } countDownLatch.countDown(); } }); thread.start(); } countDownLatch.await(); logger.info("Merge dex cost:"+(System.currentTimeMillis()-innerBegin)); FileUtil.deleteAllFile(splitAndDxTempDirectory); }catch(Exception e){ throw new AutoDexUtilException(Constant.Base.EXCEPTION, e); } } try { ObjectUtil.writeObject(cache, new FileOutputStream(cacheFullFilename)); } catch (Exception e) { logger.error("Write cache exception.", e); } logger.info("Auto dex cost:"+(System.currentTimeMillis()-outerBegin)); } /** * auto dex * @param classNameByteArrayMap * @param mainDexRootClassNameSet * @param fieldLimit * @param methodLimit * @param linearAllocLimit * @param debug * @param autoByPackage * @param fieldProcessor * @return Map<Integer, Map<String,String>>, <dexId,classNameMap> */ private static Map<Integer,Map<String,String>> autoDex(Option option, Map<String, byte[]> classNameByteArrayMap, Set<String> mainDexRootClassNameSet, final FieldProcessor fieldProcessor){ final Map<Integer,Map<String,String>> dexIdClassNameMap=new HashMap<Integer, Map<String,String>>(); try{ long begin=System.currentTimeMillis(); //all class description Map<String,List<ClassDescription>> referencedClassDescriptionListMap=new HashMap<String,List<ClassDescription>>(); Map<String,ClassDescription> classDescriptionMap=new HashMap<String,ClassDescription>(); if(classNameByteArrayMap!=null){ classDescriptionMap.putAll(AsmUtil.findClassDescriptionMap(classNameByteArrayMap, referencedClassDescriptionListMap)); } logger.info("classDescriptionMap:"+classDescriptionMap.size()+",referencedClassDescriptionListMap:"+referencedClassDescriptionListMap.size()); //all class map Map<String,String> allClassNameMap=new HashMap<String,String>(); Set<String> classNameKeySet=classDescriptionMap.keySet(); for(String className:classNameKeySet){ allClassNameMap.put(className, className); } logger.info("Find all class description cost:"+(System.currentTimeMillis()-begin)); Map<String, List<String>> samePackageClassNameListMap=null; if(option.autoByPackage){ samePackageClassNameListMap=findAllSamePackageClassNameListMap(classDescriptionMap); } //main dex begin=System.currentTimeMillis(); if(mainDexRootClassNameSet!=null){ begin=System.currentTimeMillis(); Map<Integer,Set<String>> dexClassRootSetMap=new HashMap<Integer,Set<String>>(); dexClassRootSetMap.put(0, mainDexRootClassNameSet); Queue<Integer> dexQueue=new ConcurrentLinkedQueue<Integer>(); dexQueue.add(0); final Map<Integer,AllocStat> dexAllocStatMap=new HashMap<Integer,AllocStat>(); int autoDexId=0; boolean mustMainDex=true; while(!dexQueue.isEmpty()){ Integer dexId=dexQueue.poll(); Set<String> rootClassNameSet=dexClassRootSetMap.get(dexId); Map<String,String> dependClassNameMap=null; if(option.autoByPackage){ dependClassNameMap=findAllSamePackageClassNameMap(rootClassNameSet, samePackageClassNameListMap); }else{ if(mustMainDex){ mustMainDex=false; dependClassNameMap=AsmUtil.findAllDependClassNameMap(rootClassNameSet, classDescriptionMap, referencedClassDescriptionListMap, allClassNameMap, true); }else{ dependClassNameMap=AsmUtil.findAllDependClassNameMap(rootClassNameSet, classDescriptionMap, referencedClassDescriptionListMap, allClassNameMap, !option.debug); } } //linear AllocStat thisTimeAllocStat=new AllocStat(); thisTimeAllocStat.setMethodReferenceMap(new HashMap<String,String>()); thisTimeAllocStat.setFieldReferenceMap(new HashMap<String,String>()); Set<String> keySet=dependClassNameMap.keySet(); for(String key:keySet){ AllocStat allocStat = LinearAllocUtil.estimateClass(new ByteArrayInputStream(classNameByteArrayMap.get(key))); thisTimeAllocStat.setTotalAlloc(thisTimeAllocStat.getTotalAlloc()+allocStat.getTotalAlloc()); List<MethodReference> methodReferenceList=allocStat.getMethodReferenceList(); if(methodReferenceList!=null){ for(MethodReference methodReference:methodReferenceList){ thisTimeAllocStat.getMethodReferenceMap().put(methodReference.toString(), methodReference.toString()); } } //field reference map ClassDescription classDescription=classDescriptionMap.get(key); thisTimeAllocStat.getFieldReferenceMap().putAll(classDescription.referenceFieldNameMap); for(String fieldName:classDescription.fieldNameList){ thisTimeAllocStat.getFieldReferenceMap().put(fieldName, fieldName); } allClassNameMap.remove(key); } //dex,dexId=0 AllocStat dexTotalAllocStat=null; if(dexAllocStatMap.containsKey(dexId)){ dexTotalAllocStat=dexAllocStatMap.get(dexId); }else{ dexTotalAllocStat=new AllocStat(); dexTotalAllocStat.setMethodReferenceMap(new HashMap<String,String>()); dexTotalAllocStat.setFieldReferenceMap(new HashMap<String,String>()); dexAllocStatMap.put(dexId, dexTotalAllocStat); } //dexId=0dexId=0dex,,dex int tempFieldLimit=option.fieldLimit; int tempMethodLimit=option.methodLimit; int tempLinearAllocLimit=option.linearAllocLimit; if(dexId==0){ int thisTimeFieldLimit=thisTimeAllocStat.getFieldReferenceMap().size(); int thisTimeMethodLimit=thisTimeAllocStat.getMethodReferenceMap().size(); int thisTimeTotalAlloc=dexTotalAllocStat.getTotalAlloc()+thisTimeAllocStat.getTotalAlloc(); if(thisTimeFieldLimit>tempFieldLimit){ tempFieldLimit=thisTimeFieldLimit; } if(thisTimeMethodLimit>tempMethodLimit){ tempMethodLimit=thisTimeMethodLimit; } if(thisTimeTotalAlloc>tempLinearAllocLimit){ tempLinearAllocLimit=thisTimeTotalAlloc; } } boolean normalCaculate=false; if(option.minMainDex){ if(dexId==0){ dexTotalAllocStat.setTotalAlloc(dexTotalAllocStat.getTotalAlloc()+thisTimeAllocStat.getTotalAlloc()); dexTotalAllocStat.getMethodReferenceMap().putAll(thisTimeAllocStat.getMethodReferenceMap()); //add to current dex class name map if(!dexIdClassNameMap.containsKey(dexId)){ dexIdClassNameMap.put(dexId, dependClassNameMap); } //and put the this time alloc stat to dex all stat map dexAllocStatMap.put(dexId, thisTimeAllocStat); autoDexId++; }else{ normalCaculate=true; } }else{ normalCaculate=true; } if(normalCaculate){//dex //clonemap Map<String,String> oldFieldReferenceMap=dexTotalAllocStat.getFieldReferenceMap(); Map<String,String> oldMethodReferenceMap=dexTotalAllocStat.getMethodReferenceMap(); Map<String,String> tempFieldReferenceMap=(Map<String,String>)((HashMap<String,String>)oldFieldReferenceMap).clone(); Map<String,String> tempMethodReferenceMap=(Map<String,String>)((HashMap<String,String>)oldMethodReferenceMap).clone(); tempFieldReferenceMap.putAll(thisTimeAllocStat.getFieldReferenceMap()); tempMethodReferenceMap.putAll(thisTimeAllocStat.getMethodReferenceMap()); int tempTotalAlloc=dexTotalAllocStat.getTotalAlloc()+thisTimeAllocStat.getTotalAlloc(); //method limitautoDexId if(tempFieldReferenceMap.size()<=tempFieldLimit&&tempMethodReferenceMap.size()<=tempMethodLimit&&tempTotalAlloc<=tempLinearAllocLimit){ dexTotalAllocStat.setTotalAlloc(dexTotalAllocStat.getTotalAlloc()+thisTimeAllocStat.getTotalAlloc()); dexTotalAllocStat.getMethodReferenceMap().putAll(thisTimeAllocStat.getMethodReferenceMap()); dexTotalAllocStat.getFieldReferenceMap().putAll(thisTimeAllocStat.getFieldReferenceMap()); if(!dexIdClassNameMap.containsKey(dexId)){ dexIdClassNameMap.put(dexId, dependClassNameMap); }else{ dexIdClassNameMap.get(dexId).putAll(dependClassNameMap); } }else{ //this dex is full then next one. autoDexId++; //add to new dex class name map if(!dexIdClassNameMap.containsKey(autoDexId)){ dexIdClassNameMap.put(autoDexId, dependClassNameMap); } //and put the this time alloc stat to dex all stat map dexAllocStatMap.put(autoDexId, thisTimeAllocStat); } } //autoDexIddex Set<String> remainKeySet=allClassNameMap.keySet(); for(String key:remainKeySet){ dexQueue.add(autoDexId); Set<String> set=new HashSet<String>(); set.add(key); dexClassRootSetMap.put(autoDexId, set); break; } } logger.info("Caculate class dependency cost:"+(System.currentTimeMillis()-begin)); logger.info("remain classes:"+allClassNameMap.size()); Iterator<Entry<Integer,AllocStat>> iterator=dexAllocStatMap.entrySet().iterator(); while(iterator.hasNext()){ Entry<Integer,AllocStat> entry=iterator.next(); logger.info("\tdexId:"+entry.getKey()+"\tlinearAlloc:"+entry.getValue().getTotalAlloc()+"\tfield:"+entry.getValue().getFieldReferenceMap().size()+"\tmethod:"+entry.getValue().getMethodReferenceMap().size()); } } }catch(Exception e){ throw new AutoDexUtilException(e); } return dexIdClassNameMap; } /** * split and dx * @param classNameByteArrayMap * @param outputDirectory * @param dexIdClassNameMap * @param apkDebug */ public static Map<Integer,List<String>> splitAndDx(final Map<String,byte[]> classNameByteArrayMap,final String outputDirectory,final Map<Integer,Map<String,String>> dexIdClassNameMap,final boolean apkDebug){ final Map<Integer,List<String>> subDexListMap=new HashMap<Integer,List<String>>(); long begin=System.currentTimeMillis(); try{ final String parentOutputDirectory=new File(outputDirectory).getParent(); try{ //copy all classes final CountDownLatch splitJarCountDownLatch=new CountDownLatch(dexIdClassNameMap.size()); Set<Integer> dexIdSet=dexIdClassNameMap.keySet(); final int fileCountPerJar=500; //concurrent split jar for(final int dexId:dexIdSet){ final Set<String> classNameSet=dexIdClassNameMap.get(dexId).keySet(); Thread thread=new Thread(new Runnable(){ public void run() { int total=classNameSet.size(); int subDexCount=0,count=0; ZipOutputStream dexJarOutputStream=null; String classesJar=null; String classNameTxt=null; String jarSubDexNameTxt=null; OutputStream classNameTxtOutputStream=null; OutputStream jarSubDexNameTxtOutputStream=null; try{ classNameTxt=parentOutputDirectory+"/"+dexId+Constant.Symbol.DOT+Constant.File.TXT; jarSubDexNameTxt=outputDirectory+"/"+dexId+Constant.File.JAR+Constant.Symbol.DOT+Constant.File.TXT; FileUtil.createFile(classNameTxt); FileUtil.createFile(jarSubDexNameTxt); Properties classNameProperties=new Properties(); Properties jarSubDexNameProperties=new Properties(); for(String className:classNameSet){ if(count%fileCountPerJar==0){ classesJar=outputDirectory+"/"+AUTO_DEX_DEX_CLASSES_PREFIX+dexId+Constant.Symbol.UNDERLINE+subDexCount+Constant.Symbol.DOT+Constant.File.JAR; classesJar=new File(classesJar).getAbsolutePath(); FileUtil.createFile(classesJar); dexJarOutputStream=new ZipOutputStream(new FileOutputStream(classesJar)); } ZipEntry zipEntry=new ZipEntry(className); byte[] byteArray=classNameByteArrayMap.get(className); FileUtil.addZipEntry(dexJarOutputStream, zipEntry, new ByteArrayInputStream(byteArray)); count++; classNameProperties.put(className, classesJar); if(count%fileCountPerJar==0||count==total){ if(dexJarOutputStream!=null){ dexJarOutputStream.flush(); dexJarOutputStream.close(); } String classesDex=outputDirectory+"/"+AUTO_DEX_DEX_CLASSES_PREFIX+dexId+Constant.Symbol.UNDERLINE+subDexCount+Constant.Symbol.DOT+Constant.File.DEX; classesDex=new File(classesDex).getAbsolutePath(); if(classesJar!=null){ DexUtil.androidDx(classesDex, Arrays.asList(classesJar), apkDebug); if(subDexListMap.containsKey(dexId)){ subDexListMap.get(dexId).add(classesDex); }else{ List<String> subDexList=new ArrayList<String>(); subDexList.add(classesDex); subDexListMap.put(dexId, subDexList); } } jarSubDexNameProperties.put(classesJar, classesDex); subDexCount++; } } classNameTxtOutputStream=new FileOutputStream(classNameTxt); classNameProperties.store(classNameTxtOutputStream, null); jarSubDexNameTxtOutputStream=new FileOutputStream(jarSubDexNameTxt); jarSubDexNameProperties.store(jarSubDexNameTxtOutputStream, null); }catch (Exception e) { throw new AutoDexUtilException(classesJar,e); }finally{ if(dexJarOutputStream!=null){ try { dexJarOutputStream.flush(); dexJarOutputStream.close(); } catch (Exception e) { throw new AutoDexUtilException(classesJar,e); } } if(classNameTxtOutputStream!=null){ try { classNameTxtOutputStream.flush(); classNameTxtOutputStream.close(); } catch (Exception e) { throw new AutoDexUtilException(classNameTxt,e); } } if(jarSubDexNameTxtOutputStream!=null){ try { jarSubDexNameTxtOutputStream.flush(); jarSubDexNameTxtOutputStream.close(); } catch (Exception e) { throw new AutoDexUtilException(jarSubDexNameTxt,e); } } } splitJarCountDownLatch.countDown(); } }); thread.start(); } splitJarCountDownLatch.await(); logger.info("Split multi jar and dx,file count per jar:"+fileCountPerJar+",cost:"+(System.currentTimeMillis()-begin)); }finally{ } }catch (Exception e) { throw new AutoDexUtilException(e); } return subDexListMap; } /** * find all same package class name list map * @param classDescriptionMap * @return Map<String,List<String>> */ private static Map<String,List<String>> findAllSamePackageClassNameListMap(Map<String,ClassDescription> classDescriptionMap){ Map<String, List<String>> samePackageClassNameListMap=new HashMap<String, List<String>>(); if(classDescriptionMap!=null){ Set<String> classNameSet=classDescriptionMap.keySet(); for(String className:classNameSet){ String packageName=className.substring(0, className.lastIndexOf(Constant.Symbol.SLASH_LEFT)); List<String> classNameList=null; if(samePackageClassNameListMap.containsKey(packageName)){ classNameList=samePackageClassNameListMap.get(packageName); }else{ classNameList=new ArrayList<String>(); samePackageClassNameListMap.put(packageName, classNameList); } classNameList.add(className); } } return samePackageClassNameListMap; } /** * find all same package class name map * @param rootClassNameSet * @param samePackageClassNameListMap * @return Map<String,String> */ private static Map<String,String> findAllSamePackageClassNameMap(Set<String> rootClassNameSet,Map<String,List<String>> samePackageClassNameListMap){ Map<String,String> classNameMap=new HashMap<String,String>(); if(rootClassNameSet!=null&&samePackageClassNameListMap!=null){ for(String rootClassName:rootClassNameSet){ String packageName=rootClassName.substring(0,rootClassName.lastIndexOf(Constant.Symbol.SLASH_LEFT)); List<String> samePackageClassNameList=samePackageClassNameListMap.get(packageName); if(samePackageClassNameList!=null){ for(String className:samePackageClassNameList){ classNameMap.put(className, className); } }else{ logger.error("package:"+packageName+" is not exist.", null); } } } return classNameMap; } /** * parse package name * @param androidManifestFullFilename * @return String */ private static String parsePackageName(String androidManifestFullFilename){ String packageName=null; if(FileUtil.isExist(androidManifestFullFilename)){ XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Document document = JavaXmlUtil.parse(androidManifestFullFilename); try{ XPathExpression expression = xpath.compile("/manifest[@package]"); NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET); if(nodeList!=null&&nodeList.getLength()>0){ Node node=nodeList.item(0); packageName=node.getAttributes().getNamedItem("package").getTextContent(); } }catch(Exception e){ e.printStackTrace(); } } return packageName; } /** * read all combined class * @param combinedClassList * @return AutoDexCache */ private static Cache readAllCombinedClass(List<String> combinedClassList){ Map<String, byte[]> classNameByteArrayMap=new HashMap<String,byte[]>(); if(combinedClassList!=null){ for(String combinedClassFullFilename:combinedClassList){ File combinedClassFile=new File(combinedClassFullFilename); combinedClassFullFilename=combinedClassFile.getAbsolutePath(); if(combinedClassFile.isFile()&&combinedClassFile.getName().endsWith(Constant.Symbol.DOT+Constant.File.JAR)){ logger.debug("Reading jar combined class:"+combinedClassFullFilename); ZipFile zipFile = null; try{ zipFile = new ZipFile(combinedClassFile.getAbsolutePath()); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); String zipEntryName = zipEntry.getName(); if(zipEntryName.endsWith(Constant.Symbol.DOT+Constant.File.CLASS)){ InputStream inputStream=null; try{ inputStream=zipFile.getInputStream(zipEntry); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); FileUtil.copyStream(inputStream, byteArrayOutputStream); logger.verbose(zipEntryName+","+byteArrayOutputStream.toByteArray().length); classNameByteArrayMap.put(zipEntryName, byteArrayOutputStream.toByteArray()); }catch(Exception e){ logger.error("Exception:"+zipEntryName, e); }finally{ if(inputStream!=null){ try{ inputStream.close(); }catch (Exception e) { logger.error("Close exception:"+zipEntryName, e); } } } } } }catch(Exception e){ throw new AutoDexUtilException(e); }finally{ if(zipFile!=null){ try { zipFile.close(); } catch (Exception e) { throw new AutoDexUtilException(e); } } } }else if(combinedClassFile.isDirectory()){ logger.debug("Reading directory combined class:"+combinedClassFullFilename); String combiledClassRootPath=combinedClassFile.getAbsolutePath(); List<String> allClassFullFilenameList=FileUtil.findMatchFile(combiledClassRootPath, Constant.Symbol.DOT+Constant.File.CLASS); if(allClassFullFilenameList!=null){ combiledClassRootPath=new File(combiledClassRootPath).getAbsolutePath(); for(String classFullFilename:allClassFullFilenameList){ classFullFilename=new File(classFullFilename).getAbsolutePath(); String relativeClassFilename=classFullFilename.substring(combiledClassRootPath.length()+1); relativeClassFilename=relativeClassFilename.replace(Constant.Symbol.SLASH_RIGHT, Constant.Symbol.SLASH_LEFT); byte[] byteArray=FileUtil.readFile(classFullFilename); classNameByteArrayMap.put(relativeClassFilename, byteArray); } } } } } return new Cache(classNameByteArrayMap); } /** * read all combined class * @param combinedClassList * @param cacheFullFilename */ private static Cache readAllCombinedClass(List<String> combinedClassList, String cacheFullFilename){ long begin=System.currentTimeMillis(); Cache cache=null; if(FileUtil.isExist(cacheFullFilename)){ try{ cache=(Cache)ObjectUtil.readObject(new FileInputStream(cacheFullFilename)); }catch(Exception e){ logger.error("Read cache exception.", e); } } if(cache==null){ cache=readAllCombinedClass(combinedClassList); }else{//has cache //need to update cache Map<String, byte[]> incrementalClassNameByteArrayMap=new HashMap<String,byte[]>(); Map<String, byte[]> modifiedClassNameByteArrayMap=new HashMap<String,byte[]>(); Cache newAutoDexCache=readAllCombinedClass(combinedClassList); Iterator<Entry<String,byte[]>> newIterator=newAutoDexCache.classNameByteArrayMap.entrySet().iterator(); while(newIterator.hasNext()){ Entry<String, byte[]> newEntry=newIterator.next(); String newClassName=newEntry.getKey(); byte[] newByteArray=newEntry.getValue(); String newClassFileMd5=Generator.MD5(new ByteArrayInputStream(newByteArray)); if(cache.classNameByteArrayMap.containsKey(newClassName)){ byte[] byteArray=cache.classNameByteArrayMap.get(newClassName); String oldClassFileMd5=Generator.MD5(new ByteArrayInputStream(byteArray)); if(!newClassFileMd5.equals(oldClassFileMd5)){ logger.debug("It is a modify class:"+newClassName); modifiedClassNameByteArrayMap.put(newClassName, newByteArray); }else{ logger.verbose("It is a same class:"+newClassName); } }else{ logger.debug("It is a new class:"+newClassName); incrementalClassNameByteArrayMap.put(newClassName, newByteArray); } } cache.incrementalClassNameByteArrayMap=incrementalClassNameByteArrayMap; cache.modifiedClassNameByteArrayMap=modifiedClassNameByteArrayMap; logger.info("Incremental class size:"+cache.incrementalClassNameByteArrayMap.size()); logger.info("Modified class size:"+cache.modifiedClassNameByteArrayMap.size()); } logger.info("Read all class file cost:"+(System.currentTimeMillis()-begin)); logger.info("Cache dex size:"+cache.dexIdClassNameMap.size()); return cache; } /** * find main root class set * @param combinedClassNameSet * @param classNameList * @return List<String> */ private static Set<String> findMainRootClassSet(Set<String> combinedClassNameSet, String packageName, List<String> classNameList){ List<String> regexList=new ArrayList<String>(); Set<String> allClassSet=new HashSet<String>(); if(classNameList!=null){ for(String className:classNameList){ className=className.trim(); if(StringUtil.isNotBlank(className)){ if(className.startsWith(Constant.Symbol.DOT)){ className=packageName+className; } className=className.replace(Constant.Symbol.DOT, Constant.Symbol.SLASH_LEFT); if(className.indexOf(Constant.Symbol.WILDCARD)>-1||className.indexOf(Constant.Symbol.WILDCARD+Constant.Symbol.WILDCARD)>-1){ String regex=Constant.Symbol.XOR+className.replace(Constant.Symbol.WILDCARD+Constant.Symbol.WILDCARD, "[\\S]+").replace(Constant.Symbol.WILDCARD, "[^/\\s]+")+Constant.Symbol.DOT+Constant.File.CLASS+Constant.Symbol.DOLLAR; regexList.add(regex); }else{ className=className+Constant.Symbol.DOT+Constant.File.CLASS; allClassSet.add(className); } } } } if(combinedClassNameSet!=null){ for(String combinedClassName:combinedClassNameSet){ for(String regex:regexList){ if(StringUtil.isMatchRegex(combinedClassName, regex)){ logger.verbose("match:"+combinedClassName); allClassSet.add(combinedClassName); } } } } return allClassSet; } public static final class Option{ public static final int DEFAULT_FIELD_LIMIT=0xFFD0;//dex field must less than 65536,but field stat always less then in public static final int DEFAULT_METHOD_LIMIT=0xFFFF;//dex must less than 65536,55000 is more safer then 65535 public static final int DEFAULT_LINEAR_ALLOC_LIMIT=Integer.MAX_VALUE; public List<String> combinedClassList=null; public String androidManifestFullFilename=null; public List<String> mainDexOtherClassList=null; public String outputDirectory=null; public boolean debug=true; public boolean attachBaseContext=true; public boolean autoByPackage=false; public boolean minMainDex=true; public int fieldLimit=DEFAULT_FIELD_LIMIT; public int methodLimit=DEFAULT_METHOD_LIMIT; public int linearAllocLimit=DEFAULT_LINEAR_ALLOC_LIMIT; public Option(List<String> combinedClassList, String androidManifestFullFilename, String outputDirectory, boolean debug) { this.combinedClassList=combinedClassList; this.androidManifestFullFilename=androidManifestFullFilename; this.outputDirectory=outputDirectory; this.debug=debug; this.fieldLimit=this.debug?(DEFAULT_FIELD_LIMIT-0x200):DEFAULT_FIELD_LIMIT; this.methodLimit=this.debug?(DEFAULT_METHOD_LIMIT-0x200):DEFAULT_METHOD_LIMIT; } } public static final class Cache implements Serializable{ private static final long serialVersionUID = 5668038330717176798L; private final Map<String,byte[]> classNameByteArrayMap; private final Map<Integer,Map<String,String>> dexIdClassNameMap=new HashMap<Integer, Map<String,String>>(); public volatile Map<String,byte[]> incrementalClassNameByteArrayMap=null; public volatile Map<String,byte[]> modifiedClassNameByteArrayMap=null; public Cache(Map<String,byte[]> classNameByteArrayMap) { this.classNameByteArrayMap=classNameByteArrayMap; } } private static class AutoDexUtilException extends RuntimeException{ private static final long serialVersionUID = -6167451596208904365L; public AutoDexUtilException(String message) { super(message); } public AutoDexUtilException(Throwable cause) { super(cause); } public AutoDexUtilException(String message, Throwable cause) { super(message, cause); } } }
package com.openspection.service; import com.openspection.model.Person; import com.openspection.model.Role; import com.openspection.model.Userprofile; import com.openspection.persistence.SystemDataAccess; import java.security.Principal; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class PersonService { //PEOPLE //GET @RequestMapping(value = "people", method = RequestMethod.GET) @ResponseBody public final List< Person> getAllPeople() { return SystemDataAccess.getAll("select p from Person p "); } @RequestMapping(value = "people/{id}", method = RequestMethod.GET) @ResponseBody public final Person getPerson(@PathVariable("id") final Long id) { return (Person) SystemDataAccess.get(Person.class, id); } public final Person getPersonByEmail(final String tvsEmail) { Object[][] tvoObject = new Object[1][2]; tvoObject[0][0] = "email"; tvoObject[0][1] = tvsEmail; List<Person> ppAll = SystemDataAccess.getWithParams("select p from Person p where p.email in (:email) ", tvoObject); if (ppAll.size() > 0) { return (Person) ppAll.get(0); } return null; } @RequestMapping(value = "profile/{id}", method = RequestMethod.GET) @ResponseBody public final Userprofile getPersonProfile(@PathVariable("id") final Long id) { return (Userprofile) SystemDataAccess.get(Userprofile.class, id.toString()); } @RequestMapping(value = "profile", method = RequestMethod.GET) @ResponseBody public final Userprofile getLoggedInPersonProfile(Principal fvoPrincipal) { PersonService tvoPersonService = new PersonService(); Person tvoPerson = tvoPersonService.getPersonByEmail(fvoPrincipal.getName()); return (Userprofile) SystemDataAccess.get(Userprofile.class, tvoPerson.getId().toString()); } //POST @RequestMapping(value = "people", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public final Person addPerson(@RequestBody final Person p) { Person tvoReturn = getPersonByEmail(p.getEmail()); if (tvoReturn != null) { return (Person) tvoReturn; } p.setId(null); p.setIsenabled(true); BCryptPasswordEncoder tvoBCryptEncoder = new BCryptPasswordEncoder(); p.setPassword(tvoBCryptEncoder.encode(p.getPassword())); Person pNew = (Person) SystemDataAccess.add(p); Role tvoRole = new Role(); tvoRole.setName("ROLE_CANPOST"); tvoRole.setPersonid(pNew.getId()); SystemDataAccess.add(tvoRole); Userprofile upNew = new Userprofile(); upNew.setId_str(pNew.getId().toString()); upNew.setName(pNew.getName()); upNew.setReputation(1L); SystemDataAccess.add(upNew); return pNew; } @RequestMapping(value = "people/{id}/changepassword/", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) public void changePassword(@PathVariable("id") final Long id, @RequestParam String oldpassword, @RequestParam String newpassword, @RequestParam String confirmpassword, Principal fvoPrincipal ) { //TODO: Validate new and confirm match if (!newpassword.equals(confirmpassword)) return; //TODO: confirm person exists if (!doesExist(id)) return; //TODO: confirm person is principal Person tvoPerson = getPerson(id); if (!tvoPerson.getEmail().equals(fvoPrincipal.getName())) return; //TODO: Validate old and person match BCryptPasswordEncoder tvoBCryptEncoder = new BCryptPasswordEncoder(); String tvsEncryptedOldPassword = tvoBCryptEncoder.encode(oldpassword); if (!tvoPerson.getPassword().equals(tvsEncryptedOldPassword)) return; String tvsEncryptedNewPassword = tvoBCryptEncoder.encode(newpassword); tvoPerson.setPassword(tvsEncryptedNewPassword); setPerson(id, tvoPerson, fvoPrincipal); } public boolean doesExist(Long personid){ Person tvoPerson = getPerson(personid); if (tvoPerson!=null) return true; return false; } //PUT @RequestMapping(value = "people/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public final Person setPerson(@PathVariable("id") final Long id, @RequestBody final Person p, Principal fvoPrincipal) { if (!doesExist(id)) return null; Person tvoPerson = getPerson(id); if (!tvoPerson.getEmail().equals(fvoPrincipal.getName())) return null; return (Person) SystemDataAccess.set(Person.class, id, p); } //DELETE @RequestMapping(value = "people/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) public final void deletePerson(@PathVariable("id") final Long id) { SystemDataAccess.delete(Person.class, id); } }