List of usage examples for java.util.concurrent FutureTask FutureTask
public FutureTask(Runnable runnable, V result)
From source file:com.bigdata.rdf.sail.webapp.client.RemoteRepositoryManager.java
/** * Extracts the solutions from a SPARQL query. * //w w w. ja v a 2 s . c o m * @param response * The connection from which to read the results. * @param listener * The listener to notify when the query result has been closed * (optional). * * @return The results. * * @throws Exception * If anything goes wrong. */ public TupleQueryResult tupleResults(final ConnectOptions opts, final UUID queryId, final IPreparedQueryListener listener) throws Exception { // listener handling the http response. JettyResponseListener response = null; // future for parsing that response (in the background). FutureTask<Void> ft = null; // iteration pattern returned to caller. once they hold this they are // responsible for cleaning up the request by calling close(). TupleQueryResultImpl tqrImpl = null; try { response = doConnect(opts); checkResponseCode(response); final String contentType = response.getContentType(); final MiniMime mimeType = new MiniMime(contentType); final TupleQueryResultFormat format = TupleQueryResultFormat.forMIMEType(mimeType.getMimeType()); if (format == null) throw new IOException( "Could not identify format for service response: serviceURI=" + opts.getBestRequestURL() + ", contentType=" + contentType + " : response=" + response.getResponseBody()); final TupleQueryResultParserFactory parserFactory = TupleQueryResultParserRegistry.getInstance() .get(format); if (parserFactory == null) throw new IOException("No parser for format for service response: serviceURI=" + opts.getBestRequestURL() + ", contentType=" + contentType + ", format=" + format + " : response=" + response.getResponseBody()); final TupleQueryResultParser parser = parserFactory.getParser(); final BackgroundTupleResult result = new BackgroundTupleResult(parser, response.getInputStream()); final MapBindingSet bindings = new MapBindingSet(); final InsertBindingSetCursor cursor = new InsertBindingSetCursor(result, bindings); // Wrap as FutureTask so we can cancel. ft = new FutureTask<Void>(result, null/* result */); /* * Submit task for execution. It will asynchronously consume the * response, pumping solutions into the cursor. * * Note: Can throw a RejectedExecutionException! */ executor.execute(ft); /* * Note: This will block until the binding names are received, so it * can not be done until we submit the BackgroundTupleResult for * execution. */ final List<String> list = new ArrayList<String>(result.getBindingNames()); /* * The task was accepted by the executor. Wrap with iteration * pattern. Once this object is returned to the caller they are * responsible for calling close() to provide proper error cleanup * of the resources associated with the request. */ final TupleQueryResultImpl tmp = new TupleQueryResultImpl(list, cursor) { private final AtomicBoolean notDone = new AtomicBoolean(true); @Override public boolean hasNext() throws QueryEvaluationException { final boolean hasNext = super.hasNext(); if (hasNext == false) { notDone.set(false); } return hasNext; } @Override public void handleClose() throws QueryEvaluationException { try { super.handleClose(); } finally { if (notDone.compareAndSet(true, false)) { try { cancel(queryId); } catch (Exception ex) { log.warn(ex); } } /* * Notify the listener. */ if (listener != null) { listener.closed(queryId); } } }; }; /* * Return the tuple query result listener to the caller. They now * have responsibility for calling close() on that object in order * to close the http connection and release the associated * resources. */ return (tqrImpl = tmp); } finally { if (response != null && tqrImpl == null) { /* * Error handling code path. We have an http response listener * but we were not able to setup the tuple query result * listener. */ if (ft != null) { /* * We submitted the task to parse the response. Since the * code is not returning normally (tqrImpl:=null) we cancel * the FutureTask for the background parse of that response. */ ft.cancel(true/* mayInterruptIfRunning */); } // Abort the http response handling. response.abort(); try { /* * POST back to the server to cancel the request in case it * is still running on the server. */ cancel(queryId); } catch (Exception ex) { log.warn(ex); } if (listener != null) { listener.closed(queryId); } } } }
From source file:org.cloudifysource.rest.controllers.ServiceController.java
/****************** * Uninstalls an application by uninstalling all of its services. Order of uninstallations is determined by the * context property 'com.gs.application.services' which should exist in all service PUs. * * @param applicationName//from w w w . j a va 2 s .c o m * The application name. * @param timeoutInMinutes * . * @return Map with return value. * @throws RestErrorException * When application not found or when attempting to remove management services. */ @JsonResponseExample(status = "success", responseBody = "{\"lifecycleEventContainerID\":\"bfae0a89-b5a0-4250-b393-6cedbf63ac76\"}") @PossibleResponseStatuses(responseStatuses = { @PossibleResponseStatus(code = HTTP_OK, description = "success"), @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "failed_to_locate_app") }) @RequestMapping(value = "applications/{applicationName}/timeout/{timeoutInMinutes}", method = RequestMethod.DELETE) @PreAuthorize("isFullyAuthenticated()") @ResponseBody public Map<String, Object> uninstallApplication(@PathVariable final String applicationName, @PathVariable final int timeoutInMinutes) throws RestErrorException { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // Check that Application exists final Application app = this.admin.getApplications().waitFor(applicationName, 10, TimeUnit.SECONDS); if (app == null) { logger.log(Level.INFO, "Cannot uninstall application " + applicationName + " since it has not been discovered yet."); throw new RestErrorException(FAILED_TO_LOCATE_APP, applicationName); } if (app.getName().equals(CloudifyConstants.MANAGEMENT_APPLICATION_NAME)) { logger.log(Level.INFO, "Cannot uninstall the Management application."); throw new RestErrorException(ResponseConstants.CANNOT_UNINSTALL_MANAGEMENT_APP); } validateGsmState(); final ProcessingUnit[] pus = app.getProcessingUnits().getProcessingUnits(); if (pus.length > 0) { if (permissionEvaluator != null) { final CloudifyAuthorizationDetails authDetails = new CloudifyAuthorizationDetails(authentication); // all the application PUs are supposed to have the same auth-groups setting final String puAuthGroups = pus[0].getBeanLevelProperties().getContextProperties() .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS); permissionEvaluator.verifyPermission(authDetails, puAuthGroups, "deploy"); } } final StringBuilder sb = new StringBuilder(); final List<ProcessingUnit> uninstallOrder = createUninstallOrder(pus, applicationName); // TODO: Add timeout. FutureTask<Boolean> undeployTask = null; logger.log(Level.INFO, "Starting to poll for" + applicationName + " uninstall lifecycle events."); if (uninstallOrder.size() > 0) { undeployTask = new FutureTask<Boolean>(new Runnable() { private final long startTime = System.currentTimeMillis(); @Override public void run() { for (final ProcessingUnit processingUnit : uninstallOrder) { if (permissionEvaluator != null) { final CloudifyAuthorizationDetails authDetails = new CloudifyAuthorizationDetails( authentication); final String puAuthGroups = processingUnit.getBeanLevelProperties() .getContextProperties() .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS); permissionEvaluator.verifyPermission(authDetails, puAuthGroups, "deploy"); } final long undeployTimeout = TimeUnit.MINUTES.toMillis(timeoutInMinutes) - (System.currentTimeMillis() - startTime); try { if (processingUnit.waitForManaged(TIMEOUT_WAITING_FOR_GSM_SEC, TimeUnit.SECONDS) == null) { logger.log(Level.WARNING, "Failed to locate GSM that is managing Processing Unit " + processingUnit.getName()); } else { logger.log(Level.INFO, "Undeploying Processing Unit " + processingUnit.getName()); processingUnit.undeployAndWait(undeployTimeout, TimeUnit.MILLISECONDS); final String serviceName = ServiceUtils .getApplicationServiceName(processingUnit.getName(), applicationName); logger.info( "Removing application service scope attributes for service " + serviceName); deleteServiceAttributes(applicationName, serviceName); } } catch (final Exception e) { final String msg = "Failed to undeploy processing unit: " + processingUnit.getName() + " while uninstalling application " + applicationName + ". Uninstall will continue, but service " + processingUnit.getName() + " may remain in an unstable state"; logger.log(Level.SEVERE, msg, e); } } logger.log(Level.INFO, "Application " + applicationName + " undeployment complete"); } }, Boolean.TRUE); ((InternalAdmin) admin).scheduleAdminOperation(undeployTask); } final UUID lifecycleEventContainerID = startPollingForApplicationUninstallLifecycleEvents(applicationName, uninstallOrder, timeoutInMinutes, undeployTask); final String errors = sb.toString(); if (errors.length() == 0) { final Map<String, Object> returnMap = new HashMap<String, Object>(); returnMap.put(CloudifyConstants.LIFECYCLE_EVENT_CONTAINER_ID, lifecycleEventContainerID); logger.info("Removing all application scope attributes for application " + applicationName); deleteApplicationScopeAttributes(applicationName); return RestUtils.successStatus(returnMap); } throw new RestErrorException(errors); }