List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean
public AtomicBoolean()
From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java
/** * Test method for executing non-emulated command. *///from w w w .j a va 2 s .com @Test public void executeCommand_delegate() { Assume.assumeTrue("not unix-like", SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_LINUX); File touch = new File("/usr/bin/touch"); Assume.assumeTrue("no 'touch' command", touch.isFile() && touch.canExecute()); AtomicBoolean call = new AtomicBoolean(); MockCommandEmulator.callback(args -> call.set(true)); File target = new File(framework.getWork("working"), "target"); Assume.assumeFalse(target.exists()); // exec: touch .../target TestExecutionPlan.Command command = command("generic", touch.getPath(), target.getAbsolutePath()); JobExecutor executor = new InProcessJobExecutor(context); try { executor.execute(command, Collections.emptyMap()); } catch (IOException e) { throw new AssertionError(e); } assertThat(target.exists(), is(true)); assertThat(call.get(), is(false)); }
From source file:org.pentaho.di.trans.steps.httppost.HTTPPOSTIT.java
public void testServerReturnsCorrectlyEncodedParams(String testString, String testCharset) throws Exception { AtomicBoolean testStatus = new AtomicBoolean(); startHttpServer(getEncodingCheckingHandler(testString, testCharset, testStatus)); HTTPPOSTData data = new HTTPPOSTData(); RowMeta meta = new RowMeta(); meta.addValueMeta(new ValueMetaString("fieldName")); HTTPPOSTHandler httpPost = new HTTPPOSTHandler(stepMockHelper.stepMeta, data, 0, stepMockHelper.transMeta, stepMockHelper.trans, false); RowMetaInterface inputRowMeta = mock(RowMetaInterface.class); httpPost.setInputRowMeta(inputRowMeta); httpPost.row = new Object[] { testString }; when(inputRowMeta.clone()).thenReturn(inputRowMeta); when(inputRowMeta.getString(httpPost.row, 0)).thenReturn(testString); when(stepMockHelper.processRowsStepMetaInterface.getUrl()).thenReturn(HTTP_LOCALHOST_9998); when(stepMockHelper.processRowsStepMetaInterface.getQueryField()).thenReturn(new String[] {}); when(stepMockHelper.processRowsStepMetaInterface.getArgumentField()) .thenReturn(new String[] { "testBodyField" }); when(stepMockHelper.processRowsStepMetaInterface.getArgumentParameter()) .thenReturn(new String[] { "testBodyParam" }); when(stepMockHelper.processRowsStepMetaInterface.getArgumentHeader()).thenReturn(new boolean[] { false }); when(stepMockHelper.processRowsStepMetaInterface.getFieldName()).thenReturn("ResultFieldName"); when(stepMockHelper.processRowsStepMetaInterface.getEncoding()).thenReturn(testCharset); httpPost.init(stepMockHelper.processRowsStepMetaInterface, data); Assert.assertTrue(httpPost.processRow(stepMockHelper.processRowsStepMetaInterface, data)); Assert.assertTrue(testStatus.get(), "Test failed"); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.BaselineFolderCollection.java
/** * Given a baseline file GUID, returns the full path to the baseline file in * a baseline folder. The baseline file may be compressed or uncompressed. * * * @param workspace//from w ww . ja v a 2 s . c o m * @param baselineFolders * @param baselineFileGuid * Baseline GUID to look up * @return The full path of the baseline file, if found */ public static String getBaselineLocation(final Workspace workspace, final List<BaselineFolder> baselineFolders, final byte[] baselineFileGuid) { // This overload just eats the isBaselineCompressed bit for callers that // do not need it. final AtomicBoolean isBaselineCompressed = new AtomicBoolean(); return getBaselineLocation(workspace, baselineFolders, baselineFileGuid, isBaselineCompressed); }
From source file:ch.cyberduck.core.cryptomator.impl.CryptoVaultTest.java
@Test public void testLoadInvalidPassphrase() throws Exception { final NullSession session = new NullSession(new Host(new TestProtocol())) { @Override/*from w w w . j a v a2s . c o m*/ @SuppressWarnings("unchecked") public <T> T _getFeature(final Class<T> type) { if (type == Read.class) { return (T) new Read() { @Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final String masterKey = "{\n" + " \"scryptSalt\": \"NrC7QGG/ouc=\",\n" + " \"scryptCostParam\": 16384,\n" + " \"scryptBlockSize\": 8,\n" + " \"primaryMasterKey\": \"Q7pGo1l0jmZssoQh9rXFPKJE9NIXvPbL+HcnVSR9CHdkeR8AwgFtcw==\",\n" + " \"hmacMasterKey\": \"xzBqT4/7uEcQbhHFLC0YmMy4ykVKbuvJEA46p1Xm25mJNuTc20nCbw==\",\n" + " \"versionMac\": \"hlNr3dz/CmuVajhaiGyCem9lcVIUjDfSMLhjppcXOrM=\",\n" + " \"version\": 5\n" + "}"; return IOUtils.toInputStream(masterKey, Charset.defaultCharset()); } @Override public boolean offset(final Path file) throws BackgroundException { return false; } }; } return super._getFeature(type); } }; final AtomicBoolean prompt = new AtomicBoolean(); final CryptoVault vault = new CryptoVault(new Path("/", EnumSet.of(Path.Type.directory)), new DisabledPasswordStore()); try { vault.load(session, new DisabledPasswordCallback() { @Override public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) throws LoginCanceledException { if (!prompt.get()) { assertEquals("Provide your passphrase to unlock the Cryptomator Vault /", reason); prompt.set(true); return new VaultCredentials("null"); } else { assertEquals( "Failure to decrypt master key file. Provide your passphrase to unlock the Cryptomator Vault /.", reason); throw new LoginCanceledException(); } } }); fail(); } catch (LoginCanceledException e) { // } assertTrue(prompt.get()); }
From source file:com.screenslicer.core.scrape.Scrape.java
private static String getHelper(final RemoteWebDriver driver, final Node urlNode, final String url, final boolean p_cached, final String runGuid, final HtmlNode[] clicks) { final String urlHash = CommonUtil.isEmpty(url) ? null : Crypto.fastHash(url); final long time = System.currentTimeMillis(); if (urlHash != null) { synchronized (fetchLocalCacheLock) { if (fetchLocalCache.containsKey(urlHash)) { if (time - fetchLocalCache.get(urlHash) < FETCH_LOCAL_CACHE_EXPIRES) { try { return FileUtils.readFileToString(new File("./fetch_local_cache/" + urlHash), "utf-8"); } catch (Throwable t) { Log.exception(t); fetchLocalCache.remove(urlHash); }//from www . j a va 2 s. co m } else { fetchLocalCache.remove(urlHash); } } } } if (!CommonUtil.isEmpty(url)) { final Object resultLock = new Object(); final String initVal; final String[] result; synchronized (resultLock) { initVal = Random.next(); result = new String[] { initVal }; } final AtomicBoolean started = new AtomicBoolean(); Thread thread = new Thread(new Runnable() { @Override public void run() { started.set(true); boolean cached = p_cached; String newHandle = null; String origHandle = null; try { origHandle = driver.getWindowHandle(); String content = null; if (!cached) { try { Util.get(driver, url, urlNode, false); } catch (Throwable t) { if (urlNode != null) { Util.newWindow(driver); } Util.get(driver, url, false); } if (urlNode != null) { newHandle = driver.getWindowHandle(); } Util.doClicks(driver, clicks, null); content = driver.getPageSource(); if (CommonUtil.isEmpty(content)) { cached = true; } } if (cached) { if (ScreenSlicerBatch.isCancelled(runGuid)) { return; } Util.get(driver, toCacheUrl(url), false); content = driver.getPageSource(); } content = Util.clean(content, driver.getCurrentUrl()).outerHtml(); if (WebApp.DEBUG) { try { FileUtils.writeStringToFile(new File("./" + System.currentTimeMillis()), content); } catch (IOException e) { } } //TODO make iframes work // if (!CommonUtil.isEmpty(content)) { // Document doc = Jsoup.parse(content); // Elements docFrames = doc.getElementsByTag("iframe"); // List<WebElement> iframes = driver.findElementsByTagName("iframe"); // int cur = 0; // for (WebElement iframe : iframes) { // try { // driver.switchTo().frame(iframe); // String frameSrc = driver.getPageSource(); // if (!CommonUtil.isEmpty(frameSrc) && cur < docFrames.size()) { // docFrames.get(cur).html( // Util.outerHtml(Jsoup.parse(frameSrc).body().childNodes())); // } // } catch (Throwable t) { // Log.exception(t); // } // ++cur; // } // driver.switchTo().defaultContent(); // content = doc.outerHtml(); // } synchronized (resultLock) { result[0] = content; } } catch (Throwable t) { Log.exception(t); } finally { synchronized (resultLock) { if (initVal.equals(result[0])) { result[0] = null; } } Util.driverSleepRandLong(); if (newHandle != null && origHandle != null) { try { Util.cleanUpNewWindows(driver, origHandle); } catch (Throwable t) { Log.exception(t); } } } } }); thread.start(); try { while (!started.get()) { try { Thread.sleep(WAIT); } catch (Throwable t) { Log.exception(t); } } thread.join(HANG_TIME); synchronized (resultLock) { if (initVal.equals(result[0])) { try { Log.exception(new Exception("Browser is hanging")); forceQuit(); thread.interrupt(); } catch (Throwable t) { Log.exception(t); } throw new ActionFailed(); } else if (urlHash != null && !CommonUtil.isEmpty(result[0]) && result[0].length() > MIN_FETCH_CACHE_PAGE_LEN) { synchronized (fetchLocalCacheLock) { if (fetchLocalCache.size() > MAX_FETCH_LOCAL_CACHE) { try { FileUtils.deleteQuietly(new File("./fetch_local_cache")); FileUtils.forceMkdir(new File("./fetch_local_cache")); } catch (Throwable t) { Log.exception(t); } fetchLocalCache.clear(); } FileUtils.writeStringToFile(new File("./fetch_local_cache/" + urlHash), result[0], "utf-8", false); fetchLocalCache.put(urlHash, time); } } return result[0]; } } catch (Throwable t) { Log.exception(t); } } return null; }
From source file:com.google.gdt.eclipse.designer.util.Utils.java
/** * @return <code>true</code> if given module inherits required, directly or indirectly. *///from www . j a v a 2s . c o m public static boolean inheritsModule(ModuleDescription moduleDescription, final String requiredModule) throws Exception { final AtomicBoolean result = new AtomicBoolean(); ModuleVisitor.accept(moduleDescription, new ModuleVisitor() { @Override public void endVisitModule(ModuleElement module) { if (requiredModule.equals(module.getId())) { result.set(true); } } }); return result.get(); }
From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParserTest.java
@Test public void testStackedParser() throws Exception { ActivityXmlParser parser = new ActivityXmlParser() { @Override//from w ww .j a v a2 s .c om protected Object getTextOnDemand(Node node, ActivityFieldLocator locator, ActivityContext cData, AtomicBoolean formattingNeeded) throws ParseException { return node; } }; ActivityXmlParser stackedParser = new ActivityXmlParser() { @Override protected Object getTextOnDemand(Node node, ActivityFieldLocator locator, ActivityContext cData, AtomicBoolean formattingNeeded) throws ParseException { return node; } }; parser.intXmlParser(new HashMap<String, String>()); stackedParser.intXmlParser(new HashMap<String, String>()); String data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<root xmlns:foo=\"http://www.foo.org/\" xmlns:bar=\"http://www.bar.org\">\n" + "\t<employees>\n" + "\t\t<employee id=\"1\">Johnny Dapp</employee>\n" + "\t\t<employee id=\"2\">Al Pacino</employee>\n" + "\t\t<employee id=\"3\">Robert De Niro</employee>\n" + "\t\t<employee id=\"4\">Kevin Spacey</employee>\n" + "\t\t<employee id=\"5\">Denzel Washington</employee>\n" + "\t\t\n" + "\t</employees>\n" + "\t<foo:companies>\n" + "\t\t<foo:company id=\"6\">Tata Consultancy Services</foo:company>\n" + "\t\t<foo:company id=\"7\">Wipro</foo:company>\n" + "\t\t<foo:company id=\"8\">Infosys</foo:company>\n" + "\t\t<foo:company id=\"9\">Microsoft</foo:company>\n" + "\t\t<foo:company id=\"10\">IBM</foo:company>\n" + "\t\t<foo:company id=\"11\">Apple</foo:company>\n" + "\t\t<foo:company id=\"12\">Oracle</foo:company>\n" + "\t</foo:companies>\n" + "</root>"; GenericActivityParser<Node>.ActivityContext activityContext = parser .prepareItem(mock(TNTParseableInputStream.class), data); ActivityFieldLocator locator = new ActivityFieldLocator(ActivityFieldLocatorType.Label, "/root/employees", ActivityFieldDataType.String); Object o = parser.resolveLocatorValue(locator, activityContext, new AtomicBoolean()); GenericActivityParser<Node>.ActivityContext activityContext2 = parser .prepareItem(mock(TNTParseableInputStream.class), o); ActivityFieldLocator locator2 = new ActivityFieldLocator(ActivityFieldLocatorType.Label, "/employees/*[1]", ActivityFieldDataType.String); ActivityFieldLocator locator3 = new ActivityFieldLocator(ActivityFieldLocatorType.Label, "/root/employees/*[2]", ActivityFieldDataType.String); Object s = stackedParser.resolveLocatorValue(locator2, activityContext2, new AtomicBoolean()); Object f = stackedParser.resolveLocatorValue(locator3, activityContext2, new AtomicBoolean()); if (o instanceof Node && s instanceof Node && f instanceof Node) { assertTrue(((Node) o).getTextContent().length() > 1); assertTrue(((Node) o).getTextContent().length() > 1); assertTrue(((Node) o).getTextContent().length() > 1); } else { fail(); } }
From source file:com.google.dart.java2dart.SyntaxTranslator.java
private static boolean hasConstructorInvocation(org.eclipse.jdt.core.dom.ASTNode node) { final AtomicBoolean result = new AtomicBoolean(); node.accept(new ASTVisitor() { @Override/*from ww w. ja va 2s . c o m*/ public boolean visit(ConstructorInvocation node) { result.set(true); return false; } }); return result.get(); }
From source file:at.alladin.rmbt.client.RMBTClient.java
public TestResult runTest() throws InterruptedException { System.out.println("starting test..."); long txBytes = 0; long rxBytes = 0; final long timeStampStart = System.nanoTime(); if (testStatus.get() != TestStatus.ERROR && testThreadPool != null) { if (trafficService != null) { txBytes = trafficService.getTotalTxBytes(); rxBytes = trafficService.getTotalRxBytes(); }/* w ww . j av a 2 s . c o m*/ resetSpeed(); downBitPerSec.set(-1); upBitPerSec.set(-1); pingNano.set(-1); initNano.set(-1); final long waitTime = params.getStartTime() - System.currentTimeMillis(); if (waitTime > 0) { setStatus(TestStatus.WAIT); log(String.format(Locale.US, "we have to wait %d ms...", waitTime)); Thread.sleep(waitTime); log(String.format(Locale.US, "...done.", waitTime)); } else log(String.format(Locale.US, "luckily we do not have to wait.", waitTime)); setStatus(TestStatus.INIT); statusBeforeError.set(null); if (testThreadPool.isShutdown()) throw new IllegalStateException("RMBTClient already shut down"); log("starting test..."); final int numThreads = params.getNumThreads(); aborted.set(false); result = new TotalTestResult(); if (params.isEncryption()) sslSocketFactory = createSSLSocketFactory(); log(String.format(Locale.US, "Host: %s; Port: %s; Enc: %s", params.getHost(), params.getPort(), params.isEncryption())); log(String.format(Locale.US, "starting %d threads...", numThreads)); final CyclicBarrier barrier = new CyclicBarrier(numThreads); @SuppressWarnings("unchecked") final Future<ThreadTestResult>[] results = new Future[numThreads]; final int storeResults = (int) (params.getDuration() * 1000000000L / MIN_DIFF_TIME); final AtomicBoolean fallbackToOneThread = new AtomicBoolean(); for (int i = 0; i < numThreads; i++) { testTasks[i] = new RMBTTest(this, params, i, barrier, storeResults, MIN_DIFF_TIME, fallbackToOneThread); results[i] = testThreadPool.submit(testTasks[i]); } try { long shortestPing = Long.MAX_VALUE; // wait for all threads first for (int i = 0; i < numThreads; i++) results[i].get(); if (aborted.get()) return null; final long[][] allDownBytes = new long[numThreads][]; final long[][] allDownNsecs = new long[numThreads][]; final long[][] allUpBytes = new long[numThreads][]; final long[][] allUpNsecs = new long[numThreads][]; int realNumThreads = 0; log(""); for (int i = 0; i < numThreads; i++) { final ThreadTestResult testResult = results[i].get(); if (testResult != null) { realNumThreads++; log(String.format(Locale.US, "Thread %d: Download: bytes: %d time: %.3f s", i, ThreadTestResult.getLastEntry(testResult.down.bytes), ThreadTestResult.getLastEntry(testResult.down.nsec) / 1e9)); log(String.format(Locale.US, "Thread %d: Upload: bytes: %d time: %.3f s", i, ThreadTestResult.getLastEntry(testResult.up.bytes), ThreadTestResult.getLastEntry(testResult.up.nsec) / 1e9)); final long ping = testResult.ping_shortest; if (ping < shortestPing) shortestPing = ping; if (!testResult.pings.isEmpty()) result.pings.addAll(testResult.pings); allDownBytes[i] = testResult.down.bytes; allDownNsecs[i] = testResult.down.nsec; allUpBytes[i] = testResult.up.bytes; allUpNsecs[i] = testResult.up.nsec; result.totalDownBytes += testResult.totalDownBytes; result.totalUpBytes += testResult.totalUpBytes; // aggregate speedItems result.speedItems.addAll(testResult.speedItems); } } result.calculateDownload(allDownBytes, allDownNsecs); result.calculateUpload(allUpBytes, allUpNsecs); log(""); log(String.format(Locale.US, "Total calculated bytes down: %d", result.bytes_download)); log(String.format(Locale.US, "Total calculated time down: %.3f s", result.nsec_download / 1e9)); log(String.format(Locale.US, "Total calculated bytes up: %d", result.bytes_upload)); log(String.format(Locale.US, "Total calculated time up: %.3f s", result.nsec_upload / 1e9)); // get Connection Info from thread 1 (one thread must run) result.ip_local = results[0].get().ip_local; result.ip_server = results[0].get().ip_server; result.port_remote = results[0].get().port_remote; result.encryption = results[0].get().encryption; result.num_threads = realNumThreads; result.ping_shortest = shortestPing; result.speed_download = result.getDownloadSpeedBitPerSec() / 1e3; result.speed_upload = result.getUploadSpeedBitPerSec() / 1e3; log(""); log(String.format(Locale.US, "Total Down: %.0f kBit/s", result.getDownloadSpeedBitPerSec() / 1e3)); log(String.format(Locale.US, "Total UP: %.0f kBit/s", result.getUploadSpeedBitPerSec() / 1e3)); log(String.format(Locale.US, "Ping: %.2f ms", shortestPing / 1e6)); if (controlConnection != null) { log(""); final String testId = controlConnection.getTestId(); final String testUUID = params.getUUID(); final long testTime = controlConnection.getTestTime(); log(String.format(Locale.US, "uid=%s, time=%s, uuid=%s\n", testId, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US).format(new Date(testTime)), testUUID)); } downBitPerSec.set(Math.round(result.getDownloadSpeedBitPerSec())); upBitPerSec.set(Math.round(result.getUploadSpeedBitPerSec())); log("end."); setStatus(TestStatus.SPEEDTEST_END); if (trafficService != null) { txBytes = trafficService.getTotalTxBytes() - txBytes; rxBytes = trafficService.getTotalRxBytes() - rxBytes; result.setTotalTrafficMeasurement( new TestMeasurement(rxBytes, txBytes, timeStampStart, System.nanoTime())); result.setMeasurementMap(measurementMap); } return result; } catch (final ExecutionException e) { log(e); abortTest(true); return null; } catch (final InterruptedException e) { log("RMBTClient interrupted!"); abortTest(false); throw e; } } else { setStatus(TestStatus.SPEEDTEST_END); return null; } }
From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java
private String launchProcess(final Settings settings, final PortGroup portGroup) { final AtomicBoolean ready = new AtomicBoolean(); final AtomicReference<String> logPrefix = new AtomicReference<String>(""); new Thread(new Runnable() { @Override/*ww w .j a v a2 s.com*/ public void run() { List<String> myArgs = new ArrayList<String>(); myArgs.add(settings.javaBinary() == null ? JAVA_BIN : settings.javaBinary()); myArgs.addAll(inheritedArgs); if (!settings.customClasspath()) { myArgs.addAll(classpathArgs.get()); } if (settings.javaExportModules()) { myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network=ALL-UNNAMED"); myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network.about=ALL-UNNAMED"); myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network.data=ALL-UNNAMED"); myArgs.add("-XaddExports:java.base/sun.net.www.protocol.http=ALL-UNNAMED"); myArgs.add("-XaddExports:java.base/sun.net.www.protocol.https=ALL-UNNAMED"); myArgs.add("-XaddExports:java.base/sun.net.www.protocol.file=ALL-UNNAMED"); myArgs.add("-XaddExports:java.base/sun.net.www.protocol.ftp=ALL-UNNAMED"); myArgs.add("-XaddExports:java.base/sun.net.www.protocol.jar=ALL-UNNAMED"); myArgs.add("-XaddExports:java.base/sun.net.www.protocol.mailto=ALL-UNNAMED"); myArgs.add("-XaddExports:javafx.graphics/com.sun.glass.ui=ALL-UNNAMED"); myArgs.add("-XaddExports:javafx.web/com.sun.javafx.webkit=ALL-UNNAMED"); myArgs.add("-XaddExports:javafx.web/com.sun.webkit=ALL-UNNAMED"); } myArgs.add("-Djava.io.tmpdir=" + tmpDir.getAbsolutePath()); myArgs.add("-Djava.rmi.server.hostname=" + settings.host()); myArgs.addAll(settings.javaOptions()); myArgs.add(JBrowserDriverServer.class.getName()); myArgs.add(Long.toString(portGroup.child)); myArgs.add(Long.toString(portGroup.parent)); myArgs.add(Long.toString(portGroup.parentAlt)); try { new ProcessExecutor().addListener(new ProcessListener() { @Override public void afterStart(Process proc, ProcessExecutor executor) { process.set(proc); } }).redirectOutput(new LogOutputStream() { boolean done = false; @Override protected void processLine(String line) { if (line != null && !line.isEmpty()) { if (!done) { synchronized (ready) { if (line.startsWith("ready on ports ")) { String[] parts = line.substring("ready on ports ".length()).split("/"); actualPortGroup.set(new PortGroup(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))); logPrefix.set(new StringBuilder().append("[Instance ") .append(sessionIdCounter.incrementAndGet()).append("][Port ") .append(actualPortGroup.get().child).append("]").toString()); ready.set(true); ready.notifyAll(); done = true; } else { log(settings.logger(), logPrefix.get(), line); } } } else { log(settings.logger(), logPrefix.get(), line); } } } }).redirectError(new LogOutputStream() { @Override protected void processLine(String line) { log(settings.logger(), logPrefix.get(), line); } }).destroyOnExit().command(myArgs).execute(); } catch (Throwable t) { Util.handleException(t); } synchronized (ready) { ready.set(true); ready.notifyAll(); } } }).start(); synchronized (ready) { while (!ready.get()) { try { ready.wait(); break; } catch (InterruptedException e) { } } } return logPrefix.get(); }