Example usage for java.util.concurrent FutureTask run

List of usage examples for java.util.concurrent FutureTask run

Introduction

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

Prototype

public void run() 

Source Link

Usage

From source file:io.teak.sdk.TeakNotification.java

/**
 * Cancel a push notification that was scheduled with {@link TeakNotification#scheduleNotification(String, String, long)}
 *
 * @param scheduleId/*  w w  w .  j a  v  a 2 s .c o m*/
 * @return
 */
@SuppressWarnings("unused")
public static FutureTask<String> cancelNotification(final String scheduleId) {
    if (!Teak.isEnabled()) {
        Log.e(LOG_TAG, "Teak is disabled, ignoring cancelNotification().");
        return null;
    }

    if (scheduleId == null || scheduleId.isEmpty()) {
        Log.e(LOG_TAG, "scheduleId cannot be null or empty");
        return null;
    }

    final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<>(1);
    final FutureTask<String> ret = new FutureTask<>(new Callable<String>() {
        public String call() {
            try {
                return q.take();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            }
            return null;
        }
    });

    Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
        @Override
        public void run(Session session) {
            HashMap<String, Object> payload = new HashMap<>();
            payload.put("id", scheduleId);

            new Request("/me/cancel_local_notify.json", payload, session) {
                @Override
                protected void done(int responseCode, String responseBody) {
                    try {
                        JSONObject response = new JSONObject(responseBody);
                        if (response.getString("status").equals("ok")) {
                            q.offer(response.getJSONObject("event").getString("id"));
                        } else {
                            q.offer("");
                        }
                    } catch (Exception ignored) {
                        q.offer("");
                    }
                    ret.run();
                }
            }.run();
        }
    });

    return ret;
}

From source file:io.teak.sdk.TeakNotification.java

/**
 * Schedules a push notification for some time in the future.
 *
 * @param creativeId     The identifier of the notification in the Teak dashboard (will create if not found).
 * @param defaultMessage The default message to send, may be over-ridden in the dashboard.
 * @param delayInSeconds The delay in seconds from now to send the notification.
 * @return The identifier of the scheduled notification (see {@link TeakNotification#cancelNotification(String)} or null.
 *///from  w w  w .j  a  va2  s  .c o  m
@SuppressWarnings("unused")
public static FutureTask<String> scheduleNotification(final String creativeId, final String defaultMessage,
        final long delayInSeconds) {
    if (!Teak.isEnabled()) {
        Log.e(LOG_TAG, "Teak is disabled, ignoring scheduleNotification().");
        return null;
    }

    if (creativeId == null || creativeId.isEmpty()) {
        Log.e(LOG_TAG, "creativeId cannot be null or empty");
        return null;
    }

    if (defaultMessage == null || defaultMessage.isEmpty()) {
        Log.e(LOG_TAG, "defaultMessage cannot be null or empty");
        return null;
    }

    final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<>(1);
    final FutureTask<String> ret = new FutureTask<>(new Callable<String>() {
        public String call() {
            try {
                return q.take();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            }
            return null;
        }
    });

    Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
        @Override
        public void run(Session session) {
            HashMap<String, Object> payload = new HashMap<>();
            payload.put("identifier", creativeId);
            payload.put("message", defaultMessage);
            payload.put("offset", delayInSeconds);

            new Request("/me/local_notify.json", payload, session) {
                @Override
                protected void done(int responseCode, String responseBody) {
                    try {
                        JSONObject response = new JSONObject(responseBody);
                        if (response.getString("status").equals("ok")) {
                            q.offer(response.getJSONObject("event").getString("id"));
                        } else {
                            q.offer("");
                        }
                    } catch (Exception ignored) {
                        q.offer("");
                    }

                    ret.run();
                }
            }.run();
        }
    });
    return ret;
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.RecoverStorageManager.java

public Store getOrCreateStore(final String topic, final String group) {
    final String name = this.generateKey(topic, group);
    FutureTask<Store> task = this.topicStoreMap.get(name);
    if (task != null) {
        return this.getStore(topic, task);
    } else {/* w ww .j  ava2  s  .c om*/
        task = new FutureTask<Store>(new Callable<Store>() {

            @Override
            public Store call() throws Exception {
                final File file = new File(META_RECOVER_STORE_PATH + File.separator + name);
                if (!file.exists()) {
                    file.mkdir();
                }
                return new MessageStore(META_RECOVER_STORE_PATH + File.separator + name, name);
            }

        });
        FutureTask<Store> existsTask = this.topicStoreMap.putIfAbsent(name, task);
        if (existsTask == null) {
            task.run();
            existsTask = task;
        }
        return this.getStore(name, existsTask);
    }

}

From source file:com.alibaba.napoli.metamorphosis.client.producer.ProducerZooKeeper.java

public void publishTopic(final String topic) {
    if (this.topicConnectionListeners.get(topic) != null) {
        return;/* ww w.  j  a v a 2  s.c  o  m*/
    }
    final FutureTask<BrokerConnectionListener> task = new FutureTask<BrokerConnectionListener>(
            new Callable<BrokerConnectionListener>() {
                @Override
                public BrokerConnectionListener call() throws Exception {
                    final BrokerConnectionListener listener = new BrokerConnectionListener(topic);
                    if (ProducerZooKeeper.this.zkClient != null) {
                        ProducerZooKeeper.this.publishTopicInternal(topic, listener);
                    }
                    return listener;
                }

            });

    final FutureTask<BrokerConnectionListener> existsTask = this.topicConnectionListeners.putIfAbsent(topic,
            task);
    if (existsTask == null) {
        task.run();
    }
}

From source file:com.alibaba.napoli.metamorphosis.client.extension.producer.LocalMessageStorageManager.java

private Store getOrCreateStore0(final String topic, final Partition partition) {
    final String name = this.generateKey(topic, partition);
    FutureTask<Store> task = this.topicStoreMap.get(name);
    if (task != null) {
        return this.getStore(name, task);
    } else {/*w w w  . ja v  a  2 s .  co m*/
        task = new FutureTask<Store>(new Callable<Store>() {

            @Override
            public Store call() throws Exception {
                final File file = new File(
                        LocalMessageStorageManager.this.META_LOCALMESSAGE_PATH + File.separator + name);
                if (!file.exists()) {
                    file.mkdir();
                }
                return this.newStore(name);
            }

            private Store newStore(final String name) throws IOException {
                return LocalMessageStorageManager.this.newStore(name);
            }

        });
        FutureTask<Store> existsTask = this.topicStoreMap.putIfAbsent(name, task);
        if (existsTask == null) {
            task.run();
            existsTask = task;
        }
        return this.getStore(name, existsTask);
    }
}

From source file:org.jactr.core.runtime.controller.OldController.java

public Future<Boolean> terminate() {
    if (LOGGER.isWarnEnabled())
        LOGGER.warn("NO OP");
    FutureTask<Boolean> rtn = new FutureTask<Boolean>(new Callable<Boolean>() {

        public Boolean call() throws Exception {
            try {

                return true;
            } catch (Exception e) {
                LOGGER.error("Failed to terminate runtime correctly ", e);
                return false;
            }//from  ww  w .  ja  v  a  2 s .c  o m
        }
    });

    rtn.run();
    return rtn;
}

From source file:i5.las2peer.services.videoAdapter.AdapterClass.java

@GET
@Path("playlist")
public HttpResponse getPlaylist(@QueryParam(name = "sub", defaultValue = "*") String subId,
        //@QueryParam(name="username" , defaultValue = "*") String username, 
        @QueryParam(name = "search", defaultValue = "*") String searchString,
        @QueryParam(name = "lat", defaultValue = "*") String lat,
        @QueryParam(name = "lng", defaultValue = "*") String lng,
        @QueryParam(name = "duration", defaultValue = "true") boolean duration,
        @QueryParam(name = "language", defaultValue = "true") boolean language,
        @QueryParam(name = "location", defaultValue = "true") boolean location,
        @QueryParam(name = "relevance", defaultValue = "true") boolean relevance,
        @QueryParam(name = "weightOrder", defaultValue = "true") boolean weightOrder,
        @QueryParam(name = "sequence", defaultValue = "LRDOW") String sequence,
        @QueryParam(name = "mobile", defaultValue = "false") boolean mobile,
        @QueryParam(name = "Authorization", defaultValue = "") String token) {

    String username = null;/*from w  ww  .  jav a 2 s  . c  o m*/

    System.out.println("TOKEN: " + token);

    if (token != null) {
        token = token.replace("Bearer ", "");
        username = OIDC.verifyAccessToken(token, userinfo);
    }

    System.out.println("Adapter Service Checkpoint:0 -- request received" + " - User: " + username
            + " - Search Query: " + searchString);

    //Query parameters validation

    if (!isInteger(lat))
        lat = "*";
    if (!isInteger(lng))
        lng = "*";
    if (username.isEmpty() || username.equals("undefined") || username.equals("error")) {
        HttpResponse r = new HttpResponse("User is not signed in!");
        r.setStatus(401);
        return r;
    }
    if (searchString.isEmpty() || searchString.equals("undefined")) {
        HttpResponse r = new HttpResponse("Please enter a valid search query!");
        r.setStatus(400);
        return r;
    }
    /*StopWords sw=new StopWords();
    searchString = sw.remove(searchString);*/

    System.out.println("Stemmed search query: " + searchString);

    dbm = new DatabaseManager();
    dbm.init(driverName, databaseServer, port, database, this.username, password, hostName);

    FutureTask<String> future = new FutureTask<>(new Adapt(searchString, username, lat, lng, dbm, duration,
            location, language, mobile, relevance, weightOrder, sequence, token));
    future.run();
    String annotations = "No Annotation";

    try {

        annotations = future.get();
        //System.out.println("Result="+result);

    } catch (InterruptedException | ExecutionException e) {

        System.out.println("EXCEPTION!!!");
        e.printStackTrace();
    }

    //String annotations = getAndAdapt(searchString, username, id++);

    HttpResponse r = new HttpResponse(annotations);
    r.setStatus(200);
    return r;

}

From source file:org.eclipse.che.api.builder.internal.SourcesManagerImpl.java

@Override
public void getSources(BuildLogger logger, String workspace, String project, final String sourcesUrl,
        java.io.File workDir) throws IOException {
    // Directory for sources. Keep sources to avoid download whole project before build.
    // This directory is not permanent and may be removed at any time.
    final java.io.File srcDir = new java.io.File(directory, workspace + java.io.File.separatorChar + project);
    // Temporary directory where we copy sources before build.
    final String key = workspace + project;
    try {//  ww  w .ja v a2 s  .co m
        synchronized (this) {
            while (key.equals(projectKeyHolder.get())) {
                wait();
            }
        }
    } catch (InterruptedException e) {
        LOG.error(e.getMessage(), e);
        Thread.currentThread().interrupt();
    }
    // Avoid multiple threads download source of the same project.
    Future<Void> future = tasks.get(key);
    final ValueHolder<IOException> errorHolder = new ValueHolder<>();
    if (future == null) {
        final FutureTask<Void> newFuture = new FutureTask<>(new Runnable() {
            @Override
            public void run() {
                try {
                    download(sourcesUrl, srcDir);
                } catch (IOException e) {
                    LOG.error(e.getMessage(), e);
                    errorHolder.set(e);
                }
            }
        }, null);
        future = tasks.putIfAbsent(key, newFuture);
        if (future == null) {
            future = newFuture;
            try {
                // Need a bit time before to publish sources download start message via websocket
                // as client may not have already subscribed to the channel so early in build task execution
                Thread.sleep(300);
            } catch (InterruptedException e) {
                LOG.error(e.getMessage(), e);
            }
            logger.writeLine("[INFO] Injecting source code into builder...");
            newFuture.run();
            logger.writeLine("[INFO] Source code injection finished"
                    + "\n[INFO] ------------------------------------------------------------------------");
        }
    }
    try {
        future.get(); // Block thread until download is completed.
        final IOException ioError = errorHolder.get();
        if (ioError != null) {
            throw ioError;
        }
        IoUtil.copy(srcDir, workDir, IoUtil.ANY_FILTER);
        for (SourceManagerListener listener : listeners) {
            listener.afterDownload(new SourceManagerEvent(workspace, project, sourcesUrl, workDir));
        }
        if (!srcDir.setLastModified(System.currentTimeMillis())) {
            LOG.error("Unable update modification date of {} ", srcDir);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        // Runnable does not throw checked exceptions.
        final Throwable cause = e.getCause();
        if (cause instanceof Error) {
            throw (Error) cause;
        } else {
            throw (RuntimeException) cause;
        }
    } finally {
        tasks.remove(key);
    }
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.ConsumerZooKeeper.java

/**
 * // w  w  w.j av  a  2  s .  c o m
 * 
 * @throws Exception
 */
public void registerConsumer(final ConsumerConfig consumerConfig, final FetchManager fetchManager,
        final ConcurrentHashMap<String/* topic */, SubscriberInfo> topicSubcriberRegistry,
        final OffsetStorage offsetStorage, final LoadBalanceStrategy loadBalanceStrategy) throws Exception {

    final FutureTask<ZKLoadRebalanceListener> task = new FutureTask<ZKLoadRebalanceListener>(
            new Callable<ZKLoadRebalanceListener>() {

                @Override
                public ZKLoadRebalanceListener call() throws Exception {
                    final ZKGroupDirs dirs = ConsumerZooKeeper.this.metaZookeeper.new ZKGroupDirs(
                            consumerConfig.getGroup());
                    final String consumerUUID = ConsumerZooKeeper.this.getConsumerUUID(consumerConfig);
                    final String consumerUUIDString = consumerConfig.getGroup() + "_" + consumerUUID;
                    final ZKLoadRebalanceListener loadBalanceListener = new ZKLoadRebalanceListener(
                            fetchManager, dirs, consumerUUIDString, consumerConfig, offsetStorage,
                            topicSubcriberRegistry, loadBalanceStrategy);
                    return ConsumerZooKeeper.this.registerConsumerInternal(loadBalanceListener);
                }

            });
    final FutureTask<ZKLoadRebalanceListener> existsTask = this.consumerLoadBalanceListeners
            .putIfAbsent(fetchManager, task);
    if (existsTask == null) {
        task.run();
    } else {
        throw new MetaClientException("Consumer has been already registed");
    }

}

From source file:android.webkit.cts.WebViewTest.java

private void savePrintedPage(final PrintDocumentAdapter adapter, final ParcelFileDescriptor descriptor,
        final FutureTask<Boolean> result) {
    adapter.onWrite(new PageRange[] { PageRange.ALL_PAGES }, descriptor, new CancellationSignal(),
            new WriteResultCallback() {
                @Override//from  www  .  ja  v  a2 s.  c  o  m
                public void onWriteFinished(PageRange[] pages) {
                    try {
                        descriptor.close();
                        result.run();
                    } catch (IOException ex) {
                        fail("Failed file operation: " + ex.toString());
                    }
                }
            });
}