Example usage for java.util.concurrent Callable Callable

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

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:io.neba.core.resourcemodels.caching.RequestScopedResourceModelCacheTest.java

@Test
public void testCacheIsNotSelectorSensitiveWithoutSafeMode() throws Exception {
    request(new Callable<Object>() {
        @Override/* ww  w. ja v a  2s  . c  o  m*/
        public Object call() throws Exception {

            withResourcePath("/junit/test/1");
            putModelInCache();
            lookupModelFromCache();
            assertModelWasFoundInCache();

            withSelector("new.selector");

            lookupModelFromCache();
            assertModelWasFoundInCache();
            return null;
        }
    });
}

From source file:fr.mby.opa.pics.web.controller.PicsController.java

@RequestMapping(value = "rebuildThumbnails/{width}/{height}/{format}", method = RequestMethod.GET)
public String rebuildThumbnails(@PathVariable final Integer width, @PathVariable final Integer height,
        @PathVariable final String format, final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    final Integer selectedWidth = (width != null) ? width : 800;
    final Integer selectedHeight = (height != null) ? height : 200;
    final String selectedFormat = (format != null) ? format : "jpg";

    final ExecutorService rebuildThumbnailsExecutor = Executors
            .newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    Long since = 0L;/*from   www  . j  av  a 2s . c o  m*/
    List<Picture> pictures = null;
    do {
        pictures = this.pictureDao.findAllPictures(since);
        final Collection<Future<Void>> futures = new ArrayList<>(pictures.size());

        for (final Picture picture : pictures) {
            final Future<Void> future = rebuildThumbnailsExecutor.submit(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    final BinaryImage generated = PicsController.this.pictureService.generateThumbnail(picture,
                            selectedWidth, selectedHeight, true, selectedFormat);
                    // Set the old Id to update
                    final BinaryImage thumbnailToUpdate = picture.getThumbnail();
                    thumbnailToUpdate.setData(generated.getData());
                    thumbnailToUpdate.setFormat(generated.getFormat());
                    thumbnailToUpdate.setWidth(generated.getWidth());
                    thumbnailToUpdate.setHeight(generated.getHeight());

                    picture.setThumbnail(generated);
                    picture.setThumbnailWidth(generated.getWidth());
                    picture.setThumbnailHeight(generated.getHeight());
                    picture.setThumbnailFormat(generated.getFormat());
                    picture.setThumbnailSize(generated.getData().length);

                    PicsController.this.pictureDao.updatePicture(picture);

                    // Free memory
                    picture.setThumbnail(null);
                    picture.setImage(null);

                    return null;
                }
            });

            since = picture.getOriginalTime().getTime();
            futures.add(future);
        }

        for (final Future<Void> future : futures) {
            future.get();
        }

    } while (pictures != null && pictures.size() > 0);

    return "index";
}

From source file:apiserver.services.images.controllers.MetadataController.java

/**
 * get embedded metadata//  www .  j av  a 2 s .  c o  m
 * @param file uploaded image
 * @return   height,width
 */
@ApiOperation(value = "Get the embedded metadata", responseClass = "java.util.Map")
@RequestMapping(value = "/info/metadata", method = { RequestMethod.POST })
public WebAsyncTask<Map> imageMetadataByImage(
        @ApiParam(name = "file", required = true) @RequestParam(value = "file", required = true) MultipartFile file) {
    final MultipartFile _file = file;

    Callable<Map> callable = new Callable<Map>() {
        @Override
        public Map call() throws Exception {
            FileMetadataJob job = new FileMetadataJob();
            job.setDocumentId(null);
            job.setDocument(new Document(_file));
            job.getDocument().setContentType(MimeType.getMimeType(_file.getContentType()));
            job.getDocument().setFileName(_file.getOriginalFilename());

            Future<Map> imageFuture = imageMetadataGateway.getMetadata(job);
            FileMetadataJob payload = (FileMetadataJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

            return payload.getMetadata();
        }
    };

    return new WebAsyncTask<Map>(defaultTimeout, callable);
}

From source file:com.microsoft.azure.management.compute.VirtualMachineExtensionImageOperationsImpl.java

/**
* Gets a virtual machine extension image.
*
* @param parameters Optional./*from  w w  w  . j a  v  a  2  s .  co  m*/
* @return The get virtual machine extension image operation response.
*/
@Override
public Future<VirtualMachineExtensionImageGetResponse> getAsync(
        final VirtualMachineExtensionImageGetParameters parameters) {
    return this.getClient().getExecutorService()
            .submit(new Callable<VirtualMachineExtensionImageGetResponse>() {
                @Override
                public VirtualMachineExtensionImageGetResponse call() throws Exception {
                    return get(parameters);
                }
            });
}

From source file:org.apache.abdera2.common.protocol.Session.java

public <T extends ClientResponse> Callable<T> getTask(final String uri) {
    return new Callable<T>() {
        public T call() throws Exception {
            return (T) get(uri);
        }/*from w  w w  . j  a  v a 2  s.com*/
    };
}

From source file:com.tesora.dve.sql.util.ProxyConnectionResource.java

public ResourceResponse execute(LineInfo info, final byte[] stmt) throws Throwable {
    if (info != null)
        SchemaTest.echo("Executing@" + info + ": '" + stmt + "'");
    else//w ww.ja  va 2 s  . c  o m
        SchemaTest.echo("Executing: '" + stmt + "'");

    //      final NativeCharSet clientCharSet = MysqlNativeCharSet.UTF8;
    final MysqlTextResultChunkProvider results = new MysqlTextResultChunkProvider();
    proxy.executeInContext(new Callable<Void>() {
        @SuppressWarnings("synthetic-access")
        @Override
        public Void call() throws Exception {
            try {
                ExecuteRequestExecutor.execute(proxy, results, stmt);
            } catch (PEException e) {
                throw e;
            } catch (SchemaException se) {
                throw se;
            } catch (Throwable e) {
                throw new PEException("Test statement encountered exception", e);
            }
            return null;
        }
    });

    lastHadWarning = results.getWarnings() > 0;

    return new ProxyConnectionResourceResponse(results);
}

From source file:com.glaf.core.config.ConfigFactory.java

public static String getString(final String region, final String key) {
    if (conf.getBoolean(DISTRIBUTED_ENABLED, false)) {
        String regionName = Environment.getCurrentSystemName() + "_" + region;
        String complexKey = Environment.getCurrentSystemName() + "_" + key;
        if (SystemProperties.getDeploymentSystemName() != null) {
            regionName = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName()
                    + "_" + region;
        }/*from  ww  w . java2  s  .  c o  m*/
        if (SystemProperties.getDeploymentSystemName() != null) {
            complexKey = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName()
                    + "_" + key;
        }
        final String regionName2 = regionName;
        final String complexKey2 = complexKey;

        boolean waitFor = true;
        Callable<String> task = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return channel.getString(regionName2, complexKey2);
            }
        };
        try {
            Future<String> result = pool.submit(task);
            long start = System.currentTimeMillis();
            // ?
            if (waitFor) {
                while (true) {
                    if (System.currentTimeMillis() - start > 2000) {
                        break;
                    }
                    if (result.isDone()) {
                        return result.get();
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex);
        }
    }
    return null;
}

From source file:org.fcrepo.integration.kernel.impl.observer.SuppressByMixinFilterIT.java

private void waitForEvent(final String id) {
    await().pollInterval(ONE_SECOND).until(new Callable<Boolean>() {

        @Override// w  w w  .  j  a  v a 2s  .  c  om
        public Boolean call() {
            return eventsReceived.contains(id);
        }
    });
}

From source file:org.openvpms.component.business.service.scheduler.JobRunner.java

/**
 * Called by the <code>{@link Scheduler}</code> when a <code>{@link Trigger}</code>
 * fires that is associated with the <code>Job</code>.
 *
 * @param context the execution context//from   ww  w.  j  av a  2 s .  c  o m
 * @throws JobExecutionException if there is an exception while executing the job.
 */
public void execute(final JobExecutionContext context) throws JobExecutionException {
    if (configuration == null) {
        throw new JobExecutionException("Configuration has not been registered");
    }
    if (service == null) {
        throw new JobExecutionException("ArchetypeService has not been registered");
    }
    long start = System.currentTimeMillis();
    log.info("Job " + getName(configuration) + " - starting");

    User user = getUser();
    Callable<Void> callable = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            job = createJob();
            job.execute(context);
            return null;
        }
    };
    try {
        RunAs.run(user, callable);
        long end = System.currentTimeMillis();
        log.info("Job " + getName(configuration) + " - finished in " + (end - start) + "ms");
    } catch (Throwable exception) {
        long end = System.currentTimeMillis();
        log.error("Job " + getName(configuration) + " - failed in " + (end - start) + "ms", exception);
        if (exception instanceof JobExecutionException) {
            throw (JobExecutionException) exception;
        }
        throw new JobExecutionException(exception);
    }
}

From source file:org.apache.drill.optiq.EnumerableDrill.java

/** Runs the plan as a background task. */
Future<Collection<RunOutcome>> runPlan(CompletionService<Collection<RunOutcome>> service) {
    IteratorRegistry ir = new IteratorRegistry();
    DrillConfig config = DrillConfig.create();
    config.setSinkQueues(0, queue);// ww  w  .  j a  va2  s .  c  o m
    final ReferenceInterpreter i = new ReferenceInterpreter(plan, ir, new BasicEvaluatorFactory(ir),
            new RSERegistry(config));
    try {
        i.setup();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return service.submit(new Callable<Collection<RunOutcome>>() {
        @Override
        public Collection<RunOutcome> call() throws Exception {
            Collection<RunOutcome> outcomes = i.run();

            for (RunOutcome outcome : outcomes) {
                System.out.println("============");
                System.out.println(outcome);
                if (outcome.outcome == RunOutcome.OutcomeType.FAILED && outcome.exception != null) {
                    outcome.exception.printStackTrace();
                }
            }
            return outcomes;
        }
    });
}