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:net.orfjackal.retrolambda.test.LambdaTest.java

@Test
public void method_references_to_protected_supertype_methods() throws Exception {
    Callable<String> ref1 = new SubclassInMyPackage().thing();
    assertThat(ref1.call(), equalTo("Hello"));

    Callable<String> ref2 = new SubclassInSamePackage().thing();
    assertThat(ref2.call(), equalTo("Hello"));
}

From source file:net.orfjackal.retrolambda.test.LambdaTest.java

@Test
public void method_references_to_private_methods() throws Exception {
    Callable<String> ref1 = LambdaTest::privateClassMethod;
    assertThat(ref1.call(), is("foo"));

    Callable<String> ref2 = this::privateInstanceMethod;
    assertThat(ref2.call(), is("foo"));

    // Normal method calls should still work after our magic
    // of making them them accessible from the lambda classes.
    assertThat(privateClassMethod(), is("foo"));
    assertThat(privateInstanceMethod(), is("foo"));
}

From source file:org.fishwife.jrugged.spring.retry.ExtendedRetryTemplate.java

/***
 * Execute a given {@link Callable} with retry logic.
 *
 * @param callable The callable to execute
 * @param recoveryCallback The recovery callback to execute when exceptions occur
 * @param retryState The current retryState
 * @param <T> The return type of the callable
 * @return The result of the callable/* w  ww.  j a v  a2s  . c om*/
 * @throws Exception
 * @throws ExhaustedRetryException If all retry attempts have been exhausted
 */
public <T> T execute(final Callable<T> callable, RecoveryCallback<T> recoveryCallback, RetryState retryState)
        throws Exception, ExhaustedRetryException {
    return execute(new RetryCallback<T>() {
        public T doWithRetry(RetryContext retryContext) throws Exception {
            return callable.call();
        }
    }, recoveryCallback, retryState);
}

From source file:SingleThreadRequestExecutor.java

@Override
public <T> Future<T> submit(final Callable<T> task) {
    return executor.submit(new Callable<T>() {
        @Override//from   w w w.ja  v a 2 s.c  o  m
        public T call() throws Exception {
            try {
                return task.call();
            } catch (Throwable e) {
                // This normally bad code of catch on Exception is here for a *reason*.
                // Future *eats* all exceptions *silently*. This clause at least allows
                // the exception to emit noise for debugging. This is particularly pernicious
                // if you have something like a NullPointerException

                e.printStackTrace();
                throw new RuntimeException(e);
            }

        }
    });
}

From source file:com.manydesigns.portofino.oauth.OAuthHelper.java

/**
 * Executes an action if the user's credential is known, otherwise redirects to the authorization page.
 * @param userId//from   w w w.  j a v  a2  s  .co  m
 * @param action
 * @return
 */
public Resolution doWithCredential(String userId, Callable<Resolution> action) {
    Credential credential = loadCredential(userId);
    if (credential != null) {
        try {
            return action.call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return new RedirectResolution(computeAuthorizationUrl());
}

From source file:net.orfjackal.retrolambda.test.LambdaTest.java

/**
 * Because the constructor is private, an access method must be generated for it
 * and also the NEW instruction must be done inside the access method.
 *//* w  w w.j av a2 s. c  o m*/
@Test
public void method_references_to_private_constructors() throws Exception {
    Callable<HasPrivateConstructor> factory = HasPrivateConstructor.factory();
    assertThat(factory.call(), is(instanceOf(HasPrivateConstructor.class)));

    HasPrivateConstructorWithArgs.Factory factoryArgs = HasPrivateConstructorWithArgs.factory();
    assertThat(factoryArgs.create("args"), is(instanceOf(HasPrivateConstructorWithArgs.class)));
    assertThat(factoryArgs.create("args").args, is("args"));
}

From source file:com.fitbur.testify.junit.system.internal.SpringBootInterceptor.java

public ConfigurableApplicationContext run(@SuperCall Callable<ConfigurableApplicationContext> zuper,
        @This Object object, @AllArguments Object[] args) throws Exception {
    AnnotationConfigEmbeddedWebApplicationContext context = (AnnotationConfigEmbeddedWebApplicationContext) zuper
            .call();//from   w  ww .  j  a va 2 s  . c  om

    SpringBootDescriptor descriptor = descriptors.get(context);

    descriptor.setApplication((SpringApplication) object);
    descriptor.setSources(args[0]);

    if (args.length == 2) {
        descriptor.setArgs((String[]) args[1]);
    }

    return context;
}

From source file:org.fishwife.jrugged.spring.retry.ExtendedRetryTemplate.java

/***
 * Construct a {@link Callable} which wraps the given {@link Callable},
 * and who's {@link java.util.concurrent.Callable#call()} method will execute
 * the callable via this {@link ExtendedRetryTemplate}
 *
 * @param callable The callable to wrap/*w  w w  . j a va 2 s  .c o  m*/
 * @param <T> The return type of the callback
 * @return
 */
public <T> Callable<T> asCallable(final Callable<T> callable) {
    return new Callable<T>() {
        public T call() throws Exception {
            return ExtendedRetryTemplate.this.execute(new RetryCallback<T>() {
                public T doWithRetry(RetryContext retryContext) throws Exception {
                    return callable.call();
                }
            });
        }
    };
}

From source file:net.orfjackal.retrolambda.test.LambdaTest.java

@Test
public void lambda_using_local_variables_of_primitive_types() throws Exception {
    boolean bool = true;
    byte b = 2;/*from w w  w .ja  v a  2 s.c  om*/
    short s = 3;
    int i = 4;
    long l = 5;
    float f = 6;
    double d = 7;
    char c = 8;
    Callable<Integer> lambda = () -> (int) ((bool ? 1 : 0) + b + s + i + l + f + d + c);

    assertThat(lambda.call(), is(36));
}

From source file:org.epics.archiverappliance.etl.DataReductionPostProcessorsTest.java

/**
 * 1) Set up the raw and reduced PV's//from   w  w  w  .  ja  v  a  2 s .  c o  m
 * 2) Generate data in STS
 * 3) Run ETL
 * 4) Compare
 */
private void testPostProcessor(String reduceDataUsing) throws Exception {
    cleanDataFolders();

    ConfigServiceForTests configService = new ConfigServiceForTests(new File("./bin"), 1);
    // Set up the raw and reduced PV's
    PlainPBStoragePlugin etlSTS = (PlainPBStoragePlugin) StoragePluginURLParser
            .parseStoragePlugin("pb://localhost?name=STS&rootFolder=" + shortTermFolderName
                    + "/&partitionGranularity=PARTITION_HOUR", configService);
    ;
    PlainPBStoragePlugin etlMTS = (PlainPBStoragePlugin) StoragePluginURLParser
            .parseStoragePlugin("pb://localhost?name=MTS&rootFolder=" + mediumTermFolderName
                    + "/&partitionGranularity=PARTITION_DAY", configService);
    PlainPBStoragePlugin etlLTSRaw = (PlainPBStoragePlugin) StoragePluginURLParser
            .parseStoragePlugin("pb://localhost?name=LTS&rootFolder=" + longTermFolderName
                    + "/&partitionGranularity=PARTITION_YEAR", configService);
    PlainPBStoragePlugin etlLTSReduced = (PlainPBStoragePlugin) StoragePluginURLParser
            .parseStoragePlugin(
                    "pb://localhost?name=LTS&rootFolder=" + longTermFolderName
                            + "/&partitionGranularity=PARTITION_YEAR&reducedata=" + reduceDataUsing,
                    configService);
    {
        PVTypeInfo typeInfo = new PVTypeInfo(rawPVName, ArchDBRTypes.DBR_SCALAR_DOUBLE, true, 1);
        String[] dataStores = new String[] { etlSTS.getURLRepresentation(), etlMTS.getURLRepresentation(),
                etlLTSRaw.getURLRepresentation() };
        typeInfo.setDataStores(dataStores);
        typeInfo.setPaused(true);
        configService.updateTypeInfoForPV(rawPVName, typeInfo);
        configService.registerPVToAppliance(rawPVName, configService.getMyApplianceInfo());
    }
    {
        PVTypeInfo typeInfo = new PVTypeInfo(reducedPVName, ArchDBRTypes.DBR_SCALAR_DOUBLE, true, 1);
        String[] dataStores = new String[] { etlSTS.getURLRepresentation(), etlMTS.getURLRepresentation(),
                etlLTSReduced.getURLRepresentation() };
        typeInfo.setDataStores(dataStores);
        typeInfo.setPaused(true);
        configService.updateTypeInfoForPV(reducedPVName, typeInfo);
        configService.registerPVToAppliance(reducedPVName, configService.getMyApplianceInfo());
    }
    // Control ETL manually
    configService.getETLLookup().manualControlForUnitTests();

    short currentYear = TimeUtils.getCurrentYear();

    logger.info("Testing data reduction for postprocessor " + reduceDataUsing);

    for (int day = 0; day < 40; day++) {
        // Generate data into the STS on a daily basis
        ArrayListEventStream genDataRaw = new ArrayListEventStream(86400,
                new RemotableEventStreamDesc(ArchDBRTypes.DBR_SCALAR_DOUBLE, rawPVName, currentYear));
        ArrayListEventStream genDataReduced = new ArrayListEventStream(86400,
                new RemotableEventStreamDesc(ArchDBRTypes.DBR_SCALAR_DOUBLE, reducedPVName, currentYear));
        for (int second = 0; second < 86400; second++) {
            YearSecondTimestamp ysts = new YearSecondTimestamp(currentYear, day * 86400 + second, 0);
            Timestamp ts = TimeUtils.convertFromYearSecondTimestamp(ysts);
            genDataRaw.add(new POJOEvent(ArchDBRTypes.DBR_SCALAR_DOUBLE, ts,
                    new ScalarValue<Double>(second * 1.0), 0, 0));
            genDataReduced.add(new POJOEvent(ArchDBRTypes.DBR_SCALAR_DOUBLE, ts,
                    new ScalarValue<Double>(second * 1.0), 0, 0));
        }

        try (BasicContext context = new BasicContext()) {
            etlSTS.appendData(context, rawPVName, genDataRaw);
            etlSTS.appendData(context, reducedPVName, genDataReduced);
        }
        logger.debug(
                "For postprocessor " + reduceDataUsing + " done generating data into the STS for day " + day);

        // Run ETL at the end of the day
        Timestamp timeETLruns = TimeUtils
                .convertFromYearSecondTimestamp(new YearSecondTimestamp(currentYear, day * 86400 + 86399, 0));
        ETLExecutor.runETLs(configService, timeETLruns);
        logger.debug("For postprocessor " + reduceDataUsing + " done performing ETL as though today is "
                + TimeUtils.convertToHumanReadableString(timeETLruns));

        // Compare data for raw+postprocessor and reduced PV's.
        PostProcessor postProcessor = PostProcessors.findPostProcessor(reduceDataUsing);
        postProcessor.initialize(reduceDataUsing, rawPVName);

        int rawWithPPCount = 0;
        int reducedCount = 0;

        try (BasicContext context = new BasicContext()) {
            Timestamp startTime = TimeUtils.minusDays(TimeUtils.now(), 10 * 366);
            Timestamp endTime = TimeUtils.plusDays(TimeUtils.now(), 10 * 366);
            LinkedList<Timestamp> rawTimestamps = new LinkedList<Timestamp>();
            LinkedList<Timestamp> reducedTimestamps = new LinkedList<Timestamp>();
            if (postProcessor instanceof PostProcessorWithConsolidatedEventStream) {
                List<Callable<EventStream>> callables = etlLTSRaw.getDataForPV(context, rawPVName, startTime,
                        endTime, postProcessor);
                for (Callable<EventStream> callable : callables) {
                    callable.call();
                }
                for (Event e : ((PostProcessorWithConsolidatedEventStream) postProcessor)
                        .getConsolidatedEventStream()) {
                    rawTimestamps.add(e.getEventTimeStamp());
                    rawWithPPCount++;
                }
            } else {
                try (EventStream rawWithPP = new CurrentThreadWorkerEventStream(rawPVName,
                        etlLTSRaw.getDataForPV(context, rawPVName, startTime, endTime, postProcessor))) {
                    for (Event e : rawWithPP) {
                        rawTimestamps.add(e.getEventTimeStamp());
                        rawWithPPCount++;
                    }
                }
            }
            try (EventStream reduced = new CurrentThreadWorkerEventStream(reducedPVName,
                    etlLTSReduced.getDataForPV(context, reducedPVName, startTime, endTime))) {
                for (Event e : reduced) {
                    reducedTimestamps.add(e.getEventTimeStamp());
                    reducedCount++;
                }
            }

            logger.debug(
                    "For postprocessor " + reduceDataUsing + " for day " + day + " we have " + rawWithPPCount
                            + " raw with postprocessor events and " + reducedCount + " reduced events");
            if (rawTimestamps.size() != reducedTimestamps.size()) {
                while (!rawTimestamps.isEmpty() || !reducedTimestamps.isEmpty()) {
                    if (!rawTimestamps.isEmpty())
                        logger.info("Raw/PP " + TimeUtils.convertToHumanReadableString(rawTimestamps.pop()));
                    if (!reducedTimestamps.isEmpty())
                        logger.info(
                                "Reduced" + TimeUtils.convertToHumanReadableString(reducedTimestamps.pop()));
                }
            }
            assertTrue(
                    "For postprocessor " + reduceDataUsing + " for day " + day + " we have " + rawWithPPCount
                            + " rawWithPP events and " + reducedCount + " reduced events",
                    rawWithPPCount == reducedCount);
        }
        if (day > 2) {
            assertTrue("For postprocessor " + reduceDataUsing + " for day " + day
                    + ", seems like no events were moved by ETL into LTS for " + rawPVName + " Count = "
                    + rawWithPPCount, (rawWithPPCount != 0));
            assertTrue("For postprocessor " + reduceDataUsing + " for day " + day
                    + ", seems like no events were moved by ETL into LTS for " + reducedPVName + " Count = "
                    + reducedCount, (reducedCount != 0));
        }
    }

    configService.shutdownNow();
}