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.apache.hadoop.hbase.security.access.SecureTestUtil.java

@SuppressWarnings("rawtypes")
private static void updateACLs(final HBaseTestingUtility util, Callable c) throws Exception {
    // Get the current mtimes for all access controllers
    final Map<AccessController, Long> oldMTimes = getAuthManagerMTimes(util.getHBaseCluster());

    // Run the update action
    c.call();

    // Wait until mtimes for all access controllers have incremented
    util.waitFor(WAIT_TIME, 100, new Predicate<IOException>() {
        @Override//from  www. j a v  a  2s .  co m
        public boolean evaluate() throws IOException {
            Map<AccessController, Long> mtimes = getAuthManagerMTimes(util.getHBaseCluster());
            for (Map.Entry<AccessController, Long> e : mtimes.entrySet()) {
                if (!oldMTimes.containsKey(e.getKey())) {
                    LOG.error("Snapshot of AccessController state does not include instance on region "
                            + e.getKey().getRegion().getRegionNameAsString());
                    // Error out the predicate, we will try again
                    return false;
                }
                long old = oldMTimes.get(e.getKey());
                long now = e.getValue();
                if (now <= old) {
                    LOG.info("AccessController on region " + e.getKey().getRegion().getRegionNameAsString()
                            + " has not updated: mtime=" + now);
                    return false;
                }
            }
            return true;
        }
    });
}

From source file:nl.strohalm.cyclos.utils.access.LoggedUser.java

public static <T> T runAsSystem(final Callable<T> callable) {
    Map<String, Object> previousAttributes = null;
    final boolean alreadyRunninAsSystem = isSystem();
    if (!alreadyRunninAsSystem) {
        previousAttributes = ATTRIBUTES.get();
    }/*w  ww. ja v  a  2s. c o m*/
    try {
        if (!alreadyRunninAsSystem) {
            initAsSystem();
        }
        return callable.call();
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (!alreadyRunninAsSystem) {
            ATTRIBUTES.set(previousAttributes);
        }
    }
}

From source file:com.brienwheeler.lib.db.DbTestUtils.java

public static <T> T doInHibernateSession(ApplicationContext applicationContext, Callable<T> work) {
    EntityManagerFactory entityManagerFactory = applicationContext
            .getBean("com.brienwheeler.lib.db.appEntityManagerFactory", EntityManagerFactory.class);

    EntityManagerHolder entityManagerHolder = (EntityManagerHolder) TransactionSynchronizationManager
            .getResource(entityManagerFactory);

    boolean created = entityManagerHolder == null;
    if (created) {
        entityManagerHolder = new EntityManagerHolder(entityManagerFactory.createEntityManager());
        TransactionSynchronizationManager.bindResource(entityManagerFactory, entityManagerHolder);
    }/*from   w  ww.j a  v  a 2 s . c o  m*/

    try {
        return work.call();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (created)
            TransactionSynchronizationManager.unbindResource(entityManagerFactory);
    }
}

From source file:net.sf.ehcache.server.util.WebTestUtil.java

/**
 * Runs a set of threads, for a fixed amount of time.
 *//*www  .j  a va  2  s  .c  om*/
public static void runThreads(final List<Callable<?>> callable) throws Exception {
    final long endTime = System.currentTimeMillis() + 10000;
    final Throwable[] errors = new Throwable[1];

    // Spin up the threads
    final Thread[] threads = new Thread[callable.size()];
    for (int i = 0; i < threads.length; i++) {
        final Callable<?> executable = callable.get(i);
        threads[i] = new Thread() {
            public void run() {
                try {
                    // Run the thread until the given end time
                    while (System.currentTimeMillis() < endTime) {
                        executable.call();
                    }
                } catch (Throwable t) {
                    // Hang on to any errors
                    errors[0] = t;
                }
            }
        };

        threads[i].start();
    }
    LOG.debug("Started {} threads.", threads.length);

    // Wait for the threads to finish
    for (int i = 0; i < threads.length; i++) {
        threads[i].join();
    }

    // Throw any error that happened
    if (errors[0] != null) {
        throw new Exception("Test thread failed.", errors[0]);
    }
}

From source file:io.fabric8.jube.local.NodeHelper.java

/**
 * Performs a block of code and updates the pod model if its updated
 */// w w  w .jav a 2  s  . co m
public static <T> T podTransaction(KubernetesModel model, Pod pod, Callable<T> task) throws Exception {
    String oldJson = getPodJson(pod);
    T answer = task.call();
    String newJson = getPodJson(pod);

    // lets only update the model if we've really changed the pod
    if (!java.util.Objects.equals(oldJson, newJson)) {
        model.updatePod(getName(pod), pod);
    }
    return answer;
}

From source file:org.apache.jackrabbit.oak.run.SegmentUtils.java

static void compact(File directory, boolean force) throws IOException {
    FileStore store = openFileStore(directory.getAbsolutePath(), force);
    try {//from   ww w. ja  va2  s.c  om
        boolean persistCM = Boolean.getBoolean("tar.PersistCompactionMap");
        CompactionStrategy compactionStrategy = new CompactionStrategy(false,
                CompactionStrategy.CLONE_BINARIES_DEFAULT, CompactionStrategy.CleanupType.CLEAN_ALL, 0,
                CompactionStrategy.MEMORY_THRESHOLD_DEFAULT) {

            @Override
            public boolean compacted(Callable<Boolean> setHead) throws Exception {
                // oak-run is doing compaction single-threaded
                // hence no guarding needed - go straight ahead
                // and call setHead
                return setHead.call();
            }
        };
        compactionStrategy.setOfflineCompaction(true);
        compactionStrategy.setPersistCompactionMap(persistCM);
        store.setCompactionStrategy(compactionStrategy);
        store.compact();
    } finally {
        store.close();
    }

    System.out.println("    -> cleaning up");
    store = openFileStore(directory.getAbsolutePath(), false);
    try {
        for (File file : store.cleanup()) {
            if (!file.exists() || file.delete()) {
                System.out.println("    -> removed old file " + file.getName());
            } else {
                System.out.println("    -> failed to remove old file " + file.getName());
            }
        }

        String head;
        File journal = new File(directory, "journal.log");
        JournalReader journalReader = new JournalReader(journal);
        try {
            head = journalReader.iterator().next() + " root " + System.currentTimeMillis() + "\n";
        } finally {
            journalReader.close();
        }

        RandomAccessFile journalFile = new RandomAccessFile(journal, "rw");
        try {
            System.out.println("    -> writing new " + journal.getName() + ": " + head);
            journalFile.setLength(0);
            journalFile.writeBytes(head);
            journalFile.getChannel().force(false);
        } finally {
            journalFile.close();
        }
    } finally {
        store.close();
    }
}

From source file:io.fabric8.jube.local.NodeHelper.java

/**
 * Performs a block of code and updates the pod model if its updated
 *///from w ww. j a v  a 2s.  c  om
public static <T> T excludeFromProcessMonitor(ProcessMonitor monitor, Pod pod, Callable<T> task)
        throws Exception {
    String id = getName(pod);
    monitor.addExcludedPodId(id);
    try {
        return task.call();
    } finally {
        monitor.removeExcludedPodId(id);
    }
}

From source file:com.javielinux.utils.TweetActions.java

public static void retweetStatus(final FragmentActivity activity, final long tweet_id,
        final Callable callBack) {

    ArrayList<Entity> ents = DataFramework.getInstance().getEntityList("users",
            "service is null or service = \"twitter.com\"");

    if (ents.size() == 1) {

        sendRetweet(activity, ents.get(0).getId() + "", tweet_id);
        try {/* w ww . java2 s.c  o m*/
            if (callBack != null)
                callBack.call();
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {

        final UsersAdapter adapter = new UsersAdapter(activity, ents);

        AlertDialog builder = new AlertDialog.Builder(activity).setCancelable(true).setTitle(R.string.users)
                .setAdapter(adapter, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sendRetweet(activity, adapter.getItem(which).getId() + "", tweet_id);
                        try {
                            if (callBack != null)
                                callBack.call();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }).setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create();
        builder.show();

    }

}

From source file:org.apache.flume.sink.kite.TestDatasetSink.java

/**
 * A convenience method to avoid a large number of @Test(expected=...) tests.
 *
 * This variant uses a Callable, which is allowed to throw checked Exceptions.
 *
 * @param message A String message to describe this assertion
 * @param expected An Exception class that the Runnable should throw
 * @param callable A Callable that is expected to throw the exception
 *//*from  w  w w.  j av a2  s  .c o m*/
public static void assertThrows(String message, Class<? extends Exception> expected, Callable callable) {
    try {
        callable.call();
        Assert.fail("No exception was thrown (" + message + "), expected: " + expected.getName());
    } catch (Exception actual) {
        Assert.assertEquals(message, expected, actual.getClass());
    }
}

From source file:org.seedstack.seed.cli.SeedRunner.java

/**
 * Execute a Seed CLI command (implemented by a {@link CommandLineHandler}.
 *
 * @param args the command line arguments. First argument is the name of the CLI command. Subsequent argument are
 *             passed to the CLI command.
 * @return the return code of the CLI command.
 * @throws Exception when the CLI command fails to complete.
 *///from  w  ww .  j a  va 2s.com
public static int execute(String[] args) throws Exception {
    Kernel kernel = startKernel(new CliContext(args));

    try {
        Injector injector = kernel.objectGraph().as(Injector.class);
        String defaultCommand = injector.getInstance(Application.class).getConfiguration()
                .getString(CommandLinePlugin.DEFAULT_COMMAND_CONFIG_KEY);
        Callable<Integer> callable;

        if (defaultCommand != null) {
            callable = new SeedCallable(defaultCommand, args);
        } else {
            if (args == null || args.length == 0 || args[0].isEmpty()) {
                throw SeedException.createNew(CliErrorCode.NO_COMMAND_SPECIFIED);
            }

            // A command must be provided as first argument, it is extracted from the command line
            String[] effectiveArgs = new String[args.length - 1];
            System.arraycopy(args, 1, effectiveArgs, 0, effectiveArgs.length);

            callable = new SeedCallable(args[0], effectiveArgs);
        }

        injector.injectMembers(callable);
        return callable.call();
    } finally {
        stopKernel(kernel);
    }
}