List of usage examples for java.lang Thread interrupt
public void interrupt()
From source file:uk.bl.wa.tika.TikaDeepIdentifier.java
/** * /*from w ww . j a v a 2 s .c o m*/ * @param payload * @param metadata * @return */ public String identify(InputStream payload, Metadata metadata) { // Fallback String tikaType = MediaType.OCTET_STREAM.toString(); // Set up metadata object: Metadata md = metadata; TikaInputStream tis = null; try { tis = TikaInputStream.get(payload); // Type according to Tiki: tikaType = pika.getDetector().detect(tis, md).toString(); } catch (Throwable e) { log.error("Tika.detect failed:" + e.getMessage()); //e.printStackTrace(); return MediaType.OCTET_STREAM.toString(); } finally { if (tis != null) { try { tis.close(); } catch (IOException e) { log.warn("Exception closing TikaInputStream. This leaves tmp-files: " + e.getMessage()); } } } // Now perform full parse, to find a more detailed tikaType try { // Default to detected MIME Type: md.set(Metadata.CONTENT_TYPE, tikaType.toString()); // Ensure parsing is NOT recursive: pika.setRecursive(ctx, false); // Now perform the parsing: //parser.parse( new ByteArrayInputStream( payload ), ch, md, ctx ); // One could forcibly limit the size if OOM is still causing problems, like this: //parser.parse( new ByteArrayInputStream( value.getPayload(), 0, BUF_8KB ), ch, md, ctx ); // Every resource gets it's own write-out buffer: ch = new WriteOutContentHandler(MAX_BUF); // Run the parser in a separate thread: InputStream tikainput = TikaInputStream.get(payload); ParseRunner runner = new ParseRunner(pika, tikainput, ch, md, ctx); Thread parseThread = new Thread(runner, Long.toString(System.currentTimeMillis())); parseThread.setDaemon(true); // Daemon to ensure proper shutdown when overall processing has finished try { // TODO: This should use TimeLimiter.run(parser, 30000L, false); but that is in the warc-indexer module parseThread.start(); parseThread.join(this.parseTimeout); parseThread.interrupt(); } catch (OutOfMemoryError o) { log.error("TikaExtractor.parse(): " + tikaType + " : " + o.getMessage()); } catch (RuntimeException r) { log.error("TikaExtractor.parse(): " + tikaType + " : " + r.getMessage()); } finally { if (tikainput != null) { try { tikainput.close(); } catch (IOException e) { log.warn("Exception closing TikaInputStream. This leaves tmp-files: " + e.getMessage()); } } } // Use the extended MIME type generated by the PreservationParser: String extMimeType = md.get(PreservationParser.EXT_MIME_TYPE); if (runner.complete && extMimeType != null) tikaType = extMimeType; } catch (Throwable e) { log.debug("Tika Exception: " + e.getMessage()); //e.printStackTrace(); } // Return whichever value works: return tikaType; }
From source file:uk.bl.wa.tika.TikaDeepIdentifier.java
/** * // ww w. jav a 2 s . c o m * @param payload * @return */ public String identify(byte[] payload) { // Fallback String tikaType = MediaType.OCTET_STREAM.toString(); // Set up metadata object: Metadata md = new Metadata(); TikaInputStream tis = null; try { tis = TikaInputStream.get(payload, md); // Type according to Tiki: tikaType = pika.getDetector().detect(tis, md).toString(); } catch (Throwable e) { log.error("Tika.detect failed:" + e.getMessage()); //e.printStackTrace(); return MediaType.OCTET_STREAM.toString(); } finally { if (tis != null) { try { tis.close(); } catch (IOException e) { log.warn("Exception closing TikaInputStream. This leaves tmp-files: " + e.getMessage()); } } } // Now perform full parse, to find a more detailed tikaType try { // Default to detected MIME Type: md.set(Metadata.CONTENT_TYPE, tikaType.toString()); // Ensure parsing is NOT recursive: pika.setRecursive(ctx, false); // Now perform the parsing: //parser.parse( new ByteArrayInputStream( payload ), ch, md, ctx ); // One could forcibly limit the size if OOM is still causing problems, like this: //parser.parse( new ByteArrayInputStream( value.getPayload(), 0, BUF_8KB ), ch, md, ctx ); // Every resource gets it's own write-out buffer: ch = new WriteOutContentHandler(MAX_BUF); // Run the parser in a separate thread: InputStream tikainput = TikaInputStream.get(payload, md); ParseRunner runner = new ParseRunner(pika, tikainput, ch, md, ctx); Thread parseThread = new Thread(runner, Long.toString(System.currentTimeMillis())); parseThread.setDaemon(true); // Daemon to ensure proper shutdown when overall processing has finished try { // TODO: This should use TimeLimiter.run(parser, 30000L, false); but that is in the warc-indexer module parseThread.start(); parseThread.join(this.parseTimeout); parseThread.interrupt(); } catch (OutOfMemoryError o) { log.error("TikaExtractor.parse(): " + tikaType + " : " + o.getMessage()); } catch (RuntimeException r) { log.error("TikaExtractor.parse(): " + tikaType + " : " + r.getMessage()); } finally { if (tikainput != null) { try { tikainput.close(); } catch (IOException e) { log.warn("Exception closing TikaInputStream. This leaves tmp-files: " + e.getMessage()); } } } // Use the extended MIME type generated by the PreservationParser: String extMimeType = md.get(PreservationParser.EXT_MIME_TYPE); if (runner.complete && extMimeType != null) tikaType = extMimeType; } catch (Throwable e) { log.debug("Tika Exception: " + e.getMessage()); //e.printStackTrace(); } // Return whichever value works: return tikaType; }
From source file:io.werval.maven.StartMojoIT.java
@Test public void startMojoIntegrationTest() throws IOException, InterruptedException { final Holder<Exception> errorHolder = new Holder<>(); Thread runThread = new Thread(newRunnable(errorHolder, "werval:start"), "maven-werval-start-thread"); try {//www . ja va 2s . c o m runThread.start(); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet("http://localhost:23023/"); ResponseHandler<String> handler = new BasicResponseHandler(); await().atMost(60, SECONDS).pollDelay(5, SECONDS).until(() -> { try { return client.execute(get, handler); } catch (Exception ex) { return null; } }, containsString("I ran!")); client.getConnectionManager().shutdown(); } finally { runThread.interrupt(); } }
From source file:org.kurento.test.client.TestClient.java
@SuppressWarnings("deprecation") public long getLatency() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final long[] out = new long[1]; Thread t = new Thread() { public void run() { Object latency = browserClient.executeScript("return kurentoTest.getLatency();"); if (latency != null) { out[0] = (Long) latency; } else { out[0] = Long.MIN_VALUE; }//w w w. j a va2 s . c o m latch.countDown(); } }; t.start(); if (!latch.await(browserClient.getTimeout(), TimeUnit.SECONDS)) { t.interrupt(); t.stop(); throw new LatencyException("Timeout getting latency (" + browserClient.getTimeout() + " seconds)"); } return out[0]; }
From source file:org.devtcg.five.provider.FiveSyncAdapter.java
private long getServerDiffsImpl(SyncContext context, AbstractSyncProvider serverDiffs, String feedType) { if (context.hasError() == true || context.hasCanceled() == true) return -1; String feedUrl = mSource.getFeedUrl(feedType); final HttpGet feeds = new HttpGet(feedUrl); final Thread currentThread = Thread.currentThread(); context.trigger = new CancelTrigger() { public void onCancel() { feeds.abort();//from w ww.j ava 2 s. c o m currentThread.interrupt(); } }; try { return getServerDiffsCancelable(context, serverDiffs, feedType, feeds); } finally { context.trigger = null; } }
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
/** * Run external tesseract-ocr process./*from ww w .j av a 2 s .c o m*/ * * @param input * File to be ocred * @param output * File to collect ocr result * @param config * Configuration of tesseract-ocr engine * @throws TikaException * if the extraction timed out * @throws IOException * if an input error occurred */ private void doOCR(File input, File output, TesseractOCRConfig config) throws IOException, TikaException { String[] cmd = { config.getTesseractPath() + getTesseractProg(), input.getPath(), output.getPath(), "-l", config.getLanguage(), "-psm", config.getPageSegMode(), config.getOutputType().name().toLowerCase(Locale.US), "-c", (config.getPreserveInterwordSpacing()) ? "preserve_interword_spaces=1" : "preserve_interword_spaces=0" }; ProcessBuilder pb = new ProcessBuilder(cmd); setEnv(config, pb); final Process process = pb.start(); process.getOutputStream().close(); InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); logStream("OCR MSG", out, input); logStream("OCR ERROR", err, input); FutureTask<Integer> waitTask = new FutureTask<>(new Callable<Integer>() { public Integer call() throws Exception { return process.waitFor(); } }); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(config.getTimeout(), TimeUnit.SECONDS); } catch (InterruptedException e) { waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); throw new TikaException("TesseractOCRParser interrupted", e); } catch (ExecutionException e) { // should not be thrown } catch (TimeoutException e) { waitThread.interrupt(); process.destroy(); throw new TikaException("TesseractOCRParser timeout", e); } }
From source file:com.mirth.connect.connectors.tcp.TcpDispatcher.java
private void disposeThread(String socketKey) throws InterruptedException { Thread thread = timeoutThreads.get(socketKey); if (thread != null && thread.isAlive()) { logger.trace("Interrupting thread (" + connectorProperties.getName() + " \"" + getDestinationName() + "\" on channel " + getChannelId() + ")."); thread.interrupt(); logger.trace("Joining thread (" + connectorProperties.getName() + " \"" + getDestinationName() + "\" on channel " + getChannelId() + ")."); try {//from w w w .ja v a 2s. co m thread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; } } }
From source file:org.noroomattheinn.visibletesla.AppContext.java
public void shutDown() { shuttingDown.set(true);//from www . j a va 2 s . c o m int nActive; do { nActive = 0; for (Thread t : threads) { Thread.State state = t.getState(); switch (state) { case NEW: case RUNNABLE: nActive++; break; case TERMINATED: break; case BLOCKED: case TIMED_WAITING: case WAITING: nActive++; t.interrupt(); // Should this sleep for a very short period? break; default: break; } } } while (nActive > 0); }
From source file:org.opennms.netmgt.provision.server.SimpleServer.java
/** * <p>stopServer</p>/* ww w . j a v a 2s . c o m*/ * * @throws java.io.IOException if any. */ public void stopServer() throws IOException { if (!m_stopped) { m_stopped = true; final Thread t = getServerThread(); setServerThread(null); IOUtils.closeQuietly(getSocket()); IOUtils.closeQuietly(getServerSocket()); try { Thread.sleep(200); } catch (final InterruptedException e) { } if (t != null && t.isAlive()) { t.interrupt(); } try { if (m_runnable != null) m_runnable.awaitShutdown(); } catch (final InterruptedException e) { LOG.debug("Interrupted while shutting down.", e); } } }
From source file:org.apache.hadoop.hbase.util.TestThreads.java
@Test(timeout = 60000) public void testSleepWithoutInterrupt() throws InterruptedException { Thread sleeper = new Thread(new Runnable() { @Override/*w w w .j av a2 s. c o m*/ public void run() { LOG.debug("Sleeper thread: sleeping for " + SLEEP_TIME_MS); Threads.sleepWithoutInterrupt(SLEEP_TIME_MS); LOG.debug("Sleeper thread: finished sleeping"); wasInterrupted.set(Thread.currentThread().isInterrupted()); } }); LOG.debug("Starting sleeper thread (" + SLEEP_TIME_MS + " ms)"); sleeper.start(); long startTime = System.currentTimeMillis(); LOG.debug("Main thread: sleeping for 200 ms"); Threads.sleep(200); LOG.debug("Interrupting the sleeper thread and sleeping for 500 ms"); sleeper.interrupt(); Threads.sleep(500); LOG.debug("Interrupting the sleeper thread and sleeping for 800 ms"); sleeper.interrupt(); Threads.sleep(800); LOG.debug("Interrupting the sleeper thread again"); sleeper.interrupt(); sleeper.join(); assertTrue("sleepWithoutInterrupt did not preserve the thread's " + "interrupted status", wasInterrupted.get()); long timeElapsed = System.currentTimeMillis() - startTime; // We expect to wait at least SLEEP_TIME_MS, but we can wait more if there is a GC. assertTrue( "Elapsed time " + timeElapsed + " ms is out of the expected " + " sleep time of " + SLEEP_TIME_MS, SLEEP_TIME_MS - timeElapsed < TOLERANCE_MS); LOG.debug("Target sleep time: " + SLEEP_TIME_MS + ", time elapsed: " + timeElapsed); }