Java Code Examples for javafx.concurrent.Task#setOnSucceeded()

The following examples show how to use javafx.concurrent.Task#setOnSucceeded() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UIUtils.java    From cute-proxy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Run a task with process dialog
 */
public static <T> void runTaskWithProcessDialog(Task<T> task, String failedMessage) {
    var progressDialog = new ProgressDialog();
    progressDialog.bindTask(task);

    task.setOnSucceeded(e -> Platform.runLater(progressDialog::close));
    task.setOnFailed(e -> {
        Platform.runLater(progressDialog::close);
        Throwable throwable = task.getException();
        logger.error(failedMessage, throwable);
        UIUtils.showMessageDialog(failedMessage + ": " + throwable.getMessage());
    });

    Thread thread = new Thread(task);
    thread.start();
    progressDialog.show();
}
 
Example 2
Source File: TimedUpdaterUtil.java    From Lipi with MIT License 6 votes vote down vote up
public static void callAfter(int mseconds, CallbackVisitor callback) {
    Task<Void> sleeper = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            try {
                Thread.sleep(mseconds);
            } catch (InterruptedException e) {
                ExceptionAlerter.showException(e);
            }
            return null;
        }
    };
    sleeper.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent event) {
            callback.call();
        }
    });
    new Thread(sleeper).start();
}
 
Example 3
Source File: URLContentCacheBase.java    From TweetwallFX with MIT License 6 votes vote down vote up
/**
 * Retrieves the cached content asyncronuously for {code urlString} and
 * passes it to {@code contentConsumer}. If no cached content exists the
 * content loaded and cached and then passed to {@code contentConsumer}.
 *
 * @param urlString the string of the URL content to get
 *
 * @param contentConsumer the Consumer processing the content
 */
public final void getCachedOrLoad(final String urlString, final Consumer<URLContent> contentConsumer) {
    Objects.requireNonNull(contentConsumer, "contentConsumer must not be null");
    final Task<URLContent> task = new Task<URLContent>() {

        @Override
        protected URLContent call() throws Exception {
            return getCachedOrLoadSync(urlString);
        }
    };

    task.setOnSucceeded(event
            -> contentConsumer.accept(task.getValue()));
    task.setOnFailed(event
            -> LOG.error(MESSAGE_LOAD_FAILED, cacheName, urlString, task.getException()));
    contentLoader.execute(task);
}
 
Example 4
Source File: SparkLineTileSkin.java    From tilesfx with Apache License 2.0 6 votes vote down vote up
private void smooth(final List<Double> DATA_LIST) {
    Task<Point[]> smoothTask = new Task<Point[]>() {
        @Override protected Point[] call() {
            return Helper.smoothSparkLine(DATA_LIST, minValue, maxValue, graphBounds, noOfDatapoints);
        }
    };
    smoothTask.setOnSucceeded(t -> {
        Point[] smoothedPoints = smoothTask.getValue();
        int lengthMinusOne = smoothedPoints.length - 1;
        sparkLine.getElements().clear();
        sparkLine.getElements().add(new MoveTo(smoothedPoints[0].getX(), smoothedPoints[0].getY()));
        for (int i = 1 ; i < lengthMinusOne ; i++) {
            sparkLine.getElements().add(new LineTo(smoothedPoints[i].getX(), smoothedPoints[i].getY()));
        }
        dot.setCenterX(smoothedPoints[lengthMinusOne].getX());
        dot.setCenterY(smoothedPoints[lengthMinusOne].getY());
    });
    Thread smoothThread = new Thread(smoothTask);
    smoothThread.setDaemon(true);
    smoothThread.start();
}
 
Example 5
Source File: ChatController.java    From JavaFX-Chat with GNU General Public License v3.0 6 votes vote down vote up
public synchronized void addAsServer(Message msg) {
    Task<HBox> task = new Task<HBox>() {
        @Override
        public HBox call() throws Exception {
            BubbledLabel bl6 = new BubbledLabel();
            bl6.setText(msg.getMsg());
            bl6.setBackground(new Background(new BackgroundFill(Color.ALICEBLUE,
                    null, null)));
            HBox x = new HBox();
            bl6.setBubbleSpec(BubbleSpec.FACE_BOTTOM);
            x.setAlignment(Pos.CENTER);
            x.getChildren().addAll(bl6);
            return x;
        }
    };
    task.setOnSucceeded(event -> {
        chatPane.getItems().add(task.getValue());
    });

    Thread t = new Thread(task);
    t.setDaemon(true);
    t.start();
}
 
Example 6
Source File: SearchablePaneController.java    From Everest with Apache License 2.0 5 votes vote down vote up
private void loadInitialItemsAsync() {
    Task<List<T>> entryLoader = new Task<List<T>>() {
        @Override
        protected List<T> call() {
            return loadInitialEntries();
        }
    };

    entryLoader.setOnSucceeded(e -> {
        try {
            List<T> entries = entryLoader.get();
            if (entries.size() == 0) {
                searchPromptLayer.setVisible(true);
                return;
            }

            for (T state : entries)
                addHistoryItem(state);
        } catch (InterruptedException | ExecutionException E) {
            LoggingService.logSevere("Task thread interrupted while populating HistoryTab.", E,
                    LocalDateTime.now());
        }
    });

    entryLoader.setOnFailed(e -> LoggingService.logWarning("Failed to load history.",
            (Exception) entryLoader.getException(), LocalDateTime.now()));

    MoreExecutors.directExecutor().execute(entryLoader);
}
 
Example 7
Source File: Controller.java    From everywhere with Apache License 2.0 5 votes vote down vote up
public void runIndex(ActionEvent e) {
    Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            executeIndex();
            return null;
        }
    };
    task.setOnSucceeded(event -> {
        tabPanel.getSelectionModel().select(0);
        indexLabel.setText("index finished!");
    });
    new Thread(task).start();
}
 
Example 8
Source File: GuiController.java    From Recaf with MIT License 5 votes vote down vote up
/**
 * Asynchronously load a workspace from the given file.
 *
 * @param path
 * 		Path to workspace file.
 * @param action
 * 		Additional action to run with success/fail result.
 */
public void loadWorkspace(Path path, Consumer<Boolean> action) {
	Task<Boolean> loadTask = loadWorkspace(path);
	MainWindow main = windows.getMainWindow();
	loadTask.messageProperty().addListener((n, o, v) -> main.status(v));
	loadTask.setOnRunning(e -> {
		// Clear current items since we want to load a new workspace
		main.clear();
		main.disable(true);
	});
	loadTask.setOnSucceeded(e -> {
		// Load success
		main.disable(false);
		if (action != null)
			action.accept(true);
		// Update recently loaded
		config().backend().onLoad(path);
		main.getMenubar().updateRecent();
		// Updated cached primary jar to support recompile
		getWorkspace().writePrimaryJarToTemp();
	});
	loadTask.setOnFailed(e -> {
		// Load failure
		main.status("Failed to open file:\n" + path.getFileName());
		main.disable(false);
		if (action != null)
			action.accept(false);
	});
	ThreadUtil.run(loadTask);
}
 
Example 9
Source File: Archivo.java    From archivo with GNU General Public License v3.0 5 votes vote down vote up
public void cleanShutdown() {
    if (!confirmTaskCancellation()) {
        return;
    }

    archiveHistory.save();
    saveWindowDimensions();

    int waitTimeMS = 100;
    int msLimit = 15000;
    if (archiveQueueManager.hasTasks()) {
        setStatusText("Exiting...");
        try {
            int msWaited = 0;
            archiveQueueManager.cancelAllArchiveTasks();
            while (archiveQueueManager.hasTasks() && msWaited < msLimit) {
                Thread.sleep(waitTimeMS);
                msWaited += waitTimeMS;
            }
        } catch (InterruptedException e) {
            logger.error("Interrupted while waiting for archive tasks to shutdown: ", e);
        }
    }

    boolean reportingCrashes = crashReportController.hasCrashReport() && getUserPrefs().getShareTelemetry();
    if (reportingCrashes) {
        setStatusText("Exiting...");
        Task<Void> crashReportTask = crashReportController.buildTask();
        crashReportTask.setOnSucceeded(event -> shutdown());
        crashReportTask.setOnFailed(event -> shutdown());
        Executors.newSingleThreadExecutor().submit(crashReportTask);
    } else {
        shutdown();
    }
}
 
Example 10
Source File: NSLMainController.java    From ns-usbloader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void initialize(URL url, ResourceBundle rb) {
    this.resourceBundle = rb;
    logArea.setText(rb.getString("tab3_Txt_GreetingsMessage")+" "+ NSLMain.appVersion+"!\n");
    if (System.getProperty("os.name").toLowerCase().startsWith("lin"))
        if (!System.getProperty("user.name").equals("root"))
            logArea.appendText(rb.getString("tab3_Txt_EnteredAsMsg1")+System.getProperty("user.name")+"\n"+rb.getString("tab3_Txt_EnteredAsMsg2") + "\n");

    logArea.appendText(rb.getString("tab3_Txt_GreetingsMessage2")+"\n");

    MediatorControl.getInstance().setController(this);

    if (AppPreferences.getInstance().getAutoCheckUpdates()){
        Task<List<String>> updTask = new UpdatesChecker();
        updTask.setOnSucceeded(event->{
            List<String> result = updTask.getValue();
            if (result != null){
                if (!result.get(0).isEmpty()) {
                    SettingsTabController.setNewVersionLink(result.get(0));
                    ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionAval"), resourceBundle.getString("windowTitleNewVersionAval") + ": " + result.get(0) + "\n\n" + result.get(1));
                }
            }
            else
                ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionUnknown"), resourceBundle.getString("windowBodyNewVersionUnknown"));
        });
        Thread updates = new Thread(updTask);
        updates.setDaemon(true);
        updates.start();
    }
}
 
Example 11
Source File: ADCUpdaterWindow.java    From arma-dialog-creator with MIT License 5 votes vote down vote up
public void loadTask(@NotNull Task<?> task, @Nullable EventHandler<WorkerStateEvent> succeedEvent) {
	getProgressBar().setProgress(-1);
	getLblStatus().setText("");
	task.exceptionProperty().addListener(taskExceptionPropertyListener);
	task.messageProperty().addListener(taskMessagePropertyListener);
	task.setOnSucceeded(succeedEvent);
	getProgressBar().progressProperty().bind(task.progressProperty());
	new Thread(task).start();
}
 
Example 12
Source File: LaTeXDraw.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
private void showSplash(final Stage initStage, final Task<Void> task) {
	final ProgressBar loadProgress = new ProgressBar();
	loadProgress.progressProperty().bind(task.progressProperty());

	final Pane splashLayout = new VBox();
	final Image img = new Image("res/LaTeXDrawSmall.png", 450, 250, true, true); //NON-NLS
	final ImageView splash = new ImageView(img);
	splashLayout.getChildren().addAll(splash, loadProgress);
	splashLayout.setEffect(new DropShadow());
	loadProgress.setPrefWidth(img.getWidth());

	task.setOnSucceeded(ignore -> {
		loadProgress.progressProperty().unbind();
		loadProgress.setProgress(1d);
		final FadeTransition fadeSplash = new FadeTransition(Duration.seconds(0.8), splashLayout);
		fadeSplash.setFromValue(1d);
		fadeSplash.setToValue(0d);
		fadeSplash.setOnFinished(evt -> {
			initStage.hide();
			mainStage.setIconified(false);
			mainStage.toFront();
		});
		fadeSplash.play();
	});

	final Scene splashScene = new Scene(splashLayout);
	initStage.setScene(splashScene);
	initStage.initStyle(StageStyle.UNDECORATED);
	initStage.getIcons().add(new Image("/res/LaTeXDrawIcon.png")); //NON-NLS
	initStage.centerOnScreen();
	initStage.toFront();
	initStage.show();
}
 
Example 13
Source File: Archivo.java    From archivo with GNU General Public License v3.0 5 votes vote down vote up
private void checkForUpdates() {
    Task<SoftwareUpdateDetails> updateCheck = new UpdateCheckTask();
    updateCheck.setOnSucceeded(event -> {
        SoftwareUpdateDetails update = updateCheck.getValue();
        if (update.isAvailable()) {
            logger.info("Update check: A newer version of {} is available!", APPLICATION_NAME);
            showUpdateDialog(update);
        } else {
            logger.info("Update check: This is the latest version of {} ({})", APPLICATION_NAME, APPLICATION_VERSION);
        }
    });
    updateCheck.setOnFailed(event -> logger.error("Error checking for updates: ", event.getSource().getException()));
    Executors.newSingleThreadExecutor().submit(updateCheck);
}
 
Example 14
Source File: RatingScreenController.java    From SmartCity-ParkingManagement with Apache License 2.0 5 votes vote down vote up
private void getUserIdAndOrder(){
	statusLabel.setText("Loading...");
	statusLabel.setVisible(true);
	Task<Void> getUserDetailsTask = new Task<Void>() {
           @Override
           protected Void call() throws Exception {	
           	while(userId == null){
           		
           	}
           	while(parkingOrder == null){
           		
           	}
           	return null;
        }
       };
      new Thread(getUserDetailsTask).start();
      
      progressIndicator.progressProperty().bind(getUserDetailsTask.progressProperty());
      progressIndicator.setVisible(true); 
      
      getUserDetailsTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
          @Override
          public void handle(WorkerStateEvent workerStateEvent) {
       	   headerLabel.setText("Please rate the quality of your last parking experience at " + parkingOrder.getParkingSlotId() + ".");
       	   submitButton.setDisable(false);
       	   progressIndicator.setVisible(false);
       	   statusLabel.setVisible(false);
          }
      });
}
 
Example 15
Source File: RcmController.java    From ns-usbloader with GNU General Public License v3.0 5 votes vote down vote up
private void smash(){
    statusLbl.setText("");
    if (MediatorControl.getInstance().getTransferActive()) {
        ServiceWindow.getErrorNotification(rb.getString("windowTitleError"), rb.getString("windowBodyPleaseFinishTransfersFirst"));
        return;
    }

    Task<Boolean> RcmTask;
    RadioButton selectedRadio = (RadioButton)rcmToggleGrp.getSelectedToggle();
    switch (selectedRadio.getId()){
        case "pldrRadio1":
            RcmTask = new RcmTask(payloadFPathLbl1.getText());
            break;
        case "pldrRadio2":
            RcmTask = new RcmTask(payloadFPathLbl2.getText());
            break;
        case "pldrRadio3":
            RcmTask = new RcmTask(payloadFPathLbl3.getText());
            break;
        case "pldrRadio4":
            RcmTask = new RcmTask(payloadFPathLbl4.getText());
            break;
        case "pldrRadio5":
            RcmTask = new RcmTask(payloadFPathLbl5.getText());
            break;
        default:
            return;
    }

    RcmTask.setOnSucceeded(event -> {
        if (RcmTask.getValue())
            statusLbl.setText(rb.getString("done_txt"));
        else
            statusLbl.setText(rb.getString("failure_txt"));
    });
    Thread RcmThread = new Thread(RcmTask);
    RcmThread.setDaemon(true);
    RcmThread.start();
}
 
Example 16
Source File: MainController.java    From MusicPlayer with MIT License 4 votes vote down vote up
public SubView loadView(String viewName) {
    try {
    	
    	boolean loadLetters;
    	boolean unloadLetters;
    	
    	switch (viewName.toLowerCase()) {
    	case "artists":
    	case "artistsmain":
    	case "albums":
    	case "songs":
    		if (subViewController instanceof ArtistsController
    			|| subViewController instanceof ArtistsMainController
    			|| subViewController instanceof AlbumsController
    			|| subViewController instanceof SongsController) {
    			loadLetters = false;
    			unloadLetters = false;
    		} else {
    			loadLetters = true;
    			unloadLetters = false;
    		}
    		break;
    	default:
    		if (subViewController instanceof ArtistsController
    			|| subViewController instanceof ArtistsMainController
    			|| subViewController instanceof AlbumsController
    			|| subViewController instanceof SongsController) {
    			loadLetters = false;
    			unloadLetters = true;
    		} else {
    			loadLetters = false;
    			unloadLetters = false;
    		}
    		break;
    	}
     
     final boolean loadLettersFinal = loadLetters;
     final boolean unloadLettersFinal = unloadLetters;
    	
        String fileName = viewName.substring(0, 1).toUpperCase() + viewName.substring(1) + ".fxml";
        
        FXMLLoader loader = new FXMLLoader(this.getClass().getResource(fileName));
        Node view = loader.load();
        
        CountDownLatch latch = new CountDownLatch(1);
        
        Task<Void> task = new Task<Void>() {
     	@Override protected Void call() throws Exception {
     		Platform.runLater(() -> {
     			Library.getSongs().stream().filter(x -> x.getSelected()).forEach(x -> x.setSelected(false));
     			subViewRoot.setVisible(false);
       	subViewRoot.setContent(view);
       	subViewRoot.getContent().setOpacity(0);
       	latch.countDown();
     		});
      	return null;
     	}
     };
     
     task.setOnSucceeded(x -> new Thread(() -> {
            try {
                latch.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Platform.runLater(() -> {
                subViewRoot.setVisible(true);
                if (loadLettersFinal) {
                    loadLettersAnimation.play();
                }
                loadViewAnimation.play();
            });
        }).start());
     
     Thread thread = new Thread(task);
        
        unloadViewAnimation.setOnFinished(x -> thread.start());
        
        loadViewAnimation.setOnFinished(x -> viewLoadedLatch.countDown());
        
        if (subViewRoot.getContent() != null) {
        	if (unloadLettersFinal) {
        		unloadLettersAnimation.play();
        	}
         unloadViewAnimation.play();
    	} else {
    		subViewRoot.setContent(view);
    		if (loadLettersFinal) {
    			loadLettersAnimation.play();
    		}
    		loadViewAnimation.play();
    	}
        
        subViewController = loader.getController();
        return subViewController;

    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
Example 17
Source File: MainScreenController.java    From SmartCity-ParkingManagement with Apache License 2.0 4 votes vote down vote up
@FXML
public void cancelOrderButtonClicked(ActionEvent event) throws Exception {
	PresentOrder order = futureOrdersTable.getSelectionModel().getSelectedItem();
	if (order == null){
		statusLabel.setText("No selection");
		statusLabel.setVisible(true);
		return;
	}
	if (order.getStartTime().getTime() - new Date().getTime() <=	4 * 60 * 60 * 1000){
		statusLabel.setText("You can't cancel a booking less than 4 hours before it starts");
		statusLabel.setVisible(true);
		return;
	}
	cancelOrderButton.setDisable(true);
	Task<Void> cancelOrderTask = new Task<Void>() {
           @Override
           protected Void call() throws Exception {	
           	DatabaseManager d = DatabaseManagerImpl.getInstance();
           	UserOrderManaging.cancleOrder(order, d);
           	return null;
        }
       };
      new Thread(cancelOrderTask).start();
      
      progressIndicator.progressProperty().bind(cancelOrderTask.progressProperty());
      progressIndicator.setVisible(true); 
      statusLabel.setVisible(false);
      
      cancelOrderTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
          @Override
          public void handle(WorkerStateEvent workerStateEvent) {
       	   progressIndicator.setVisible(false);	   
       	   
       	   int index = 0;
       	   ObservableList<PresentOrder> updatedFutureOrders = futureOrdersTable.getItems();
       	   for (PresentOrder p: updatedFutureOrders){
       		   if (p.getOrderId().equals(order.getOrderId())){
       			   updatedFutureOrders.remove(index);
       			   break;
       		   }
       		   index++;
       	   }
       	   cancelOrderButton.setDisable(false);
          }
      });
      
}
 
Example 18
Source File: PortLayerConfiguration.java    From trex-stateless-gui with Apache License 2.0 4 votes vote down vote up
private void handleStartIPv6Scan(ActionEvent actionEvent) {
    LogsController.getInstance().appendText(LogType.INFO, "Start scanning IPv6 neighbor hosts.");
    AsyncResponseManager.getInstance().muteLogger();
    AsyncResponseManager.getInstance().suppressIncomingEvents(true);


    boolean multicastEnabled = model.getMulticast();
    if (!multicastEnabled) {
        model.multicastProperty().setValue(true);
    }
    getIPv6NDService();
    startScanIpv6Btn.setDisable(true);
    ipv6Hosts.getItems().clear();
    ipv6Hosts.setPlaceholder(new Label("Scanning in progress..."));
    Task<Optional<Map<String, Ipv6Node>>> scanIpv6NeighborsTask = new Task<Optional<Map<String, Ipv6Node>>>() {
        @Override
        public Optional<Map<String, Ipv6Node>> call() {
            try {
                return Optional.of(iPv6NDService.scan(model.getIndex(), 10, null, null));
            } catch (ServiceModeRequiredException e) {
                AsyncResponseManager.getInstance().unmuteLogger();
                AsyncResponseManager.getInstance().suppressIncomingEvents(false);
                Platform.runLater(() -> {
                    ipv6Hosts.setPlaceholder(ipv6HostsDefaultPlaceholder);
                    LogsController.getInstance().appendText(LogType.ERROR, "Service mode is not enabled for port: " + model.getIndex() + ". Enable Service Mode in Control tab.");
                });
            }
            return Optional.empty();
        }
    };
    scanIpv6NeighborsTask.setOnSucceeded(e -> {
        AsyncResponseManager.getInstance().unmuteLogger();
        AsyncResponseManager.getInstance().suppressIncomingEvents(false);
        startScanIpv6Btn.setDisable(false);

        Optional<Map<String, Ipv6Node>> result = scanIpv6NeighborsTask.getValue();
        result.ifPresent((hosts) -> {
            ipv6Hosts.getItems().addAll(
                hosts.entrySet().stream()
                    .map(entry -> new IPv6Host(entry.getValue().getMac(), entry.getValue().getIp()))
                    .collect(Collectors.toList())
            );

            if (hosts.isEmpty()) {
                ipv6Hosts.setPlaceholder(ipv6HostsNotFoundPlaceholder);
            }
            LogsController.getInstance().appendText(LogType.INFO, "Found " + hosts.size() + " nodes.");
            LogsController.getInstance().appendText(LogType.INFO, "Scanning complete.");
        });

        if (!multicastEnabled) {
            model.multicastProperty().setValue(false);
        }
    });

    executorService.submit(scanIpv6NeighborsTask);
}
 
Example 19
Source File: ChooseParkingSlotController.java    From SmartCity-ParkingManagement with Apache License 2.0 4 votes vote down vote up
@FXML
public void continueButtonClicked(ActionEvent event) throws Exception{
		
	ParseGeoPoint point = getSelectedDestination();
	
   	LocalDate date = datePicker.getValue();
   	LocalTime arrivalTime = arrivalTimePicker.getValue();
   	LocalTime departureTime = departureTimePicker.getValue();
   	
   	if (date == null || arrivalTime == null || departureTime == null){
   		statusLabel.setText("You have to fill all the date and time fields");
   		statusLabel.setVisible(true);
   		return;
   	}
   			        	
   	Calendar arrivalDateTime = Calendar.getInstance();
   	arrivalDateTime.set(Calendar.YEAR, date.getYear());
   	arrivalDateTime.set(Calendar.MONTH, date.getMonthValue()-1);
   	arrivalDateTime.set(Calendar.DAY_OF_MONTH,date.getDayOfMonth());
   	arrivalDateTime.set(Calendar.HOUR_OF_DAY, arrivalTime.getHour());
   	arrivalDateTime.set(Calendar.MINUTE, roundMinutes(arrivalTime.getMinute(), false));
   	arrivalDateTime.set(Calendar.SECOND, 0);

   	if (!arrivalTime.isBefore(departureTime)){
   		statusLabel.setText("Departure time must be after your arrival time");
   		statusLabel.setVisible(true);
   		return;
   	}
   	orderButton.setDisable(true);
   	showRatingChartButton.setDisable(true);
   	showDistanceChartButton.setDisable(true);
   	continueButton.setDisable(true);
   	
   	statusLabel.setVisible(false);
   	engine.executeScript("reloadAux();");
   	slotsTable.getItems().clear();

       Task<List<PresentParkingSlot>> slotsTask = new Task<List<PresentParkingSlot>>() {
            @Override
            protected List<PresentParkingSlot> call() throws Exception {
            	
            	
            	DatabaseManager d = DatabaseManagerImpl.getInstance();
            	
	        	int departureMinutes = roundMinutes(departureTime.getMinute(), true);
	        	int quartersCounter = 0;
	        	if (departureMinutes == 60){
	        		quartersCounter = (departureTime.getHour() + 1)*4;
	        	} else {
	        		quartersCounter = departureTime.getHour()*4 + departureMinutes/15;
	        	}
	        	int diff = quartersCounter - (arrivalDateTime.get(Calendar.HOUR_OF_DAY)*4 + arrivalDateTime.get(Calendar.MINUTE)/15);
	        	request = new ParkingSlotRequest(point, arrivalDateTime.getTime(), diff, d);
	        	return request.getAllAvailableParkingSlot(new BasicBilling());

	        }
        };
        
       new Thread(slotsTask).start();
       
       progressIndicator.progressProperty().bind(slotsTask.progressProperty());
       progressIndicator.setVisible(true); 
       slotsTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
           @Override
           public void handle(WorkerStateEvent workerStateEvent) {
               	List<PresentParkingSlot> result = slotsTask.getValue();   //here you get the return value of your service
               	statusLabel.setVisible(false);
               	slotsTable.setItems(getSlots(result));
       			slotsTable.getColumns().setAll(idColumn, priceColumn, distanceColumn, ratingColumn);
       			for (PresentParkingSlot slot : result){
       				double distance = slot.getDistance();
       				slot.setDistance(Math.round(distance * 100.0) / 100.0);
       				double price = slot.getPrice();
       				slot.setPrice(Math.round(price * 100.0) / 100.0);
       				double rating = slot.getRating();
       				slot.setRating(Math.round(rating * 100.0) / 100.0);
       				engine.executeScript("addMarker(" + slot.getLat() + ", " + slot.getLon() + ", '" + slot.getName() + "');");
       			}
       			progressIndicator.setVisible(false);
       			engine.executeScript("firstRefresh();");
       			
       		   	orderButton.setDisable(false);
       		   	showRatingChartButton.setDisable(false);
       		   	showDistanceChartButton.setDisable(false);
       	    	continueButton.setDisable(false);
       			
       			if (result.size() != 0){
       				slotsTable.getSelectionModel().selectFirst();
       			} else {
       				statusLabel.setText("There are no available parking slots");
       	    		statusLabel.setVisible(true);
       	    		return;
       			}
       			
           }
       });

}
 
Example 20
Source File: ChooseParkingSlotController.java    From SmartCity-ParkingManagement with Apache License 2.0 4 votes vote down vote up
private void handleOrderTask(ActionEvent event, boolean result, String slotId, double price){
	    	
	if(result){
		
		Task<Void> sendingEmailTask = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
    			Map<String, Object> key = new HashMap<String, Object>();
    			key.put("id", userId);
    			Map<String, Object> map = DBManager.getObjectFieldsByKey("Driver", key);
    			String emailFromDb = (String)map.get("email");
    			Date endDate = new Date(request.getDate().getTime() + (request.getHoursAmount() * 15 * 60 * 1000));
            	EmailNotification.ParkingConfirmation(emailFromDb, slotId, request.getDate().toString(), endDate.toString(), price);
            	orderButton.setDisable(false);
            	showRatingChartButton.setDisable(false);
            	showDistanceChartButton.setDisable(false);
            	continueButton.setDisable(false);
            	backButton.setDisable(false);
        		return null;
	        }
        };
       new Thread(sendingEmailTask).start();
       
       progressIndicator.progressProperty().bind(sendingEmailTask.progressProperty());
       progressIndicator.setVisible(true); 
       
       sendingEmailTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
           @Override
           public void handle(WorkerStateEvent workerStateEvent) {
        	   try{
   				Stage window = (Stage) ((Node)event.getSource()).getScene().getWindow();
    			window.setTitle("Main Screen");
    			FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MainScreen.fxml"));     
    			Parent root = (Parent)fxmlLoader.load();          
    			MainScreenController controller = fxmlLoader.<MainScreenController>getController();
    			controller.setUserId(userId);
    			window.setScene(new Scene(root, ScreenSizesConstants.MainScreenWidth, ScreenSizesConstants.MainScreenHeight));		
    			window.show();   
        	   } catch(Exception e){
        		   
        	   }
           }
       });
      
	} else {

		   statusLabel.setText("The slot you choose got taken. Choose another one or search for new slots.");
		   statusLabel.setVisible(true);
       orderButton.setDisable(false);
       showRatingChartButton.setDisable(false);
       showDistanceChartButton.setDisable(false);
       continueButton.setDisable(false);
       backButton.setDisable(false);
	}
}