Example usage for java.util.concurrent Callable call

List of usage examples for java.util.concurrent Callable call

Introduction

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

Prototype

V call() throws Exception;

Source Link

Document

Computes a result, or throws an exception if unable to do so.

Usage

From source file:org.grails.orm.hibernate.HibernateDatastore.java

@Override
public void withFlushMode(FlushMode flushMode, Callable<Boolean> callable) {
    final org.hibernate.Session session = sessionFactory.getCurrentSession();
    org.hibernate.FlushMode previousMode = null;
    Boolean reset = true;/*  w ww.  ja  v a 2 s .c  o m*/
    try {
        if (session != null) {
            previousMode = HibernateVersionSupport.getFlushMode(session);
            HibernateVersionSupport.setFlushMode(session, org.hibernate.FlushMode.valueOf(flushMode.name()));
        }
        try {
            reset = callable.call();
        } catch (Exception e) {
            reset = false;
        }
    } finally {
        if (session != null && previousMode != null && reset) {
            HibernateVersionSupport.setFlushMode(session, previousMode);
        }
    }
}

From source file:org.kuali.rice.krad.kpme.pm.controller.PositionMaintenanceController.java

protected ModelAndView showProcessChangeWarningIfNeeded(@ModelAttribute("KualiForm") DocumentFormBase form,
        BindingResult result, HttpServletRequest request, HttpServletResponse response,
        Callable<ModelAndView> callable) throws Exception {

    ModelAndView retVal = null;/* w  w  w. j  a v a  2  s .  c om*/
    String oldProcess = request.getParameter("oldProcess");

    if (!hasDialogBeenAnswered(KPME_PROCESS_CHANGE_WARNING_DIALOG, form)) {
        if (StringUtils.isEmpty(oldProcess)) {
            retVal = getUIFModelAndView(form);
        } else {
            // redirect back to client to display lightbox
            retVal = showDialog(KPME_PROCESS_CHANGE_WARNING_DIALOG, form, request, response);
        }
    } else {
        boolean areYouSure = getBooleanDialogResponse(KPME_PROCESS_CHANGE_WARNING_DIALOG, form, request,
                response);
        // clear all dialogs in order to display warning again
        form.getDialogManager().removeAllDialogs();
        if (areYouSure) {
            // call the registered handler method; user has confirmed
            retVal = callable.call();
        } else {
            // revert to old process

            MaintenanceDocument maintenanceDocument = (MaintenanceDocument) form.getDocument();
            ((PositionBo) maintenanceDocument.getNewMaintainableObject().getDataObject())
                    .setProcess(oldProcess);
            retVal = getUIFModelAndView(form);
        }
    }
    return retVal;
}

From source file:org.pentaho.platform.plugin.services.importexport.legacy.MondrianCatalogRepositoryHelper.java

private void initOlapServersFolder() {
    final RepositoryFile etcOlapServers = repository.getFile(ETC_OLAP_SERVERS_JCR_FOLDER);
    if (etcOlapServers == null) {
        final Callable<Void> callable = new Callable<Void>() {
            public Void call() throws Exception {
                repository.createFolder(repository.getFile(RepositoryFile.SEPARATOR + "etc").getId(),
                        new RepositoryFile.Builder("olap-servers").folder(true).build(),
                        "Creating olap-servers directory in /etc");
                return null;
            }//from w  w w .java  2s  .  c  o  m
        };
        try {
            if (isSecured) {
                SecurityHelper.getInstance().runAsSystem(callable);
            } else {
                callable.call();
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to create folder /etc/olap-servers in the repository.", e);
        }
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.TestHFileOutputFormat.java

private void quickPoll(Callable<Boolean> c, int waitMs) throws Exception {
    int sleepMs = 10;
    int retries = (int) Math.ceil(((double) waitMs) / sleepMs);
    while (retries-- > 0) {
        if (c.call().booleanValue()) {
            return;
        }//from w w w .  jav a2 s .c  o m
        Thread.sleep(sleepMs);
    }
    fail();
}

From source file:org.ow2.proactive.scheduler.task.data.TaskProActiveDataspaces.java

private DataSpacesFileObject initDataSpace(Callable<DataSpacesFileObject> dataSpaceBuilder,
        String dataSpaceName, boolean input) throws Exception {
    try {/*from www. ja v a 2  s.  co m*/
        DataSpacesFileObject result = dataSpaceBuilder.call();
        result = resolveToExisting(result, dataSpaceName, input);
        result = createTaskIdFolder(result, dataSpaceName);
        return result;
    } catch (FileSystemException fse) {
        String message = dataSpaceName + " space is disabled";
        logger.warn(message, fse);
        logDataspacesStatus(message, DataspacesStatusLevel.WARNING);
        logDataspacesStatus(getStackTraceAsString(fse), DataspacesStatusLevel.WARNING);
    }
    return null;
}

From source file:com.alertlogic.aws.kinesis.test1.kcl.CountingRecordProcessorTest.java

/**
 * A test helper to prevent calls to System.exit() from existing our JVM. We need to test failure behavior and want
 * to know if System.exit() was called./*from   w  ww. java2  s .  com*/
 *
 * @param testBlock A code block that is expected to call System.exit().
 */
private void expectSystemExitWhenExecuting(Callable<Void> testBlock) throws Exception {
    final SecurityException expectedPreventionOfSystemExit = new SecurityException(
            "System.exit not allowed for this test.");
    // Disable System.exit() for this test
    final SecurityManager sm = new SecurityManager() {
        @Override
        public void checkExit(int status) {
            throw expectedPreventionOfSystemExit;
        }

        @Override
        public void checkPermission(Permission perm) {
            // Do nothing, allowing this security manager to be replaced
        }
    };
    SecurityManager oldSm = System.getSecurityManager();
    System.setSecurityManager(sm);
    boolean systemExitCalled = false;
    try {
        testBlock.call();
        fail("Expected System.exit to be called and throw a SecurityException by our test SecurityManager");
    } catch (SecurityException ex) {
        assertEquals("Expected SecurityException to be thrown when System.exit called",
                expectedPreventionOfSystemExit, ex);
        systemExitCalled = true;
    } finally {
        System.setSecurityManager(oldSm);
    }
    assertTrue("Expected test to call System.exit", systemExitCalled);
}

From source file:org.eclipse.ecr.core.storage.sql.LockManager.java

/**
 * Calls the callable, inside a transaction if in cluster mode.
 * <p>/*from  w  w w .  j  a v  a 2  s.  c  o  m*/
 * Called under {@link #serializationLock}.
 */
protected Lock callInTransaction(Callable<Lock> callable) throws StorageException {
    Xid xid = null;
    boolean txStarted = false;
    boolean txSuccess = false;
    try {
        if (clusteringEnabled) {
            xid = new XidImpl(
                    "nuxeolockmanager." + System.currentTimeMillis() + "." + txCounter.incrementAndGet());
            try {
                mapper.start(xid, XAResource.TMNOFLAGS);
            } catch (XAException e) {
                throw new StorageException(e);
            }
            txStarted = true;
        }
        // else no need to process invalidations,
        // only this mapper writes locks

        // actual call
        Lock result;
        try {
            result = callable.call();
        } catch (StorageException e) {
            throw e;
        } catch (Exception e) {
            throw new StorageException(e);
        }

        txSuccess = true;
        return result;
    } finally {
        if (txStarted) {
            try {
                if (txSuccess) {
                    mapper.end(xid, XAResource.TMSUCCESS);
                    mapper.commit(xid, true);
                } else {
                    mapper.end(xid, XAResource.TMFAIL);
                    mapper.rollback(xid);
                }
            } catch (XAException e) {
                throw new StorageException(e);
            }
        }
    }
}

From source file:org.wso2.carbon.identity.provisioning.OutboundProvisioningManager.java

private void executeOutboundProvisioning(ProvisioningEntity provisioningEntity, ExecutorService executors,
        String connectorType, String idPName, Callable<Boolean> proThread, boolean isBlocking)
        throws IdentityProvisioningException {
    if (!isBlocking) {
        executors.submit(proThread);//from w  w w .  j  av a  2 s. c o m
    } else {
        try {

            boolean success = proThread.call();
            if (!success) {
                if (executors != null) {
                    executors.shutdown();
                }
                throw new IdentityProvisioningException(generateMessageOnFailureProvisioningOperation(idPName,
                        connectorType, provisioningEntity));
                //DO Rollback
            }
        } catch (Exception e) { //call() of Callable interface throws this exception
            handleException(idPName, connectorType, provisioningEntity, executors, e);
        }
    }
}

From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java

private String getDatasourcesXml() {
    final Callable<String> call = new Callable<String>() {
        public String call() throws Exception {
            return generateInMemoryDatasourcesXml();
        }/*w w w . j a  va  2  s  .  c  o m*/
    };
    try {
        if (isSecurityEnabled()) {
            return SecurityHelper.getInstance().runAsSystem(call);
        } else {
            return call.call();
        }
    } catch (Exception e) {
        throw new IOlapServiceException(e);
    }
}

From source file:org.glowroot.central.SyntheticMonitorService.java

private void runSyntheticMonitor(AgentRollup agentRollup, SyntheticMonitorConfig syntheticMonitorConfig,
        List<AlertConfig> alertConfigs, Callable<FutureWithStartTick> callable) throws Exception {
    SyntheticMonitorUniqueKey uniqueKey = ImmutableSyntheticMonitorUniqueKey.of(agentRollup.id(),
            syntheticMonitorConfig.getId());
    if (!activeSyntheticMonitors.add(uniqueKey)) {
        return;/*from  ww  w.j  a  v  a  2  s .co  m*/
    }
    FutureWithStartTick future = callable.call();
    // important that uniqueKey is always removed on completion even on unexpected errors
    future.whenComplete((v, t) -> activeSyntheticMonitors.remove(uniqueKey));
    OnRunComplete onRunComplete = new OnRunComplete(agentRollup, syntheticMonitorConfig);
    if (alertConfigs.isEmpty()) {
        future.thenAccept(onRunComplete);
        return;
    }
    int maxAlertThresholdMillis = 0;
    for (AlertConfig alertConfig : alertConfigs) {
        maxAlertThresholdMillis = Math.max(maxAlertThresholdMillis,
                alertConfig.getCondition().getSyntheticMonitorCondition().getThresholdMillis());
    }
    long captureTime;
    long durationNanos;
    boolean success;
    String errorMessage;
    try {
        // wait an extra second to make sure no edge case where TimeoutException occurs with
        // stopwatch.elapsed(MILLISECONDS) < maxAlertThresholdMillis
        SyntheticRunResult result = future.get(maxAlertThresholdMillis + 1000L, MILLISECONDS);
        captureTime = result.captureTime();
        durationNanos = result.durationNanos();
        Throwable throwable = result.throwable();
        if (throwable == null) {
            success = true;
            errorMessage = null;
        } else {
            success = false;
            errorMessage = getBestMessageForSyntheticFailure(throwable);
        }
    } catch (TimeoutException e) {
        logger.debug(e.getMessage(), e);
        captureTime = clock.currentTimeMillis();
        durationNanos = 0; // durationNanos is only used below when success is true
        success = false;
        errorMessage = null;
    }
    if (!isCurrentlyDisabled(agentRollup.id())) {
        if (success) {
            for (AlertConfig alertConfig : alertConfigs) {
                AlertCondition alertCondition = alertConfig.getCondition();
                SyntheticMonitorCondition condition = alertCondition.getSyntheticMonitorCondition();
                boolean currentlyTriggered = durationNanos >= MILLISECONDS
                        .toNanos(condition.getThresholdMillis());
                sendAlertIfStatusChanged(agentRollup, syntheticMonitorConfig, alertConfig, condition,
                        captureTime, currentlyTriggered, null);
            }
        } else {
            sendAlertOnErrorIfStatusChanged(agentRollup, syntheticMonitorConfig, alertConfigs, errorMessage,
                    captureTime);
        }
    }
    // need to run at end to ensure new synthetic response doesn't get stored before consecutive
    // count is checked in sendAlertOnErrorIfStatusChanged()
    future.thenAccept(onRunComplete);
}