List of usage examples for java.lang InterruptedException InterruptedException
public InterruptedException()
InterruptedException
with no detail message. From source file:org.kalypso.simulation.core.ant.FeatureVisitorOperation.java
private IStatus visitPath(final GMLWorkspace workspace, final String featurePath, final IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { FeatureVisitor visitor;// ww w . j a v a 2 s . co m try { final ILogger logger = getLogger(); final URL context = m_visitorTask.getContext(); visitor = m_visitorTask.createVisitor(context, logger); // count features final int depth = m_visitorTask.getDepth(); final int count = countFeatures(workspace, featurePath, depth); final MonitorFeatureVisitor wrappedVisitor = new MonitorFeatureVisitor(monitor, count, visitor); workspace.accept(wrappedVisitor, featurePath, depth); } catch (final OperationCanceledException e) { throw new InterruptedException(); } finally { monitor.done(); } return m_visitorTask.statusFromVisitor(visitor); }
From source file:org.cloudfoundry.tools.timeout.HotSwappingTimeoutProtectionStrategyTest.java
@Test public void shouldHandleInterruptedWatingForAfterRequest() throws Exception { given(this.requestCoordinator.isPollResponseConsumed()).willReturn(true); willThrow(new InterruptedException()).given(this.requestCoordinator).awaitFinish(FAIL_TIMEOUT); try {/* w w w.j a v a2s .c o m*/ this.strategy.handlePoll(this.request, this.response); fail("Did not throw"); } catch (IllegalStateException e) { // Expected assertThat(e.getMessage(), is("Timeout waiting for cleanup")); } verify(this.requestCoordinators).delete(this.request); }
From source file:nya.miku.wishmaster.http.streamer.HttpStreamer.java
/** * HTTP ? ?. ? ? ? ?, release() !//from w ww . java2s . c o m * ? ? ?? ? ? If-Modified-Since, ? * ? ?? ? Modified ({@link #removeFromModifiedMap(String)})! * @param url ? ? * @param requestModel ? ( null, GET If-Modified) * @param httpClient HTTP , ?? ? * @param listener ? ?? ?? ( null) * @param task , ( null) * @return ? HTTP * @throws HttpRequestException ?, ? ? ? */ public HttpResponseModel getFromUrl(String url, HttpRequestModel requestModel, HttpClient httpClient, ProgressListener listener, CancellableTask task) throws HttpRequestException { if (requestModel == null) requestModel = HttpRequestModel.builder().setGET().build(); // Request HttpUriRequest request = null; try { RequestConfig requestConfigBuilder = ExtendedHttpClient .getDefaultRequestConfigBuilder(requestModel.timeoutValue) .setRedirectsEnabled(!requestModel.noRedirect).build(); RequestBuilder requestBuilder = null; switch (requestModel.method) { case HttpRequestModel.METHOD_GET: requestBuilder = RequestBuilder.get().setUri(url); break; case HttpRequestModel.METHOD_POST: requestBuilder = RequestBuilder.post().setUri(url).setEntity(requestModel.postEntity); break; default: throw new IllegalArgumentException("Incorrect type of HTTP Request"); } if (requestModel.customHeaders != null) { for (Header header : requestModel.customHeaders) { requestBuilder.addHeader(header); } } if (requestModel.checkIfModified && requestModel.method == HttpRequestModel.METHOD_GET) { synchronized (ifModifiedMap) { if (ifModifiedMap.containsKey(url)) { requestBuilder .addHeader(new BasicHeader(HttpHeaders.IF_MODIFIED_SINCE, ifModifiedMap.get(url))); } } } request = requestBuilder.setConfig(requestConfigBuilder).build(); } catch (Exception e) { Logger.e(TAG, e); HttpResponseModel.release(request, null); throw new IllegalArgumentException(e); } // ? HttpResponseModel responseModel = new HttpResponseModel(); HttpResponse response = null; try { IOException responseException = null; for (int i = 0; i < 5; ++i) { try { if (task != null && task.isCancelled()) throw new InterruptedException(); response = httpClient.execute(request); responseException = null; break; } catch (IOException e) { Logger.e(TAG, e); responseException = e; if (e.getMessage() == null) break; if (e.getMessage().indexOf("Connection reset by peer") != -1 || e.getMessage().indexOf("I/O error during system call, Broken pipe") != -1) { continue; } else { break; } } } if (responseException != null) { throw responseException; } if (task != null && task.isCancelled()) throw new InterruptedException(); // ???? HTTP StatusLine status = response.getStatusLine(); responseModel.statusCode = status.getStatusCode(); responseModel.statusReason = status.getReasonPhrase(); // (headers) String lastModifiedValue = null; if (responseModel.statusCode == 200) { Header header = response.getFirstHeader(HttpHeaders.LAST_MODIFIED); if (header != null) lastModifiedValue = header.getValue(); } Header header = response.getFirstHeader(HttpHeaders.LOCATION); if (header != null) responseModel.locationHeader = header.getValue(); responseModel.headers = response.getAllHeaders(); // HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { responseModel.contentLength = responseEntity.getContentLength(); if (listener != null) listener.setMaxValue(responseModel.contentLength); InputStream stream = responseEntity.getContent(); responseModel.stream = IOUtils.modifyInputStream(stream, listener, task); } responseModel.request = request; responseModel.response = response; if (lastModifiedValue != null) { synchronized (ifModifiedMap) { ifModifiedMap.put(url, lastModifiedValue); } } } catch (Exception e) { Logger.e(TAG, e); HttpResponseModel.release(request, response); throw new HttpRequestException(e); } return responseModel; }
From source file:cc.arduino.utils.network.FileDownloader.java
private void downloadFile(boolean noResume) throws InterruptedException { RandomAccessFile file = null; try {// ww w.jav a 2s .co m // Open file and seek to the end of it file = new RandomAccessFile(outputFile, "rw"); initialSize = file.length(); if (noResume && initialSize > 0) { // delete file and restart downloading Files.delete(outputFile.toPath()); initialSize = 0; } file.seek(initialSize); setStatus(Status.CONNECTING); Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI()); if ("true".equals(System.getProperty("DEBUG"))) { System.err.println("Using proxy " + proxy); } HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); setDownloaded(0); // Connect connection.connect(); int resp = connection.getResponseCode(); if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) { URL newUrl = new URL(connection.getHeaderField("Location")); proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI()); // open the new connnection again connection = (HttpURLConnection) newUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); connection.connect(); resp = connection.getResponseCode(); } if (resp < 200 || resp >= 300) { throw new IOException("Received invalid http status code from server: " + resp); } // Check for valid content length. long len = connection.getContentLength(); if (len >= 0) { setDownloadSize(len); } setStatus(Status.DOWNLOADING); synchronized (this) { stream = connection.getInputStream(); } byte buffer[] = new byte[10240]; while (status == Status.DOWNLOADING) { int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); setDownloaded(getDownloaded() + read); if (Thread.interrupted()) { file.close(); throw new InterruptedException(); } } if (getDownloadSize() != null) { if (getDownloaded() < getDownloadSize()) throw new Exception("Incomplete download"); } setStatus(Status.COMPLETE); } catch (InterruptedException e) { setStatus(Status.CANCELLED); // lets InterruptedException go up to the caller throw e; } catch (SocketTimeoutException e) { setStatus(Status.CONNECTION_TIMEOUT_ERROR); setError(e); } catch (Exception e) { setStatus(Status.ERROR); setError(e); } finally { IOUtils.closeQuietly(file); synchronized (this) { IOUtils.closeQuietly(stream); } } }
From source file:org.globus.ftp.vanilla.FTPControlChannel.java
private int checkSocketDone(Flag aborted, int ioDelay, int maxWait) throws ServerException, IOException, InterruptedException { int oldTOValue = this.socket.getSoTimeout(); int c = -10;//from w w w .j a v a2 s.co m int time = 0; boolean done = false; if (ioDelay <= 0) { ioDelay = 2000; } while (!done) { try { if (aborted.flag) { throw new InterruptedException(); } this.socket.setSoTimeout(ioDelay); ftpIn.mark(2); c = ftpIn.read(); done = true; } catch (SocketTimeoutException e) { // timeouts will happen logger.debug("temp timeout" + e); } catch (Exception e) { throw new InterruptedException(); } finally { ftpIn.reset(); this.socket.setSoTimeout(oldTOValue); } time += ioDelay; if (time > maxWait && maxWait != WAIT_FOREVER) { throw new ServerException(ServerException.REPLY_TIMEOUT); } } return c; }
From source file:org.marketcetera.util.except.ExceptUtilsTest.java
@Test public void swallow() { swallowHelper(new CloneNotSupportedException(), false); swallowHelper(new InterruptedException(), true); swallowHelper(new InterruptedIOException(), true); swallowHelper(new ClosedByInterruptException(), true); swallowHelper(new FileLockInterruptionException(), true); swallowHelper(new InterruptedNamingException(), true); swallowHelper(new I18NInterruptedException(), true); swallowHelper(new I18NInterruptedRuntimeException(), true); }
From source file:de.blizzy.backup.restore.RestoreDialog.java
@Override public int open() { final ProgressMonitorDialog dlg = new ProgressMonitorDialog(getParentShell()); IRunnableWithProgress runnable = new IRunnableWithProgress() { @Override/*www.j av a 2 s .co m*/ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(Messages.Title_OpenBackupDatabase, IProgressMonitor.UNKNOWN); final boolean[] ok = { true }; List<StorageInterceptorDescriptor> descs = BackupPlugin.getDefault().getStorageInterceptors(); for (final StorageInterceptorDescriptor desc : descs) { final IStorageInterceptor interceptor = desc.getStorageInterceptor(); SafeRunner.run(new ISafeRunnable() { @Override public void run() { IDialogSettings settings = Utils .getChildSection(Utils.getSection("storageInterceptors"), desc.getId()); //$NON-NLS-1$ if (!interceptor.initialize(dlg.getShell(), settings)) { ok[0] = false; } } @Override public void handleException(Throwable t) { ok[0] = false; interceptor.showErrorMessage(t, dlg.getShell()); BackupPlugin.getDefault().logError( "error while initializing storage interceptor '" + desc.getName() + "'", t); //$NON-NLS-1$ //$NON-NLS-2$ } }); storageInterceptors.add(interceptor); } if (!ok[0]) { monitor.done(); throw new InterruptedException(); } Cursor<BackupsRecord> cursor = null; try { database.open(storageInterceptors); database.initialize(); cursor = database.factory().selectFrom(Tables.BACKUPS) .where(Tables.BACKUPS.NUM_ENTRIES.isNotNull()).orderBy(Tables.BACKUPS.RUN_TIME.desc()) .fetchLazy(); while (cursor.hasNext()) { BackupsRecord record = cursor.fetchOne(); Backup backup = new Backup(record.getId().intValue(), new Date(record.getRunTime().getTime()), record.getNumEntries().intValue()); backups.add(backup); } } catch (SQLException | IOException e) { boolean handled = false; for (IStorageInterceptor interceptor : storageInterceptors) { if (interceptor.showErrorMessage(e, dlg.getShell())) { handled = true; } } if (handled) { throw new InterruptedException(); } throw new InvocationTargetException(e); } finally { database.closeQuietly(cursor); monitor.done(); } } }; try { dlg.run(true, false, runnable); } catch (InvocationTargetException e) { // TODO BackupPlugin.getDefault().logError("Error while opening backup database", e); //$NON-NLS-1$ } catch (InterruptedException e) { return Window.CANCEL; } return super.open(); }
From source file:org.kalypso.ui.repository.RepositoryDumper.java
/** * Creates the dump structure in the file-system and into one structure file <br/> * REMARK: this uses the file format which is compatible to the Kalypso-PSICompact-Fake implementation. So exported * repositories can directly be included via that repository implementation. * /*from w w w. j a v a2 s . c o m*/ * @param structureWriter * @param directory * The choosen directory. * @param monitor * A progress monitor. * @throws InterruptedException * @throws RepositoryException */ private void dumpExtendedRecursive(final Writer structureWriter, final File directory, final IRepositoryItem item, final IProgressMonitor monitor) throws InterruptedException, RepositoryException, IOException { /* If the user canceled the operation, abort. */ if (monitor.isCanceled()) throw new InterruptedException(); try { /* Write entry for structure file */ final String identifier = item.getIdentifier(); monitor.subTask(identifier); /* The name will be used as filename. */ final String name = FileUtilities.resolveValidFileName(item.getName()); final File zmlFile = new File(directory, name + ".zml"); //$NON-NLS-1$ dumpItem(structureWriter, zmlFile, item); /* This is the directory, where the children are placed. */ final File newDirectory = new File(directory, name); FileUtils.forceMkdir(newDirectory); final IRepositoryItem[] items = item.getChildren(); if (items != null) { for (final IRepositoryItem item2 : items) dumpExtendedRecursive(structureWriter, newDirectory, item2, monitor); } monitor.worked(1); } catch (final NoSuchElementException ex) { ex.printStackTrace(); final String msg = String.format(Messages.getString("RepositoryDumper.3"), item.getName()); //$NON-NLS-1$ m_stati.add(IStatus.ERROR, msg, ex); } finally { monitor.worked(1); } }