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.microsoft.windowsazure.management.sql.ServerOperationsImpl.java

/**
* Changes the administrative password of an existing Azure SQL Database
* Server for a given subscription.//from w  w w . j a  v  a 2 s.  c  o  m
*
* @param serverName Required. The name of the Azure SQL Database Server
* that will have the administrator password changed.
* @param parameters Required. The necessary parameters for modifying the
* adminstrator password for a server.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public Future<OperationResponse> changeAdministratorPasswordAsync(final String serverName,
        final ServerChangeAdministratorPasswordParameters parameters) {
    return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
        @Override
        public OperationResponse call() throws Exception {
            return changeAdministratorPassword(serverName, parameters);
        }
    });
}

From source file:com.microsoft.windowsazure.management.servicebus.NotificationHubOperationsImpl.java

/**
* Deletes a notification hub associated with a namespace.
*
* @param namespaceName Required. The namespace name.
* @param notificationHubName Required. The notification hub name.
* @return A standard service response including an HTTP status code and
* request ID./*from ww w  .jav  a  2s. com*/
*/
@Override
public Future<OperationResponse> deleteAsync(final String namespaceName, final String notificationHubName) {
    return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
        @Override
        public OperationResponse call() throws Exception {
            return delete(namespaceName, notificationHubName);
        }
    });
}

From source file:fr.dutra.confluence2wordpress.wp.WordpressClient.java

/**
 * @see "http://codex.wordpress.org/XML-RPC_wp#wp.getAuthors"
 * @return the list of {@link WordpressUser}s of the blog.
 * @throws WordpressXmlRpcException//from  w  w  w  .j av  a  2  s  . c o m
 */
public Future<List<WordpressUser>> getUsers() {
    return pool.submit(new Callable<List<WordpressUser>>() {

        @Override
        public List<WordpressUser> call() throws Exception {

            Vector<Object> params = new Vector<Object>();

            params.add(wordpressConnection.getBlogId());
            params.add(wordpressConnection.getUsername());
            params.add(wordpressConnection.getPassword());

            List<Map<String, Object>> rows = invoke(GET_USERS_METHOD_NAME, params);

            List<WordpressUser> users = new ArrayList<WordpressUser>(rows.size());
            for (Map<String, Object> row : rows) {
                WordpressUser user = new WordpressUser();
                user.setId(Integer.valueOf(row.get("user_id").toString()));
                user.setLogin(row.get("user_login").toString());
                user.setDisplayName((String) row.get("display_name"));
                user.setFirstName((String) row.get("first_name"));
                user.setLastName((String) row.get("last_name"));
                user.setNiceName((String) row.get("user_nicename"));
                if (row.get("user_level") != null && StringUtils.isNotEmpty(row.get("user_level").toString())) {
                    user.setLevel(Integer.valueOf(row.get("user_level").toString()));
                }
                users.add(user);
            }

            return users;
        }

    });
}

From source file:com.microsoft.windowsazure.management.network.NetworkOperationsImpl.java

/**
* The Begin Setting Network Configuration operation asynchronously
* configures the virtual network.  (see//from   w  ww  . jav  a 2  s .  co m
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the Set Network
* Configuration operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public Future<OperationResponse> beginSettingConfigurationAsync(
        final NetworkSetConfigurationParameters parameters) {
    return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
        @Override
        public OperationResponse call() throws Exception {
            return beginSettingConfiguration(parameters);
        }
    });
}

From source file:com.microsoft.windowsazure.management.network.ClientRootCertificateOperationsImpl.java

/**
* The Upload Client Root Certificate operation is used to upload a new
* client root certificate to Azure.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx for
* more information)//from   w  ww .  j a v  a 2  s . c  o m
*
* @param networkName Required. The name of the virtual network for this
* gateway.
* @param parameters Required. Parameters supplied to the Upload Client Root
* Certificate Virtual Network Gateway operation.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public Future<GatewayOperationResponse> createAsync(final String networkName,
        final ClientRootCertificateCreateParameters parameters) {
    return this.getClient().getExecutorService().submit(new Callable<GatewayOperationResponse>() {
        @Override
        public GatewayOperationResponse call() throws Exception {
            return create(networkName, parameters);
        }
    });
}

From source file:com.googlecode.concurrentlinkedhashmap.MultiThreadedTest.java

@Test(dataProvider = "builder")
public void weightedConcurrency(Builder<Integer, List<Integer>> builder) {
    final ConcurrentLinkedHashMap<Integer, List<Integer>> map = builder.weigher(Weighers.<Integer>list())
            .maximumWeightedCapacity(threads).concurrencyLevel(threads).build();
    final Queue<List<Integer>> values = new ConcurrentLinkedQueue<List<Integer>>();
    for (int i = 1; i <= threads; i++) {
        Integer[] array = new Integer[i];
        Arrays.fill(array, Integer.MIN_VALUE);
        values.add(Arrays.asList(array));
    }//from  w  w w  . j  a v a 2 s.c o  m
    executeWithTimeOut(map, new Callable<Long>() {
        @Override
        public Long call() throws Exception {
            return timeTasks(threads, new Runnable() {
                @Override
                public void run() {
                    List<Integer> value = values.poll();
                    for (int i = 0; i < iterations; i++) {
                        map.put(i % 10, value);
                    }
                }
            });
        }
    });
}

From source file:com.wavemaker.tools.data.ExportDB.java

@Override
protected void customRun() {

    init();//from ww w.j  a  va  2 s . com

    final Configuration cfg = new Configuration();

    // cfg.addDirectory(this.hbmFilesDir);

    this.hbmFilesDir.find().files().performOperation(new ResourceOperation<com.wavemaker.tools.io.File>() {

        @Override
        public void perform(com.wavemaker.tools.io.File file) {
            if (file.getName().endsWith(".hbm.xml")) {
                cfg.addInputStream(file.getContent().asInputStream());
            }
        }
    });

    Properties connectionProperties = getHibernateConnectionProperties();

    cfg.addProperties(connectionProperties);

    SchemaExport export = null;
    SchemaUpdate update = null;
    File ddlFile = null;

    try {
        if (this.overrideTable) {
            Callable<SchemaExport> t = new Callable<SchemaExport>() {

                @Override
                public SchemaExport call() {
                    return new SchemaExport(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    export = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                export = ResourceClassLoaderUtils.runInClassLoaderContext(true, t, this.classesDir);
            }

            ddlFile = File.createTempFile("ddl", ".sql");
            ddlFile.deleteOnExit();

            export.setOutputFile(ddlFile.getAbsolutePath());
            export.setDelimiter(";");
            export.setFormat(true);

            String extraddl = prepareForExport(this.exportToDatabase);

            export.create(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(export.getExceptions());
            this.errors = filterError(this.errors, connectionProperties);

            this.ddl = IOUtils.read(ddlFile);

            if (!ObjectUtils.isNullOrEmpty(extraddl)) {
                this.ddl = extraddl + "\n" + this.ddl;
            }
        } else {
            Callable<SchemaUpdate> t = new Callable<SchemaUpdate>() {

                @Override
                public SchemaUpdate call() {
                    return new SchemaUpdate(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    update = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                update = ResourceClassLoaderUtils.runInClassLoaderContext(t, this.classesDir);
            }

            prepareForExport(this.exportToDatabase);

            Connection conn = JDBCUtils.getConnection(this.connectionUrl.toString(), this.username,
                    this.password, this.driverClassName);

            Dialect dialect = Dialect.getDialect(connectionProperties);

            DatabaseMetadata meta = new DatabaseMetadata(conn, dialect);

            String[] updateSQL = cfg.generateSchemaUpdateScript(dialect, meta);

            update.execute(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(update.getExceptions());
            StringBuilder sb = new StringBuilder();
            for (String line : updateSQL) {
                sb = sb.append(line);
                sb = sb.append("\n");
            }
            this.ddl = sb.toString();

        }
    } catch (IOException ex) {
        throw new DataServiceRuntimeException(ex);
    } catch (SQLException qex) {
        throw new DataServiceRuntimeException(qex);
    } catch (RuntimeException rex) {
        if (rex.getCause() != null && rex.getCause().getMessage().contains(NO_SUITABLE_DRIVER)
                && WMAppContext.getInstance().isCloudFoundry()) {
            String msg = rex.getMessage() + " - " + UNKNOWN_DATABASE;
            throw new DataServiceRuntimeException(msg);
        } else {
            throw new DataServiceRuntimeException(rex);
        }
    } finally {
        try {
            ddlFile.delete();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java

@Test
public void testThatDowngradingRespectsThreads() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {/*from   www  . j a v a  2s .c  o  m*/
        client.start();

        final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock");
        ExecutorService t1 = Executors.newSingleThreadExecutor();
        ExecutorService t2 = Executors.newSingleThreadExecutor();

        final CountDownLatch latch = new CountDownLatch(1);

        Future<Object> f1 = t1.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                lock.writeLock().acquire();
                latch.countDown();
                return null;
            }
        });

        Future<Object> f2 = t2.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
                Assert.assertFalse(lock.readLock().acquire(5, TimeUnit.SECONDS));
                return null;
            }
        });

        f1.get();
        f2.get();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testOverSubscribed() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    ExecutorService service = Executors.newCachedThreadPool();
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(service);
    try {//from ww w  . java2  s.c o  m
        client.start();

        final Semaphore semaphore = new Semaphore(0);
        final CountDownLatch latch = new CountDownLatch(1);
        for (int i = 0; i < (QTY + 1); ++i) {
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY) {
                        @Override
                        protected List<String> getChildrenForEntering() throws Exception {
                            semaphore.release();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            return super.getChildrenForEntering();
                        }
                    };
                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));
                    Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS));
                    return null;
                }
            });
        }

        Assert.assertTrue(semaphore.tryAcquire(QTY + 1, timing.seconds(), TimeUnit.SECONDS)); // wait until all QTY+1 barriers are trying to enter
        latch.countDown();

        for (int i = 0; i < (QTY + 1); ++i) {
            completionService.take().get(); // to check for assertions
        }
    } finally {
        service.shutdown();
        IOUtils.closeQuietly(client);
    }
}

From source file:com.microsoft.azure.management.dns.ZoneOperationsImpl.java

/**
* Creates a DNS zone within a resource group.
*
* @param resourceGroupName Required. The name of the resource group.
* @param zoneName Required. The name of the zone without a terminating dot.
* @param parameters Required. Parameters supplied to the CreateOrUpdate
* operation.//  www  .j  a  va 2 s. c  om
* @return The response to a Zone CreateOrUpdate operation.
*/
@Override
public Future<ZoneCreateOrUpdateResponse> createOrUpdateAsync(final String resourceGroupName,
        final String zoneName, final ZoneCreateOrUpdateParameters parameters) {
    return this.getClient().getExecutorService().submit(new Callable<ZoneCreateOrUpdateResponse>() {
        @Override
        public ZoneCreateOrUpdateResponse call() throws Exception {
            return createOrUpdate(resourceGroupName, zoneName, parameters);
        }
    });
}