List of usage examples for java.util.concurrent TimeoutException TimeoutException
public TimeoutException()
From source file:fr.inria.atlanmod.neoemf.datastore.estores.impl.DirectWriteHbaseResourceEStoreImpl.java
protected Object remove(NeoEMFEObject object, EReference eReference, int index) { Object oldValue = get(object, eReference, index); try {/* ww w. j av a 2 s . c o m*/ String[] array; boolean passed = false; int attemp = 0; do { array = (String[]) getFromTable(object, eReference); //array = (String[]) ArrayUtils.add(array, index, referencedObject.neoemfId()); Put put = new Put(Bytes.toBytes(object.neoemfId())).add(PROPERTY_FAMILY, Bytes.toBytes(eReference.getName()), NeoEMFUtil.EncoderUtil.toBytesReferences((String[]) ArrayUtils.remove(array, index))); passed = table.checkAndPut(Bytes.toBytes(object.neoemfId()), PROPERTY_FAMILY, Bytes.toBytes(eReference.getName()), array == null ? null : NeoEMFUtil.EncoderUtil.toBytesReferences(array), put); if (!passed) { if (attemp > ATTEMP_TIMES_DEFAULT) throw new TimeoutException(); Thread.sleep((++attemp) * SLEEP_DEFAULT); } } while (!passed); } catch (IOException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format( "Unable to delete ''{0}[{1}''] for element ''{2}''", eReference.getName(), index, object)); } catch (TimeoutException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format( "Unable to delete ''{0}[{1}''] for element ''{2}''", eReference.getName(), index, object)); e.printStackTrace(); } catch (InterruptedException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat .format("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage())); e.printStackTrace(); } return oldValue; }
From source file:org.apache.stratos.cloud.controller.iaases.cloudstack.CloudStackIaas.java
private boolean waitForStatus(String volumeId, Volume.State expectedStatus, int timeoutInMilliseconds) throws TimeoutException { int timeout = 1000 * 60 * timeoutInMilliseconds; long timout = System.currentTimeMillis() + timeout; IaasProvider iaasInfo = getIaasProvider(); ComputeServiceContext context = iaasInfo.getComputeService().getContext(); CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class); //get volume/*from w ww .jav a 2 s . co m*/ org.jclouds.cloudstack.domain.Volume volume = cloudStackApi.getVolumeApi().getVolume(volumeId); Volume.State volumeState = volume.getState(); while (volumeState != expectedStatus) { try { if (log.isDebugEnabled()) { log.debug(String.format("Volume %s is still NOT in %s. Current State=%s", volumeId, expectedStatus, volumeState)); } if (volumeState == Volume.State.FAILED || volumeState == Volume.State.DESTROYED || volumeState == Volume.State.UNRECOGNIZED) { log.error("Volume " + volumeId + " is in state" + volumeState); return false; } Thread.sleep(1000); volumeState = volume.getState(); if (System.currentTimeMillis() > timout) { throw new TimeoutException(); } } catch (InterruptedException e) { // Ignoring the exception } } if (log.isDebugEnabled()) { log.debug(String.format("Volume %s status became %s", volumeId, expectedStatus)); } return true; }
From source file:fr.inria.atlanmod.neoemf.data.hbase.store.DirectWriteHBaseStore.java
@Override protected void addReference(PersistentEObject object, EReference eReference, int index, PersistentEObject referencedObject) { try {// w w w .jav a 2 s. c o m /* * As long as the element is not attached to the resource, the containment and type information are not * stored. */ updateLoadedEObjects(referencedObject); updateContainment(object, eReference, referencedObject); updateInstanceOf(referencedObject); if (index == NO_INDEX) { addAsAppend(object, eReference, true, referencedObject); } else { String[] array; boolean passed; int attemp = 0; do { array = (String[]) getFromTable(object, eReference); // array = (String[]) ArrayUtils.add(array, index, referencedObject.neoemfId()); Put put = new Put(Bytes.toBytes(object.id().toString())).addColumn(PROPERTY_FAMILY, Bytes.toBytes(eReference.getName()), HBaseEncoderUtil.toBytesReferences( ArrayUtils.add(array, index, referencedObject.id().toString()))); passed = table.checkAndPut(Bytes.toBytes(object.id().toString()), PROPERTY_FAMILY, Bytes.toBytes(eReference.getName()), isNull(array) ? null : HBaseEncoderUtil.toBytesReferences(array), put); if (!passed) { if (attemp > ATTEMP_TIMES_DEFAULT) { throw new TimeoutException(); } Thread.sleep((++attemp) * SLEEP_DEFAULT); } } while (!passed); } } catch (IOException e) { NeoLogger.error("Unable to add ''{0}'' to ''{1}'' for element ''{2}''", referencedObject, eReference.getName(), object); } catch (TimeoutException e) { NeoLogger.error("Unable to add ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times", referencedObject, eReference.getName(), object, ATTEMP_TIMES_DEFAULT); } catch (InterruptedException e) { NeoLogger.error("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage()); } }
From source file:fr.inria.atlanmod.neoemf.data.hbase.store.DirectWriteHBaseStore.java
@Override protected Object removeAttribute(PersistentEObject object, EAttribute eAttribute, int index) { Object oldValue = get(object, eAttribute, index); try {/* w w w .j a v a 2s .co m*/ String[] array; boolean passed; int attemp = 0; do { array = (String[]) getFromTable(object, eAttribute); // array = (String[]) ArrayUtils.add(array, index, serializeValue(eAttribute, value)); Put put = new Put(Bytes.toBytes(object.id().toString())).addColumn(PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), HBaseEncoderUtil.toBytes(ArrayUtils.remove(array, index))); passed = table.checkAndPut(Bytes.toBytes(object.id().toString()), PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), HBaseEncoderUtil.toBytes(array), put); if (!passed) { if (attemp > ATTEMP_TIMES_DEFAULT) { throw new TimeoutException(); } Thread.sleep((++attemp) * SLEEP_DEFAULT); oldValue = get(object, eAttribute, index); } } while (!passed); } catch (IOException e) { NeoLogger.error("Unable to delete ''{0}'' to ''{1}'' for element ''{2}''", oldValue, eAttribute.getName(), object); } catch (TimeoutException e) { NeoLogger.error("Unable to delete ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times", oldValue, eAttribute.getName(), object, ATTEMP_TIMES_DEFAULT); } catch (InterruptedException e) { NeoLogger.error("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage()); } return oldValue; }
From source file:net.sourceforge.vulcan.core.support.ProjectBuilderTest.java
public void testTopLevelBuildReportsTimeout() throws Exception { doTopLevelBuildTest(new RunnableCallback() { public void run(BuildContext buildContext) throws Exception { builder.abortCurrentBuild(true, "watchdog"); throw new TimeoutException(); }//from w w w .j a va 2s. c o m }); assertEquals(Status.ERROR, buildStatus.getStatus()); assertEquals("messages.build.timeout", buildStatus.getMessageKey()); }
From source file:fr.inria.atlanmod.neoemf.data.hbase.store.DirectWriteHBaseStore.java
@Override protected Object removeReference(PersistentEObject object, EReference eReference, int index) { Object oldValue = get(object, eReference, index); try {/*from w w w .j ava2s . c o m*/ String[] array; boolean passed; int attemp = 0; do { array = (String[]) getFromTable(object, eReference); // array = (String[]) ArrayUtils.add(array, index, referencedObject.neoemfId()); Put put = new Put(Bytes.toBytes(object.id().toString())).addColumn(PROPERTY_FAMILY, Bytes.toBytes(eReference.getName()), HBaseEncoderUtil.toBytesReferences(ArrayUtils.remove(array, index))); passed = table.checkAndPut(Bytes.toBytes(object.id().toString()), PROPERTY_FAMILY, Bytes.toBytes(eReference.getName()), HBaseEncoderUtil.toBytesReferences(array), put); if (!passed) { if (attemp > ATTEMP_TIMES_DEFAULT) { throw new TimeoutException(); } Thread.sleep((++attemp) * SLEEP_DEFAULT); } } while (!passed); } catch (IOException | TimeoutException e) { NeoLogger.error("Unable to delete ''{0}[{1}''] for element ''{2}''", eReference.getName(), index, object); } catch (InterruptedException e) { NeoLogger.error("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage()); } return oldValue; }
From source file:net.sourceforge.vulcan.core.support.ProjectBuilderTest.java
public void testTopLevelBuildReportsKilled() throws Exception { doTopLevelBuildTest(new RunnableCallback() { public void run(BuildContext buildContext) throws Exception { builder.abortCurrentBuild(false, "impatient user"); throw new TimeoutException(); }/* ww w .j a va2s . c o m*/ }); assertEquals(Status.ERROR, buildStatus.getStatus()); assertEquals("messages.build.killed", buildStatus.getMessageKey()); assertEquals(Arrays.asList("impatient user"), Arrays.asList(buildStatus.getMessageArgs())); }
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * This will establish a connection to the MQTT broker and if successful, notify all * publishers and subscribers that the connection has become active. This method will * do nothing if there is already an active connection. * * @return Returns a future that completes with true if already connected or connecting, * completes with false if a connection timeout has happened and completes exceptionally otherwise. *///from w w w . ja v a 2 s .c om public CompletableFuture<Boolean> start() { // We don't want multiple concurrent threads to start a connection synchronized (this) { if (connectionState() != MqttConnectionState.DISCONNECTED) { return CompletableFuture.completedFuture(true); } // Perform the connection attempt isConnecting = true; connectionObservers.forEach(o -> o.connectionStateChanged(MqttConnectionState.CONNECTING, null)); } // Ensure the reconnect strategy is started if (reconnectStrategy != null) { reconnectStrategy.start(); } // Close client if there is still one existing if (client != null) { try { client.close(); } catch (org.eclipse.paho.client.mqttv3.MqttException ignore) { } client = null; } CompletableFuture<Boolean> future = connectionCallback.createFuture(); StringBuilder serverURI = new StringBuilder(); switch (protocol) { case TCP: serverURI.append(secure ? "ssl://" : "tcp://"); break; case WEBSOCKETS: serverURI.append(secure ? "wss://" : "ws://"); break; default: future.completeExceptionally(new ConfigurationException("protocol", "Protocol unknown")); return future; } serverURI.append(host); serverURI.append(":"); serverURI.append(port); // Storage Path persistencePath = this.persistencePath; if (persistencePath == null) { persistencePath = Paths.get(ConfigConstants.getUserDataFolder()).resolve("mqtt").resolve(host); } try { persistencePath = Files.createDirectories(persistencePath); } catch (IOException e) { future.completeExceptionally(new MqttException(e)); return future; } MqttDefaultFilePersistence _dataStore = new MqttDefaultFilePersistence(persistencePath.toString()); // Create the client MqttAsyncClient _client; try { _client = createClient(serverURI.toString(), clientId, _dataStore); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { future.completeExceptionally(new MqttException(e)); return future; } // Assign to object this.client = _client; this.dataStore = _dataStore; // Connect _client.setCallback(clientCallback); try { _client.connect(createMqttOptions(), null, connectionCallback); logger.info("Starting MQTT broker connection to '{}' with clientid {} and file store '{}'", host, getClientId(), persistencePath); } catch (org.eclipse.paho.client.mqttv3.MqttException | ConfigurationException e) { future.completeExceptionally(new MqttException(e)); return future; } // Connect timeout ScheduledExecutorService executor = timeoutExecutor; if (executor != null) { final ScheduledFuture<?> timeoutFuture = this.timeoutFuture .getAndSet(executor.schedule(() -> connectionCallback.onFailure(null, new TimeoutException()), timeout, TimeUnit.MILLISECONDS)); if (timeoutFuture != null) { timeoutFuture.cancel(false); } } return future; }
From source file:cm.aptoide.pt.data.webservices.ManagerDownloads.java
private void download(ViewDownload download, boolean overwriteCache) { ViewCache localCache = download.getCache(); ViewNotification notification = download.getNotification(); String localPath = localCache.getLocalPath(); String remotePath = download.getRemotePath(); int targetBytes; FileOutputStream fileOutputStream = null; try {// w ww . j av a 2s. co m fileOutputStream = new FileOutputStream(localPath, !overwriteCache); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(remotePath); Log.d("Aptoide-download", "downloading from: " + remotePath + " to: " + localPath); // Log.d("Aptoide-download","downloading with: "+getUserAgentString()+" login: "+download.isLoginRequired()); // httpGet.setHeader("User-Agent", getUserAgentString()); //TODO is consistently getting 404 from server String resumeLength = Long.toString(download.getCache().getFile().length()); int resumeLengthInt = Integer.parseInt(resumeLength); if (!overwriteCache) { Log.d("Aptoide-download", "downloading from [bytes]: " + resumeLength); httpGet.setHeader("Range", "bytes=" + resumeLength + "-"); notification.incrementProgress(resumeLengthInt); } if (download.isLoginRequired()) { //TODO refactor using username/password args when using webservices (only exception left is when getting hard-disk files) URL url = new URL(remotePath); httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(download.getLogin().getUsername(), download.getLogin().getPassword())); } HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse == null) { Log.d("Aptoide-ManagerDownloads", "Problem in network... retry..."); httpResponse = httpClient.execute(httpGet); if (httpResponse == null) { Log.d("Aptoide-ManagerDownloads", "Major network exception... Exiting!"); /*msg_al.arg1= 1; download_error_handler.sendMessage(msg_al);*/ throw new TimeoutException(); } } if (httpResponse.getStatusLine().getStatusCode() == 401) { Log.d("Aptoide-ManagerDownloads", "401 Time out!"); fileOutputStream.close(); managerCache.clearCache(download.getCache()); throw new TimeoutException(); } else if (httpResponse.getStatusLine().getStatusCode() == 404) { fileOutputStream.close(); managerCache.clearCache(download.getCache()); throw new AptoideExceptionNotFound("404 Not found!"); } else { Log.d("Aptoide-ManagerDownloads", "Download target size: " + notification.getProgressCompletionTarget()); // if(download.isSizeKnown()){ // targetBytes = download.getSize()*Constants.KBYTES_TO_BYTES; //TODO check if server sends kbytes or bytes // notification.setProgressCompletionTarget(targetBytes); // }else{ if (httpResponse.containsHeader("Content-Length") && resumeLengthInt != 0) { targetBytes = Integer.parseInt(httpResponse.getFirstHeader("Content-Length").getValue()); Log.d("Aptoide-ManagerDownloads", "targetBytes: " + targetBytes); // notification.setProgressCompletionTarget(targetBytes); } // } InputStream inputStream = null; if ((httpResponse.getEntity().getContentEncoding() != null) && (httpResponse.getEntity().getContentEncoding().getValue().equalsIgnoreCase("gzip"))) { Log.d("Aptoide-ManagerDownloads", "with gzip"); inputStream = new GZIPInputStream(httpResponse.getEntity().getContent()); } else { // Log.d("Aptoide-ManagerDownloads","No gzip"); inputStream = httpResponse.getEntity().getContent(); } byte data[] = new byte[8096]; int bytesRead; while ((bytesRead = inputStream.read(data, 0, 8096)) > 0) { notification.incrementProgress(bytesRead); fileOutputStream.write(data, 0, bytesRead); } Log.d("Aptoide-ManagerDownloads", "Download done! Name: " + notification.getActionsTargetName() + " localPath: " + localPath); notification.setCompleted(true); fileOutputStream.flush(); fileOutputStream.close(); inputStream.close(); if (localCache.hasMd5Sum()) { getManagerCache().md5CheckOk(localCache); //TODO md5check boolean return handle by raising exception } } } catch (Exception e) { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (Exception e1) { } e.printStackTrace(); if (notification.getNotificationType().equals(EnumNotificationTypes.GET_APP) && download.getCache().getFile().length() > 0) { notification.setCompleted(true); serviceData.scheduleInstallApp(notification.getTargetsHashid()); } throw new AptoideExceptionDownload(e); } }
From source file:pt.aptoide.backupapps.data.webservices.ManagerDownloads.java
private void download(ViewDownload download, boolean overwriteCache) { ViewCache localCache = download.getCache(); ViewNotification notification = download.getNotification(); boolean resuming = false; String localPath = localCache.getLocalPath(); String remotePath = download.getRemotePath(); int targetBytes; FileOutputStream fileOutputStream = null; try {//from w w w . j a v a 2 s . c om fileOutputStream = new FileOutputStream(localPath, !overwriteCache); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = Constants.SERVER_CONNECTION_TIMEOUT; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = Constants.SERVER_READ_TIMEOUT; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); httpClient.setParams(httpParameters); HttpGet httpGet = new HttpGet(remotePath); Log.d("Aptoide-download", "downloading from: " + remotePath + " to: " + localPath); Log.d("Aptoide-download", "downloading with: " + getUserAgentString() + " private: " + download.isLoginRequired()); httpGet.setHeader("User-Agent", getUserAgentString()); String resumeLength = Long.toString(download.getCache().getFile().length()); int resumeLengthInt = Integer.parseInt(resumeLength); if (!overwriteCache) { if (resumeLengthInt > 0) { resuming = true; } Log.d("Aptoide-download", "downloading from [bytes]: " + resumeLength); httpGet.setHeader("Range", "bytes=" + resumeLength + "-"); notification.incrementProgress(resumeLengthInt); } if (download.isLoginRequired()) { URL url = new URL(remotePath); httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(download.getLogin().getUsername(), download.getLogin().getPassword())); } HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse == null) { Log.d("Aptoide-ManagerDownloads", "Problem in network... retry..."); httpResponse = httpClient.execute(httpGet); if (httpResponse == null) { Log.d("Aptoide-ManagerDownloads", "Major network exception... Exiting!"); /*msg_al.arg1= 1; download_error_handler.sendMessage(msg_al);*/ if (!resuming) { managerCache.clearCache(download.getCache()); } throw new TimeoutException(); } } int httpStatusCode = httpResponse.getStatusLine().getStatusCode(); Log.d("Aptoide-download", "Server Response Status Code: " + httpStatusCode); switch (httpStatusCode) { case 401: fileOutputStream.close(); if (!resuming) { managerCache.clearCache(download.getCache()); } // download.setFailReason(EnumDownloadFailReason.TIMEOUT); throw new TimeoutException(httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase()); case 403: fileOutputStream.close(); if (!resuming) { managerCache.clearCache(download.getCache()); } // download.setFailReason(EnumDownloadFailReason.IP_BLACKLISTED); throw new AptoideExceptionDownload( httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase()); case 404: fileOutputStream.close(); if (!resuming) { managerCache.clearCache(download.getCache()); } // download.setFailReason(EnumDownloadFailReason.NOT_FOUND); throw new AptoideExceptionNotFound( httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase()); case 416: fileOutputStream.close(); if (!resuming) { managerCache.clearCache(download.getCache()); } notification.setCompleted(true); // try { // downloadStatusClient.updateDownloadStatus(cache.hashCode(), download); // } catch (RemoteException e4) { // e4.printStackTrace(); // } return; default: Log.d("Aptoide-ManagerDownloads", "Download target size: " + notification.getProgressCompletionTarget()); // if(download.isSizeKnown()){ // targetBytes = download.getSize()*Constants.KBYTES_TO_BYTES; //TODO check if server sends kbytes or bytes // notification.setProgressCompletionTarget(targetBytes); // }else{ if (httpResponse.containsHeader("Content-Length") && resumeLengthInt != 0) { targetBytes = Integer.parseInt(httpResponse.getFirstHeader("Content-Length").getValue()); Log.d("Aptoide-ManagerDownloads", "targetBytes: " + targetBytes); // notification.setProgressCompletionTarget(targetBytes); } // } InputStream inputStream = null; if ((httpResponse.getEntity().getContentEncoding() != null) && (httpResponse.getEntity().getContentEncoding().getValue().equalsIgnoreCase("gzip"))) { Log.d("Aptoide-ManagerDownloads", "with gzip"); inputStream = new GZIPInputStream(httpResponse.getEntity().getContent()); } else { // Log.d("Aptoide-ManagerDownloads","No gzip"); inputStream = httpResponse.getEntity().getContent(); } byte data[] = new byte[8096]; int bytesRead; while ((bytesRead = inputStream.read(data, 0, 8096)) > 0) { notification.incrementProgress(bytesRead); fileOutputStream.write(data, 0, bytesRead); } Log.d("Aptoide-ManagerDownloads", "Download done! Name: " + notification.getActionsTargetName() + " localPath: " + localPath); notification.setCompleted(true); fileOutputStream.flush(); fileOutputStream.close(); inputStream.close(); if (localCache.hasMd5Sum()) { if (!getManagerCache().md5CheckOk(localCache)) { managerCache.clearCache(download.getCache()); throw new AptoideExceptionDownload("md5 check failed!"); } } return; } } catch (Exception e) { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (Exception e1) { } e.printStackTrace(); if (notification.getNotificationType().equals(EnumNotificationTypes.GET_APP) && download.getCache().getFile().length() > 0) { notification.setCompleted(true); serviceData.scheduleInstallApp(notification.getTargetsHashid()); } throw new AptoideExceptionDownload(e); } }