Example usage for java.util.concurrent FutureTask FutureTask

List of usage examples for java.util.concurrent FutureTask FutureTask

Introduction

In this page you can find the example usage for java.util.concurrent FutureTask FutureTask.

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:com.nextgis.ngm_clink_monitoring.fragments.CreateObjectFragment.java

protected void createObject() {
    String fieldName = null;/*from  ww w.  j  a v a  2  s. c om*/

    switch (mFoclStructLayerType) {
    case FoclConstants.LAYERTYPE_FOCL_REAL_OPTICAL_CABLE_POINT:
        if (null == mLayingMethod.getValue()) {
            fieldName = getActivity().getString(R.string.laying_method);
        }
        break;

    case FoclConstants.LAYERTYPE_FOCL_REAL_FOSC:
        //                if (null == mFoscType.getValue()) {
        //                    fieldName = getActivity().getString(R.string.fosc_type);
        //                    break;
        //                }
        if (null == mFoscPlacement.getValue()) {
            fieldName = getActivity().getString(R.string.fosc_placement);
        }
        break;

    case FoclConstants.LAYERTYPE_FOCL_REAL_OPTICAL_CROSS:
        //                if (null == mOpticalCrossType.getValue()) {
        //                    fieldName = getActivity().getString(R.string.optical_cross_type);
        //                }
        break;

    case FoclConstants.LAYERTYPE_FOCL_REAL_ACCESS_POINT:
        break;

    case FoclConstants.LAYERTYPE_FOCL_REAL_SPECIAL_TRANSITION_POINT:
        if (null == mSpecialLayingMethod.getValue()) {
            fieldName = getActivity().getString(R.string.special_laying_method);
            break;
        }
        if (null == mMarkType.getValue()) {
            fieldName = getActivity().getString(R.string.mark_type);
        }
        break;
    }

    if (null != fieldName) {
        YesNoDialog dialog = new YesNoDialog();
        dialog.setKeepInstance(true).setIcon(R.drawable.ic_action_warning).setTitle(R.string.warning)
                .setMessage(String.format(getString(R.string.empty_field_warning), fieldName))
                .setPositiveText(R.string.ok)
                .setOnPositiveClickedListener(new YesNoDialog.OnPositiveClickedListener() {
                    @Override
                    public void onPositiveClicked() {
                        // cancel
                    }
                }).show(getActivity().getSupportFragmentManager(),
                        FoclConstants.FRAGMENT_YES_NO_DIALOG + "FieldsNotNull");
        return; // we do not need logcat here
    }

    if (!mNewStartPoint && 0 < mObjectCount
            && FoclConstants.LAYERTYPE_FOCL_REAL_OPTICAL_CABLE_POINT == mFoclStructLayerType
            && null != mDistance && FoclConstants.MAX_DISTANCE_FROM_PREV_POINT < mDistance) {

        showDistanceExceededDialog();
        return; // we do not need logcat here
    }

    if (null == mObjectPhotoFileAdapter || mObjectPhotoFileAdapter.getItemCount() == 0) {
        YesNoDialog dialog = new YesNoDialog();
        dialog.setKeepInstance(true).setIcon(R.drawable.ic_action_warning).setTitle(R.string.warning)
                .setMessage(getString(R.string.take_photos_to_confirm)).setPositiveText(R.string.ok)
                .setOnPositiveClickedListener(new YesNoDialog.OnPositiveClickedListener() {
                    @Override
                    public void onPositiveClicked() {
                        // cancel
                    }
                }).show(getActivity().getSupportFragmentManager(),
                        FoclConstants.FRAGMENT_YES_NO_DIALOG + "TakePhotos");
        return; // we do not need logcat here
    }

    LayoutInflater inflater = LayoutInflater.from(getActivity());
    View view = inflater.inflate(R.layout.dialog_waiting, null);

    final YesNoDialog waitProgressDialog = new YesNoDialog();
    waitProgressDialog.setKeepInstance(true).setIcon(R.drawable.ic_action_data_usage).setTitle(R.string.waiting)
            .setView(view, true);

    waitProgressDialog.setCancelable(false);
    waitProgressDialog.show(getActivity().getSupportFragmentManager(),
            FoclConstants.FRAGMENT_YES_NO_DIALOG + "WaitProgress");

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case CREATE_OBJECT_DONE:
                waitProgressDialog.dismiss();
                break;
            case CREATE_OBJECT_OK:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case CREATE_OBJECT_FAILED:
                Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_LONG).show();
                waitProgressDialog.dismiss();
                break;
            }
        }
    };

    RunnableFuture<Void> future = new FutureTask<Void>(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            createObjectTask();
            return null;
        }
    }) {
        @Override
        protected void done() {
            super.done();
            handler.sendEmptyMessage(CREATE_OBJECT_DONE);
        }

        @Override
        protected void set(Void aVoid) {
            super.set(aVoid);
            handler.sendEmptyMessage(CREATE_OBJECT_OK);
        }

        @Override
        protected void setException(Throwable t) {
            super.setException(t);
            Message msg = handler.obtainMessage(CREATE_OBJECT_FAILED, t.getLocalizedMessage());
            msg.sendToTarget();
        }
    };

    new Thread(future).start();
}

From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java

/**
 * Retrieve profiles from database. This should run asynchronously as it may search on MySQL.
 *
 * @param onlinePlayer online player instance to build Profiles
 * @return a set of profiles, null if any error occurred
 *//*from w  w  w.j  ava  2s.co  m*/
public FutureTask<Set<Profile>> retrieveProfiles(final OnlinePlayer onlinePlayer) {
    return new FutureTask<>(() -> {
        synchronized (playerProfiles) {
            ProfileStorage profileStorage = playerProfiles
                    .remove(onlinePlayer.getOfflinePlayer().getPlayerId());
            // Check if profile was queued to be removed
            if (profileStorage != null)
                return profileStorage.profiles;
        }

        // Prepare for database search
        HashSet<Profile> profiles = new HashSet<>();
        checkConnection();

        try {
            // Get all profiles types
            for (Profile.ProfileType profileType : Profile.ProfileType.values())
                // Note: getConstructor(OnlinePlayer) won't work
                profiles.add(profileType.getProfileClass().getDeclaredConstructor(OnlinePlayer.class)
                        .newInstance(onlinePlayer).loadProfileFromDatabase(connection));
            return profiles;
        } catch (Exception exception) {
            exception.printStackTrace();
            return null;
        }
    });
}

From source file:com.wso2telco.Endpoints.java

/**
 * Mepin confirm.//w w w .  j a va  2 s .co  m
 *
 * @param identifier        the identifier
 * @param transactionId     the transaction id
 * @param allow             the allow
 * @param transactionStatus the transaction status
 * @return the response
 * @throws SQLException the SQL exception
 */
@POST
@Path("/mepin/response")
@Consumes("application/x-www-form-urlencoded")
public Response mepinConfirm(@FormParam("identifier") String identifier,
        @FormParam("transaction_id") String transactionId, @FormParam("allow") String allow,
        @FormParam("transaction_status") String transactionStatus) throws SQLException {

    if (log.isDebugEnabled()) {
        log.debug("MePIN transactionID : " + transactionId);
        log.debug("MePIN identifier : " + identifier);
        log.debug("MePIN transactionStatus : " + transactionStatus);
    }

    MePinStatusRequest mePinStatus = new MePinStatusRequest(transactionId);
    FutureTask<String> futureTask = new FutureTask<String>(mePinStatus);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(futureTask);

    return Response.status(200).build();
}

From source file:org.cloudifysource.rest.controllers.DeploymentsController.java

/**
 * Uninstalls a service./*www.j a v a2s.c  o  m*/
 * 
 * @param appName
 *            the application name
 * @param serviceName
 *            the service name
 * @param timeoutInMinutes
 *            timeout in minutes
 * @return UUID of this action, can be used to follow the relevant events
 * @throws ResourceNotFoundException
 *             Indicates the service could not be found
 * @throws RestErrorException
 *             Indicates the uninstall operation could not be performed
 */
@RequestMapping(value = "/{appName}/services/{serviceName}", method = RequestMethod.DELETE)
@PreAuthorize("isFullyAuthenticated()")
public UninstallServiceResponse uninstallService(@PathVariable final String appName,
        @PathVariable final String serviceName,
        @RequestParam(required = false, defaultValue = "5") final Integer timeoutInMinutes)
        throws ResourceNotFoundException, RestErrorException {

    final ProcessingUnit processingUnit = controllerHelper.getService(appName, serviceName);
    final String deploymentId = processingUnit.getBeanLevelProperties().getContextProperties()
            .getProperty(CloudifyConstants.CONTEXT_PROPERTY_DEPLOYMENT_ID);

    if (permissionEvaluator != null) {
        final String puAuthGroups = processingUnit.getBeanLevelProperties().getContextProperties()
                .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS);
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final CloudifyAuthorizationDetails authDetails = new CloudifyAuthorizationDetails(authentication);
        permissionEvaluator.verifyPermission(authDetails, puAuthGroups, "deploy");
    }

    // validations
    validateUninstallService();

    populateEventsCache(deploymentId, processingUnit);

    final FutureTask<Boolean> undeployTask = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            boolean result = processingUnit.undeployAndWait(timeoutInMinutes, TimeUnit.MINUTES);
            deleteServiceAttributes(appName, serviceName);
            // write to events cache
            DeploymentEvent undeployFinishedEvent = new DeploymentEvent();
            undeployFinishedEvent.setDescription(CloudifyConstants.UNDEPLOYED_SUCCESSFULLY_EVENT);

            eventsCache.add(new EventsCacheKey(deploymentId), undeployFinishedEvent);
            return result;
        }
    });
    serviceUndeployExecutor.execute(undeployTask);

    final UninstallServiceResponse uninstallServiceResponse = new UninstallServiceResponse();
    uninstallServiceResponse.setDeploymentID(deploymentId);
    return uninstallServiceResponse;
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

/**
 * undeploys the specified service of the specific application.
 *
 * @param applicationName//from w  w  w .  ja  v  a  2  s. co m
 *            The application name.
 * @param serviceName
 *            The service name.
 * @param timeoutInMinutes
 *            .
 * @return success status if service was undeployed successfully, else returns failure status.
 * @throws RestErrorException
 *             When failed to locate service.
 */
@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_service") })
@RequestMapping(value = "applications/{applicationName}/services/{serviceName}/timeout/{timeoutInMinutes}/undeploy", method = RequestMethod.DELETE)
public @ResponseBody @PreAuthorize("isFullyAuthenticated()") Map<String, Object> undeploy(
        @PathVariable final String applicationName, @PathVariable final String serviceName,
        @PathVariable final int timeoutInMinutes) throws RestErrorException {
    final String absolutePuName = ServiceUtils.getAbsolutePUName(applicationName, serviceName);
    final ProcessingUnit processingUnit = admin.getProcessingUnits().waitFor(absolutePuName,
            PU_DISCOVERY_TIMEOUT_SEC, TimeUnit.SECONDS);
    if (processingUnit == null) {
        return unavailableServiceError(absolutePuName);
    }

    if (permissionEvaluator != null) {
        final String puAuthGroups = processingUnit.getBeanLevelProperties().getContextProperties()
                .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS);
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final CloudifyAuthorizationDetails authDetails = new CloudifyAuthorizationDetails(authentication);
        permissionEvaluator.verifyPermission(authDetails, puAuthGroups, "deploy");
    }
    validateGsmState();

    final FutureTask<Boolean> undeployTask = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            boolean result = processingUnit.undeployAndWait(timeoutInMinutes, TimeUnit.MINUTES);
            deleteServiceAttributes(applicationName, serviceName);
            return result;
        }

    });
    serviceUndeployExecutor.execute(undeployTask);
    final UUID lifecycleEventContainerID = startPollingForServiceUninstallLifecycleEvents(applicationName,
            serviceName, timeoutInMinutes, undeployTask);

    final Map<String, Object> returnMap = new HashMap<String, Object>();
    returnMap.put(CloudifyConstants.LIFECYCLE_EVENT_CONTAINER_ID, lifecycleEventContainerID);
    return successStatus(returnMap);
}

From source file:org.alfresco.repo.content.metadata.AbstractMappingMetadataExtracter.java

/**
 * Calls the {@link AbstractMappingMetadataExtracter#extractRaw(ContentReader)} method
 * using the given limits./*w  w  w  .  ja v  a 2  s .com*/
 * <p>
 * Currently the only limit supported by {@link MetadataExtracterLimits} is a timeout
 * so this method uses {@link AbstractMappingMetadataExtracter#getExecutorService()}
 * to execute a {@link FutureTask} with any timeout defined.
 * <p>
 * If no timeout limit is defined or is unlimited (-1),
 * the <code>extractRaw</code> method is called directly.
 * 
 * @param reader        the document to extract the values from.  This stream provided by
 *                      the reader must be closed if accessed directly.
 * @param limits        the limits to impose on the extraction
 * @return              Returns a map of document property values keyed by property name.
 * @throws Throwable    All exception conditions can be handled.
 */
private Map<String, Serializable> extractRaw(ContentReader reader, MetadataExtracterLimits limits)
        throws Throwable {
    if (limits == null || limits.getTimeoutMs() == -1) {
        return extractRaw(reader);
    }
    FutureTask<Map<String, Serializable>> task = null;
    StreamAwareContentReaderProxy proxiedReader = null;
    try {
        proxiedReader = new StreamAwareContentReaderProxy(reader);
        task = new FutureTask<Map<String, Serializable>>(new ExtractRawCallable(proxiedReader));
        getExecutorService().execute(task);
        return task.get(limits.getTimeoutMs(), TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        task.cancel(true);
        if (null != proxiedReader) {
            proxiedReader.release();
        }
        throw e;
    } catch (InterruptedException e) {
        // We were asked to stop
        task.cancel(true);
        return null;
    } catch (ExecutionException e) {
        // Unwrap our cause and throw that
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof ExtractRawCallableException) {
            cause = ((ExtractRawCallableException) cause).getCause();
        }
        throw cause;
    }
}

From source file:org.orcid.core.manager.impl.OrcidProfileManagerImpl.java

@Override
public void processProfilesPendingIndexing() {
    // XXX There are some concurrency related edge cases to fix here.
    LOG.info("About to process profiles pending indexing");
    if (executorService == null || executorService.isShutdown()) {
        synchronized (executorServiceLock) {
            if (executorService == null || executorService.isShutdown()) {
                executorService = createThreadPoolForIndexing();
            } else {
                // already running
                return;
            }/*from w w w  . ja  v  a 2  s. c  o  m*/
        }
    } else {
        // already running
        return;
    }

    List<String> orcidsForIndexing = new ArrayList<>();
    List<String> orcidFailures = new ArrayList<>();
    List<IndexingStatus> indexingStatuses = new ArrayList<IndexingStatus>(2);
    indexingStatuses.add(IndexingStatus.PENDING);
    indexingStatuses.add(IndexingStatus.REINDEX);
    do {
        orcidsForIndexing = profileDao.findOrcidsByIndexingStatus(indexingStatuses, INDEXING_BATCH_SIZE,
                orcidFailures);
        LOG.info("Got batch of {} profiles for indexing", orcidsForIndexing.size());
        for (final String orcid : orcidsForIndexing) {
            FutureTask<String> task = new FutureTask<String>(new GetPendingOrcid(orcid));
            executorService.execute(task);
            futureHM.put(orcid, task);
        }
        for (final String orcid : orcidsForIndexing) {
            try {
                futureHM.remove(orcid).get(240, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                orcidFailures.add(orcid);
                LOG.error(orcid + " InterruptedException ", e);
                profileDao.updateIndexingStatus(orcid, IndexingStatus.FAILED);
            } catch (ExecutionException e) {
                orcidFailures.add(orcid);
                LOG.error(orcid + " ExecutionException ", e);
                profileDao.updateIndexingStatus(orcid, IndexingStatus.FAILED);
            } catch (TimeoutException e) {
                orcidFailures.add(orcid);
                LOG.error(orcid + " TimeoutException ", e);
                profileDao.updateIndexingStatus(orcid, IndexingStatus.FAILED);
            }
        }
    } while (!orcidsForIndexing.isEmpty());
    if (!executorService.isShutdown()) {
        synchronized (executorServiceLock) {
            if (!executorService.isShutdown()) {
                executorService.shutdown();
                try {
                    executorService.awaitTermination(120, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    LOG.warn("Received an interupt exception whilst waiting for the indexing to complete", e);
                }
                LOG.info("Finished processing profiles pending indexing");
            }
        }
    }
}

From source file:android.webkit.cts.WebViewTest.java

public void testPrinting() throws Throwable {
    if (!NullWebViewUtils.isWebViewAvailable()) {
        return;/* w  w w.  jav a  2s .  com*/
    }
    mOnUiThread.loadDataAndWaitForCompletion("<html><head></head>" + "<body>foo</body></html>", "text/html",
            null);
    final PrintDocumentAdapter adapter = mOnUiThread.createPrintDocumentAdapter();
    printDocumentStart(adapter);
    PrintAttributes attributes = new PrintAttributes.Builder().setMediaSize(PrintAttributes.MediaSize.ISO_A4)
            .setResolution(new PrintAttributes.Resolution("foo", "bar", 300, 300))
            .setMinMargins(PrintAttributes.Margins.NO_MARGINS).build();
    final WebViewCtsActivity activity = getActivity();
    final File file = activity.getFileStreamPath(PRINTER_TEST_FILE);
    final ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file,
            ParcelFileDescriptor.parseMode("w"));
    final FutureTask<Boolean> result = new FutureTask<Boolean>(new Callable<Boolean>() {
        public Boolean call() {
            return true;
        }
    });
    printDocumentLayout(adapter, null, attributes, new LayoutResultCallback() {
        // Called on UI thread
        @Override
        public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {
            savePrintedPage(adapter, descriptor, result);
        }
    });
    try {
        result.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
        assertTrue(file.length() > 0);
        FileInputStream in = new FileInputStream(file);
        byte[] b = new byte[PDF_PREAMBLE.length()];
        in.read(b);
        String preamble = new String(b);
        assertEquals(PDF_PREAMBLE, preamble);
    } finally {
        // close the descriptor, if not closed already.
        descriptor.close();
        file.delete();
    }
}

From source file:com.datatorrent.stram.StreamingContainerManager.java

public FutureTask<Object> getPhysicalOperatorProperty(int operatorId, String propertyName, long waitTime) {
    PTOperator o = this.plan.getAllOperators().get(operatorId);
    StramToNodeGetPropertyRequest request = new StramToNodeGetPropertyRequest();
    request.setOperatorId(operatorId);/*from   w ww.j a v  a  2s  .c om*/
    request.setPropertyName(propertyName);
    addOperatorRequest(o, request);
    RequestHandler task = new RequestHandler();
    task.requestId = nodeToStramRequestIds.incrementAndGet();
    task.waitTime = waitTime;
    request.requestId = task.requestId;
    FutureTask<Object> future = new FutureTask<Object>(task);
    dispatch(future);
    return future;
}

From source file:com.datatorrent.stram.StreamingContainerManager.java

/**
 * Asynchronously process the logical, physical plan and execution layer changes.
 * Caller can use the returned future to block until processing is complete.
 *
 * @param requests/*  ww w  . j  ava2s .  co m*/
 * @return future
 * @throws Exception
 */
public FutureTask<Object> logicalPlanModification(List<LogicalPlanRequest> requests) throws Exception {
    // delegate processing to dispatch thread
    FutureTask<Object> future = new FutureTask<Object>(new LogicalPlanChangeRunnable(requests));
    dispatch(future);
    //LOG.info("Scheduled plan changes: {}", requests);
    return future;
}