List of usage examples for java.lang Thread run
@Override public void run()
From source file:pt.lsts.neptus.console.bathymLayer.TidePanel.java
@Override public void initSubPanel() { storedMenuPath = I18n.text("Tools") + ">" + I18n.text("Tides") + ">" + I18n.textf("Using '%file'", GeneralPreferences.tidesFile.getName()); tidesItem = addMenuItem(storedMenuPath, null, new ActionListener() { @Override/*from www .j a va 2 s .c o m*/ public void actionPerformed(ActionEvent e) { JMenuItem menu = (JMenuItem) e.getSource(); Thread t = new Thread("Tide chooser") { @Override public void run() { try { File usedTidesSource = GeneralPreferences.tidesFile; String currentSource = usedTidesSource == null || !usedTidesSource.exists() ? null : usedTidesSource.getName(); Date startDate = new Date(System.currentTimeMillis() - 2 * DateTimeUtil.DAY); Date endDate = new Date(System.currentTimeMillis() + 3 * DateTimeUtil.DAY); String harbor = TidePredictionFactory.showTidesSourceChooserGuiPopup(getConsole(), currentSource, startDate, endDate); if (harbor != null && !harbor.isEmpty() && TidePredictionFactory.getTidesSourceFileFrom(harbor).exists()) { GeneralPreferences.tidesFile = TidePredictionFactory.getTidesSourceFileFrom(harbor); GeneralPreferences.saveProperties(); preferencesUpdated(); // Force the tide file reload TidePredictionFactory.getTideLevel(System.currentTimeMillis()); } } catch (Exception e) { e.printStackTrace(); } finally { menu.setEnabled(true); } } }; t.setDaemon(true); menu.setEnabled(false); t.run(); } }); // tidesItem.setEnabled(false); addMenuItem(I18n.text("Tools") + ">" + I18n.text("Tides") + ">" + I18n.text("Update Predictions"), null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JMenuItem menu = (JMenuItem) e.getSource(); Thread t = new Thread("Tide fetcher") { public void run() { try { String harbor = TidePredictionFactory.fetchData(getConsole()); if (harbor != null && !harbor.isEmpty()) { File used = GeneralPreferences.tidesFile; File f = new File(ConfigFetch.getConfFolder() + "/tides/" + harbor + "." + TidePredictionFactory.defaultTideFormat); if (f.exists() && !f.getAbsolutePath().equals(used.getAbsolutePath())) { int resp = GuiUtils.confirmDialog(getConsole(), I18n.text("Tide Predictions"), I18n.textf( "The selected location does not match the current location in use (%harbor). Do you wish to set the current location as %selection?", used.getName(), harbor + "." + TidePredictionFactory.defaultTideFormat), ModalityType.DOCUMENT_MODAL); if (resp == JOptionPane.YES_OPTION) { GeneralPreferences.tidesFile = f; GeneralPreferences.saveProperties(); preferencesUpdated(); // Force the tide file reload TidePredictionFactory.getTideLevel(System.currentTimeMillis()); } } } } catch (Exception e) { e.printStackTrace(); } finally { menu.setEnabled(true); } }; }; t.setDaemon(true); menu.setEnabled(false); t.start(); } }); ts = new TimeSeries(I18n.text("Tide level")); tsc.addSeries(ts); for (double i = -12; i < 12; i += 0.25) { Date d = new Date(System.currentTimeMillis() + (long) (i * 1000 * 3600)); ts.addOrUpdate(new Millisecond(d), TidePredictionFactory.getTideLevel(d)); } timeSeriesChart.getXYPlot().addDomainMarker(marker); levelMarker.setValue(TidePredictionFactory.getTideLevel(new Date())); timeSeriesChart.getXYPlot().addRangeMarker(levelMarker); }
From source file:com.mibr.android.intelligentreminder.INeedToo.java
/** Called when the activity is first created. */ @Override// w ww. ja v a 2 s .c o m public void onCreate(Bundle savedInstanceState) { /* this was just a test if(mLocationManager==null) { mLocationManager=(android.location.LocationManager) getSystemService(Context.LOCATION_SERVICE); } */ // TabHost host=this.getTabHost(); // host.setOnTabChangedListener(new TabHost.OnTabChangeListener() { // // @Override // public void onTabChanged(String tabId) { // if(INeedToo.this._doingCreatingTabs==false) { // if(tabId.equals("tab1")) { // INeedToo.this._forceNonCompany=true; // } // } // } // }); super.onCreate(savedInstanceState); mLocationClient = new LocationClient(this, this, this); mLocationClient.connect(); try { if (getIntent().getAction() != null && getIntent().getAction().equals("doPrimitiveDeletedNeed")) { transmitNetwork(getIntent().getStringExtra("phoneid")); return; } } catch (Exception eieio) { return; } try { /* putExtra("needId",needId). putExtra("foreignNeedId",foreignNeedId). putExtra("phoneid",phoneid). putExtra("foreignLocationId",foreignLocationId) */ if (getIntent().getAction() != null && getIntent().getAction().equals("transmitNetworkDeletedThisNeedByOnBehalfOf")) { long needId = getIntent().getLongExtra("needId", -11); long foreignNeedId = getIntent().getLongExtra("foreignNeedId", -11); String phoneId = getIntent().getStringExtra("phoneid"); long foreignLocationId = getIntent().getLongExtra("foreignLocationId", -11); if (needId != -11 && foreignNeedId != -11 && foreignLocationId != -11 && isNothingNot(phoneId)) transmitNetworkDeletedThisNeedByOnBehalfOf(needId, foreignNeedId, phoneId, foreignLocationId); return; } } catch (Exception ei3) { return; } /*bbhbb 2011-03-26*/ /*bbhbb2013_05_01 isn't this being done below? * Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler("")); */ mHandler = new Handler(); doBindService(); mSingleton = this; ///////////mSingleton.log("onCreating_INeedToo", 1); if (getPackageName().toLowerCase().indexOf("trial") != -1 && !isSpecialPhone()) { if (!iveCheckedAuthorizationStatusForThisPhone) { doViewCount = true; iveCheckedAuthorizationStatusForThisPhone = true; final Timer jdTimer = new Timer("Registering"); jdTimer.schedule(new TimerTask() { public void run() { Thread thread = new Thread(new Runnable() { public void run() { Intent intent = new Intent(INeedToo.this, INeedWebService.class) .setAction("CheckStatus"); startService(intent); jdTimer.cancel(); } }); thread.setPriority(Thread.MIN_PRIORITY); thread.run(); } }, 3000, 1000 * 60 * 10); } } else { if (IS_ANDROID_VERSION) { if (!isSpecialPhone() || INeedToo.mSingleton.getPhoneId().toLowerCase().equals("20013fc135cd6097xx")) { final Timer jdTimer = new Timer("Licensing"); jdTimer.schedule(new TimerTask() { public void run() { Thread thread = new Thread(new Runnable() { public void run() { // Construct the LicenseCheckerCallback. The library calls this when done. mLicenseCheckerCallback = new MyLicenseCheckerCallback(); // Construct the LicenseChecker with a Policy. mChecker = new LicenseChecker(INeedToo.this, new ServerManagedPolicy(INeedToo.this, new AESObfuscator(SALT, getPackageName(), // "com.mibr.android.intelligentreminder", getDeviceId())), BASE64_PUBLIC_KEY // Your public licensing key. ); mChecker.checkAccess(mLicenseCheckerCallback); } }); thread.setPriority(Thread.MIN_PRIORITY); thread.run(); } }, 3000, 1000 * 60 * 10); } } } try { _logFilter = Integer .valueOf(getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE) .getString("LoggingLevel", "3")); } catch (Exception e) { } if (!INeedLocationService.USING_LOCATION_SERVICES) { int logFilter = 3; try { logFilter = Integer .valueOf(getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE) .getString("LoggingLevel", "3")); } catch (Exception e) { } Intent jdIntent = new Intent(this, INeedTimerServices.class).putExtra("logFilter", logFilter); getApplicationContext().startService(jdIntent); } Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler("")); if (INeedToo.mSingleton.getPhoneId().toLowerCase().equals("22a100000d9f25c5")) { DELAYPOSTTTS = 100; } // I don't need this because IHaveNeeds.onresume does it getApplicationContext().startService(new Intent(this, INeedLocationService.class)); if (!_doneSplashy) { _doneSplashy = true; if (!getVersionFile()) { stampVersion(); showDialog(DIALOG_SPLASH); } else { //showDialog(DIALOG_SPLASH); } } if (allItems != null) { whereImAtInAllItems++; if (whereImAtInAllItems < allItems.size()) { showDialog(DOING_SAMPLE_NEEDS_DIALOG); } else { allItems = null; } } setTitle(getHeading()); Bundle bundle = getIntent().getExtras(); if (bundle != null) { _initialTabIndex = bundle.getInt("initialtabindex", 0); _didContact = bundle.getBoolean("iscontact", false); if (_initialTabIndex == 1) { _doingLocationCompany = bundle.getString("doingcompany"); } else { _doingLocationCompany = null; } } else { _doingLocationCompany = null; } final TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Need", getResources().getDrawable(R.drawable.status_bar2_blackwhite)) .setContent(new Intent(this, IHaveNeeds.class).putExtra("iscontact", this._didContact))); tabHost.addTab(tabHost.newTabSpec("tab2") .setIndicator("Location", (BitmapDrawable) getResources().getDrawable(android.R.drawable.ic_menu_mapmode)) .setContent( new Intent(this, IHaveLocations.class).putExtra("doingcompany", _doingLocationCompany))); Intent intent = new Intent(this, NeedMap.class).putExtra("doingcompany", _doingLocationCompany); tabHost.addTab(tabHost.newTabSpec("tab2a") .setIndicator("Map", (BitmapDrawable) getResources().getDrawable(R.drawable.ic_dialog_map)) .setContent(intent)); /* tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator( "History",(BitmapDrawable) getResources().getDrawable( R.drawable.chart)).setContent( new Intent(this, IHaveHistory.class))); */ tabHost.addTab(tabHost.newTabSpec("tab4") .setIndicator("System", (BitmapDrawable) getResources().getDrawable(R.drawable.status_bar1_blackwhite)) .setContent(new Intent(this, ListPlus.class))); /* tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator( "Need", scaleTo((BitmapDrawable) getResources().getDrawable( R.drawable.status_bar2_blackwhite), 36f)).setContent( new Intent(this, IHaveNeeds.class).putExtra("iscontact", this._didContact))); tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator( "Location", scaleTo((BitmapDrawable) getResources().getDrawable( android.R.drawable.ic_menu_mapmode), 36f)).setContent( new Intent(this, IHaveLocations.class).putExtra("doingcompany", _doingLocationCompany))); tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator( "History", scaleTo((BitmapDrawable) getResources().getDrawable( R.drawable.chart), 36f)).setContent( new Intent(this, IHaveHistory.class))); tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator( "System", scaleTo((BitmapDrawable) getResources().getDrawable( R.drawable.status_bar1_blackwhite), 31f)).setContent( new Intent(this, ListPlus.class))); */ tabHost.setCurrentTab(_initialTabIndex); boolean networkingOutbound = getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE) .getBoolean("Networking_Outbound_Enabled", false); if (INeedWebService.mSingleton == null) { if (networkingOutbound) { enableTransmitting(); } if (getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE) .getBoolean("Networking_Inbound_Enabled", false)) { enableReceiving(); } } }
From source file:com.dish.browser.activity.BrowserActivity.java
@SuppressLint("NewApi") @SuppressWarnings("deprecation") private synchronized void initialize() { setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);// w ww. jav a 2s . c o m ActionBar actionBar = getSupportActionBar(); mPreferences = PreferenceManager.getInstance(); mDarkTheme = mPreferences.getUseDarkTheme() || isIncognito(); mActivity = this; mWebViews.clear(); mClickHandler = new ClickHandler(this); mBrowserFrame = (FrameLayout) findViewById(R.id.content_frame); mToolbarLayout = (LinearLayout) findViewById(R.id.toolbar_layout); // initialize background ColorDrawable mBackground.setColor(((ColorDrawable) mToolbarLayout.getBackground()).getColor()); mUiLayout = (LinearLayout) findViewById(R.id.ui_layout); mProgressBar = (AnimatedProgressBar) findViewById(R.id.progress_view); RelativeLayout newTab = (RelativeLayout) findViewById(R.id.new_tab_button); mDrawerLeft = (LinearLayout) findViewById(R.id.left_drawer); // Drawer stutters otherwise mDrawerLeft.setLayerType(View.LAYER_TYPE_HARDWARE, null); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerListLeft = (ListView) findViewById(R.id.left_drawer_list); setNavigationDrawerWidth(); mWebpageBitmap = Utils.getWebpageBitmap(getResources(), mDarkTheme); mHomepage = mPreferences.getHomepage(); mTitleAdapter = new LightningViewAdapter(this, R.layout.tab_list_item, mWebViews); mDrawerListLeft.setAdapter(mTitleAdapter); mDrawerListLeft.setOnItemClickListener(new DrawerItemClickListener()); mDrawerListLeft.setOnItemLongClickListener(new DrawerItemLongClickListener()); mHistoryDatabase = HistoryDatabase.getInstance(getApplicationContext()); // set display options of the ActionBar actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowCustomEnabled(true); actionBar.setCustomView(R.layout.toolbar_content); View v = actionBar.getCustomView(); LayoutParams lp = v.getLayoutParams(); lp.width = LayoutParams.MATCH_PARENT; v.setLayoutParams(lp); mArrowDrawable = new DrawerArrowDrawable(this); mArrowImage = (ImageView) actionBar.getCustomView().findViewById(R.id.arrow); // Use hardware acceleration for the animation mArrowImage.setLayerType(View.LAYER_TYPE_HARDWARE, null); mArrowImage.setImageDrawable(mArrowDrawable); LinearLayout arrowButton = (LinearLayout) actionBar.getCustomView().findViewById(R.id.arrow_button); arrowButton.setOnClickListener(this); mI2PHelper = new I2PAndroidHelper(this); RelativeLayout back = (RelativeLayout) findViewById(R.id.action_back); back.setOnClickListener(this); RelativeLayout forward = (RelativeLayout) findViewById(R.id.action_forward); forward.setOnClickListener(this); // create the search EditText in the ToolBar mSearch = (AutoCompleteTextView) actionBar.getCustomView().findViewById(R.id.search); mUntitledTitle = getString(R.string.untitled); mBackgroundColor = getResources().getColor(R.color.primary_color); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mDeleteIcon = getResources().getDrawable(R.drawable.ic_action_delete); mRefreshIcon = getResources().getDrawable(R.drawable.ic_action_refresh); mCopyIcon = getResources().getDrawable(R.drawable.ic_action_copy); } else { Theme theme = getTheme(); mDeleteIcon = getResources().getDrawable(R.drawable.ic_action_delete, theme); mRefreshIcon = getResources().getDrawable(R.drawable.ic_action_refresh, theme); mCopyIcon = getResources().getDrawable(R.drawable.ic_action_copy, theme); } int iconBounds = Utils.convertDpToPixels(24); mDeleteIcon.setBounds(0, 0, iconBounds, iconBounds); mRefreshIcon.setBounds(0, 0, iconBounds, iconBounds); mCopyIcon.setBounds(0, 0, iconBounds, iconBounds); mIcon = mRefreshIcon; SearchClass search = new SearchClass(); mSearch.setCompoundDrawables(null, null, mRefreshIcon, null); mSearch.setOnKeyListener(search.new KeyListener()); mSearch.setOnFocusChangeListener(search.new FocusChangeListener()); mSearch.setOnEditorActionListener(search.new EditorActionListener()); mSearch.setOnTouchListener(search.new TouchListener()); mSystemBrowser = getSystemBrowser(); Thread initialize = new Thread(new Runnable() { @Override public void run() { initializeSearchSuggestions(mSearch); } }); initialize.run(); newTab.setOnClickListener(this); newTab.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { String url = mPreferences.getSavedUrl(); if (url != null) { newTab(url, true); Toast.makeText(mActivity, R.string.deleted_tab, Toast.LENGTH_SHORT).show(); } mPreferences.setSavedUrl(null); return true; } }); mDrawerLayout.setDrawerShadow(R.drawable.drawer_right_shadow, GravityCompat.END); mDrawerLayout.setDrawerShadow(R.drawable.drawer_left_shadow, GravityCompat.START); initializeTabs(); if (API <= Build.VERSION_CODES.JELLY_BEAN_MR2) { WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath()); } checkForProxy(); }
From source file:com.machinepublishers.jbrowserdriver.diagnostics.Test.java
private void doTests() { JBrowserDriver driver = null;//from w w w .j ava2 s. c om Thread shutdownHook = null; try { HttpServer.launch(TEST_PORT_HTTP); final File cacheDir = Files.createTempDirectory("jbd_test_cache").toFile(); final File userDataDir = Files.createTempDirectory("jbd_test_userdata").toFile(); shutdownHook = new Thread(new Runnable() { @Override public void run() { FileUtils.deleteQuietly(cacheDir); FileUtils.deleteQuietly(userDataDir); } }); Runtime.getRuntime().addShutdownHook(shutdownHook); final String mainPage = "http://" + InetAddress.getLoopbackAddress().getHostAddress() + ":" + TEST_PORT_HTTP; final int ajaxWait = 150; final Settings.Builder builder = Settings.builder().processes(TEST_PORTS_RMI) .screen(new Dimension(1024, 768)).logger(null).logJavascript(true).ajaxWait(ajaxWait) .cacheDir(cacheDir).cache(true).ignoreDialogs(false); driver = new JBrowserDriver(builder.build()); /* * Load a page */ driver.get(mainPage); test(driver.getStatusCode() == 200); long initialRequestId = HttpServer.previousRequestId(); /* * Load page from cache */ driver.get(mainPage); test(driver.getStatusCode() == 200); test(HttpServer.previousRequestId() == initialRequestId); boolean viaHeader = false; for (String line : HttpServer.previousRequest()) { if (line.toLowerCase().startsWith("via:")) { viaHeader = true; break; } } test(!viaHeader); /* * Driver reset */ driver.reset(); driver.get(mainPage); test(driver.getStatusCode() == 200); test(HttpServer.previousRequestId() == initialRequestId); driver.reset(builder.cacheDir(null).build()); driver.get(mainPage); test(driver.getStatusCode() == 200); test(HttpServer.previousRequestId() != initialRequestId); /* * Javascript logs */ int messages = 0; for (LogEntry entry : driver.manage().logs().get("javascript").filter(Level.ALL)) { ++messages; test(!StringUtils.isEmpty(entry.getMessage())); } test(messages == 3); /* * User-data directory */ driver.findElement(By.id("populate-local-storage")).click(); driver.findElement(By.id("load-from-local-storage")).click(); test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); driver.get(mainPage); driver.findElement(By.id("load-from-local-storage")).click(); test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); driver.reset(); driver.get(mainPage); driver.findElement(By.id("load-from-local-storage")).click(); test("".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); driver.reset(builder.userDataDirectory(userDataDir).build()); driver.get(mainPage); driver.findElement(By.id("populate-local-storage")).click(); driver.findElement(By.id("load-from-local-storage")).click(); test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); driver.reset(); driver.get(mainPage); driver.findElement(By.id("load-from-local-storage")).click(); test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); /* * Select DOM elements */ test("test-data-attr".equals(driver.findElement(By.id("divtext1")).getAttribute("data-selected"))); test(driver.findElement(By.id("divtext1")).getAttribute("undefinedattr") == null); test(driver.findElement(By.id("divtext1")).getAttribute("innerText").equals("test1")); test(driver.findElements(By.name("divs")).size() == 2); test(driver.findElements(By.name("divs")).get(1).getAttribute("innerText").equals("test2")); test(driver.findElementByClassName("divclass").getAttribute("id").equals("divtext1")); test(driver.findElementsByClassName("divclass").get(1).getAttribute("id").equals("divtext2")); test(driver.findElementByCssSelector("#divtext1").getAttribute("id").equals("divtext1")); test(driver.findElementsByCssSelector("html > *").get(1).getAttribute("id").equals("testbody")); test(driver.findElementById("divtext1").getTagName().equals("div")); test(driver.findElementsById("divtext1").get(0).getTagName().equals("div")); test(driver.findElementByLinkText("anchor").getAttribute("id").equals("anchor1")); test(driver.findElementsByLinkText("anchor").get(1).getAttribute("id").equals("anchor2")); test(driver.findElementByName("divs").getAttribute("id").equals("divtext1")); test(driver.findElementsByName("divs").get(1).getAttribute("id").equals("divtext2")); test(driver.findElementByPartialLinkText("anch").getAttribute("id").equals("anchor1")); test(driver.findElementsByPartialLinkText("anch").get(1).getAttribute("id").equals("anchor2")); test(driver.findElementByTagName("div").getAttribute("id").equals("divtext1")); test(driver.findElementsByTagName("div").get(1).getAttribute("id").equals("divtext2")); test(driver.findElementByXPath("//*[@id='divtext1']").getAttribute("id").equals("divtext1")); test(driver.findElementByTagName("body").findElement(By.xpath("//*[@id='divtext1']")).getAttribute("id") .equals("divtext1")); test(driver.findElementsByXPath("//html/*").get(1).getAttribute("id").equals("testbody")); test(driver.findElement(By.xpath("//a[contains(@href,'1')]")).getAttribute("id").equals("anchor1")); test(driver.findElementsByXPath("//a[contains(@href,'!!!')]").isEmpty()); test(driver.findElementsByClassName("xx").isEmpty()); test(driver.findElementsByTagName("xx").isEmpty()); test(driver.findElementsByCssSelector("#xx").isEmpty()); Throwable error = null; try { driver.findElementByTagName("xx"); } catch (NoSuchElementException e) { error = e; } test(error != null); error = null; try { driver.findElementByCssSelector("#xx"); } catch (NoSuchElementException e) { error = e; } test(error != null); error = null; try { driver.findElementsByXPath("!!!"); } catch (WebDriverException e) { error = e; } test(error != null); error = null; try { driver.findElement(By.id("divtext1")).findElements(By.cssSelector("???")); } catch (WebDriverException e) { error = e; } test(error != null); /* * WebElement Equals/HashCode */ test(driver.findElements(By.name("divs")).get(0).equals(driver.findElements(By.name("divs")).get(0))); test(driver.findElements(By.name("divs")).get(0).hashCode() == driver.findElements(By.name("divs")) .get(0).hashCode()); /* * Typing text */ driver.findElement(By.id("text-input")).sendKeys("testing"); driver.findElement(By.id("text-input")).sendKeys(""); test(driver.findElement(By.id("text-input")).getAttribute("value").equals("testing")); driver.findElement(By.id("text-input")).sendKeys(JBrowserDriver.KEYBOARD_DELETE); test(driver.findElement(By.id("text-input")).getAttribute("value") == null); driver.findElement(By.id("text-input")).sendKeys("testing"); test(driver.findElement(By.id("text-input")).getAttribute("value").equals("testing")); driver.findElement(By.id("text-input")).clear(); test(driver.findElement(By.id("text-input")).getAttribute("value") == null); /* * Clicking on elements */ test(!driver.findElement(By.id("testoption2")).isSelected()); driver.findElement(By.id("testoption2")).click(); test(driver.findElement(By.id("testoption2")).isSelected()); driver.findElement(By.id("testoption1")).click(); test(driver.findElement(By.id("testoption1")).isSelected()); driver.findElement(By.id("anchor5")).click(); test("anchor clicked".equals(driver.findElement(By.id("testspan")).getText())); /* * Execute javascript */ test(((WebElement) driver.executeScript("return arguments[0];", driver.findElement(By.id("divtext1")))) .getAttribute("innerText").equals("test1")); test(((WebElement) driver.executeScript("return arguments[0].parentNode;", driver.findElement(By.id("divtext1")))).getTagName().equals("body")); test(((WebElement) ((JavascriptExecutor) driver.findElement(By.id("divtext1"))) .executeAsyncScript("arguments[0](this);")).getAttribute("innerText").equals("test1")); test((driver.executeAsyncScript("arguments[1](arguments[0].innerText);", driver.findElement(By.id("divtext1")))).equals("test1")); Map<String, Object> map = (Map<String, Object>) driver.executeScript("return {" + "key1:['value1','value2','value3'], " + "key2:5," + "key3:function(){return 'testing';}, " + "key4:undefined, key5:null, key6:1/0, key7:0/0, key8:'', key9:[], key10:{}, key11:[{},{}]," + "key12:document.getElementById('divtext1'), " + "key13:document.getElementsByName('divs'), " + "key14:[document.getElementById('divtext1'),document.getElementsByName('divs'),{subkey1:'subval1'}]};"); test(map.size() == 14); test(((List) map.get("key1")).size() == 3); test(((List) map.get("key1")).get(2).equals("value3")); test(((List) map.get("key1")).get(2) instanceof String); test(map.get("key2").equals(new Long(5))); test("function () {return 'testing';}".equals(map.get("key3")) || "function (){return 'testing';}".equals(map.get("key3"))); test(map.get("key4") == null); test(map.get("key5") == null); test(Double.isInfinite(((Double) map.get("key6")).doubleValue())); test(Double.isNaN(((Double) map.get("key7")).doubleValue())); test("".equals(map.get("key8"))); test(map.get("key9") instanceof List); test(map.get("key10") instanceof Map); test(((List) map.get("key11")).size() == 2); test(((Map) ((List) map.get("key11")).get(1)).isEmpty()); test("test1".equals(((WebElement) map.get("key12")).getAttribute("innerText"))); test(((List<WebElement>) map.get("key13")).size() == 2); test(((List<WebElement>) map.get("key13")).get(1).getAttribute("innerText").equals("test2")); test(((List) map.get("key14")).size() == 3); test(((List) ((List) map.get("key14")).get(1)).size() == 2); test(((WebElement) ((List) ((List) map.get("key14")).get(1)).get(1)).getAttribute("innerText") .equals("test2")); test(((Map) ((List) map.get("key14")).get(2)).size() == 1); test("subval1".equals(((Map) ((List) map.get("key14")).get(2)).get("subkey1"))); test(((List) driver.executeScript("return [];")).isEmpty()); test(((Map) driver.executeScript("return {};")).isEmpty()); error = null; try { driver.executeScript("invalid.execute()"); } catch (WebDriverException e) { error = e; } test(error != null); /* * DOM element properties */ WebElement element = driver.findElement(By.id("divtext1")); Point point = element.getLocation(); test(point.getX() > 0); test(point.getY() > 0); Dimension dimension = element.getSize(); test(dimension.width > 0); test(dimension.height > 0); Rectangle rect = element.getRect(); test(rect.x == point.getX()); test(rect.y == point.getY()); test(rect.width == dimension.getWidth()); test(rect.height == dimension.getHeight()); test("Testing\ntext.".equals(driver.findElement(By.id("text-node1")).getText())); test("".equals(driver.findElement(By.id("text-node2")).getText())); test("".equals(driver.findElement(By.id("text-node3")).getText())); List<WebElement> options = driver.findElementsByCssSelector("#testselect option"); test(options.size() == 2); test(options.get(0).isSelected()); test(!options.get(1).isSelected()); test(driver.findElementById("checkbox1").isSelected()); test(!driver.findElementById("checkbox2").isSelected()); /* * Cookie manager */ driver.manage().addCookie(new Cookie("testname", "testvalue")); Cookie cookie = driver.manage().getCookieNamed("testname"); test(cookie.getValue().equals("testvalue")); test(InetAddress.getLoopbackAddress().getHostAddress().equals(cookie.getDomain())); /* * Screenshots */ test(driver.getScreenshotAs(OutputType.BYTES).length > 0); /* * File Input Type */ driver.findElement(By.id("upload")).sendKeys("some-file"); test("event-test".equals(driver.findElement(By.id("file-input-onchange")).getText())); test(driver.findElement(By.id("upload")).getAttribute("value").endsWith("some-file")); /* * Javascript alerts */ driver.findElement(By.tagName("button")).click(); test(driver.switchTo().alert().getText().equals("test-alert")); driver.switchTo().alert().dismiss(); test(driver.switchTo().alert().getText().equals("test-confirm")); driver.switchTo().alert().dismiss(); test(driver.switchTo().alert().getText().equals("test-prompt")); driver.switchTo().alert().sendKeys("test-input"); driver.switchTo().alert().accept(); test(driver.findElement(By.id("testspan")).getAttribute("innerHTML").equals("test-input")); /* * Request headers */ List<String> request = HttpServer.previousRequest(); if (TEST_PORT_HTTP != 443 && TEST_PORT_HTTP != 80) { test(request.get(1).endsWith(":" + TEST_PORT_HTTP)); } test(request.size() > 1); Set<String> headers = new HashSet<String>(); for (String line : request) { if (line.contains(":")) { headers.add(line.split(":")[0].toLowerCase()); } } test(request.size() - 2 == headers.size()); /* * HTTP Post */ driver.findElement(By.id("form-submit")).click(); test(driver.getStatusCode() == 201); test("form-field=test-form-value" .equals(HttpServer.previousRequest().get(HttpServer.previousRequest().size() - 1))); /* * Frames */ driver.switchTo().frame(driver.findElementByTagName("iframe")); test(driver.findElementById("iframebody") != null); driver.switchTo().parentFrame(); test(driver.findElementById("testbody") != null); driver.switchTo().frame(0); test(driver.findElementById("iframebody") != null); driver.switchTo().defaultContent(); driver.switchTo().frame("testiframe"); test(driver.findElementById("iframebody") != null); driver.get(mainPage); test(driver.getPageSource() != null); driver.switchTo().frame(driver.findElementByTagName("iframe")); test(driver.findElementById("iframebody") != null); driver.switchTo().parentFrame(); driver.findElement(By.id("anchor3")).click(); test(driver.getPageSource() != null); driver.switchTo().frame(driver.findElementByTagName("iframe")); driver.findElement(By.id("iframe-anchor")).click(); //TODO iframe coord offset needed on any other methods? driver.pageWait(); test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe")); driver.get(mainPage); driver.switchTo().frame(driver.findElementByTagName("iframe")); Actions actions = new Actions(driver); actions.moveToElement(driver.findElement(By.id("iframe-anchor"))); actions.click(); actions.build().perform(); driver.pageWait(); test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe")); driver.get(mainPage); driver.switchTo().frame(driver.findElementByTagName("iframe")); driver.getMouse().click(((Locatable) driver.findElement(By.id("iframe-anchor"))).getCoordinates()); driver.getMouse().mouseMove(((Locatable) driver.findElement(By.id("iframe-anchor"))).getCoordinates(), 5, 5); driver.pageWait(); test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe")); //TODO fingerprinting //System.out.println(driver.findElement(By.id("iframe-useragent")).getAttribute("innerHTML")); //System.out.println(driver.findElement(By.id("iframe-nested-useragent")).getAttribute("innerHTML")); /* * Redirects and cookies */ driver.get(mainPage + "/redirect/site1#testfragment"); test(HttpServer.previousRequestId() != initialRequestId); test(driver.getStatusCode() == 200); test(driver.getCurrentUrl().endsWith("/redirect/site2#testfragment")); cookie = driver.manage().getCookieNamed("JSESSIONID"); test(cookie.getValue().equals("ABC123")); test(InetAddress.getLoopbackAddress().getHostAddress().equals(cookie.getDomain())); /* * Cookies set by Javascript */ test("jsCookieValue1".equals(driver.manage().getCookieNamed("jsCookieName1").getValue())); test("jsCookieValue2".equals(driver.manage().getCookieNamed("jsCookieName2").getValue())); test("jsCookieValue3".equals(driver.manage().getCookieNamed("jsCookieName3").getValue())); test("jsCookieValue4".equals(driver.manage().getCookieNamed("jsCookieName4").getValue())); /* * Window size and position */ driver.manage().window().setSize(new Dimension(5000, 5000)); test(driver.manage().window().getSize().getWidth() == 1024); test(driver.manage().window().getSize().getHeight() == 768); driver.manage().window().setSize(new Dimension(800, 600)); test(driver.manage().window().getSize().getWidth() == 800); test(driver.manage().window().getSize().getHeight() == 600); driver.manage().window().setPosition(new Point(5000, 5000)); test(driver.manage().window().getPosition().getX() == 224); test(driver.manage().window().getPosition().getY() == 168); driver.manage().window().setPosition(new Point(20, 50)); test(driver.manage().window().getPosition().getX() == 20); test(driver.manage().window().getPosition().getY() == 50); driver.manage().window().maximize(); test(driver.manage().window().getPosition().getX() == 0); test(driver.manage().window().getPosition().getY() == 0); test(driver.manage().window().getSize().getWidth() == 1024); test(driver.manage().window().getSize().getHeight() == 768); driver.manage().window().setSize(new Dimension(800, 600)); driver.manage().window().setPosition(new Point(20, 50)); driver.manage().window().fullscreen(); test(driver.manage().window().getPosition().getX() == 0); test(driver.manage().window().getPosition().getY() == 0); test(driver.manage().window().getSize().getWidth() == 1024); test(driver.manage().window().getSize().getHeight() == 768); driver.manage().window().fullscreen(); test(driver.manage().window().getPosition().getX() == 20); test(driver.manage().window().getPosition().getY() == 50); test(driver.manage().window().getSize().getWidth() == 800); test(driver.manage().window().getSize().getHeight() == 600); driver.manage().window().setSize(new Dimension(400, 200)); driver.manage().window().setPosition(new Point(10, 30)); test(driver.manage().window().getPosition().getX() == 10); test(driver.manage().window().getPosition().getY() == 30); test(driver.manage().window().getSize().getWidth() == 400); test(driver.manage().window().getSize().getHeight() == 200); driver.manage().window().setSize(new Dimension(1024, 768)); test(driver.manage().window().getPosition().getX() == 0); test(driver.manage().window().getPosition().getY() == 0); test(driver.manage().window().getSize().getWidth() == 1024); test(driver.manage().window().getSize().getHeight() == 768); /* * Element visibility */ test(driver.findElement(By.id("iframe-anchor")).isDisplayed()); test(!driver.findElement(By.id("anchor-visibility-hidden")).isDisplayed()); test(!driver.findElement(By.id("anchor-display-none")).isDisplayed()); error = null; try { driver.findElement(By.id("anchor-visibility-hidden")).click(); } catch (ElementNotVisibleException e) { error = e; } test(error != null); error = null; try { driver.findElement(By.id("anchor-display-none")).click(); } catch (ElementNotVisibleException e) { error = e; } test(error != null); /* * Operations on elements that no longer exist */ WebElement body = driver.findElement(By.tagName("body")); test(!StringUtils.isEmpty(body.getAttribute("outerHTML"))); driver.get("about:blank"); error = null; try { body.getAttribute("outerHTML"); } catch (StaleElementReferenceException e) { error = e; } test(error != null); /* * Timeouts */ driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.MILLISECONDS); error = null; try { driver.get(mainPage + "/wait-forever"); } catch (TimeoutException e) { error = e; } test(error != null); } catch (Throwable t) { outputError(testLabel("failed", curTest + 1, t)); } finally { try { driver.quit(); } catch (Throwable t) { outputError(toString(t)); } try { HttpServer.stop(); } catch (Throwable t) { outputError(toString(t)); } try { Runtime.getRuntime().removeShutdownHook(shutdownHook); shutdownHook.run(); } catch (Throwable t) { } } }