Example usage for javafx.concurrent Task Task

List of usage examples for javafx.concurrent Task Task

Introduction

In this page you can find the example usage for javafx.concurrent Task Task.

Prototype

public Task() 

Source Link

Document

Creates a new Task.

Usage

From source file:com.cooksys.httpserver.HttpServerStarter.java

@Override
protected Task createTask() {
    return new Task<Void>() {
        @Override/*from   w  w  w  .j a  v  a  2 s. c  o m*/
        protected Void call() throws Exception {
            // Set up the HTTP protocol processor
            HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
                    .add(new ResponseServer("PostMaster/1.1")).add(new ResponseContent())
                    .add(new ResponseConnControl()).build();

            // Set up request handlers
            UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper();
            registry.register("*", new IncomingHttpHandler());

            // Set up the HTTP service that listens for incoming requests
            HttpService httpService = new HttpService(httpproc, registry);

            //RequestListenerThread extends the Thread class, but since we are
            //letting the concurrency handle background tasks, it would not 
            //make sense to spawn another thread inside this task, so we
            //will just call run() method instead of start()
            System.out.println("creating serverThread...");
            try {
                serverThread = new RequestListenerThread(postmasterModel.getPort(), httpService);
            } catch (IOException e) {
                System.out.println("Caught IOException:" + e.getMessage());
                //end the server task
                this.updateMessage(e.getMessage());
                throw e;
            }
            System.out.println("serverThread created: " + serverThread);
            serverThread.run(); //the compiler will warn here, but we did this on purpose

            return null;
        }

        @Override
        protected void failed() {

        }
    };
}

From source file:dtv.tools.DuplicateRemover.java

@Override
protected Task<List<DVBChannel>> createTask() {

    return new Task<List<DVBChannel>>() {
        @Override/*ww  w .j  ava2  s  . c o  m*/
        protected List<DVBChannel> call() throws Exception {
            Set<DVBChannel> serviceSet = new LinkedHashSet<DVBChannel>(services);
            updateProgress(-1, 0);

            services.setAll(serviceSet);
            Utils.initIds(services);

            return services;
        }
    };
}

From source file:org.kles.m3.service.M3ConnectorBuilderService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {

        @Override/* w  ww . ja v a 2  s  . co  m*/
        protected Void call() throws MAKException, InterruptedException {
            beginTime = System.currentTimeMillis();
            updateMessage("Initialisation des donnes de " + m3Connector.getEnv().getName());
            m3Connector.getMapEntityByConfiguration().entrySet().stream()
                    .forEach((Map.Entry<M3ConfigurationInfo, M3ConfigurationDetail> key) -> {

                        if (key.getKey().getName().equals(m3Connector.getMainConfig().getName())
                                && !m3Connector.getMainConfig().getName().equals("MVX")) {
                            ArrayList<M3ClassPathEntry> l = new ArrayList<>();
                            for (Map.Entry<String, M3Component> component : key.getValue().getListComponent()
                                    .entrySet()) {
                                if (m3Connector.getListComponentSelect().contains(component.getValue())
                                        && !component.getValue().getNameComponent().equals("MVX")) {
                                    l.addAll(component.getValue().getListComponentPath());
                                }
                            }
                            key.getValue().setConfigClassPath(l);
                        } else {
                            key.getValue().setConfigClassPath(key.getValue().getCompleteClassPath());
                        }
                        ArrayList<Path> arrayPath = new ArrayList<>();
                        ProcessFile fileProcessor = new ProcessFile();
                        fileProcessor.setExtFilter(".class");
                        for (M3ClassPathEntry cl1 : key.getValue().getConfigClassPath()) {
                            try {
                                if (new File(cl1.getPath().toOSString()).exists()) {
                                    updateMessage("Recherche d'objets dans " + cl1.getPath().toOSString());
                                    Files.walkFileTree(Paths.get(cl1.getPath().toString()), fileProcessor);
                                }
                            } catch (IOException ex) {
                                Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            arrayPath.addAll(fileProcessor.getList());
                        }

                        int cpt = 0;
                        for (Path p : arrayPath) {
                            updateMessage("Traitement des objets de " + p.toString());
                            LinkedHashMap<String, SourceObject> entity = key.getValue().getMapEntity()
                                    .get(M3Utils.getPgmType(p.toFile().getAbsolutePath()));
                            if (entity != null) {
                                String name = FilenameUtils.getBaseName(p.toString());
                                if (!entity.containsKey(name)) {
                                    if (M3Utils.getPgmType(p.toFile().getAbsolutePath()).equals(Resource.DB)
                                            && name.contains("$")) {
                                        continue;
                                    }
                                    SourceObject obj = new SourceObject();
                                    obj.setObjectPath(p);
                                    entity.put(name, obj);
                                    cpt++;
                                }
                            }
                        }
                        updateMessage(cpt + " objets trouvs appartenant  la configuration "
                                + key.getKey().getName() + "(" + key.getKey().getName() + ")");
                    });
            updateMessage("Fin de la recherche d'objet");
            Thread.sleep(2000);
            return null;
            /*beginTime = System.currentTimeMillis();
             updateMessage("Initialisation des donnes");
             m3Connector.getMapEntityByConfiguration().entrySet().stream().forEach((key) -> {
                    
             ArrayList<Path> arrayPath = new ArrayList<>();
             ProcessFile fileProcessor = new ProcessFile();
             fileProcessor.setExtFilter(".class");
             for (M3ClassPathEntry cl1 : key.getValue().getConfigClassPath()) {
             try {
             if (new File(cl1.getPath().toOSString()).exists()) {
             updateMessage("Recherche d'objets dans " + cl1.getPath().toOSString());
             Files.walkFileTree(Paths.get(cl1.getPath().toString()), fileProcessor);
             }
             } catch (IOException ex) {
             Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
             }
             arrayPath.addAll(fileProcessor.getList());
             }
                    
             int cpt = 0;
             for (Path p : arrayPath) {
             updateMessage("Traitement des objets de " + p.toString());
             LinkedHashMap<String, SourceObject> entity = key.getValue().getMapEntity().get(M3Utils.getPgmType(p.toFile().getAbsolutePath()));
             if (entity != null) {
             String name = FilenameUtils.getBaseName(p.toString());
             if (!entity.containsKey(name)) {
             if (M3Utils.getPgmType(p.toFile().getAbsolutePath()).equals(Resource.DB) && name.contains("$")) {
             continue;
             }
             SourceObject obj = new SourceObject();
             obj.setObjectPath(p);
             entity.put(name, obj);
             cpt++;
             }
             }
             }
             updateMessage(cpt + " objets trouvs appartenant  la configuration " + key.getKey().getName() + "(" + key.getKey().getName() + ")");
             });
             updateMessage("Fin de la recherche d'objet");
             Thread.sleep(2000);
             return null;*/
        }
    };
}

From source file:poe.trade.assist.service.SearchFormService.java

@Override
protected Task<String> createTask() {
    return new Task<String>() {

        @Override/*  w  w  w.jav a  2  s  .co  m*/
        protected String call() throws Exception {
            String url = SearchFormService.this.url.get();
            if (isNotBlank(url)) {
                String html = doDownload(url);
                // FileUtils.writeStringToFile(new File(search.getName()),
                // html);
                return html;
            }
            return "Something went really wrong";
        }
    };
}

From source file:org.kles.m3.service.CheckM3ConnectionService.java

@Override
protected Task<Boolean> createTask() {
    return new Task<Boolean>() {

        @Override//from   w w w  .  ja va2s.c  o m
        protected Boolean call() throws MAKException {
            updateMessage("Initialisation des donnes");
            waiter(1000);
            if (m3connector.get().getEnv() != null) {
                updateMessage("Cration du runtime M3");
                waiter(1000);
                EnvironmentProperties e = new EnvironmentProperties();
                e.setServerAddress(m3connector.get().getEnv().getM3BEHost());
                e.setServerPort(m3connector.get().getEnv().getM3BEPort());
                e.setRootPath(m3connector.get().getEnv().getM3BEPath());
                ZUserCredentialsProvider credentialsProvider = new ZUserCredentialsProvider();
                credentialsProvider
                        .setUserPwd(new UsernamePasswordCredentials(m3connector.get().getEnv().getM3BELogin(),
                                m3connector.get().getEnv().getM3BEPassword()));
                credentialsProvider.getCachedCredentials(m3connector.get().getEnv().getM3BEHost(),
                        m3connector.get().getEnv().getM3BEPort());
                m3connector.get().setM3Runtime(M3RuntimeFactory.getRuntime(e.getServerRootPath().toString(),
                        e.getServerAddress(), e.getServerPort(), credentialsProvider));
                m3connector.get().setInitOK(false);
                if (m3connector.get().getM3Runtime() != null) {
                    m3connector.get().setEnvironmentProperties(e);
                    updateMessage("Vrification de la connexion");
                    waiter(1000);
                    ConfigurationProperties configurationProperties = new ConfigurationProperties();
                    configurationProperties.setName("MVX");
                    configurationProperties.setDescription("Standard Configuration");
                    configurationProperties.setClassPath(
                            m3connector.get().getM3Runtime().getClassPath(configurationProperties.getName()));
                    MovexSystem mvxSys = MovexSystemFactory.newMovexSystem(e, configurationProperties, null);
                    m3connector.get().setInitOK(mvxSys.isInitialized());
                }
                if (!m3connector.get().isInitOK()) {
                    new RuntimeException("Error de connexion  M3!");
                    this.failed();
                    return false;
                }
            } else {
                new RuntimeException("M3 Environment null");
                this.failed();
                return false;
            }
            updateMessage("");
            return true;
        }
    };
}

From source file:ijfx.service.remote.DefaultLoginService.java

@Override
public Task<Boolean> login(final String email, final String password) {

    Task<Boolean> task = new Task() {

        @Override//from  w ww  .  ja  va2s. c o m
        protected Boolean call() throws Exception {

            int response = Request.Get(server + API_USER)
                    .bodyString(JSONUtils.generateJSON(EMAIL, email, PASSWORD, password),
                            ContentType.APPLICATION_JSON)
                    .execute().returnResponse().getStatusLine().getStatusCode();

            return response == 200;
        }

    };

    ImageJFX.getThreadPool().submit(task);
    return task;

}

From source file:ch.unibas.fittingwizard.presentation.base.progress.ProgressPage.java

@Override
public void initializeData() {
    if (task == null) {
        task = new Task<Boolean>() {
            @Override/*from  w w w .jav  a 2  s.co  m*/
            protected Boolean call() throws Exception {
                return ProgressPage.this.run(ProgressPage.this);
            }
        };
        task.setOnCancelled(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent event) {
                logger.info("Task canceled.");
                goBack();
            }
        });
        task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent event) {
                logger.info("Task succeeded.");
                final boolean result = task.getValue();
                Platform.runLater(new CatchedRunnable() {
                    @Override
                    public void safelyRun() {
                        handleFinishedRun(result);
                    }
                });
                task = null;
            }
        });
        task.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent event) {
                logger.info("Task failed.");
                String error = "No exception details available.";
                if (task.getException() != null) {
                    error = ExceptionUtils.getMessage(task.getException());
                    logger.error("Task failed with exception.", task.getException());
                }

                OverlayDialog.showError("Error in the task execution",
                        "There was an error in the task execution.\n\n" + error);
                goBack();
            }
        });
    }

    logger.info("Starting task");
    new Thread(task).start();
    logger.info("Task started.");
}

From source file:ninja.eivind.hotsreplayuploader.services.AccountService.java

@Override
protected Task<List<Account>> createTask() {
    return new Task<List<Account>>() {
        @Override//from  w w w  .jav  a 2  s . c  o  m
        protected List<Account> call() throws Exception {
            final List<String> accountUris = stormHandler.getAccountStringUris();
            final List<Account> value = new ArrayList<>();
            for (final String accountUri : accountUris) {
                final String response = httpClient.simpleRequest(accountUri);
                value.add(mapper.readValue(response, Account.class));
            }
            return value;
        }
    };
}

From source file:ok.MyService2.java

@Override
protected Task<BlockingQueue> createTask() {
    final Task<BlockingQueue> task;
    task = new Task<BlockingQueue>() {

        @Override/*from ww  w  .  j  ava2  s. c  o  m*/
        protected BlockingQueue call() throws Exception {
            BlockingQueue result = new LinkedBlockingQueue<String>();

            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(100);

            CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
            try {
                ExecutorService executor = Executors.newFixedThreadPool(sites.size());
                List<Future<String>> results = new ArrayList<Future<String>>();
                for (int i = 0; i < sites.size(); i++) {
                    HttpGet httpget = new HttpGet(sites.get(i));
                    Callable worker = new MyCallable(httpclient, httpget);
                    Future<String> res = executor.submit(worker);
                    results.add(res);
                    // String url = hostList[i];
                    //   Runnable worker = new MyRunnable(url);
                    //   executor.execute(worker);
                    //   executor.submit(null);

                }
                executor.shutdown();
                // Wait until all threads are finish
                //                   while (!executor.isTerminated()) {
                //
                //                   }
                for (Future<String> element : results) {
                    result.add(element.get());
                }
                System.out.println("\nFinished all threads");

            } finally {
                httpclient.close();
            }
            return result;
        }

    };
    return task;
}

From source file:ninja.javafx.smartcsv.fx.util.LoadFileService.java

@Override
protected Task createTask() {
    return new Task() {
        @Override//from w w  w . j a  va2  s.  co m
        protected Void call() throws Exception {
            if (file != null) {
                file.load();
            }
            return null;
        }
    };
}