List of usage examples for java.lang InterruptedException InterruptedException
public InterruptedException(String s)
InterruptedException
with the specified detail message. From source file:com.github.horrorho.liquiddonkey.cloud.engine.Donkey.java
Map<ICloud.MBSFile, Outcome> process(ChunkServer.StorageHostChunkList chunkList) throws InterruptedException, IOException { logger.trace("<< process() < chunk list: {}", chunkList.getHostInfo().getUri()); request.set(chunksClient.get(chunkList)); int count = 0; while (true) { Map<ByteString, DataWriter> writers; if (request.get() == null || Thread.currentThread().isInterrupted()) { throw new InterruptedException("Interrupted"); }//w w w. jav a 2 s .co m try { byte[] data = agent .execute(client -> client.execute(request.get(), chunksClient.responseHandler())); writers = storeManager.put(chunkList.getChunkInfoList(), data); } catch (HttpResponseException ex) { if (ex.getStatusCode() == 401) { fail(ex, chunkList); throw ex; } if (++count >= retryCount) { // TODO consider aggression option return fail(ex, chunkList); } logger.warn("-- process() > count: {} exception: {}", count, ex); continue; } catch (BadDataException ex) { if (++count >= retryCount) { return fail(ex, chunkList); } logger.warn("-- process() > count: {} exception: {}", count, ex); continue; } Map<ICloud.MBSFile, Outcome> outcomes; outcomes = write(chunkList, writers); logger.trace(">> process() > outcomes: {}", outcomes.size()); return outcomes; } }
From source file:nl.nn.adapterframework.processors.TransactionAttributePipeLineProcessor.java
public PipeLineResult processPipeLine(PipeLine pipeLine, String messageId, String message, IPipeLineSession pipeLineSession, String firstPipe) throws PipeRunException { try {/*from w w w. ja v a2s . co m*/ //TransactionStatus txStatus = txManager.getTransaction(txDef); IbisTransaction itx = new IbisTransaction(txManager, pipeLine.getTxDef(), "pipeline of adapter [" + pipeLine.getOwner().getName() + "]"); TransactionStatus txStatus = itx.getStatus(); try { TimeoutGuard tg = new TimeoutGuard("pipeline of adapter [" + pipeLine.getOwner().getName() + "]"); Throwable tCaught = null; try { tg.activateGuard(pipeLine.getTransactionTimeout()); PipeLineResult pipeLineResult = pipeLineProcessor.processPipeLine(pipeLine, messageId, message, pipeLineSession, firstPipe); boolean mustRollback = false; if (pipeLineResult == null) { mustRollback = true; log.warn("Pipeline received null result for messageId [" + messageId + "], transaction (when present and active) will be rolled back"); } else { if (StringUtils.isNotEmpty(pipeLine.getCommitOnState()) && !pipeLine.getCommitOnState().equalsIgnoreCase(pipeLineResult.getState())) { mustRollback = true; log.warn("Pipeline result state [" + pipeLineResult.getState() + "] for messageId [" + messageId + "] is not equal to commitOnState [" + pipeLine.getCommitOnState() + "], transaction (when present and active) will be rolled back"); } } if (mustRollback) { try { txStatus.setRollbackOnly(); } catch (Exception e) { throw new PipeRunException(null, "Could not set RollBackOnly", e); } } return pipeLineResult; } catch (Throwable t) { tCaught = t; throw tCaught; } finally { if (tg.cancel()) { if (tCaught == null) { throw new InterruptedException(tg.getDescription() + " was interrupted"); } else { log.warn("Thread interrupted, but propagating other caught exception of type [" + ClassUtils.nameOf(tCaught) + "]"); } } } } catch (Throwable t) { log.debug("setting RollBackOnly for pipeline after catching exception"); txStatus.setRollbackOnly(); if (t instanceof Error) { throw (Error) t; } else if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof PipeRunException) { throw (PipeRunException) t; } else { throw new PipeRunException(null, "Caught unknown checked exception", t); } } finally { //txManager.commit(txStatus); itx.commit(); } } catch (RuntimeException e) { throw new PipeRunException(null, "RuntimeException calling PipeLine with tx attribute [" + pipeLine.getTransactionAttribute() + "]", e); } }
From source file:com.aliyun.odps.flume.sink.OdpsWriter.java
/** * Write list of {@link com.aliyun.odps.flume.sink.dataobject.OdpsRowDO} to ODPS table. * @param rowList List of {@link com.aliyun.odps.flume.sink.dataobject.OdpsRowDO} built from event batch. *///from w w w. j a va2 s. c om public void write(List<OdpsRowDO> rowList) throws InterruptedException { if (rowList == null || rowList.isEmpty()) { return; } List<OdpsStreamRecordPackDO> packDOList = buildRecordPackList(rowList); if (packDOList == null || packDOList.isEmpty()) { return; } for (OdpsStreamRecordPackDO streamRecordPackDO : packDOList) { boolean exceptionFlag = true; int i = 0; while (exceptionFlag) { try { writePack(streamRecordPackDO); exceptionFlag = false; } catch (Exception e) { ++i; logger.error("OdpsWriter write() error, will retry after " + i * 200 + "ms...", e); if (i == 50) { i = 1; } try { Thread.sleep(i * 200); } catch (InterruptedException e1) { logger.error("OdpsWriter write() failed, user stopped retry."); throw new InterruptedException("OdpsWriter write() failed, user stopped retry."); } } } } }
From source file:fr.fastconnect.cargo.container.openspaces.OpenSpacesContainerHelper.java
public void waitGridStart(Admin admin) throws InterruptedException { logger.info("Waiting for grid to start"); logger.info("Waiting for GSA"); GridServiceAgent gsa = admin.getGridServiceAgents().waitForAtLeastOne(START_WAIT_TIMEOUT, TimeUnit.MILLISECONDS); if (gsa == null) { throw new InterruptedException("timeout occured before GSA is started"); }/*from w w w .j a va 2 s . co m*/ logger.info("GSA found"); int gscCount = 0; int gsmCount = 0; int lusCount = 0; Iterator<AgentProcessDetails> processIterator = gsa.getProcessesDetails().iterator(); while (processIterator.hasNext()) { AgentProcessDetails apd = processIterator.next(); if (apd.getServiceType().equals("gsc")) { gscCount++; } if (apd.getServiceType().equals("gsm")) { gsmCount++; } if (apd.getServiceType().equals("lus")) { lusCount++; } } // wait for grid to be started if (!(admin.getGridServiceContainers().waitFor(gscCount, START_WAIT_TIMEOUT, TimeUnit.MILLISECONDS) && admin.getGridServiceManagers().waitFor(gsmCount, START_WAIT_TIMEOUT, TimeUnit.MILLISECONDS) && admin.getLookupServices().waitFor(lusCount, START_WAIT_TIMEOUT, TimeUnit.MILLISECONDS))) { final int discoveredGSC = admin.getGridServiceContainers().getSize(); final int discoveredGSM = admin.getGridServiceManagers().getSize(); final int discoveredLUS = admin.getLookupServices().getSize(); throw new InterruptedException("Timeout occured before Grid components are started; " + "discovered <" + discoveredGSC + "> GSC, <" + discoveredGSM + "> GSM and <" + discoveredLUS + "> LUS using locators <" + Arrays.toString(admin.getLocators()) + "> and groups <" + Arrays.toString(admin.getGroups()) + ">" + "but was expecting <" + gscCount + "> GSC, <" + gsmCount + "> GSM and <" + lusCount + "> LUS."); } logger.info("Grid started."); // if there is some deployables to deploy deploy them here deployProcessingUnits(admin); logger.info("Processing units deployed."); }
From source file:ddf.common.test.AdminConfig.java
/** * Waits until a {@link ConfigurationPredicate} returns {@code true}. * * @param pid ID of the {@link Configuration} object that the {@link ConfigurationPredicate} * will use to validate the condition * @param predicate predicate to wait on * @param timeoutMs wait timeout//from ww w. j a v a2 s. c om * @return {@link Configuration} object * @throws IOException thrown if the {@link Configuration} object cannot be accessed * @throws InterruptedException thrown if the wait times out * @deprecated Use {@link WaitCondition} instead. */ public Configuration waitForConfiguration(String pid, ConfigurationPredicate predicate, long timeoutMs) throws IOException, InterruptedException { LOGGER.debug("Waiting for condition {} in Configuration object [{}] to be true", predicate.toString(), pid); Configuration configuration = configAdmin.getConfiguration(pid, null); int waitPeriod = 0; while ((waitPeriod < timeoutMs) && !predicate.test(configuration)) { TimeUnit.MILLISECONDS.sleep(CONFIG_WAIT_POLLING_INTERVAL); waitPeriod += CONFIG_WAIT_POLLING_INTERVAL; configuration = configAdmin.getConfiguration(pid, null); } LOGGER.debug("Waited for {}ms", waitPeriod); if (waitPeriod >= timeoutMs) { LOGGER.error("Timed out after waiting {}ms for condition {} to be true on configuration object {}", waitPeriod, predicate.toString(), pid); throw new InterruptedException( String.format("Timed out waiting for condition [%s] to be true in configuration object [%s]", predicate.toString(), pid)); } return configuration; }
From source file:BlockingQueue.java
/** * Returns the element on top of the queue without popping it. * Unlike the peek() method, this method does not block * for longer than the given amount of milliseconds. When the given amount of milliseconds * have passed, this method will throw an InterruptedException. *///from w w w . j a va2s .c om public Object peek(long timeout) throws InterruptedException { synchronized (popLock) { synchronized (this) { if (queue.isEmpty()) { wait(timeout); if (queue.isEmpty()) throw new InterruptedException("Timed out"); } } return queue.firstElement(); } }
From source file:com.flicklib.folderscanner.AdvancedFolderScanner.java
/** * /*w w w . ja v a 2 s . c o m*/ * @param folder * @param monitor * @return true, if it contained movie file * @throws InterruptedException * @throws FileSystemException */ private boolean browse(FileObject folder, AsyncMonitor monitor) throws InterruptedException, FileSystemException { URL url = folder.getURL(); LOGGER.trace("entering " + url); FileObject[] files = folder.getChildren(); if (monitor != null) { if (monitor.isCanceled()) { throw new InterruptedException("at " + url); } monitor.step("scanning " + url); } Set<String> plainFileNames = new HashSet<String>(); int subDirectories = 0; int compressedFiles = 0; Set<String> directoryNames = new HashSet<String>(); for (FileObject f : files) { if (isDirectory(f)) { subDirectories++; directoryNames.add(f.getName().getBaseName().toLowerCase()); } else { String ext = getExtension(f); if (ext == null) { LOGGER.trace("Ignoring file without extension: " + f.getURL()); } else { if (MovieFileType.getTypeByExtension(ext) == MovieFileType.COMPRESSED) { compressedFiles++; } if (ext != null && MovieFileFilter.VIDEO_EXTENSIONS.contains(ext)) { plainFileNames.add(getNameWithoutExt(f)); } } } } // check for multiple compressed files, the case of: // Title_of_the_film/abc.rar // Title_of_the_film/abc.r01 // Title_of_the_film/abc.r02 if (compressedFiles > 0) { FileGroup fg = initStorableMovie(folder); fg.getLocations().add(new FileLocation(currentLabel, folder.getURL())); addCompressedFiles(fg, files); add(fg); return true; } if (subDirectories >= 2 && subDirectories <= 5) { // the case of : // Title_of_the_film/cd1/... // Title_of_the_film/cd2/... // with an optional sample/subs directory // Title_of_the_film/sample/ // Title_of_the_film/subs/ // Title_of_the_film/subtitles/ // or // Title_of_the_film/bla1.avi // Title_of_the_film/bla2.avi // Title_of_the_film/sample/ // Title_of_the_film/subs/ if (isMovieFolder(directoryNames)) { FileGroup fg = initStorableMovie(folder); fg.getLocations().add(new FileLocation(currentLabel, folder.getURL())); for (String cdFolder : getCdFolders(directoryNames)) { addCompressedFiles(fg, files, cdFolder); } for (FileObject file : folder.getChildren()) { if (!isDirectory(file)) { String ext = getExtension(file); if (MovieFileFilter.VIDEO_EXT_EXTENSIONS.contains(ext)) { fg.getFiles().add(createFileMeta(file, MovieFileType.getTypeByExtension(ext))); } } } add(fg); return true; } } boolean subFolderContainMovie = false; for (FileObject f : files) { final String baseName = f.getName().getBaseName(); if (isDirectory(f) && !baseName.equalsIgnoreCase("sample") && !baseName.startsWith(".")) { subFolderContainMovie |= browse(f, monitor); } } // We want to handle the following cases: // 1, // Title_of_the_film/abc.avi // Title_of_the_film/abc.srt // --> no subdirectory, one film -> the title should be name of the // directory // // 2, // Title_of_the_film/abc-cd1.avi // Title_of_the_film/abc-cd1.srt // Title_of_the_film/abc-cd2.srt // Title_of_the_film/abc-cd2.srt // if (subDirectories > 0 && subFolderContainMovie) { return genericMovieFindProcess(files) || subFolderContainMovie; } else { int foundFiles = plainFileNames.size(); switch (foundFiles) { case 0: return subFolderContainMovie; case 1: { FileGroup fg = initStorableMovie(folder); fg.getLocations().add(new FileLocation(currentLabel, folder.getURL())); addFiles(fg, files, plainFileNames.iterator().next()); add(fg); return true; } case 2: { Iterator<String> it = plainFileNames.iterator(); String name1 = it.next(); String name2 = it.next(); if (LevenshteinDistance.distance(name1, name2) < 3) { // the difference is -cd1 / -cd2 FileGroup fg = initStorableMovie(folder); fg.getLocations().add(new FileLocation(currentLabel, folder.getURL())); addFiles(fg, files, name1); add(fg); return true; } // the difference is significant, we use the generic // solution } default: { return genericMovieFindProcess(files); } } } }
From source file:org.kalypso.ui.rrm.internal.conversion.to12_02.CalcCasesConverter.java
@Override protected void doExecute(final IProgressMonitor monitor) throws InterruptedException { try {//from w w w .ja va 2s .c o m /* Monitor. */ final SubMonitor progress = SubMonitor.convert(monitor, Messages.getString("CalcCasesConverter_1"), //$NON-NLS-1$ 101); /* Find all calc cases. */ final CalcCaseConvertWalker walker = new CalcCaseConvertWalker(m_globalData.getSourceDir()); final File[] calcCases = walker.execute(); /* Monitor. */ ProgressUtilities.worked(progress, 1); progress.setWorkRemaining(calcCases.length); /* Convert all calc cases into scenarios. */ for (int i = 0; i < calcCases.length; i++) { /* Monitor. */ progress.subTask(String.format(Messages.getString("CalcCasesConverter_2"), calcCases[i].getName(), //$NON-NLS-1$ i + 1, calcCases.length)); /* Determine the directories. */ final File sourceDir = calcCases[i]; final File targetDir = determineTargetDir(sourceDir); try { /* Convert the calc case to a scenario. */ final CalcCaseConverter calcCaseConverter = new CalcCaseConverter(sourceDir, targetDir, m_globalData); final IStatus status = calcCaseConverter.execute(progress.newChild(1)); getLog().add(status); } catch (final CoreException ce) { final IStatus status = ce.getStatus(); if (status.matches(IStatus.CANCEL)) throw new InterruptedException(Messages.getString("CalcCasesConverter_3")); //$NON-NLS-1$ getLog().add(status); } catch (final InvocationTargetException e) { getLog().add(IStatus.ERROR, Messages.getString("CalcCasesConverter_4"), e.getTargetException(), //$NON-NLS-1$ calcCases[i].getName()); } catch (final Throwable e) { getLog().add(IStatus.ERROR, Messages.getString("CalcCasesConverter_4"), e, //$NON-NLS-1$ calcCases[i].getName()); } } } catch (final IOException e) { e.printStackTrace(); getLog().add(IStatus.ERROR, Messages.getString("CalcCasesConverter_5"), e); //$NON-NLS-1$ } }
From source file:org.paxle.core.threading.impl.Pool.java
public IWorker<Data> getWorker(boolean fromPool) throws Exception { if (this.closed) { // thread pool already closed. Notify the master thread about this circumstance throw new InterruptedException("Thread pool was closed."); }// www . jav a 2 s . c om // creating or borrowing a new worker @SuppressWarnings("unchecked") IWorker<Data> newWorker = (fromPool) ? (IWorker<Data>) super.borrowObject() : this.createWorker(); // remember the new active worker this.addActiveWorker(newWorker, fromPool); // return worker return newWorker; }
From source file:net.fenyo.gnetwatch.actions.ExternalCommand.java
/** * Reads a line from the process output. * @param r reader.//from w w w . ja v a2 s.c om * @return line read. * @throws IOException IO exception. * @throws InterruptedException exception. */ // data read is lost when interrupted // returns null if EOF // major feature: it never blocks the current thread while reading a stream // On peut amliorer les perfs en gardant dans sb ce qui est lu et donc en lisant plusieurs caractres la fois // et en ne retournant que jusqu'au retour chariot. // this private method must be called from synchronized methods // any thread private String readLine(Reader r) throws IOException, InterruptedException { sb.setLength(0); while (!Thread.currentThread().isInterrupted()) { if (r.ready()) { final int ret = r.read(); if (ret == -1) return sb.length() != 0 ? sb.toString() : null; if (ret == '\n') return sb.toString(); sb.append((char) ret); } else { try { process.exitValue(); return sb.length() != 0 ? sb.toString() : null; } catch (final IllegalThreadStateException ex) { } Thread.sleep(100); } } log.info("readLine(): was interrupted"); throw new InterruptedException("readLine()"); }