List of usage examples for javafx.concurrent Task Task
public Task()
From source file:de.pro.dbw.application.testdata.service.TipOfTheNightService.java
@Override protected Task<Void> createTask() { return new Task<Void>() { {//from w ww. jav a2 s . c o m updateProgress(0, saveMaxEntities); } @Override protected Void call() throws Exception { LoggerFacade.INSTANCE.deactivate(Boolean.TRUE); final StopWatch stopWatch = new StopWatch(); stopWatch.start(); final ICrudService crudService = DatabaseFacade.INSTANCE.getCrudService(entityName); // crudService.beginTransaction(); long id = -1_000_000_000L + DatabaseFacade.INSTANCE.getCrudService().count(entityName); for (int i = 1; i <= saveMaxEntities; i++) { crudService.beginTransaction(); final TipOfTheNightModel model = new TipOfTheNightModel(); model.setGenerationTime(TipOfTheNightService.this.createGenerationTime()); model.setId(id++); model.setTitle(LoremIpsum.getDefault().getTitle()); model.setText(LoremIpsum.getDefault() .getTextWithMaxEntries(LoremIpsum.MAX_ENTRIES_FOR__TIP_OF_THE_NIGHT)); crudService.create(model, false); updateProgress(i - 1, saveMaxEntities); crudService.commitTransaction(); // if (i % 250 == 0) { // crudService.commitTransaction(); // crudService.beginTransaction(); // } } // crudService.commitTransaction(); LoggerFacade.INSTANCE.deactivate(Boolean.FALSE); stopWatch.split(); LoggerFacade.INSTANCE.debug(this.getClass(), " + " + stopWatch.toSplitString() + " for " + saveMaxEntities + " TipOfTheNights."); // NOI18N stopWatch.stop(); return null; } }; }
From source file:com.github.naoghuman.testdata.abclist.service.ExerciseService.java
@Override protected Task<Void> createTask() { return new Task<Void>() { {/*ww w.j av a 2 s. c o m*/ updateProgress(0, saveMaxEntities); } @Override protected Void call() throws Exception { LoggerFacade.getDefault().deactivate(Boolean.TRUE); final StopWatch stopWatch = new StopWatch(); stopWatch.start(); final ObservableList<Topic> topics = SqlProvider.getDefault().findAllTopics(); final int removeMaxTopics = (int) (Double.parseDouble(String.valueOf(topics.size())) * 0.001d); for (int counter = removeMaxTopics; counter > 0; counter--) { topics.remove(TestdataGenerator.RANDOM.nextInt(topics.size())); } final int sizeTopics = topics.size(); final CrudService crudService = DatabaseFacade.getDefault().getCrudService(entityName); final ETime[] times = ETime.values(); final int sizeTimes = times.length; long id = -1_000_000_000L + DatabaseFacade.getDefault().getCrudService().count(entityName); for (int index = 0; index < saveMaxEntities; index++) { final Exercise exercise = ModelProvider.getDefault().getExercise(); exercise.setChoosenTime((times[TestdataGenerator.RANDOM.nextInt(sizeTimes)]).toString()); exercise.setConsolidated(false); // TODO later ? exercise.setFinishedTime(ExerciseService.this.createGenerationTime()); exercise.setGenerationTime(ExerciseService.this.createGenerationTime()); if (exercise.getGenerationTime() > exercise.getFinishedTime()) { final long generationTime = exercise.getGenerationTime(); final long finishedTime = exercise.getFinishedTime(); exercise.setGenerationTime(finishedTime); exercise.setFinishedTime(generationTime); } exercise.setId(id++); exercise.setReady(TestdataGenerator.RANDOM.nextDouble() > 0.001d); // TODO if ready then add terms final long topicId = topics.get(TestdataGenerator.RANDOM.nextInt(sizeTopics)).getId(); exercise.setTopicId(topicId); crudService.create(exercise); updateProgress(index, saveMaxEntities); } LoggerFacade.getDefault().deactivate(Boolean.FALSE); stopWatch.split(); LoggerFacade.getDefault().debug(this.getClass(), " + " + stopWatch.toSplitString() + " for " + saveMaxEntities + " Exercises."); // NOI18N stopWatch.stop(); return null; } }; }
From source file:ninja.eivind.hotsreplayuploader.services.UploaderService.java
@Override protected Task<ReplayFile> createTask() { if (isIdle()) { return new Task<ReplayFile>() { @Override//from w w w.j a v a 2 s . c o m protected ReplayFile call() throws Exception { Thread.sleep(2000); return null; } }; } try { logger.info("Attempting to take file from queue"); final ReplayFile replayFile = uploadQueue.take(); if (!replayFile.getFile().exists()) { fileRepository.deleteReplay(replayFile); files.remove(replayFile); return createTask(); } final UploadTask uploadTask = new UploadTask(providers, replayFile, parser); uploadTask.setOnSucceeded(event -> { try { final ReplayFile result = uploadTask.get(); final Status status = result.getStatus(); logger.info("Resolved status {} for {}", status, result); switch (status) { case UPLOADED: final int newCount = Integer.valueOf(uploadedCount.getValue()) + 1; uploadedCount.setValue(String.valueOf(newCount)); logger.info("Upload count updated to " + newCount); case UNSUPPORTED_GAME_MODE: result.getFailedProperty().setValue(false); logger.info("Removing {} from display list", result); files.remove(result); break; case EXCEPTION: case NEW: logger.warn("Upload failed for replay " + result + ". Tagging replay."); result.getFailedProperty().set(true); break; } logger.info("Updating {} in database.", result); fileRepository.updateReplay(result); logger.info("Finished handling file."); } catch (InterruptedException | ExecutionException e) { logger.error("Could not execute task successfully.", e); } }); uploadTask.setOnFailed(event -> { logger.error("UploadTask failed.", event.getSource().getException()); uploadQueue.add(replayFile); }); logger.info("Prepared task"); return uploadTask; } catch (InterruptedException e) { logger.warn("Service interrupted while waiting for task", e); return null; } }
From source file:com.respam.comniq.Controller.java
public Task createWorker() { return new Task() { @Override//from ww w . ja v a 2 s.com protected Object call() throws Exception { localMovies = inputPath.getText(); File loc = new File(localMovies); JSONArray jsonArr = new JSONArray(); String[] folders = loc.list(); for (int i = 0; i < folders.length; i++) { JSONObject jsonObj = new JSONObject(); if (!(excluded.contains(folders[i]))) { if (folders[i].charAt(0) == '(' || folders[i].charAt(0) == '{') { String[] movieYear = folders[i].split("[({})]"); jsonObj.put("movie", movieYear[2].trim()); jsonObj.put("year", movieYear[1]); } else if ((folders[i].charAt(folders[i].length() - 1) == ')') || (folders[i].charAt(folders[i].length() - 1) == '}')) { String[] movieName = folders[i].split("[({]"); String[] movieYear = movieName[1].split("[)}]"); jsonObj.put("movie", movieName[0].trim()); jsonObj.put("year", movieYear[0]); } else { jsonObj.put("movie", folders[i].trim()); jsonObj.put("year", null); } jsonArr.add(jsonObj); } updateProgress(i, folders.length - 1); } MovieListParser mp = new MovieListParser(); mp.JSONWriter(jsonArr); return true; } }; }
From source file:calendarioSeries.vistas.NewSerieController.java
@FXML public void handleOk() { String tituloAux = titulo.getText().replaceAll(" ", "+").toLowerCase(); String toJson = readUrl(BASE + tituloAux + "&type=series" + "&r=json"); resultados.getChildren().clear();/*from w w w . j a v a 2s . com*/ try { JSONObject busqueda = new JSONObject(toJson); if (busqueda.getString("Response").equals("True")) { JSONArray res = busqueda.getJSONArray("Search"); resultados.setPrefRows(res.length()); for (int i = 0; i < res.length(); i++) { JSONObject resActual = new JSONObject(res.get(i).toString()); HBox resultadoActual = new HBox(50); resultadoActual.setMaxWidth(Double.MAX_VALUE); resultadoActual.setAlignment(Pos.CENTER_LEFT); ImageView posterActual = new ImageView(); try { Image image = new Image(resActual.getString("Poster")); posterActual.setImage(image); posterActual.setFitHeight(240); posterActual.setFitWidth(180); posterActual.setPreserveRatio(false); resultadoActual.getChildren().add(posterActual); } catch (IllegalArgumentException e) { // System.out.println("Bad url"); Image image = new Image( MainApp.class.getResource("resources/no-image.png").toExternalForm()); posterActual.setImage(image); posterActual.setFitHeight(240); posterActual.setFitWidth(180); posterActual.setPreserveRatio(false); resultadoActual.getChildren().add(posterActual); } String details; String nomSerie = new String(resActual.getString("Title").getBytes(), "UTF-8"); String anoSerie = new String(resActual.getString("Year").getBytes(), "UTF-8"); if (nomSerie.length() > 15) { details = "%-12.12s...\t\t Ao: %-10s"; } else { details = "%-12s\t\t Ao: %-10s"; } details = String.format(details, nomSerie, anoSerie); Label elemento = new Label(details); elemento.setMaxWidth(Double.MAX_VALUE); elemento.setMaxHeight(Double.MAX_VALUE); resultadoActual.getChildren().add(elemento); posterActual.setId(resActual.getString("imdbID")); posterActual.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { ImageView clickedButton = (ImageView) event.getSource(); Stage stage = (Stage) clickedButton.getScene().getWindow(); Task task = new Task() { @Override protected Object call() throws Exception { mainController.mainApp.scene.setCursor(Cursor.WAIT); Serie toAdd = new Serie(clickedButton.getId()); boolean possible = true; for (Serie serie : mainController.getSeries()) { if (serie.equals(toAdd)) possible = false; } if (possible) mainController.getSeries().add(toAdd); try { mainController.populateImagenes(); mainController.showDetallesMes(mainController.getMesActual()); } catch (Exception e) { e.printStackTrace(); } finally { mainController.mainApp.scene.setCursor(Cursor.DEFAULT); return mainController.getSeries(); } } }; Thread th = new Thread(task); th.setDaemon(true); th.start(); stage.close(); } }); resultados.getChildren().add(resultadoActual); } } else { resultados.getChildren().add(new Label("La busqueda no obtuvo resultados")); } } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(NewSerieController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:sh.isaac.pombuilder.upload.SrcUploadCreator.java
/** * Creates the src upload configuration. * * @param uploadType - What type of content is being uploaded. * @param version - What version number does the passed in content represent * @param extensionName - optional - If the upload type is a type such as {@link SupportedConverterTypes#SCT_EXTENSION} which contains a * wildcard '*' in its {@link SupportedConverterTypes#getArtifactId()} value, this parameter must be provided, and is the string to use to * replace the wildcard. This would typically be a value such as "en" or "fr", when used for snomed extension content. * @param filesToUpload the files to upload * @param gitRepositoryURL - The URL to publish this built project to * @param gitUsername - The username to utilize to publish this project * @param gitPassword the git password//from w w w . j a v a 2s . c o m * @param artifactRepositoryURL - The artifact server path where the created artifact should be transferred. This path should go all the way down to * a specific repository, such as http://artifactory.isaac.sh/artifactory/libs-release-local or http://artifactory.isaac.sh/artifactory/termdata-release-local * This should not point to a URL that represents a 'group' repository view. * @param repositoryUsername - The username to utilize to upload the artifact to the artifact server * @param repositoryPassword - The passwordto utilize to upload the artifact to the artifact server * @return the tag created in the repository that carries the created project * - the task handle - which will return the tag that was created in the git repository upon completion. Note that the task is NOT yet started, when * it is returned. * @throws Throwable the throwable */ public static Task<String> createSrcUploadConfiguration(SupportedConverterTypes uploadType, String version, String extensionName, List<File> filesToUpload, String gitRepositoryURL, String gitUsername, char[] gitPassword, String artifactRepositoryURL, String repositoryUsername, String repositoryPassword) throws Throwable { LOG.info( "Building the task to create a source upload configuration for {}, version: {}, extensionName: {}, to git: {} and artifact server: {}", uploadType, version, extensionName, gitRepositoryURL, artifactRepositoryURL); if (LOG.isDebugEnabled() && (filesToUpload != null)) { LOG.debug("Provided files []", Arrays.toString(filesToUpload.toArray(new File[filesToUpload.size()]))); } if ((filesToUpload == null) || (filesToUpload.size() == 0)) { LOG.info("Throwing an exception because No content was found to upload"); throw new Exception("No content was found to upload!"); } final Task<String> uploader = new Task<String>() { @Override protected String call() throws Exception { updateMessage("Preparing"); File baseFolder = null; try { baseFolder = Files.createTempDirectory("src-upload").toFile(); // Otherwise, move forward. Create our native-source folder, and move everything into it. final File nativeSource = new File(baseFolder, "native-source"); if (nativeSource.exists()) { LOG.info("Task failing due to unexpected file in upload content '{}'", nativeSource); throw new RuntimeException("Unexpected file found in upload content!"); } nativeSource.mkdir(); for (final File f : filesToUpload) { // validate it is a file, move it into native-source if (f.isFile()) { Files.move(f.toPath(), nativeSource.toPath().resolve(f.toPath().getFileName())); } else { LOG.info("Task failing due to unexpected directory in upload content: '{}'", f.getAbsolutePath()); throw new Exception( "Unexpected directory found in upload content! " + f.getAbsolutePath()); } } final StringBuffer noticeAppend = new StringBuffer(); final HashMap<String, String> pomSwaps = new HashMap<>(); pomSwaps.put("#VERSION#", version); pomSwaps.put("#SCM_URL#", GitPublish.constructChangesetRepositoryURL(gitRepositoryURL)); if (uploadType.getArtifactId().contains("*") && StringUtils.isBlank(extensionName)) { throw new Exception( "ExtensionName is required when the upload type artifact id contains a wildcard"); } pomSwaps.put("#GROUPID#", uploadType.getSourceUploadGroupId()); String temp = uploadType.getArtifactId(); if (temp.contains("*")) { temp = temp.replace("*", extensionName); } pomSwaps.put("#ARTIFACTID#", temp); pomSwaps.put("#NAME#", uploadType.getNiceName() + " Source Upload"); pomSwaps.put("#LICENSE#", uploadType.getLicenseInformation()[0]); // we only use the first license for source upload noticeAppend.append(uploadType.getNoticeInformation()[0]); // only use the first notice info final String tagWithoutRevNumber = pomSwaps.get("#GROUPID#") + "/" + pomSwaps.get("#ARTIFACTID#") + "/" + pomSwaps.get("#VERSION#"); LOG.debug("Desired tag (withoutRevNumber): {}", tagWithoutRevNumber); final ArrayList<String> existingTags = GitPublish.readTags(gitRepositoryURL, gitUsername, gitPassword); if (LOG.isDebugEnabled()) { LOG.debug("Currently Existing tags in '{}': {} ", gitRepositoryURL, Arrays.toString(existingTags.toArray(new String[existingTags.size()]))); } final int highestBuildRevision = GitPublish.readHighestRevisionNumber(existingTags, tagWithoutRevNumber); String tag; // Fix version number if (highestBuildRevision == -1) { // No tag at all - create without rev number, don't need to change our pomSwaps tag = tagWithoutRevNumber; } else { // If we are a SNAPSHOT, don't embed a build number, because nexus won't allow the upload, otherwise, embed a rev number if (!pomSwaps.get("#VERSION#").endsWith("SNAPSHOT")) { pomSwaps.put("#VERSION#", pomSwaps.get("#VERSION#") + "-" + (highestBuildRevision + 1)); } tag = tagWithoutRevNumber + "-" + (highestBuildRevision + 1); } LOG.info("Final calculated tag: '{}'", tag); pomSwaps.put("#SCM_TAG#", tag); FileUtil.writeFile("shared", "LICENSE.txt", baseFolder); FileUtil.writeFile("shared", "NOTICE.txt", baseFolder, null, noticeAppend.toString()); FileUtil.writeFile("srcUploadProjectTemplate", "native-source/DOTgitignore", baseFolder); FileUtil.writeFile("srcUploadProjectTemplate", "assembly.xml", baseFolder); FileUtil.writeFile("srcUploadProjectTemplate", "pom.xml", baseFolder, pomSwaps, ""); updateTitle("Publishing configuration to Git"); GitPublish.publish(baseFolder, gitRepositoryURL, gitUsername, gitPassword, tag); updateTitle("Zipping content"); LOG.debug("Zipping content"); final Zip z = new Zip(pomSwaps.get("#ARTIFACTID#"), pomSwaps.get("#VERSION#"), null, null, new File(baseFolder, "target"), nativeSource, false); final ArrayList<File> toZip = new ArrayList<>(); for (final File f : nativeSource.listFiles()) { if (f.getName().equals(".gitignore")) { // noop } else { toZip.add(f); } } z.getStatus().addListener( (ChangeListener<String>) (observable, oldValue, newValue) -> updateMessage(newValue)); z.getTotalWork().add(z.getWorkComplete()) .addListener((ChangeListener<Number>) (observable, oldValue, newValue) -> updateProgress(z.getWorkComplete().get(), z.getTotalWork().get())); // This blocks till complete final File zipFile = z.addFiles(toZip); LOG.info("Zip complete, publishing to artifact repo {}", artifactRepositoryURL); updateTitle("Publishing files to the Artifact Repository"); final MavenPublish pm = new MavenPublish(pomSwaps.get("#GROUPID#"), pomSwaps.get("#ARTIFACTID#"), pomSwaps.get("#VERSION#"), new File(baseFolder, "pom.xml"), new File[] { zipFile }, artifactRepositoryURL, repositoryUsername, repositoryPassword); pm.progressProperty().addListener((ChangeListener<Number>) (observable, oldValue, newValue) -> updateProgress(pm.getWorkDone(), pm.getTotalWork())); pm.messageProperty().addListener( (ChangeListener<String>) (observable, oldValue, newValue) -> updateMessage(newValue)); WorkExecutors.get().getExecutor().execute(pm); // block till upload complete pm.get(); updateTitle("Cleaning Up"); try { FileUtil.recursiveDelete(baseFolder); } catch (final Exception e) { LOG.error("Problem cleaning up temp folder " + baseFolder, e); } updateTitle("Complete"); return tag; } catch (final Throwable e) { LOG.error("Unexpected error", e); throw new RuntimeException(e); } finally { try { FileUtil.recursiveDelete(baseFolder); } catch (final Exception e) { LOG.error("Problem cleaning up temp folder " + baseFolder, e); } } } }; return uploader; }
From source file:org.mskcc.shenkers.control.track.bam.BamView1.java
@Override public Task<Pane> getContent(BamContext context) { return context.spanProperty().getValue().map(i -> { if (false) { SamReader reader = context.readerProperty().getValue(); int[] coverage = coverage(reader, i.getChr(), i.getStart(), i.getEnd()); String chr = i.getChr(); int start = i.getStart(); int end = i.getEnd(); PaneTask task = new PaneTask(context, chr, start, end); // LineHistogramView lhv = new LineHistogramView(); // lhv.setMin(0); // OptionalInt max = IntStream.of(coverage).max(); // max.ifPresent(m -> lhv.setMax(m)); // double[] data = ArrayUtils.toPrimitive(IntStream.of(coverage).mapToDouble(j -> j + 0.).boxed().collect(Collectors.toList()).toArray(new Double[0])); // lhv.setData(data); // logger.info("coverage {}", IntStream.of(coverage).mapToDouble(j -> j + 0.).boxed().collect(Collectors.toList()).toString()); }/* w ww .j a v a 2 s . c om*/ SamReader reader = context.readerProperty().getValue(); String chr = i.getChr(); int start = i.getStart(); int end = i.getEnd(); Task<Pane> task = new PaneTask(context, chr, start, end); // LineHistogramView lhv = new LineHistogramView(); // SamReader reader = context.readerProperty().getValue(); // // Pane content = get(reader, i.getChr(), i.getStart(), i.getEnd()); // Task<Pane> task = new BAMCoverageTask(lhv, reader, i.getChr(), i.getStart(), i.getEnd()); // start a background thread to load the track // logger.info("canceling"); // bcs.cancel(); // logger.info("reseting"); // bcs.reset(); // // logger.info("reading context"); // SamReader reader = context.readerProperty().getValue(); // logger.info("setting region"); // bcs.setRegion(reader, i.getChr(), i.getStart(), i.getEnd()); // // logger.info("starting service"); // bcs.start(); logger.info("returning task"); return task; }).orElse(new Task<Pane>() { @Override protected Pane call() throws Exception { return new BorderPane(new Label("bamview1: span not set")); } } // new BorderPane(new Label("bamview1: span not set")) // new Pane() ); }
From source file:herudi.controller.microMarketController.java
private void selectWithService() { Service<Integer> service = new Service<Integer>() { @Override/*from w w w.j a v a 2s . c om*/ protected Task<Integer> createTask() { selectData(); return new Task<Integer>() { @Override protected Integer call() throws Exception { Integer max = crud.selectData().size(); if (max > 35) { max = 30; } updateProgress(0, max); for (int k = 0; k < max; k++) { Thread.sleep(40); updateProgress(k + 1, max); } return max; } }; } }; service.start(); bar.progressProperty().bind(service.progressProperty()); service.setOnRunning((WorkerStateEvent event) -> { imgLoad.setVisible(true); }); service.setOnSucceeded((WorkerStateEvent event) -> { imgLoad.setVisible(false); new FadeInUpTransition(paneTabel).play(); }); }
From source file:slideshow.client.ui.ClientUIController.java
/** * Initializes FXML panel to default//from w w w .j a v a 2s . c o m * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { System.out.println("slideshow.client.ui.ClientUIController.initialize"); //Initializes members assert rootVBox != null : "fx:id=\"rootVBox\" was not injected: check your FXML file 'clientUI.fxml'."; assert songListView != null : "fx:id=\"songListView\" was not injected: check your FXML file 'clientUI.fxml'."; assert spotifyTextField != null : "fx:id=\"spotifyTextField\" was not injected: check your FXML file 'clientUI.fxml'."; assert spotifyLabel != null : "fx:id=\"spotifyLabel\" was not injected: check your FXML file 'clientUI.fxml'."; assert prevSongButton != null : "fx:id=\"prevSongButton\" was not injected: check your FXML file 'clientUI.fxml'."; assert playSongButton != null : "fx:id=\"playSongButton\" was not injected: check your FXML file 'clientUI.fxml'."; assert nextSongButton != null : "fx:id=\"nextSongButton\" was not injected: check your FXML file 'clientUI.fxml'."; assert fullscreenButton != null : "fx:id=\"fullScreenButton\" was not injected: check your FXML file 'clientUI.fxml'."; assert prevPhotoButton != null : "fx:id=\"prevPhotoButton\" was not injected: check your FXML file 'clientUI.fxml'."; assert nextPhotoButton != null : "fx:id=\"nextPhotoButton\" was not injected: check your FXML file 'clientUI.fxml'."; assert photoImageView != null : "fx:id=\"photoImageView\" was not injected: check your FXML file 'clientUI.fxml'."; assert imagePane != null : "fx:id=\"imagePane\" was not injected: check your FXML file 'clientUI.fxml'."; this.mMusic = new Music(); //load information try { System.out.println("Loading Local Directories"); this.mSongsLocal = loadDir(new File(this.getClass().getResource(this.DIRECTORY_MUSIC).toURI())); this.mPhotosLocal = loadDir(new File(this.getClass().getResource(this.DIRECTORY_PHOTOS).toURI())); ObservableList<String> songs = FXCollections.observableArrayList(this.mSongsLocal.keySet()); Collections.sort(songs); this.songListView.setItems(songs); //this.listProperty.set(FXCollections.observableArrayList(this.songsLocal.keySet())); } catch (URISyntaxException e) { System.out.println(e.getMessage()); } this.photoImageView.fitWidthProperty().bind(this.imagePane.widthProperty()); this.photoImageView.fitHeightProperty().bind(this.imagePane.heightProperty()); this.mConnectServer = new Task<Integer>() { @Override protected Integer call() throws Exception { ClientUIController.this.mConnect = new Connect(InetAddress.getLocalHost(), 6001); ClientUIController.this.mBufferedReader = new BufferedReader( new InputStreamReader(ClientUIController.this.mConnect.getSocket().getInputStream())); ClientUIController.this.mPhotoAddress = ClientUIController.this.mBufferedReader.readLine(); ClientUIController.this.photoImageView.setImage(new Image(ClientUIController.this.mPhotoAddress)); int iterations = 0; do { System.out.println("Fetching photo"); ClientUIController.this.mPhotoAddress = ClientUIController.this.mBufferedReader.readLine(); ClientUIController.this.photoImageView .setImage(new Image(ClientUIController.this.mPhotoAddress)); Thread.sleep(10000); } while (ClientUIController.this.mPhotoAddress != null); return 1; } }; Thread th = new Thread(this.mConnectServer); th.setDaemon(true); th.start(); }
From source file:com.QuarkLabs.BTCeClientJavaFX.PublicTradesController.java
@FXML void initialize() { assert publicTradesTable != null : "fx:id=\"publicTradesTable\" was not injected: check your FXML file 'markettrades.fxml'."; assert publicTradesTableAmountColumn != null : "fx:id=\"publicTradesTableAmountColumn\" was not injected: check your FXML file 'markettrades.fxml'."; assert publicTradesTableDateColumn != null : "fx:id=\"publicTradesTableDateColumn\" was not injected: check your FXML file 'markettrades.fxml'."; assert publicTradesTableItemColumn != null : "fx:id=\"publicTradesTableItemColumn\" was not injected: check your FXML file 'markettrades.fxml'."; assert publicTradesTablePriceColumn != null : "fx:id=\"publicTradesTablePriceColumn\" was not injected: check your FXML file 'markettrades.fxml'."; assert publicTradesTablePriceCurrencyColumn != null : "fx:id=\"publicTradesTablePriceCurrencyColumn\" was not injected: check your FXML file 'markettrades.fxml'."; assert publicTradesTableTIDColumn != null : "fx:id=\"publicTradesTableTIDColumn\" was not injected: check your FXML file 'markettrades.fxml'."; assert publicTradesTableTradeTypeColumn != null : "fx:id=\"publicTradesTableTradeTypeColumn\" was not injected: check your FXML file 'markettrades.fxml'."; publicTradesTable.setItems(publicTrades); publicTradesTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); publicTradesTableAmountColumn.setCellValueFactory(new PropertyValueFactory<PublicTrade, Double>("amount")); publicTradesTableDateColumn.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<PublicTrade, String>, ObservableValue<String>>() { @Override/* w w w.j av a 2 s . c om*/ public ObservableValue<String> call( TableColumn.CellDataFeatures<PublicTrade, String> publicTradeStringCellDataFeatures) { PublicTrade publicTrade = publicTradeStringCellDataFeatures.getValue(); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(publicTrade.getDate() * 1000); DateFormat dateFormat = DateFormat.getDateTimeInstance(); return new SimpleStringProperty(dateFormat.format(calendar.getTime())); } }); publicTradesTableItemColumn.setCellValueFactory(new PropertyValueFactory<PublicTrade, String>("item")); publicTradesTablePriceColumn.setCellValueFactory(new PropertyValueFactory<PublicTrade, Double>("price")); publicTradesTablePriceCurrencyColumn .setCellValueFactory(new PropertyValueFactory<PublicTrade, String>("priceCurrency")); publicTradesTableTIDColumn.setCellValueFactory(new PropertyValueFactory<PublicTrade, Long>("tid")); publicTradesTableTradeTypeColumn .setCellValueFactory(new PropertyValueFactory<PublicTrade, String>("tradeType")); Task<JSONArray> loadPublicTrades = new Task<JSONArray>() { @Override protected JSONArray call() throws Exception { return App.getPublicTrades(pair); } }; loadPublicTrades.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent workerStateEvent) { JSONArray jsonArray = (JSONArray) workerStateEvent.getSource().getValue(); publicTrades.clear(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject item = jsonArray.getJSONObject(i); PublicTrade publicTrade = new PublicTrade(); publicTrade.setDate(item.getLong("date")); publicTrade.setAmount(item.getDouble("amount")); publicTrade.setItem(item.getString("item")); publicTrade.setPrice(item.getDouble("price")); publicTrade.setPriceCurrency(item.getString("price_currency")); publicTrade.setTid(item.getLong("tid")); publicTrade.setTradeType(item.getString("trade_type")); publicTrades.add(publicTrade); } } }); Thread thread = new Thread(loadPublicTrades); thread.start(); }