List of usage examples for java.lang Thread interrupt
public void interrupt()
From source file:org.waarp.openr66.context.task.ExecOutputTask.java
@Override public void run() { /*/*from www . j a v a2s. c o m*/ * First apply all replacements and format to argRule from context and argTransfer. Will * call exec (from first element of resulting string) with arguments as the following value * from the replacements. Return 0 if OK, else 1 for a warning else as an error. In case of * an error (> 0), all the line from output will be send back to the partner with the Error * code. No change is made to the file. */ logger.info("ExecOutput with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Force the WaitForValidation waitForValidation = true; if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); LocalExecResult result = localExecClient.getLocalExecResult(); finalize(result.getStatus(), result.getResult(), finalname); localExecClient.disconnect(); return; } // else continue } String[] args = finalname.split(" "); File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + finalname); R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner()); futureCompletion.setResult(result); futureCompletion.cancel(); return; } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = null; try { outputStream = new PipedOutputStream(inputStream); } catch (IOException e1) { try { inputStream.close(); } catch (IOException e) { } logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1); futureCompletion.setFailure(e1); return; } PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } AllLineReader allLineReader = new AllLineReader(inputStream); Thread thread = new Thread(allLineReader, "ExecRename" + session.getRunner().getSpecialId()); thread.setDaemon(true); Configuration.configuration.getExecutorService().execute(thread); int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status, commandLine); return; } catch (IOException e1) { try { outputStream.flush(); } catch (IOException e2) { } try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } else { finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status, commandLine); return; } } catch (IOException e) { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } try { outputStream.flush(); } catch (IOException e) { } try { outputStream.close(); } catch (IOException e) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } try { if (delay > 0) { thread.join(delay); } else { thread.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { inputStream.close(); } catch (IOException e1) { } String newname = null; if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) status = -1; newname = "TimeOut"; } else { newname = allLineReader.getLastLine().toString(); } finalize(status, newname, commandLine.toString()); }
From source file:edu.rit.flick.genetics.FastFileInflator.java
@Override public synchronized File inflate(final Configuration configuration, final File fileIn, final File fileOut) { assert fileIn.exists(); try {//from w ww .ja v a 2s . c om // Inflate to Directory final String outputDirectoryPath = fileOut.getPath() .replaceAll("." + Files.getFileExtension(fileOut.getPath()), FLICK_FAST_FILE_TMP_DIR_SUFFIX); final File tmpOutputDirectory = new File(outputDirectoryPath); if (tmpOutputDirectory.exists()) FileUtils.deleteDirectory(tmpOutputDirectory); final AtomicReference<Thread> cleanHookAtomic = new AtomicReference<Thread>(); final Thread inflateToDirectoryThread = new Thread(() -> { try { // Inflate Fast file to a temporary directory inflateFromFile(fileIn, tmpOutputDirectory); // Inflate Directory to a zip file inflateFromDirectory(tmpOutputDirectory, fileOut); // Clean up IO close(); System.gc(); Thread.sleep(100); // Clean up temporary directory FileUtils.deleteDirectory(tmpOutputDirectory); Runtime.getRuntime().removeShutdownHook(cleanHookAtomic.get()); } catch (final Exception e) { if (!interrupted) System.err.println(e.getMessage()); } }, "Default_Inflation_Thread"); // Make cleaning hook final Thread cleanHook = new Thread(() -> { interrupted = true; configuration.setFlag(VERBOSE_FLAG, false); configuration.setFlag(DELETE_FLAG, false); try { if (inflateToDirectoryThread.isAlive()) inflateToDirectoryThread.interrupt(); // Clean up IO close(); System.gc(); Thread.sleep(100); synchronized (this) { while (inflateToDirectoryThread.isAlive()) this.wait(); } } catch (final IOException | InterruptedException e) { e.printStackTrace(); } finally { // Clean up temporary directory FileUtils.deleteQuietly(tmpOutputDirectory); // Clean up INCOMPLETE output file FileUtils.deleteQuietly(fileOut); System.out.println(); } }, "Inflation_Cleaning_Thread"); cleanHookAtomic.set(cleanHook); Runtime.getRuntime().addShutdownHook(cleanHook); inflateToDirectoryThread.start(); inflateToDirectoryThread.join(); } catch (final IOException | InterruptedException e) { e.printStackTrace(); } return fileOut; }
From source file:com.oltpbenchmark.benchmarks.auctionmark.AuctionMarkLoader.java
@Override public void load() { if (LOG.isDebugEnabled()) LOG.debug(String.format("Starting loader [scaleFactor=%.2f]", profile.getScaleFactor())); final EventObservableExceptionHandler handler = new EventObservableExceptionHandler(); final List<Thread> threads = new ArrayList<Thread>(); for (AbstractTableGenerator generator : this.generators.values()) { // if (isSubGenerator(generator)) continue; Thread t = new Thread(generator); t.setName(generator.getTableName()); t.setUncaughtExceptionHandler(handler); // Call init() before we start! // This will setup non-data related dependencies generator.init();/*ww w . jav a2 s . c o m*/ threads.add(t); } // FOR assert (threads.size() > 0); handler.addObserver(new EventObserver<Pair<Thread, Throwable>>() { @Override public void update(EventObservable<Pair<Thread, Throwable>> o, Pair<Thread, Throwable> t) { fail = true; for (Thread thread : threads) thread.interrupt(); t.second.printStackTrace(); } }); // Construct a new thread to load each table // Fire off the threads and wait for them to complete // If debug is set to true, then we'll execute them serially try { for (Thread t : threads) { t.start(); } // FOR for (Thread t : threads) { t.join(); } // FOR } catch (InterruptedException e) { LOG.fatal("Unexpected error", e); } finally { if (handler.hasError()) { throw new RuntimeException("Error while generating table data.", handler.getError()); } } // Save the benchmark profile out to disk so that we can send it // to all of the clients try { profile.saveProfile(this.conn); } catch (SQLException ex) { throw new RuntimeException("Failed to save profile information in database", ex); } LOG.info("Finished generating data for all tables"); }
From source file:it.evilsocket.dsploit.core.UpdateService.java
/** * wait that a shell terminate or user cancel the notification. * @param shell the Thread returned by {@link it.evilsocket.dsploit.core.Shell#async(String, it.evilsocket.dsploit.core.Shell.OutputReceiver, boolean)} * @param cancellationMessage the message of the CancellationException * @throws java.io.IOException when cannot execute shell * @throws java.util.concurrent.CancellationException when user cancelled the notification */// w ww .j av a 2 s . com private int execShell(Thread shell, String cancellationMessage) throws IOException, CancellationException, InterruptedException { if (!(shell instanceof Shell.StreamGobbler)) throw new IOException("cannot execute shell commands"); shell.start(); while (mRunning && shell.getState() != Thread.State.TERMINATED) Thread.sleep(10); if (!mRunning) { shell.interrupt(); throw new CancellationException(cancellationMessage); } else shell.join(); int ret = ((Shell.StreamGobbler) shell).exitValue; if (ret != 0 && mErrorOutput.length() > 0) for (String line : mErrorOutput.toString().split("\n")) if (line.length() > 0) Logger.error(line); return ret; }
From source file:com.gargoylesoftware.htmlunit.javascript.JavaScriptEngineTest.java
/** * @throws Exception if the test fails//from ww w .ja va2s .c o m */ @Test public void timeout() throws Exception { final WebClient client = getWebClient(); final long timeout = 2000; final long oldTimeout = client.getJavaScriptTimeout(); client.setJavaScriptTimeout(timeout); try { client.setThrowExceptionOnScriptError(false); final String content = "<html><body><script>while(1) {}</script></body></html>"; final MockWebConnection webConnection = new MockWebConnection(); webConnection.setDefaultResponse(content); client.setWebConnection(webConnection); final Exception[] exceptions = { null }; final Thread runner = new Thread() { @Override public void run() { try { client.getPage(URL_FIRST); } catch (final Exception e) { exceptions[0] = e; } } }; runner.start(); runner.join(timeout * 2); if (runner.isAlive()) { runner.interrupt(); fail("Script was still running after timeout"); } assertNull(exceptions[0]); } finally { client.setJavaScriptTimeout(oldTimeout); } }
From source file:org.kchine.rpf.db.DBLayer.java
public Remote lookup(String name) throws RemoteException, NotBoundException, AccessException { Statement stmt = null;//from w w w . j av a 2s.c o m ResultSet rset = null; try { checkConnection(); stmt = _connection.createStatement(); rset = stmt.executeQuery("select STUB_HEX,CODEBASE from SERVANTS where NAME='" + name + "'"); if (rset.next()) { final String stubHex = rset.getString(1); final String codeBaseStr = rset.getString(2); final ClassLoader cl = (codeBaseStr != null ? new URLClassLoader(PoolUtils.getURLS(codeBaseStr), DBLayer.class.getClassLoader()) : DBLayer.class.getClassLoader()); System.out.println("codeBaseStr ::" + codeBaseStr); final Object[] resultHolder = new Object[1]; Runnable lookupRunnable = new Runnable() { public void run() { try { resultHolder[0] = hexToStub(stubHex, cl); } catch (Exception e) { final boolean wasInterrupted = Thread.interrupted(); if (wasInterrupted) { resultHolder[0] = new LookUpInterrupted(); } else { resultHolder[0] = e; } } } }; Thread lookupThread = InterruptibleRMIThreadFactory.getInstance().newThread(lookupRunnable); lookupThread.start(); long t1 = System.currentTimeMillis(); while (resultHolder[0] == null) { if ((System.currentTimeMillis() - t1) > PoolUtils.LOOKUP_TIMEOUT_MILLISEC) { lookupThread.interrupt(); resultHolder[0] = new LookUpTimeout(); registerPingFailure(name); break; } Thread.sleep(10); } if (resultHolder[0] instanceof Throwable) { if (resultHolder[0] instanceof NotBoundException) throw (NotBoundException) resultHolder[0]; else throw (RemoteException) resultHolder[0]; } return (Remote) resultHolder[0]; } else { throw new NotBoundException(); } } catch (NotBoundException nbe) { throw nbe; } catch (AccessException ae) { throw ae; } catch (LookUpTimeout lue) { throw lue; } catch (LookUpInterrupted lui) { throw lui; } catch (SQLException sqle) { if (isNoConnectionError(sqle) && canReconnect()) { return lookup(name); } else { throw new RemoteException("", (sqle)); } } catch (Exception e) { throw new RemoteException("", (e)); } finally { if (rset != null) try { stmt.close(); } catch (Exception e) { throw new RemoteException("", (e)); } if (stmt != null) try { stmt.close(); } catch (Exception e) { throw new RemoteException("", (e)); } } }
From source file:com.android.exchange.ExchangeService.java
static public void reloadFolderList(Context context, long accountId, boolean force) { ExchangeService exchangeService = INSTANCE; if (exchangeService == null) return;/*w ww . j av a 2s . co m*/ Cursor c = context.getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + "=? AND " + MailboxColumns.TYPE + "=?", new String[] { Long.toString(accountId), Long.toString(Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) }, null); try { if (c.moveToFirst()) { synchronized (sSyncLock) { Mailbox mailbox = new Mailbox(); mailbox.restore(c); Account acct = Account.restoreAccountWithId(context, accountId); if (acct == null) { reloadFolderListFailed(accountId); return; } String syncKey = acct.mSyncKey; // No need to reload the list if we don't have one if (!force && (syncKey == null || syncKey.equals("0"))) { reloadFolderListFailed(accountId); return; } // Change all ping/push boxes to push/hold ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH_HOLD); context.getContentResolver().update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX, new String[] { Long.toString(accountId) }); log("Set push/ping boxes to push/hold"); long id = mailbox.mId; AbstractSyncService svc = exchangeService.mServiceMap.get(id); // Tell the service we're done if (svc != null) { synchronized (svc.getSynchronizer()) { svc.stop(); // Interrupt the thread so that it can stop Thread thread = svc.mThread; if (thread != null) { thread.setName(thread.getName() + " (Stopped)"); thread.interrupt(); } } // Abandon the service exchangeService.releaseMailbox(id); // And have it start naturally kick("reload folder list"); } } } } finally { c.close(); } }
From source file:backup.integration.MiniClusterTestBase.java
@Test public void testIntegrationBlockCheckWhenSomeBackupStoreBlocksMissing() throws Exception { File hdfsDir = setupHdfsLocalDir(); Configuration conf = setupConfig(hdfsDir); MiniDFSCluster hdfsCluster = new MiniDFSCluster.Builder(conf).build(); Thread thread = null; try (BackupStore backupStore = BackupStore.create(BackupUtil.convert(conf))) { DistributedFileSystem fileSystem = hdfsCluster.getFileSystem(); writeFile(fileSystem, new Path("/testing1.txt")); writeFile(fileSystem, new Path("/testing2.txt")); writeFile(fileSystem, new Path("/testing3.txt")); Thread.sleep(TimeUnit.SECONDS.toMillis(10)); Set<ExtendedBlock> original = getLastGeneration(toSet(backupStore.getExtendedBlocks())); destroyOneBackupStoreBlock(backupStore); NameNode nameNode = hdfsCluster.getNameNode(); NameNodeRestoreProcessor processor = SingletonManager.getManager(NameNodeRestoreProcessor.class) .getInstance(nameNode);/*from www . j a va 2 s . com*/ processor.runBlockCheck(); Thread.sleep(TimeUnit.SECONDS.toMillis(5)); Set<ExtendedBlock> current = toSet(backupStore.getExtendedBlocks()); for (ExtendedBlock eb : original) { System.out.println("ORIGINAL=" + eb); } for (ExtendedBlock eb : current) { System.out.println("CURRENT=" + eb); } assertEquals(original, current); } finally { if (thread != null) { thread.interrupt(); } hdfsCluster.shutdown(); destroyBackupStore(conf); } }
From source file:RhodesService.java
private File downloadPackage(String url) throws IOException { final Context ctx = RhodesActivity.getContext(); final Thread thisThread = Thread.currentThread(); final Runnable cancelAction = new Runnable() { public void run() { thisThread.interrupt(); }//from ww w . j av a2 s. c om }; BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage("Cancel download?"); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cancelAction.run(); } }); dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Nothing } }); dialog.show(); } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) { cancelAction.run(); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD); filter.addAction(ACTION_CANCEL_DOWNLOAD); ctx.registerReceiver(downloadReceiver, filter); File tmpFile = null; InputStream is = null; OutputStream os = null; try { updateDownloadNotification(url, -1, 0); /* List<File> folders = new ArrayList<File>(); folders.add(Environment.getDownloadCacheDirectory()); folders.add(Environment.getDataDirectory()); folders.add(ctx.getCacheDir()); folders.add(ctx.getFilesDir()); try { folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir)); } catch (NameNotFoundException e1) { // Ignore } folders.add(Environment.getExternalStorageDirectory()); for (File folder : folders) { File tmpRootFolder = new File(folder, "rhodownload"); File tmpFolder = new File(tmpRootFolder, ctx.getPackageName()); if (tmpFolder.exists()) deleteFilesInFolder(tmpFolder.getAbsolutePath()); else tmpFolder.mkdirs(); File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk"); Logger.D(TAG, "Check path " + of.getAbsolutePath() + "..."); try { os = new FileOutputStream(of); } catch (FileNotFoundException e) { Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path"); continue; } Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app"); tmpFile = of; break; } */ tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk"); os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE); Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "..."); URL u = new URL(url); URLConnection conn = u.openConnection(); int totalBytes = -1; if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; totalBytes = httpConn.getContentLength(); } is = conn.getInputStream(); int downloaded = 0; updateDownloadNotification(url, totalBytes, downloaded); long prevProgress = 0; byte[] buf = new byte[65536]; for (;;) { if (thisThread.isInterrupted()) { tmpFile.delete(); Logger.D(TAG, "Download of " + url + " was canceled"); return null; } int nread = is.read(buf); if (nread == -1) break; //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes..."); os.write(buf, 0, nread); downloaded += nread; if (totalBytes > 0) { // Update progress view only if current progress is greater than // previous by more than 10%. Otherwise, if update it very frequently, // user will no have chance to click on notification view and cancel if need long progress = downloaded * 10 / totalBytes; if (progress > prevProgress) { updateDownloadNotification(url, totalBytes, downloaded); prevProgress = progress; } } } Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath()); return tmpFile; } catch (IOException e) { if (tmpFile != null) tmpFile.delete(); throw e; } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (os != null) os.close(); } catch (IOException e) { } mNM.cancel(DOWNLOAD_PACKAGE_ID); ctx.unregisterReceiver(downloadReceiver); } }
From source file:com.ngdata.sep.impl.fork.ForkedReplicationSource.java
/** * Check if the slave is down by trying to establish a connection * @return true if down, false if up// w ww . j a v a 2 s . com * @throws InterruptedException */ public boolean isSlaveDown() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Thread pingThread = new Thread() { public void run() { try { HRegionInterface rrs = getRS(); // Dummy call which should fail rrs.getHServerInfo(); latch.countDown(); } catch (IOException ex) { if (ex instanceof RemoteException) { ex = ((RemoteException) ex).unwrapRemoteException(); } LOG.info("Slave cluster looks down: " + ex.getMessage()); } } }; pingThread.start(); // awaits returns true if countDown happened boolean down = !latch.await(this.sleepForRetries, TimeUnit.MILLISECONDS); pingThread.interrupt(); return down; }