List of usage examples for java.util TimerTask cancel
public boolean cancel()
From source file:edu.iu.dymoro.Scheduler.java
public void schedule(List<Partition<S>>[] hMap) { for (int i = 0; i < numRowSplits; i++) { freeRow[numFreeRows++] = i;/* www. j ava 2 s . com*/ } for (int i = 0; i < numColSplits; i++) { freeCol[numFreeCols++] = i; } while (numFreeRows > 0 && numFreeCols > 0) { RowColSplit<D, S> split = new RowColSplit<>(); int rowIndex = random.nextInt(numFreeRows); int colIndex = random.nextInt(numFreeCols); split.row = freeRow[rowIndex]; split.col = freeCol[colIndex]; split.rData = vWHMap[split.row]; split.cData = hMap[split.col]; splitMap[split.row][split.col]++; rowCount[split.row]++; colCount[split.col]++; freeRow[rowIndex] = freeRow[--numFreeRows]; freeCol[colIndex] = freeCol[--numFreeCols]; compute.submit(split); } isRunning.set(true); TimerTask timerTask = new TimerTask() { @Override public void run() { isRunning.set(false); } }; timer.schedule(timerTask, time); while (compute.hasOutput()) { RowColSplit<D, S> split = compute.waitForOutput(); int freeRowID = -1; if (rowCount[split.row] < numRowLimit) { freeRowID = split.row; } int freeColID = -1; if (colCount[split.col] < numColLimit) { freeColID = split.col; } numItemsTrained += split.numItems; split = null; if (isRunning.get()) { // Find a matched col for the last row if (freeRowID != -1) { for (int i = 0; i < numFreeCols; i++) { if (splitMap[freeRowID][freeCol[i]] == 0) { split = new RowColSplit<>(); split.row = freeRowID; split.col = freeCol[i]; split.rData = vWHMap[split.row]; split.cData = hMap[split.col]; split.numItems = 0L; splitMap[split.row][split.col]++; rowCount[split.row]++; colCount[split.col]++; freeCol[i] = freeCol[--numFreeCols]; freeRowID = -1; compute.submit(split); break; } } } // Find a matched row for the last col if (freeColID != -1) { for (int i = 0; i < numFreeRows; i++) { if (splitMap[freeRow[i]][freeColID] == 0) { split = new RowColSplit<>(); split.row = freeRow[i]; split.col = freeColID; split.rData = vWHMap[split.row]; split.cData = hMap[split.col]; split.numItems = 0L; splitMap[split.row][split.col]++; rowCount[split.row]++; colCount[split.col]++; freeRow[i] = freeRow[--numFreeRows]; freeColID = -1; compute.submit(split); break; } } } if (freeRowID != -1) { freeRow[numFreeRows++] = freeRowID; } if (freeColID != -1) { freeCol[numFreeCols++] = freeColID; } } else { break; } } timerTask.cancel(); clean(); compute.pauseNow(); while (compute.hasOutput()) { numItemsTrained += compute.waitForOutput().numItems; } compute.cleanInputQueue(); compute.start(); }
From source file:org.andrewberman.sync.PDFSearcher.java
public void startMe() throws Exception { if (username.length() == 0 || password.length() == 0) { status("Error: Username or password is blank. Try again."); return;/*from www. ja v a 2 s .co m*/ } initPatternArray(); login(); do { getArticleInfo(); List<CiteULikeReference> articlesWithoutPDFs = getArticlesWithoutPDFs(this.refs); itemMax = articlesWithoutPDFs.size(); itemNum = 0; utd += this.refs.size() - articlesWithoutPDFs.size(); Thread.sleep(1000); for (int i = 0; i < articlesWithoutPDFs.size(); i++) { itemNum++; waitOrExit(); cnt = String.valueOf(i + 1) + "/" + articlesWithoutPDFs.size(); status("Searching..."); /* * Set the timeout timer. */ TimerTask task = new TimerTask() { public void run() { skipToNext = true; } }; timer.schedule(task, (long) timeout * 1000); try { CiteULikeReference ref = articlesWithoutPDFs.get(i); System.out.println(ref.href); setArticleLink("Current article ID: " + ref.article_id, ref.href); waitOrExit(); GetMethod get = null; for (String linkOut : ref.linkouts) { try { get = pdfScrape(linkOut, 5); if (get != null) break; } catch (Exception e) { System.err.println("Error retrieving article: " + e.getMessage()); System.err.println(" Will continue to the next one..."); continue; } } // Sorry, no PDF for you! if (get == null) { throw new Exception("No PDF was found!"); } /* * Looks like we really found a PDF. Let's download it. */ try { InputStream in = get.getResponseBodyAsStream(); ByteArrayOutputStream ba = new ByteArrayOutputStream(); waitOrExit(); status("Downloading..."); debug("Downloading..."); int j = 0; int ind = 0; long length = get.getResponseContentLength(); int starRatio = (int) length / 20; int numStars = 0; while ((j = in.read()) != -1) { if (length != -1 && ind % starRatio == 0) { status("Downloading..." + repeat(".", ++numStars)); } if (ind % 1000 == 0) { waitOrExit(); } ba.write(j); ind++; } /* * Set up the Multipart POST file upload. */ // String id = url.substring(url.lastIndexOf("/") + 1, url // .length()); StringPart p1 = new StringPart("article_id", ref.article_id); StringPart p2 = new StringPart("username", username); StringPart p3 = new StringPart("check", "v2"); ByteArrayPartSource source = new ByteArrayPartSource("temp.pdf", ba.toByteArray()); FilePart fp = new FilePart("file", source); fp.setName("file"); Part[] parts = new Part[] { p1, p2, p3, fp }; status("Uploading..."); debug("Uploading..."); waitOrExit(); PostMethod filePost = new PostMethod(BASE_URL + "personal_pdf_upload"); try { filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); httpclient.executeMethod(filePost); String response = filePost.getResponseBodyAsString(); System.out.println(response); if (response.contains("didn't work")) throw new Exception("CiteULike thinks the PDF is invalid!"); } finally { ba = null; source = null; parts = null; filePost.releaseConnection(); } } finally { get.releaseConnection(); } status("Done!"); Thread.sleep(BETWEEN_SEARCH_ITEMS_SLEEP_TIME); dl++; } catch (Exception e) { if (isStopped()) { throw e; } else if (skipToNext) { err++; status("Timed out."); Thread.sleep(BETWEEN_SEARCH_ITEMS_SLEEP_TIME); continue; } else if (e instanceof Exception) { err++; status(e.getMessage()); Thread.sleep(BETWEEN_SEARCH_ITEMS_SLEEP_TIME); continue; } else { err++; e.printStackTrace(); status("Failed. See the Java console for more info."); Thread.sleep(BETWEEN_SEARCH_ITEMS_SLEEP_TIME); continue; } } finally { task.cancel(); skipToNext = false; } } } while (this.refs.size() != 0); setArticleLink("", ""); this.pageNum = 0; status("Finished. " + dl + " found, " + utd + " existing and " + err + " failed."); }
From source file:org.apache.geronimo.mavenplugins.geronimo.server.StartServerMojo.java
protected void doExecute() throws Exception { if (install) { installAssembly();//w w w. j a va 2s . c o m } else { log.info("Skipping assembly installation"); if (!geronimoHome.exists()) { throw new MojoExecutionException("Missing pre-installed assembly directory: " + geronimoHome); } } log.info("Starting Geronimo server..."); // Setup the JVM to start the server with final Java java = (Java) createTask("java"); java.setClassname("org.apache.geronimo.cli.daemon.DaemonCLI"); Path path = java.createClasspath(); File libDir = new File(geronimoHome, "lib"); FileSet fileSet = new FileSet(); fileSet.setDir(libDir); path.addFileset(fileSet); java.setDir(geronimoHome); java.setFailonerror(true); java.setFork(true); if (javaVirtualMachine != null) { if (!javaVirtualMachine.exists()) { throw new MojoExecutionException("Java virtual machine is not valid: " + javaVirtualMachine); } log.info("Using Java virtual machine: " + javaVirtualMachine); java.setJvm(javaVirtualMachine.getCanonicalPath()); } if (timeout > 0) { java.setTimeout(new Long(timeout * 1000)); } if (maximumMemory != null) { java.setMaxmemory(maximumMemory); } if (maxPermSize != null) { java.createJvmarg().setValue("-XX:MaxPermSize=" + maxPermSize); } // Load the Java programming language agent for JPA File javaAgentJar = new File(geronimoHome, "lib/agent/transformer.jar"); if (javaAgentJar.exists()) { java.createJvmarg().setValue("-javaagent:" + javaAgentJar.getCanonicalPath()); } // Propagate some properties from Maven to the server if enabled if (propagateGeronimoProperties) { Properties props = System.getProperties(); Iterator iter = props.keySet().iterator(); while (iter.hasNext()) { String name = (String) iter.next(); String value = System.getProperty(name); if (name.equals("geronimo.bootstrap.logging.enabled")) { // Skip this property, never propagate it } else if (name.startsWith("org.apache.geronimo") || name.startsWith("geronimo")) { if (log.isDebugEnabled()) { log.debug("Propagating: " + name + "=" + value); } setSystemProperty(java, name, value); } } } // Apply option sets if (options != null && (optionSets == null || optionSets.length == 0)) { throw new MojoExecutionException("At least one optionSet must be defined to select one using options"); } else if (options == null) { options = "default"; } if (optionSets != null && optionSets.length != 0) { OptionSet[] sets = selectOptionSets(); for (int i = 0; i < sets.length; i++) { if (log.isDebugEnabled()) { log.debug("Selected option set: " + sets[i]); } else { log.info("Selected option set: " + sets[i].getId()); } String[] options = sets[i].getOptions(); if (options != null) { for (int j = 0; j < options.length; j++) { java.createJvmarg().setValue(options[j]); } } Properties props = sets[i].getProperties(); if (props != null) { Iterator iter = props.keySet().iterator(); while (iter.hasNext()) { String name = (String) iter.next(); String value = props.getProperty(name); setSystemProperty(java, name, value); } } } } // Set the properties which we pass to the JVM from the startup script setSystemProperty(java, "org.apache.geronimo.home.dir", geronimoHome); setSystemProperty(java, "karaf.home", geronimoHome); setSystemProperty(java, "karaf.base", geronimoHome); // Use relative path setSystemProperty(java, "java.io.tmpdir", "var/temp"); setSystemProperty(java, "java.endorsed.dirs", prefixSystemPath("java.endorsed.dirs", new File(geronimoHome, "lib/endorsed"))); setSystemProperty(java, "java.ext.dirs", prefixSystemPath("java.ext.dirs", new File(geronimoHome, "lib/ext"))); // set console properties setSystemProperty(java, "karaf.startLocalConsole", "false"); setSystemProperty(java, "karaf.startRemoteShell", "true"); if (quiet) { java.createArg().setValue("--quiet"); } else { java.createArg().setValue("--long"); } if (verbose) { java.createArg().setValue("--verbose"); } if (veryverbose) { java.createArg().setValue("--veryverbose"); } if (startModules != null) { if (startModules.length == 0) { throw new MojoExecutionException("At least one module name must be configured with startModule"); } log.info("Overriding the set of modules to be started"); java.createArg().setValue("--override"); for (int i = 0; i < startModules.length; i++) { java.createArg().setValue(startModules[i]); } } // // TODO: Check if this really does capture STDERR or not! // if (logOutput) { File file = getLogFile(); FileUtils.forceMkdir(file.getParentFile()); log.info("Redirecting output to: " + file); java.setOutput(file); } // Holds any exception that was thrown during startup final ObjectHolder errorHolder = new ObjectHolder(); StopWatch watch = new StopWatch(); watch.start(); // Start the server int a seperate thread Thread t = new Thread("Geronimo Server Runner") { public void run() { try { java.execute(); } catch (Exception e) { errorHolder.set(e); // // NOTE: Don't log here, as when the JVM exists an exception will get thrown by Ant // but that should be fine. // } } }; t.start(); log.info("Waiting for Geronimo server..."); // Setup a callback to time out verification final ObjectHolder verifyTimedOut = new ObjectHolder(); TimerTask timeoutTask = new TimerTask() { public void run() { verifyTimedOut.set(Boolean.TRUE); } }; if (verifyTimeout > 0) { if (log.isDebugEnabled()) { log.debug("Starting verify timeout task; triggers in: " + verifyTimeout + " seconds"); } timer.schedule(timeoutTask, verifyTimeout * 1000); } // Verify server started ServerProxy server = new ServerProxy(hostname, port, username, password); boolean started = false; while (!started) { if (verifyTimedOut.isSet()) { throw new MojoExecutionException("Unable to verify if the server was started in the given time (" + verifyTimeout + " seconds)"); } if (errorHolder.isSet()) { throw new MojoExecutionException("Failed to start Geronimo server", (Throwable) errorHolder.get()); } started = server.isFullyStarted(); if (!started) { Throwable error = server.getLastError(); if ((error != null) && (log.isDebugEnabled())) { log.debug("Server query failed; ignoring", error); } Thread.sleep(5 * 1000); } } server.closeConnection(); // Stop the timer, server should be up now timeoutTask.cancel(); log.info("Geronimo server started in " + watch); if (!background) { log.info("Waiting for Geronimo server to shutdown..."); t.join(); } }
From source file:org.apache.geronimo.shell.geronimo.ProcessLauncher.java
public void launch() throws Exception { assert name != null; Runnable runner = new Inner(); Thread t = new Thread(runner, name + " Runner"); out.println("Launching " + name + "..."); //System.console().flush(); StopWatch watch = new StopWatch(); watch.start();/*from w w w . ja v a2s. c o m*/ t.start(); if (verifier()) { Timer timer = new Timer(name + " Timer", true); TimerTask timeoutTask = new TimingTimerTask(); if (timeout > 0) { timer.schedule(timeoutTask, timeout * 1000); } boolean started = false; log.debug("Waiting for " + name + " ..."); while (!started) { if (timedOut) { throw new Exception("Unable to verify if " + name + " was started in the given time (" + timeout + " seconds)"); } if (error != null) { throw new Exception("Failed to start: " + name, error); } if (verifier()) { started = true; } else { Thread.sleep(verifyWaitDelay); } } timeoutTask.cancel(); } out.println(name + " started in " + watch); //System.console().flush(); if (!background) { log.debug("Waiting for " + name + " to shutdown..."); t.join(); log.debug(name + " has shutdown"); } }
From source file:org.apache.slide.webdav.event.NotificationTrigger.java
public void refreshSubscriber(final Subscriber subscriber, boolean persist) { TimerTask lifetimeTask = subscriber.getLifetime(); if (lifetimeTask != null) lifetimeTask.cancel(); if (subscriber.getSubscriptionLifetime() > 0) { Domain.log("Refreshing subscriber with ID: " + subscriber.getId(), LOG_CHANNEL, Logger.INFO); TimerTask lifetime = new TimerTask() { public void run() { Domain.log("Removing subscriber with ID: " + subscriber.getId(), LOG_CHANNEL, Logger.INFO); refreshSubscriber(subscriber, true); }//from w w w . j a v a 2s. c om }; subscriber.setLifetime(lifetime); timer.schedule(lifetime, subscriber.getSubscriptionLifetime() * 1000); } if (persist) saveSubscribers(); }
From source file:org.codelibs.fess.screenshot.impl.CommandGenerator.java
@Override public void generate(final String url, final File outputFile) { if (logger.isDebugEnabled()) { logger.debug("Generate ScreenShot: " + url); }/*from ww w . j a v a 2 s .c om*/ if (outputFile.exists()) { if (logger.isDebugEnabled()) { logger.debug("The screenshot file exists: " + outputFile.getAbsolutePath()); } return; } final File parentFile = outputFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } if (!parentFile.isDirectory()) { logger.warn("Not found: " + parentFile.getAbsolutePath()); return; } final String outputPath = outputFile.getAbsolutePath(); final List<String> cmdList = new ArrayList<>(); for (final String value : commandList) { cmdList.add(value.replace("${url}", url).replace("${outputFile}", outputPath)); } ProcessBuilder pb = null; Process p = null; if (logger.isDebugEnabled()) { logger.debug("ScreenShot Command: " + cmdList); } TimerTask task = null; try { pb = new ProcessBuilder(cmdList); pb.directory(baseDir); pb.redirectErrorStream(true); p = pb.start(); task = new ProcessDestroyer(p, cmdList); try { destoryTimer.schedule(task, commandTimeout); String line; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset())); while ((line = br.readLine()) != null) { if (logger.isDebugEnabled()) { logger.debug(line); } } } finally { IOUtils.closeQuietly(br); } p.waitFor(); } catch (final Exception e) { p.destroy(); } } catch (final Exception e) { logger.warn("Failed to generate a screenshot of " + url, e); } if (task != null) { task.cancel(); task = null; } if (outputFile.isFile() && outputFile.length() == 0) { logger.warn("ScreenShot File is empty. URL is " + url); if (outputFile.delete()) { logger.info("Deleted: " + outputFile.getAbsolutePath()); } } if (logger.isDebugEnabled()) { logger.debug("ScreenShot File: " + outputPath); } }
From source file:org.codelibs.fess.thumbnail.impl.CommandGenerator.java
protected void executeCommand(final String thumbnailId, final List<String> cmdList) { ProcessBuilder pb = null;/*from ww w .j a va 2 s .co m*/ Process p = null; if (logger.isDebugEnabled()) { logger.debug("Thumbnail Command: " + cmdList); } TimerTask task = null; try { pb = new ProcessBuilder(cmdList); pb.directory(baseDir); pb.redirectErrorStream(true); p = pb.start(); task = new ProcessDestroyer(p, cmdList); try { destoryTimer.schedule(task, commandTimeout); String line; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset())); while ((line = br.readLine()) != null) { if (logger.isDebugEnabled()) { logger.debug(line); } } } finally { IOUtils.closeQuietly(br); } p.waitFor(); } catch (final Exception e) { p.destroy(); } } catch (final Exception e) { logger.warn("Failed to generate a thumbnail of " + thumbnailId, e); } if (task != null) { task.cancel(); task = null; } }
From source file:org.hyperic.hq.escalation.server.session.EscalationRuntimeImpl.java
private void doUnscheduleEscalation_(Integer stateId) { if (stateId != null) { TimerTask task = (TimerTask) _stateIdsToTasks.remove(stateId); if (task != null) { task.cancel(); log.debug("Canceled state[" + stateId + "]"); } else {/* w ww . j a v a 2s.co m*/ log.debug("Canceling state[" + stateId + "] but was " + "not found"); } } }
From source file:org.knime.al.nodes.score.novelty.localnoveltyscorer.LocalNoveltyScorer.java
public double[] calculateNoveltyScores() throws Exception { final ThreadPool pool = KNIMEConstants.GLOBAL_THREAD_POOL; final int procCount = (int) (Runtime.getRuntime().availableProcessors() * (2.0 / 3)); final Semaphore semaphore = new Semaphore(procCount); final int numTestSamples = m_globalKernelMatrix.getColumnDimension(); final NoveltyScoreCalculationCallable[] nct = new NoveltyScoreCalculationCallable[numTestSamples]; for (int i = 0; i < numTestSamples; i++) { nct[i] = new NoveltyScoreCalculationCallable(i, semaphore, m_numNeighbors, m_trainingKernelMatrix, m_globalKernelMatrix, m_labels, m_normalize); }/* w ww .ja va2 s.c o m*/ final Future<?>[] scores = new Future<?>[numTestSamples]; final KNIMETimer timer = KNIMETimer.getInstance(); final TimerTask timerTask = new TimerTask() { @Override public void run() { try { m_exec.checkCanceled(); } catch (final CanceledExecutionException ce) { for (int i = 0; i < scores.length; i++) { if (scores[i] != null) { scores[i].cancel(true); } } super.cancel(); } } }; timer.scheduleAtFixedRate(timerTask, 0, 3000); double progCounter = 0; for (int i = 0; i < numTestSamples; i++) { try { m_exec.checkCanceled(); } catch (final Exception e) { for (int j = 0; j < i; j++) { if (scores[j] != null) { scores[j].cancel(true); } } timerTask.cancel(); throw e; } semaphore.acquire(); scores[i] = pool.enqueue(nct[i]); m_exec.setProgress(progCounter / (2 * numTestSamples), "Local novelty score calculation started (" + i + "/" + numTestSamples + ")"); progCounter += 1; } final double[] result = new double[numTestSamples]; for (int i = 0; i < numTestSamples; i++) { semaphore.acquire(); try { m_exec.checkCanceled(); result[i] = (Double) scores[i].get(); nct[i].ok(); } catch (final Exception e) { for (int j = 0; j < scores.length; j++) { scores[j].cancel(true); } timerTask.cancel(); throw e; } m_exec.setProgress(progCounter / (2 * numTestSamples), "Local novelty score calculated (" + i + "/" + numTestSamples + ")"); progCounter += 1; semaphore.release(); } timerTask.cancel(); return result; }
From source file:org.neo4j.server.guard.GuardingRequestFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { if (req instanceof HttpServletRequest && res instanceof HttpServletResponse) { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; int timeLimit = getTimeLimit(request); if (timeLimit <= 0) { chain.doFilter(req, res);//from www . ja v a 2 s .c o m } else { final long valid = currentTimeMillis() + timeLimit; guard.startTimeout(valid); final TimerTask timerTask = new TimerTask() { @Override public void run() { LOG.warn("request canceled"); LOG.error( "TODO: restarting the server is not proper implemented, request was not canceled"); // TODO current.interrupt(); + restart server } }; timer.schedule(timerTask, valid + 5000); try { chain.doFilter(req, res); } catch (GuardException e) { response.setStatus(SC_REQUEST_TIMEOUT); } finally { timerTask.cancel(); guard.stop(); } } } else { chain.doFilter(req, res); } }