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:com.anrisoftware.globalpom.threads.listenablefuture.DefaultListenableFuture.java

private static <V> Callable<V> createExceptionCallable(final Callable<V> callable) {
    return new Callable<V>() {

        @Override//from  ww w  .  java 2 s. c  om
        public V call() throws Exception {
            try {
                return callable.call();
            } catch (Exception e) {
                logger.error("", e);
                throw e;
            }
        }
    };
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.ServerConfigurationDaoImplTest.java

@Test
public void testCreateUpdate() throws Exception {
    this.execute(new Callable<Object>() {
        @Override/*from   w  w w. j  ava2s .  co m*/
        public Object call() {
            final BlackboardServerConfigurationResponse configurationResponse = new BlackboardServerConfigurationResponse();
            configurationResponse.setBoundaryTime(30);
            configurationResponse.setMaxAvailableTalkers(6);
            configurationResponse.setMaxAvailableCameras(6);
            configurationResponse.setRaiseHandOnEnter(false);
            configurationResponse.setMayUseTelephony(false);
            configurationResponse.setMayUseSecureSignOn(false);
            configurationResponse.setMustReserveSeats(false);
            configurationResponse.setTimeZone("Mountain (North America/Canada, GMT -06:00)");

            final ServerConfiguration serverConfiguration = serverConfigurationDao
                    .createOrUpdateConfiguration(configurationResponse);
            assertNotNull(serverConfiguration);

            assertEquals(DateTimeZone.forOffsetHours(-6), serverConfiguration.getTimezone());

            return null;
        }
    });

    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final BlackboardServerConfigurationResponse configurationResponse = new BlackboardServerConfigurationResponse();
            configurationResponse.setBoundaryTime(30);
            configurationResponse.setMaxAvailableTalkers(6);
            configurationResponse.setMaxAvailableCameras(6);
            configurationResponse.setRaiseHandOnEnter(false);
            configurationResponse.setMayUseTelephony(false);
            configurationResponse.setMayUseSecureSignOn(false);
            configurationResponse.setMustReserveSeats(false);
            configurationResponse.setTimeZone("Mountain (North America/Canada, GMT -07:00)");

            final ServerConfiguration serverConfiguration = serverConfigurationDao
                    .createOrUpdateConfiguration(configurationResponse);
            assertNotNull(serverConfiguration);

            assertEquals(DateTimeZone.forOffsetHours(-7), serverConfiguration.getTimezone());

            return null;
        }
    });
}

From source file:mergedoc.core.MergeManager.java

/**
 * ???/*from   ww  w .j a  va 2s .c o  m*/
 * @param pref 
 */
public void setPreference(final Preference pref) {

    this.pref = pref;
    workingState.initialize();

    // ??????????????
    entrySizeFuture = entrySizeGetExecutor.submit(new Callable<Integer>() {

        @Override
        public Integer call() throws Exception {
            ArchiveInputStream is = null;
            try {
                is = ArchiveInputStream.create(pref.getInputArchive());
                int size = 0;
                for (; is.getNextEntry() != null; size++) {
                    ;
                }
                return size;
            } catch (Exception e) {
                return 0;
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
    });
}

From source file:com.spotify.helios.system.CliDeploymentTest.java

@Test
public void testDeployAndUndeployJob() throws Exception {
    startDefaultMaster();//from  w  w  w  .j av  a2  s . c  om

    // Wait for master to come up
    Polling.await(LONG_WAIT_SECONDS, SECONDS, new Callable<String>() {
        @Override
        public String call() throws Exception {
            final String output = cli("masters");
            return output.contains(masterName()) ? output : null;
        }
    });

    startDefaultAgent(testHost());

    final String image = BUSYBOX;
    final Map<String, PortMapping> ports = ImmutableMap.of("foo", PortMapping.of(4711), "bar",
            PortMapping.of(5000, externalPort));
    final Map<ServiceEndpoint, ServicePorts> registration = ImmutableMap.of(
            ServiceEndpoint.of("foo-service", "tcp"), ServicePorts.of("foo"),
            ServiceEndpoint.of("bar-service", "http"), ServicePorts.of("bar"));
    final Map<String, String> env = ImmutableMap.of("BAD", "f00d");

    // Wait for agent to come up
    awaitHostRegistered(testHost(), LONG_WAIT_SECONDS, SECONDS);
    awaitHostStatus(testHost(), UP, LONG_WAIT_SECONDS, SECONDS);

    // Create job
    final JobId jobId = createJob(testJobName, testJobVersion, image, IDLE_COMMAND, env, ports, registration);

    // Query for job
    final Job expected = Job.newBuilder().setName(testJobName).setVersion(testJobVersion).setImage(image)
            .setCommand(IDLE_COMMAND).setEnv(env).setPorts(ports).setRegistration(registration)
            .setCreatingUser(TEST_USER).build();
    final String inspectOutput = cli("inspect", "--json", jobId.toString());
    final Job parsed = Json.read(inspectOutput, Job.class);
    assertJobEquals(expected, parsed);
    assertThat(cli("jobs", testJobName, "-q"), containsString(jobId.toString()));
    assertThat(cli("jobs", testJobName + ":" + testJobVersion, "-q"), containsString(jobId.toString()));
    assertEquals("job pattern foozbarz matched no jobs", cli("jobs", "foozbarz").trim());
    assertTrue(cli("jobs", "foozbarz", "-q").isEmpty());

    // Create a new job using the first job as a template
    final Job expectedCloned = expected.toBuilder().setVersion(expected.getId().getVersion() + "-cloned")
            .build();
    final JobId clonedJobId = JobId.parse(WHITESPACE.trimFrom(cli("create", "-q", "-t",
            testJobName + ":" + testJobVersion, testJobName + ":" + testJobVersion + "-cloned")));
    final String clonedInspectOutput = cli("inspect", "--json", clonedJobId.toString());
    final Job clonedParsed = Json.read(clonedInspectOutput, Job.class);
    assertJobEquals(expectedCloned, clonedParsed);

    // Verify that port mapping and environment variables are correct
    final String statusString = cli("status", "--job", jobId.toString(), "--json");
    final Map<JobId, JobStatus> statuses = Json.read(statusString, STATUSES_TYPE);
    final Job job = statuses.get(jobId).getJob();
    assertEquals(ServicePorts.of("foo"), job.getRegistration().get(ServiceEndpoint.of("foo-service", "tcp")));
    assertEquals(ServicePorts.of("bar"), job.getRegistration().get(ServiceEndpoint.of("bar-service", "http")));
    assertEquals(4711, job.getPorts().get("foo").getInternalPort());
    assertEquals(PortMapping.of(5000, externalPort), job.getPorts().get("bar"));
    assertEquals("f00d", job.getEnv().get("BAD"));

    final String duplicateJob = cli("create", testJobName + ":" + testJobVersion, image, "--", IDLE_COMMAND);
    assertThat(duplicateJob, containsString("JOB_ALREADY_EXISTS"));

    final String prestop = stopJob(jobId, testHost());
    assertThat(prestop, containsString("JOB_NOT_DEPLOYED"));

    // Deploy job
    deployJob(jobId, testHost());

    // Stop job
    final String stop1 = stopJob(jobId, BOGUS_HOST);
    assertThat(stop1, containsString("HOST_NOT_FOUND"));
    final String stop2 = stopJob(BOGUS_JOB, testHost());
    assertThat(stop2, containsString("Unknown job"));
    final String stop3 = stopJob(jobId, testHost());
    assertThat(stop3, containsString(testHost() + ": done"));

    // Verify that undeploying the job from a nonexistent host fails
    assertThat(cli("undeploy", jobId.toString(), BOGUS_HOST), containsString("HOST_NOT_FOUND"));

    // Verify that undeploying a nonexistent job from the host fails
    assertThat(cli("undeploy", BOGUS_JOB.toString(), testHost()), containsString("Unknown job"));

    // Undeploy job
    undeployJob(jobId, testHost());
}

From source file:gobblin.hive.HiveMetastoreClientPool.java

/**
 * Get a {@link HiveMetastoreClientPool} for the requested metastore URI. Useful for using the same pools across
 * different classes in the code base. Note that if a pool already exists for that metastore, the max number of
 * objects available will be unchanged, and it might be lower than requested by this method.
 *
 * @param properties {@link Properties} used to generate the pool.
 * @param metastoreURI URI of the Hive metastore. If absent, use default metastore.
 * @return a {@link HiveMetastoreClientPool}.
 * @throws IOException//from   w ww  .  j  a  v a2  s  .  c om
 */
public static HiveMetastoreClientPool get(final Properties properties, final Optional<String> metastoreURI)
        throws IOException {
    try {
        return poolCache.get(metastoreURI, new Callable<HiveMetastoreClientPool>() {
            @Override
            public HiveMetastoreClientPool call() throws Exception {
                return new HiveMetastoreClientPool(properties, metastoreURI);
            }
        });
    } catch (ExecutionException ee) {
        throw new IOException("Failed to get " + HiveMetastoreClientPool.class.getSimpleName(), ee.getCause());
    }
}

From source file:com.facerecog.rest.service.RecognitionService.java

public Callable<RecognitionDTO> detectedAndIdentifyAsync(final byte[] byteImage, final int imageType,
        final int imageWidth, final int imageHeight) {
    return new Callable<RecognitionDTO>() {
        @Override//from w  ww.j  a v a2s  .  c  o  m
        public RecognitionDTO call() throws Exception {
            return detectAndIdentify(byteImage, imageType, imageWidth, imageHeight);
        }
    };
}

From source file:org.ngrinder.agent.controller.MonitorManagerController.java

/**
 * Get the target's monitored data by the given IP.
 *
 * @param ip target host IP//w  w w .  java  2s. c  om
 * @return json message containing the target's monitoring data.
 */
@RequestMapping("/state")
@RestAPI
public HttpEntity<String> getRealTimeMonitorData(@RequestParam final String ip)
        throws InterruptedException, ExecutionException, TimeoutException {
    Future<SystemInfo> submit = Executors.newCachedThreadPool().submit(new Callable<SystemInfo>() {
        @Override
        public SystemInfo call() {
            return monitorInfoStore.getSystemInfo(ip, getConfig().getMonitorPort());
        }
    });
    SystemInfo systemInfo = checkNotNull(submit.get(2, TimeUnit.SECONDS), "Monitoring data is not available.");
    return toJsonHttpEntity(new SystemDataModel(systemInfo, "UNKNOWN"));
}

From source file:com.microsoft.azure.keyvault.extensions.test.KeyVaultExtensionsIntegrationTestBase.java

protected static void createKeyVaultClient() throws Exception {
    Configuration config = createConfiguration();

    keyVaultClient = KeyVaultClientService.create(config);
    addClient(keyVaultClient.getServiceClient(), new Callable<Void>() {
        @Override//from   w  ww . j a v a2  s .  c o  m
        public Void call() throws Exception {
            createKeyVaultClient();
            return null;
        }
    });
    addRegexRule(getLiveVaultUri1(), MOCK_URI);
    addRegexRule(getLiveVaultUri2(), MOCK_URI);
}

From source file:com.amazonaws.services.kinesis.multilang.MessageWriter.java

/**
 * Writes the message then writes the line separator provided by the system. Flushes each message to guarantee it
 * is delivered as soon as possible to the subprocess.
 * /*from w  ww  . jav  a  2  s  . c o  m*/
 * @param message A message to be written to the subprocess.
 * @return
 * @throws IOException
 */
private Future<Boolean> writeMessageToOutput(final String message) throws IOException {
    Callable<Boolean> writeMessageToOutputTask = new Callable<Boolean>() {
        public Boolean call() throws Exception {
            try {
                /*
                 * If the message size exceeds the size of the buffer, the write won't be guaranteed to be atomic,
                 * so we synchronize on the writer to avoid interlaced lines from different calls to this method.
                 */
                synchronized (writer) {
                    writer.write(message, 0, message.length());
                    writer.write(System.lineSeparator(), 0, System.lineSeparator().length());
                    writer.flush();
                }
                LOG.info("Message size == " + message.getBytes().length + " bytes for shard " + shardId);
            } catch (IOException e) {
                open = false;
            }
            return open;
        }
    };

    if (open) {
        return this.executorService.submit(writeMessageToOutputTask);
    } else {
        String errorMessage = "Cannot write message " + message + " because writer is closed for shard "
                + shardId;
        LOG.info(errorMessage);
        throw new IllegalStateException(errorMessage);
    }
}

From source file:com.echopf.ECHOFile.java

/**
 * {@.en Gets a remote file data.}// ww  w . j a v a 2 s  .c o  m
 * {@.ja ??????}
 * @throws ECHOException 
 */
public byte[] getRemoteBytes() throws ECHOException {

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<byte[]> communicator = new Callable<byte[]>() {
        @Override
        public byte[] call() throws Exception {
            InputStream is = getRemoteInputStream();

            int nRead;
            byte[] data = new byte[16384];
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();

            return buffer.toByteArray();
        }
    };

    Future<byte[]> future = executor.submit(communicator);

    try {
        return future.get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // ignore/reset
    } catch (ExecutionException e) {
        Throwable e2 = e.getCause();
        throw new ECHOException(e2);
    }

    return null;
}