Como lidar com o progresso do download do java web start (jnlp) em um pré-carregador?
Eu tenho um pré-carregador para o meu aplicativo que lida com a inicialização específica do aplicativo. Agora, estou tentando estender isso para que o pré-carregador também mostre o progresso dos JARs do aplicativo baixado.
TL; DRPor que o pré-carregador não está sendo carregado duranteFase 2, pois isso deve lidar com oPreloaderFx::handleProgressNotification();
rastrear o download dos JARs, suponho?
Atualização 14 de março de 2016: Usar o DownloadServiceListener é a maneira de resolver isso? Como conectar isso a um estágio JavaFX?
DocumentaçãoDe acordo com a Oracle, há quatro fases quando um aplicativo é iniciado:
Fase 1: Inicialização: Inicialização do Java Runtime e um exame inicial identifica componentes que devem ser carregados e executados antes de iniciar o aplicativo. Durante esta fase, uma tela inicial é mostrada. O padrão é este:Fase 2: Carregamento e preparação: Os recursos necessários são carregados da rede ou de um cache de disco e ocorrem procedimentos de validação. Todos os modos de execução veem o pré-carregador padrão ou personalizado. Durante esta fase, meu pré-carregador personalizado deve ser mostrado.
Fase 3: Inicialização específica do aplicativo: O aplicativo é iniciado, mas pode ser necessário carregar recursos adicionais ou executar outras preparações demoradas antes de ficar totalmente funcional. No momento, meu pré-carregador personalizado é mostrado:
Fase 4: execução do aplicativo: O aplicativo é exibido e está pronto para uso. No meu caso, uma janela de login é mostrada e o usuário pode prosseguir.O meu casoA primeira coisa que noto é que emFase 2, o pré-carregador JavaFX padrão que manipula o download dos JARs do aplicativo não está aparecendo. Por esse motivo, o usuário tem a sensação de que o programa não foi iniciado ou finalizado prematuramente, fazendo com que eles abram o arquivo JNLP várias vezes. Depois que os JARs são baixados, entramosFase 3 e o pré-carregador é mostrado.
No entanto, eu gostaria que meu pré-carregador personalizado também lidasse com o progresso do download no ProgressBar (Fase 2). Tornei tudo o mais simples possível para rastrear quais eventos estão acontecendo durante a inicialização do meu aplicativo. Isso é baseado em umexemplo de Jewelsea e emExemplos Oracle:
Pré-carregador:
public class PreloaderFX extends Preloader {
Stage stage;
//boolean noLoadingProgress = true;
public static final String APPLICATION_ICON
= "http://cdn1.iconfinder.com/data/icons/Copenhagen/PNG/32/people.png";
public static final String SPLASH_IMAGE
= "http://fxexperience.com/wp-content/uploads/2010/06/logo.png";
private Pane splashLayout;
private ProgressBar loadProgress;
private Label progressText;
private static final int SPLASH_WIDTH = 676;
private static final int SPLASH_HEIGHT = 227;
@Override
public void init() {
ImageView splash = new ImageView(new Image(
SPLASH_IMAGE
));
loadProgress = new ProgressBar();
loadProgress.setPrefWidth(SPLASH_WIDTH - 20);
progressText = new Label("Loading . . .");
splashLayout = new VBox();
splashLayout.getChildren().addAll(splash, loadProgress, progressText);
progressText.setAlignment(Pos.CENTER);
splashLayout.setStyle(
"-fx-padding: 5; "
+ "-fx-background-color: white; "
+ "-fx-border-width:5; "
);
splashLayout.setEffect(new DropShadow());
}
@Override
public void start(Stage stage) throws Exception {
System.out.println("PreloaderFx::start();");
//this.stage = new Stage(StageStyle.DECORATED);
stage.setTitle("Title");
stage.getIcons().add(new Image(APPLICATION_ICON));
stage.initStyle(StageStyle.UNDECORATED);
final Rectangle2D bounds = Screen.getPrimary().getBounds();
stage.setScene(new Scene(splashLayout));
stage.setX(bounds.getMinX() + bounds.getWidth() / 2 - SPLASH_WIDTH / 2);
stage.setY(bounds.getMinY() + bounds.getHeight() / 2 - SPLASH_HEIGHT / 2);
stage.show();
this.stage = stage;
}
@Override
public void handleProgressNotification(ProgressNotification pn) {
System.out.println("PreloaderFx::handleProgressNotification(); progress = " + pn.getProgress());
//application loading progress is rescaled to be first 50%
//Even if there is nothing to load 0% and 100% events can be
// delivered
if (pn.getProgress() != 1.0 /*|| !noLoadingProgress*/) {
loadProgress.setProgress(pn.getProgress() / 2);
/*if (pn.getProgress() > 0) {
noLoadingProgress = false;
}*/
}
}
@Override
public void handleStateChangeNotification(StateChangeNotification evt) {
//ignore, hide after application signals it is ready
System.out.println("PreloaderFx::handleStateChangeNotification(); state = " + evt.getType());
}
@Override
public void handleApplicationNotification(PreloaderNotification pn) {
if (pn instanceof ProgressNotification) {
//expect application to send us progress notifications
//with progress ranging from 0 to 1.0
double v = ((ProgressNotification) pn).getProgress();
System.out.println("PreloaderFx::handleApplicationNotification(); progress = " + v);
//if (!noLoadingProgress) {
//if we were receiving loading progress notifications
//then progress is already at 50%.
//Rescale application progress to start from 50%
v = 0.5 + v / 2;
//}
loadProgress.setProgress(v);
} else if (pn instanceof StateChangeNotification) {
System.out.println("PreloaderFx::handleApplicationNotification(); state = " + ((StateChangeNotification) pn).getType());
//hide after get any state update from application
stage.hide();
}
}
}
Código que está sendo tratadoFase 3 é do aplicativo principal que interage com o pré-carregador, é o que está sendo visto na barra de progresso:
public class MainApp extends Application {
BooleanProperty ready = new SimpleBooleanProperty(false);
public static void main(String[] args) throws Exception {
launch(args);
}
@Override
public void start(final Stage initStage) throws Exception {
System.out.println("MainApp::start();");
this.mainStage = initStage;
longStart();
ready.addListener((ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) -> {
if (Boolean.TRUE.equals(t1)) {
Platform.runLater(() -> {
System.out.println("MainApp::showMainStage();");
showMainStage();
});
}
});
}
private void longStart() {
//simulate long init in background
Task task = new Task<Void>() {
@Override
protected Void call() throws Exception {
int max = 10;
for (int i = 1; i <= max; i++) {
Thread.sleep(500);
System.out.println("longStart " + i);
// Send progress to preloader
notifyPreloader(new ProgressNotification(((double) i)/max)); //this moves the progress bar of the preloader
}
// After init is ready, the app is ready to be shown
// Do this before hiding the preloader stage to prevent the
// app from exiting prematurely
ready.setValue(Boolean.TRUE);
notifyPreloader(new StateChangeNotification(
StateChangeNotification.Type.BEFORE_START));
return null;
}
};
new Thread(task).start();
}
private void showMainStage() {
//showing the login window
}
}
JNLP
<jnlp spec="1.0+" xmlns:jfx="http://javafx.com" codebase="<***>/preloadertest/jnlp" href="launch.jnlp">
<information>
...
</information>
<resources>
<j2se version="1.6+" href="http://java.sun.com/products/autodl/j2se" />
... //whole bunch of JARS
<jar href="lib/preloader-1.1.1.jar" download="progress" />
</resources>
<security>
<all-permissions/>
</security>
<applet-desc width="1024" height="768" main-class="com.javafx.main.NoJavaFXFallback" name="JavaFX Client">
<param name="requiredFXVersion" value="8.0+"/>
</applet-desc>
<jfx:javafx-desc width="1024" height="768" main-class="GUI.MainApp" name="JavaFX Client" preloader-class="GUI.PreloaderFX" />
<update check="background"/>
</jnlp>
DepuraçãoEu observei atentamente o Java Console ao iniciar o arquivo (com o Show log ativado, o show tracing desativado) e observei o seguinte:
DuranteFase 2, nada aparece no console Java (o console fecha após esta fase)
DuranteFase 3, a seguinte saída é gerada (em uma nova janela do console):
PreloaderFx::start();
PreloaderFx::handleProgressNotification(); progress = 1.0
PreloaderFx::handleStateChangeNotification(); state = BEFORE_LOAD
PreloaderFx::handleStateChangeNotification(); state = BEFORE_INIT
PreloaderFx::handleStateChangeNotification(); state = BEFORE_START
MainApp::start();
MainApp::longstart();
longStart 1
PreloaderFx::handleApplicationNotification(); progress = 0.1
longStart 2
PreloaderFx::handleApplicationNotification(); progress = 0.2
longStart 3
PreloaderFx::handleApplicationNotification(); progress = 0.3
longStart 4
PreloaderFx::handleApplicationNotification(); progress = 0.4
longStart 5
PreloaderFx::handleApplicationNotification(); progress = 0.5
longStart 6
PreloaderFx::handleApplicationNotification(); progress = 0.6
longStart 7
PreloaderFx::handleApplicationNotification(); progress = 0.7
longStart 8
PreloaderFx::handleApplicationNotification(); progress = 0.8
longStart 9
PreloaderFx::handleApplicationNotification(); progress = 0.9
longStart 10
PreloaderFx::handleApplicationNotification(); progress = 1.0
MainApp::showMainStage();
PreloaderFx::handleApplicationNotification(); state = BEFORE_START
Atualizações 13 de março de 2016:
Ajustou o código para que o estágio passado no método seja usado em vez de criar um novo e comentou tudo relacionado aonoLoadingProgress
booleano (sugerido por nilatado)Adicionado alguns extrasSystem.out.println()
no MainAppSoluçãoAdição simples<jfx:javafx-runtime version="8.0+"/>
para o arquivo JNLP o corrigiu. Com essa linha adicionada, o pré-carregador mostra na Fase 2. Também tomei a liberdade de alterar oj2se version="1.6+"
paraj2se version="1.8+"
O resultado:
Os primeiros 50% são o manuseio dos downloads JAR. Isso é feito pelohandleProgressNotification()
método. Os segundos 50% são a inicialização real do MainApp (longstart()
que notifica o pré-carregador), feito pelohandleApplicationNotification()
.