List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean
public AtomicBoolean()
From source file:com.tc.process.Exec.java
@SuppressWarnings("resource") public static Result execute(final Process process, String cmd[], String outputLog, byte[] input, File workingDir, final long timeout) throws Exception { final AtomicBoolean processFinished = new AtomicBoolean(); if (timeout > 0) { Thread timeoutThread = new Thread() { @Override//from ww w . jav a 2s. com public void run() { ThreadUtil.reallySleep(timeout); if (!processFinished.get()) { process.destroy(); } } }; timeoutThread.start(); } Thread inputThread = new InputPumper(input == null ? new byte[] {} : input, process.getOutputStream()); StreamCollector stderr = null; StreamCollector stdout = null; FileOutputStream fileOutput = null; StreamAppender outputLogger = null; String errString = null; String outString = null; try { if (outputLog != null) { errString = "stderr output redirected to file " + outputLog; outString = "stdout output redirected to file " + outputLog; fileOutput = new FileOutputStream(outputLog); outputLogger = new StreamAppender(fileOutput); outputLogger.writeInput(process.getErrorStream(), process.getInputStream()); } else { stderr = new StreamCollector(process.getErrorStream()); stdout = new StreamCollector(process.getInputStream()); stderr.start(); stdout.start(); } inputThread.start(); final int exitCode = process.waitFor(); processFinished.set(true); inputThread.join(); if (outputLogger != null) { outputLogger.finish(); } if (stderr != null) { stderr.join(); errString = stderr.toString(); } if (stdout != null) { stdout.join(); outString = stdout.toString(); } return new Result(cmd, outString, errString, exitCode); } finally { closeQuietly(fileOutput); } }
From source file:net.minecraftforge.gradle.util.ZipFileTree.java
public void visit(FileVisitor visitor) { if (!zipFile.exists()) { DeprecationLogger.nagUserOfDeprecatedBehaviour(String.format( "The specified zip file %s does not exist and will be silently ignored", getDisplayName())); return;/*from www . j a v a 2 s .c o m*/ } if (!zipFile.isFile()) { throw new InvalidUserDataException( String.format("Cannot expand %s as it is not a file.", getDisplayName())); } AtomicBoolean stopFlag = new AtomicBoolean(); try { ZipFile zip = new ZipFile(zipFile); try { // The iteration order of zip.getEntries() is based on the hash of the zip entry. This isn't much use // to us. So, collect the entries in a map and iterate over them in alphabetical order. Map<String, ZipEntry> entriesByName = new TreeMap<String, ZipEntry>(); Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); entriesByName.put(entry.getName(), entry); } Iterator<ZipEntry> sortedEntries = entriesByName.values().iterator(); while (!stopFlag.get() && sortedEntries.hasNext()) { ZipEntry entry = sortedEntries.next(); if (entry.isDirectory()) { visitor.visitDir(new DetailsImpl(entry, zip, stopFlag)); } else { visitor.visitFile(new DetailsImpl(entry, zip, stopFlag)); } } } finally { zip.close(); } } catch (Exception e) { throw new GradleException(String.format("Could not expand %s.", getDisplayName()), e); } }
From source file:at.sciencesoft.osgi.OXAdminGuiServletActivator.java
/** * Initializes a new {@link mwOXAdminGuiServletActivator} */ public OXAdminGuiServletActivator() { super(); registered = new AtomicBoolean(); }
From source file:com.gopivotal.cloudfoundry.test.core.MemoryUtils.java
public byte[][] outOfMemory() { try {//from w ww .ja va 2 s. c o m AtomicBoolean flag = new AtomicBoolean(); this.executor.submit(new MemorySizeLogger(flag)); return this.executor.submit(new MemoryExhauster(flag, this.outOfMemorySize)).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }
From source file:nl.rav.comparision.integration.unitofwork.java.UnitOfWorkSpringTest.java
@Before public void initializeTest() { doFail = new AtomicBoolean(); createRouteBuilder(); }
From source file:com.microsoft.alm.plugin.idea.tfvc.ui.checkout.TfvcCheckoutModel.java
@Override public void doCheckout(final Project project, final CheckoutProvider.Listener listener, final ServerContext context, final VirtualFile destinationParent, final String directoryName, final String parentDirectory, final boolean isAdvancedChecked) { final String workspaceName = directoryName; final String teamProjectName = getRepositoryName(context); final String localPath = Path.combine(parentDirectory, directoryName); final AtomicBoolean checkoutResult = new AtomicBoolean(); (new Task.Backgroundable(project, TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_TFVC_CREATING_WORKSPACE), true, PerformInBackgroundOption.DEAF) { public void run(@NotNull final ProgressIndicator indicator) { IdeaHelper.setProgress(indicator, 0.10, TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_TFVC_PROGRESS_CREATING)); try { // Create the workspace with default values final CreateWorkspaceCommand command = new CreateWorkspaceCommand(context, workspaceName, TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_TFVC_WORKSPACE_COMMENT), null, null); command.runSynchronously(); } catch (final WorkspaceAlreadyExistsException e) { logger.warn("Error creating workspace: " + LocalizationServiceImpl.getInstance().getExceptionMessage(e)); // TODO: allow user to change name in the flow instead of starting over IdeaHelper.runOnUIThread(new Runnable() { @Override//from w w w . ja v a 2 s . c om public void run() { Messages.showErrorDialog(project, LocalizationServiceImpl.getInstance().getExceptionMessage(e), TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_TFVC_FAILED_TITLE)); } }); // returning since the workspace failed to create so we can't proceed with the next steps return; } IdeaHelper.setProgress(indicator, 0.20, TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_TFVC_PROGRESS_ADD_ROOT)); // Map the project root to the local folder final String serverPath = VcsHelper.TFVC_ROOT + teamProjectName; final UpdateWorkspaceMappingCommand mappingCommand = new UpdateWorkspaceMappingCommand(context, workspaceName, new Workspace.Mapping(serverPath, localPath, false), false); mappingCommand.runSynchronously(); IdeaHelper.setProgress(indicator, 0.30, TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_TFVC_PROGRESS_CREATE_FOLDER)); // Ensure that the local folder exists final File file = new File(localPath); if (!file.mkdirs()) { //TODO should we throw here? } // if advanced is set, then sync just some of the files (those that we need for IntelliJ) // Otherwise, sync all the files for the team project if (!isAdvancedChecked) { IdeaHelper.setProgress(indicator, 0.50, TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_TFVC_PROGRESS_SYNC)); // Sync all files recursively CommandUtils.syncWorkspace(context, localPath); } IdeaHelper.setProgress(indicator, 1.00, "", true); // No exception means that it was successful checkoutResult.set(true); } public void onSuccess() { if (checkoutResult.get()) { // Check the isAdvanced flag if (isAdvancedChecked) { // The user wants to edit the workspace before syncing... final RepositoryContext repositoryContext = RepositoryContext.createTfvcContext(localPath, workspaceName, teamProjectName, context.getServerUri().toString()); final WorkspaceController controller = new WorkspaceController(project, repositoryContext, workspaceName); if (controller.showModalDialog(false)) { // Save and Sync the workspace (this will be backgrounded) controller.saveWorkspace(localPath, true, new Runnable() { @Override public void run() { // Files are all synchronized, so trigger the VCS update UpdateVersionControlSystem(project, parentDirectory, directoryName, destinationParent, listener); } }); } } else { // We don't have to wait for the workspace to be updated, so just trigger the VCS update UpdateVersionControlSystem(project, parentDirectory, directoryName, destinationParent, listener); } } } }).queue(); }
From source file:edu.cornell.mannlib.vitro.webapp.tboxreasoner.ConfiguredReasonerListener.java
public ConfiguredReasonerListener(ReasonerConfiguration reasonerConfiguration, TBoxReasonerDriver reasonerDriver) { this.reasonerConfiguration = reasonerConfiguration; this.reasonerDriver = reasonerDriver; this.drivingPatternMap = new DrivingPatternMap(reasonerConfiguration.getInferenceDrivingPatternAllowSet()); this.changeSet = new AtomicReference<>(new TBoxChanges()); this.suspended = new AtomicBoolean(); }
From source file:com.github.brandtg.switchboard.MysqlLogPuller.java
/** * Creates an agent to listen to MySQL changes (via binlog). * * @param database/*from w w w . ja v a2 s . com*/ * The MySQL database name * @param sourceAddress * The switchboard server address from which to pull events * @param sinkAddress * The local listener port to receive raw binlog data * @param lastIndex * The last index that was processed by whoever is constructing this (if -1, processed none) */ public MysqlLogPuller(String database, InetSocketAddress sourceAddress, InetSocketAddress sinkAddress, long lastIndex) { this.database = database; this.lastIndex = lastIndex; this.sourceAddress = sourceAddress; this.sinkAddress = sinkAddress; this.inputStream = new PipedInputStream(); this.outputStream = new PipedOutputStream(); this.isStarted = new AtomicBoolean(); }
From source file:ch.cyberduck.core.sftp.SFTPChallengeResponseAuthentication.java
public boolean authenticate(final Host host, final Credentials credentials, final LoginCallback controller) throws BackgroundException { if (StringUtils.isBlank(host.getCredentials().getPassword())) { return false; }//from w w w . j a va 2 s. c om if (log.isDebugEnabled()) { log.debug(String.format("Login using challenge response authentication with credentials %s", credentials)); } try { session.getClient().auth(credentials.getUsername(), new AuthKeyboardInteractive(new ChallengeResponseProvider() { /** * Password sent flag */ private final AtomicBoolean password = new AtomicBoolean(); private String name = StringUtils.EMPTY; private String instruction = StringUtils.EMPTY; @Override public List<String> getSubmethods() { return Collections.emptyList(); } @Override public void init(final Resource resource, final String name, final String instruction) { if (StringUtils.isNoneBlank(instruction)) { this.instruction = instruction; } if (StringUtils.isNoneBlank(name)) { this.name = name; } } @Override public char[] getResponse(final String prompt, final boolean echo) { if (log.isDebugEnabled()) { log.debug(String.format("Reply to challenge name %s with instruction %s", name, instruction)); } final String response; // For each prompt, the corresponding echo field indicates whether the user input should // be echoed as characters are typed if (!password.get() // Some servers ask for one-time passcode first && !StringUtils.contains(prompt, "Verification code")) { // In its first callback the server prompts for the password if (log.isDebugEnabled()) { log.debug("First callback returning provided credentials"); } response = credentials.getPassword(); password.set(true); } else { final StringAppender message = new StringAppender().append(instruction) .append(prompt); // Properly handle an instruction field with embedded newlines. They should also // be able to display at least 30 characters for the name and prompts. final Credentials additional = new Credentials(credentials.getUsername()) { @Override public String getPasswordPlaceholder() { return StringUtils.removeEnd(StringUtils.strip(prompt), ":"); } }; try { final StringAppender title = new StringAppender().append(name).append( LocaleFactory.localizedString("Provide additional login credentials", "Credentials")); controller.prompt(host, additional, title.toString(), message.toString(), new LoginOptions().user(false).keychain(false)); } catch (LoginCanceledException e) { return EMPTY_RESPONSE; } response = additional.getPassword(); } // Responses are encoded in ISO-10646 UTF-8. return response.toCharArray(); } @Override public boolean shouldRetry() { return false; } })); } catch (IOException e) { throw new SFTPExceptionMappingService().map(e); } return session.getClient().isAuthenticated(); }
From source file:ch.cyberduck.core.SingleTransferWorkerTest.java
@Test public void testTransferredSizeRepeat() throws Exception { final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final byte[] content = new byte[62768]; new Random().nextBytes(content); final OutputStream out = local.getOutputStream(false); IOUtils.write(content, out);//from w w w .j a v a 2s. co m out.close(); final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch", new Credentials(System.getProperties().getProperty("webdav.user"), System.getProperties().getProperty("webdav.password"))); host.setDefaultPath("/dav/basic"); final AtomicBoolean failed = new AtomicBoolean(); final DAVSession session = new DAVSession(host) { final DAVUploadFeature upload = new DAVUploadFeature(this) { @Override protected InputStream decorate(final InputStream in, final MessageDigest digest) throws IOException { if (failed.get()) { // Second attempt successful return in; } return new CountingInputStream(in) { @Override protected void beforeRead(final int n) throws IOException { super.beforeRead(n); if (this.getByteCount() >= 32768L) { failed.set(true); throw new SocketTimeoutException(); } } }; } }; @Override @SuppressWarnings("unchecked") public <T> T getFeature(final Class<T> type) { if (type == Upload.class) { return (T) upload; } return super.getFeature(type); } }; session.open(new DisabledHostKeyCallback(), new DisabledTranscriptListener()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final Transfer t = new UploadTransfer(new Host(new TestProtocol()), test, local); final BytecountStreamListener counter = new BytecountStreamListener(new DisabledStreamListener()); assertTrue(new SingleTransferWorker(session, t, new TransferOptions(), new TransferSpeedometer(t), new DisabledTransferPrompt() { @Override public TransferAction prompt(final TransferItem file) { return TransferAction.overwrite; } }, new DisabledTransferErrorCallback(), new DisabledTransferItemCallback(), new DisabledProgressListener(), counter, new DisabledLoginCallback(), TransferItemCache.empty()) { }.run(session)); local.delete(); assertEquals(62768L, counter.getSent(), 0L); assertEquals(62768L, new DAVAttributesFeature(session).find(test).getSize()); assertTrue(failed.get()); new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }