List of usage examples for java.util.concurrent TimeoutException TimeoutException
public TimeoutException()
From source file:org.fusesource.meshkeeper.cloudmix.CloudMixProvisioner.java
public String findMeshRegistryUri() throws MeshProvisioningException { if (cachedRegistryConnectUri == null) { RestGridClient controller = getGridClient(); FeatureDetails fd = controller.getFeature(MESH_KEEPER_CONTROL_FEATURE_ID); if (fd == null) { throw new MeshProvisioningException("MeshKeeper is not deployed"); }/*from w w w. j a v a 2 s .c o m*/ String provisionerId = null; for (PropertyDefinition pd : fd.getProperties()) { if (pd.getId().equals(Provisioner.MESHKEEPER_PROVISIONER_ID_PROPERTY)) { provisionerId = pd.getExpression(); } } long timeout = System.currentTimeMillis() + provisioningTimeout; while (true) { try { if (System.currentTimeMillis() > timeout) { throw new TimeoutException(); } List<? extends ProcessClient> clients = controller .getProcessClientsForFeature(MESH_KEEPER_CONTROL_FEATURE_ID); if (clients == null || clients.isEmpty()) { LOG.warn("No processes found running: " + MESH_KEEPER_CONTROL_FEATURE_ID); throw new MeshProvisioningException("MeshKeeper is not deployed"); } ProcessClient pc = clients.get(0); byte[] controllerProps = pc .directoryResource("meshkeeper/server/" + ControlServer.CONTROLLER_PROP_FILE_NAME) .get(byte[].class); Properties p = new Properties(); p.load(new ByteArrayInputStream(controllerProps)); //Make sure the provisionerId matches that of the feature (e.g. we don't want to be looking at a //stale properties file: if (provisionerId != null && provisionerId.equals(p.getProperty(MESHKEEPER_PROVISIONER_ID_PROPERTY))) { LOG.debug("Provisioned provisionerId match"); cachedRegistryConnectUri = (String) p.get(MeshKeeperFactory.MESHKEEPER_REGISTRY_PROPERTY); if (cachedRegistryConnectUri == null) { throw new Exception(MeshKeeperFactory.MESHKEEPER_REGISTRY_PROPERTY + " not found in " + "meshkeeper/server/" + ControlServer.CONTROLLER_PROP_FILE_NAME); } return cachedRegistryConnectUri; } else { LOG.debug("Provisioned provisionerId doesn't match"); } } catch (UniformInterfaceException uie) { //if we get a 404 retry if (uie.getResponse().getStatus() != 404) { throw new MeshProvisioningException("Error retrieving controller properties", uie); } } catch (Exception e) { throw new MeshProvisioningException("Error retrieving controller properties", e); } try { Thread.sleep(1000); } catch (InterruptedException e) { throw new MeshProvisioningException("Error retrieving controller properties", e); } } // List<String> agents = controller.getAgentsAssignedToFeature(MESH_KEEPER_CONTROL_FEATURE_ID); // if (agents != null) { // // getProcessClientsForFeature(featureId) // AgentDetails details = controller.getAgentDetails(agents.get(0)); // details.getHostname(); // String controlHost = details.getHostname(); // details.get // for (Process p : details.getProcesses().getProcesses()) // { // // } // // cachedRegistryConnectUri = "zk:tcp://" + controlHost + ":4040"; // } else { // throw new MeshProvisioningException("MeshKeeper is not deployed"); // } } return cachedRegistryConnectUri; }
From source file:io.druid.data.input.impl.PrefetchableTextFilesFirehoseFactory.java
@Override public Firehose connect(StringInputRowParser firehoseParser, File temporaryDirectory) throws IOException { if (maxCacheCapacityBytes == 0 && maxFetchCapacityBytes == 0) { return super.connect(firehoseParser, temporaryDirectory); }/*from w w w . ja v a 2 s .c om*/ if (objects == null) { objects = ImmutableList.copyOf(Preconditions.checkNotNull(initObjects(), "objects")); } Preconditions.checkState(temporaryDirectory.exists(), "temporaryDirectory[%s] does not exist", temporaryDirectory); Preconditions.checkState(temporaryDirectory.isDirectory(), "temporaryDirectory[%s] is not a directory", temporaryDirectory); // fetchExecutor is responsible for background data fetching final ExecutorService fetchExecutor = createFetchExecutor(); return new FileIteratingFirehose(new Iterator<LineIterator>() { // When prefetching is enabled, fetchFiles and nextFetchIndex are updated by the fetchExecutor thread, but // read by both the main thread (in hasNext()) and the fetchExecutor thread (in fetch()). To guarantee that // fetchFiles and nextFetchIndex are updated atomically, this lock must be held before updating // them. private final Object fetchLock = new Object(); private final LinkedBlockingQueue<FetchedFile> fetchFiles = new LinkedBlockingQueue<>(); // Number of bytes currently fetched files. // This is updated when a file is successfully fetched or a fetched file is deleted. private final AtomicLong fetchedBytes = new AtomicLong(0); private final boolean cacheInitialized; private final boolean prefetchEnabled; private Future<Void> fetchFuture; private int cacheIterateIndex; // nextFetchIndex indicates which object should be downloaded when fetch is triggered. private int nextFetchIndex; { cacheInitialized = totalCachedBytes > 0; prefetchEnabled = maxFetchCapacityBytes > 0; if (cacheInitialized) { nextFetchIndex = cacheFiles.size(); } if (prefetchEnabled) { fetchIfNeeded(totalCachedBytes); } } private void fetchIfNeeded(long remainingBytes) { if ((fetchFuture == null || fetchFuture.isDone()) && remainingBytes <= prefetchTriggerBytes) { fetchFuture = fetchExecutor.submit(() -> { fetch(); return null; }); } } /** * Fetch objects to a local disk up to {@link PrefetchableTextFilesFirehoseFactory#maxFetchCapacityBytes}. * This method is not thread safe and must be called by a single thread. Note that even * {@link PrefetchableTextFilesFirehoseFactory#maxFetchCapacityBytes} is 0, at least 1 file is always fetched. * This is for simplifying design, and should be improved when our client implementations for cloud storages * like S3 support range scan. */ private void fetch() throws Exception { for (int i = nextFetchIndex; i < objects.size() && fetchedBytes.get() <= maxFetchCapacityBytes; i++) { final ObjectType object = objects.get(i); LOG.info("Fetching object[%s], fetchedBytes[%d]", object, fetchedBytes.get()); final File outFile = File.createTempFile(FETCH_FILE_PREFIX, null, temporaryDirectory); fetchedBytes.addAndGet(download(object, outFile, 0)); synchronized (fetchLock) { fetchFiles.put(new FetchedFile(object, outFile)); nextFetchIndex++; } } } /** * Downloads an object. It retries downloading {@link PrefetchableTextFilesFirehoseFactory#maxFetchRetry} * times and throws an exception. * * @param object an object to be downloaded * @param outFile a file which the object data is stored * @param tryCount current retry count * * @return number of downloaded bytes * * @throws IOException */ private long download(ObjectType object, File outFile, int tryCount) throws IOException { try (final InputStream is = openObjectStream(object); final CountingOutputStream cos = new CountingOutputStream(new FileOutputStream(outFile))) { IOUtils.copy(is, cos); return cos.getCount(); } catch (IOException e) { final int nextTry = tryCount + 1; if (!Thread.currentThread().isInterrupted() && nextTry < maxFetchRetry) { LOG.error(e, "Failed to download object[%s], retrying (%d of %d)", object, nextTry, maxFetchRetry); outFile.delete(); return download(object, outFile, nextTry); } else { LOG.error(e, "Failed to download object[%s], retries exhausted, aborting", object); throw e; } } } @Override public boolean hasNext() { synchronized (fetchLock) { return (cacheInitialized && cacheIterateIndex < cacheFiles.size()) || !fetchFiles.isEmpty() || nextFetchIndex < objects.size(); } } @Override public LineIterator next() { if (!hasNext()) { throw new NoSuchElementException(); } // If fetch() fails, hasNext() always returns true because nextFetchIndex must be smaller than the number // of objects, which means next() is always called. The below method checks that fetch() threw an exception // and propagates it if exists. checkFetchException(); final OpenedObject openedObject; try { // Check cache first if (cacheInitialized && cacheIterateIndex < cacheFiles.size()) { final FetchedFile fetchedFile = cacheFiles.get(cacheIterateIndex++); openedObject = new OpenedObject(fetchedFile, getNoopCloser()); } else if (prefetchEnabled) { openedObject = openObjectFromLocal(); } else { openedObject = openObjectFromRemote(); } final InputStream stream = wrapObjectStream(openedObject.object, openedObject.objectStream); return new ResourceCloseableLineIterator(new InputStreamReader(stream, Charsets.UTF_8), openedObject.resourceCloser); } catch (IOException e) { throw Throwables.propagate(e); } } private void checkFetchException() { if (fetchFuture != null && fetchFuture.isDone()) { try { fetchFuture.get(); fetchFuture = null; } catch (InterruptedException | ExecutionException e) { throw Throwables.propagate(e); } } } private OpenedObject openObjectFromLocal() throws IOException { final FetchedFile fetchedFile; final Closeable resourceCloser; if (!fetchFiles.isEmpty()) { // If there are already fetched files, use them fetchedFile = fetchFiles.poll(); resourceCloser = cacheIfPossibleAndGetCloser(fetchedFile, fetchedBytes); fetchIfNeeded(fetchedBytes.get()); } else { // Otherwise, wait for fetching try { fetchIfNeeded(fetchedBytes.get()); fetchedFile = fetchFiles.poll(fetchTimeout, TimeUnit.MILLISECONDS); if (fetchedFile == null) { // Check the latest fetch is failed checkFetchException(); // Or throw a timeout exception throw new RuntimeException(new TimeoutException()); } resourceCloser = cacheIfPossibleAndGetCloser(fetchedFile, fetchedBytes); // trigger fetch again for subsequent next() calls fetchIfNeeded(fetchedBytes.get()); } catch (InterruptedException e) { throw Throwables.propagate(e); } } return new OpenedObject(fetchedFile, resourceCloser); } private OpenedObject openObjectFromRemote() throws IOException { final OpenedObject openedObject; final Closeable resourceCloser = getNoopCloser(); if (totalCachedBytes < maxCacheCapacityBytes) { LOG.info("Caching object[%s]", objects.get(nextFetchIndex)); try { // Since maxFetchCapacityBytes is 0, at most one file is fetched. fetch(); FetchedFile fetchedFile = fetchFiles.poll(); if (fetchedFile == null) { throw new ISE("Cannot fetch object[%s]", objects.get(nextFetchIndex)); } cacheIfPossible(fetchedFile); fetchedBytes.addAndGet(-fetchedFile.length()); openedObject = new OpenedObject(fetchedFile, resourceCloser); } catch (Exception e) { throw Throwables.propagate(e); } } else { final ObjectType object = objects.get(nextFetchIndex++); LOG.info("Reading object[%s]", object); openedObject = new OpenedObject(object, openObjectStream(object), resourceCloser); } return openedObject; } }, firehoseParser, () -> { fetchExecutor.shutdownNow(); try { Preconditions.checkState(fetchExecutor.awaitTermination(fetchTimeout, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ISE("Failed to shutdown fetch executor during close"); } }); }
From source file:cm.aptoide.pt.RemoteInSearch.java
private String downloadFile(int position) { Vector<DownloadNode> tmp_serv = new Vector<DownloadNode>(); String getserv = new String(); String md5hash = null;// w w w.j a v a 2 s . c o m String repo = null; try { tmp_serv = db.getPathHash(apk_lst.get(position).apkid); if (tmp_serv.size() > 0) { DownloadNode node = tmp_serv.get(0); getserv = node.repo + "/" + node.path; md5hash = node.md5h; repo = node.repo; } if (getserv.length() == 0) throw new TimeoutException(); Message msg = new Message(); msg.arg1 = 0; msg.obj = new String(getserv); download_handler.sendMessage(msg); /*BufferedInputStream getit = new BufferedInputStream(new URL(getserv).openStream()); String path = new String(APK_PATH+apk_lst.get(position).name+".apk"); FileOutputStream saveit = new FileOutputStream(path); BufferedOutputStream bout = new BufferedOutputStream(saveit,1024); byte data[] = new byte[1024]; int readed = getit.read(data,0,1024); while(readed != -1) { bout.write(data,0,readed); readed = getit.read(data,0,1024); } bout.close(); getit.close(); saveit.close();*/ String path = new String(APK_PATH + apk_lst.get(position).name + ".apk"); FileOutputStream saveit = new FileOutputStream(path); DefaultHttpClient mHttpClient = new DefaultHttpClient(); HttpGet mHttpGet = new HttpGet(getserv); String[] logins = null; logins = db.getLogin(repo); if (logins != null) { URL mUrl = new URL(getserv); mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials(logins[0], logins[1])); } HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); if (mHttpResponse.getStatusLine().getStatusCode() == 401) { return null; } else { byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity()); saveit.write(buffer); } File f = new File(path); Md5Handler hash = new Md5Handler(); if (md5hash == null || md5hash.equalsIgnoreCase(hash.md5Calc(f))) { return path; } else { return null; } } catch (Exception e) { return null; } }
From source file:fr.inria.atlanmod.neoemf.datastore.estores.impl.DirectWriteHbaseResourceEStoreImpl.java
protected void add(NeoEMFEObject object, EReference eReference, int index, NeoEMFInternalEObject referencedObject) { try {//w w w .j ava2 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, index == NO_INDEX, referencedObject); } else { 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.add(array, index, referencedObject.neoemfId()))); 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 add ''{0}'' to ''{1}'' for element ''{2}''", referencedObject, eReference.getName(), object)); } catch (TimeoutException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format("Unable to add ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times", referencedObject, eReference.getName(), object, ATTEMP_TIMES_DEFAULT)); e.printStackTrace(); } catch (InterruptedException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat .format("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage())); e.printStackTrace(); } }
From source file:com.ning.http.client.providers.NettyAsyncHttpProvider.java
public <T> Future<T> execute(final Request request, final AsyncHandler<T> handler) throws IOException { if (connectionsPool.size() >= config.getMaxTotalConnections()) { throw new IOException("Too many connections"); }/* w w w.java 2 s . com*/ Url url = createUrl(request.getUrl()); Channel channel = performConnect(url); HttpRequest nettyRequest = null; switch (request.getType()) { case GET: nettyRequest = construct(request, HttpMethod.GET, url); break; case POST: nettyRequest = construct(request, HttpMethod.POST, url); break; case DELETE: nettyRequest = construct(request, HttpMethod.DELETE, url); break; case PUT: nettyRequest = construct(request, HttpMethod.PUT, url); break; case HEAD: nettyRequest = construct(request, HttpMethod.HEAD, url); break; } if (log.isDebugEnabled()) log.debug("Executing the execute operation: " + handler); final NettyResponseFuture<T> f = new NettyResponseFuture<T>(url, request, handler, nettyRequest, config.getRequestTimeout()); channel.getConfig().setConnectTimeoutMillis((int) config.getConnectionTimeoutInMs()); channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(f); channel.write(nettyRequest); config.reaper().schedule(new Callable<Object>() { public Object call() { if (!f.isDone()) { f.onThrowable(new TimeoutException()); } return null; } }, config.getRequestTimeout(), TimeUnit.MILLISECONDS); return f; }
From source file:fr.inria.atlanmod.neoemf.data.hbase.store.DirectWriteHBaseStore.java
@Override protected Object setAttribute(PersistentEObject object, EAttribute eAttribute, int index, Object value) { Object oldValue = isSet(object, eAttribute) ? get(object, eAttribute, index) : null; try {// ww w. j av a2 s .co m if (!eAttribute.isMany()) { Put put = new Put(Bytes.toBytes(object.id().toString())); put.addColumn(PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), Bytes.toBytes(serializeToProperty(eAttribute, value).toString())); table.put(put); } else { try { 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((String[]) ArrayUtils .add(array, index, serializeToProperty(eAttribute, value)))); passed = table.checkAndPut(Bytes.toBytes(object.id().toString()), PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), isNull(array) ? null : HBaseEncoderUtil.toBytes(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 set ''{0}'' to ''{1}'' for element ''{2}''", value, eAttribute.getName(), object); } catch (TimeoutException e) { NeoLogger.error("Unable to set ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times", value, eAttribute.getName(), object, ATTEMP_TIMES_DEFAULT); } catch (InterruptedException e) { NeoLogger.error("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage()); } } } catch (IOException e) { NeoLogger.error("Unable to set information for element ''{0}''", object); } return oldValue; }
From source file:org.apache.stratos.cloud.controller.iaases.openstack.OpenstackIaas.java
private boolean waitForStatus(String volumeId, Volume.Status expectedStatus, int timeoutInMins) throws TimeoutException { int timeout = 1000 * 60 * timeoutInMins; long timout = System.currentTimeMillis() + timeout; IaasProvider iaasInfo = getIaasProvider(); String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo); ComputeServiceContext context = iaasInfo.getComputeService().getContext(); NovaApi novaApi = context.unwrapApi(NovaApi.class); VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get(); Volume.Status volumeStatus = this.getVolumeStatus(volumeApi, volumeId); while (volumeStatus != expectedStatus) { try {// w w w . j a va 2 s . c o m if (log.isDebugEnabled()) { log.debug(String.format("Volume %s is still NOT in %s. Current State=%s", volumeId, expectedStatus, volumeStatus)); } if (volumeStatus == Volume.Status.ERROR) { log.error("Volume " + volumeId + " is in state ERROR"); return false; } Thread.sleep(1000); volumeStatus = this.getVolumeStatus(volumeApi, volumeId); 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.datastore.estores.impl.DirectWriteHbaseResourceEStoreImpl.java
protected Object remove(NeoEMFEObject object, EAttribute eAttribute, int index) { Object oldValue = get(object, eAttribute, index); try {// w w w . j a va2 s .com String[] array; boolean passed = false; 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.neoemfId())).add(PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), NeoEMFUtil.EncoderUtil.toBytes((String[]) ArrayUtils.remove(array, index))); passed = table.checkAndPut(Bytes.toBytes(object.neoemfId()), PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), array == null ? null : NeoEMFUtil.EncoderUtil.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) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format("Unable to delete ''{0}'' to ''{1}'' for element ''{2}''", oldValue, eAttribute.getName(), object)); } catch (TimeoutException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format( "Unable to delete ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times", oldValue, eAttribute.getName(), object, ATTEMP_TIMES_DEFAULT)); 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:fr.inria.atlanmod.neoemf.data.hbase.store.DirectWriteHBaseStore.java
@Override protected void addAttribute(PersistentEObject object, EAttribute eAttribute, int index, Object value) { try {// ww w .j ava2s .c om 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(index < 0 ? (String[]) ArrayUtils.add(array, serializeToProperty(eAttribute, value)) : (String[]) ArrayUtils.add(array, serializeToProperty(eAttribute, value)))); passed = table.checkAndPut(Bytes.toBytes(object.id().toString()), PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), isNull(array) ? null : HBaseEncoderUtil.toBytes(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}''", value, eAttribute.getName(), object); } catch (TimeoutException e) { NeoLogger.error("Unable to add ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times", value, eAttribute.getName(), object, ATTEMP_TIMES_DEFAULT); } catch (InterruptedException e) { NeoLogger.error("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage()); } }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
/** * Executes {@link org.apache.http.client.methods.HttpUriRequest} * * @param rq - Request/*from www. j a va2 s.co m*/ * @param callback - Callback to be applied on response * @param <RS> type of response * @return - Serialized Response Body * @throws RestEndpointIOException IO exception */ private <RS> Will<Response<RS>> executeInternal(final HttpUriRequest rq, final HttpEntityCallback<RS> callback) throws RestEndpointIOException { final SettableFuture<Response<RS>> future = SettableFuture.create(); httpClient.execute(rq, new FutureCallback<org.apache.http.HttpResponse>() { @Override public void completed(final org.apache.http.HttpResponse response) { try { if (errorHandler.hasError(response)) { errorHandler.handle(rq, response); } HttpEntity entity = response.getEntity(); Header[] allHeaders = response.getAllHeaders(); ImmutableMultimap.Builder<String, String> headersBuilder = ImmutableMultimap.builder(); for (Header header : allHeaders) { for (HeaderElement element : header.getElements()) { headersBuilder.put(header.getName(), null == element.getValue() ? "" : element.getValue()); } } Response<RS> rs = new Response<RS>(rq.getURI().toASCIIString(), response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), headersBuilder.build(), callback.callback(entity)); future.set(rs); } catch (SerializerException e) { future.setException(e); } catch (IOException e) { future.setException(new RestEndpointIOException("Unable to execute request", e)); } catch (Exception e) { future.setException(e); } } @Override public void failed(final Exception ex) { future.setException(new RestEndpointIOException("Unable to execute request", ex)); } @Override public void cancelled() { final TimeoutException timeoutException = new TimeoutException(); future.setException(timeoutException); } }); return Wills.forListenableFuture(future); }