diff --git a/build.gradle b/build.gradle index 51ee670a1e93e115f183c48e7c58d4bbf2e54ec7..ac4696b5b41dc535f530471c6380cb36b55b9465 100644 --- a/build.gradle +++ b/build.gradle @@ -32,6 +32,7 @@ sourceSets.main { } } repositories { + maven { url "https://mvnrepository.com/" } mavenCentral() } @@ -47,8 +48,14 @@ description = 'Modular easy-installer' mainClassName = "$moduleName/ecorp.easy.installer.EasyInstaller" dependencies { + compile group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1' + compile 'ch.qos.logback:logback-classic:1.2.3' + compile 'ch.qos.logback:logback-core:1.2.3' + compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.30' compile 'org.yaml:snakeyaml:1.25' testCompile 'junit:junit:4.12' + + //compile 'org.slf4j:slf4j-log4j1:1.7.5' } // Application Configuration diff --git a/src/main/java/ecorp/easy/installer/EasyInstaller.java b/src/main/java/ecorp/easy/installer/EasyInstaller.java index 32bc0bf66e039de53c9acfa2955a926fc92f6625..ca6305f8a384ff957a877642151dc559d5685b5b 100644 --- a/src/main/java/ecorp/easy/installer/EasyInstaller.java +++ b/src/main/java/ecorp/easy/installer/EasyInstaller.java @@ -31,29 +31,29 @@ import javafx.scene.Scene; import javafx.scene.text.Font; import javafx.stage.Screen; import javafx.stage.Stage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * * @author Vincent Bourgmayer */ public class EasyInstaller extends Application { + private final static Logger logger = LoggerFactory.getLogger(EasyInstaller.class); public final static String FXML_PATH ="/fxml/"; private ResourceBundle i18n; //i18n mean "internationalization" - private MainWindowController controller; @Override public void start(Stage stage) throws Exception { - //four lines below are just for test - System.out.println("OS name: "+OsName); - System.out.println("Java Home: "+JavaHome); - System.out.println("Current working dir: "+Paths.get("").toAbsolutePath().toString()); - System.out.println("ADB folder path: "+AppConstants.getADBFolderPath() ); + + logger.debug("\nOS name = {}\nJava Home = {}\nCurrent working dir = {}\nADB folder path = {}", OsName, JavaHome, Paths.get("").toAbsolutePath().toString(), AppConstants.getADBFolderPath()); Locale currentLocale= Locale.getDefault(); - i18n = ResourceBundle.getBundle("lang.translation", currentLocale); + logger.debug("language = {}, country = {} ", currentLocale.getLanguage(), currentLocale.getCountry()); + //Load main view FXMLLoader loader = new FXMLLoader(getClass().getResource(FXML_PATH+"mainWindow.fxml")); loader.setResources(i18n); @@ -79,6 +79,8 @@ public class EasyInstaller extends Application { stage.setWidth(screenWidth); stage.setHeight(screenHeight); } + + logger.debug("Detected screen's size = {} x {}\nstage's size = {} x {}", screenWidth, screenHeight, stage.getWidth(), stage.getHeight()); //Display UI stage.show(); } @@ -93,7 +95,7 @@ public class EasyInstaller extends Application { @Override public void stop(){ - System.out.println("Stage is closing"); + logger.info("stage is closing"); // Save file controller.onStop(); } diff --git a/src/main/java/ecorp/easy/installer/controllers/MainWindowController.java b/src/main/java/ecorp/easy/installer/controllers/MainWindowController.java index cf4e6c8764390a570e3d77b4b3ea450d0486cc5b..9f0eca9c63a2d478bc6159773c615574374845ae 100644 --- a/src/main/java/ecorp/easy/installer/controllers/MainWindowController.java +++ b/src/main/java/ecorp/easy/installer/controllers/MainWindowController.java @@ -40,13 +40,15 @@ import javafx.fxml.FXMLLoader; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.scene.control.Button; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Main window Controller class * * @author Vincent Bourgmayer */ public class MainWindowController implements Initializable { - + private final static Logger logger = LoggerFactory.getLogger(MainWindowController.class); @FXML AnchorPane root; @FXML Button nextButton; @FXML Label titleLabel; @@ -64,6 +66,7 @@ public class MainWindowController implements Initializable { */ @Override public void initialize(URL url, ResourceBundle rb) { + logger.info("initialize()"); this.i18n = rb; disableNextButton(false); //just for test loadSubScene(); @@ -71,8 +74,8 @@ public class MainWindowController implements Initializable { fontSize.bind(root.widthProperty().add(root.heightProperty()).divide(123.2)); //72 = 1440 (default width): 20 (default font size). 51.2 = 1024 / 20 root.styleProperty().bind( - Bindings.concat("-fx-font-size: ", - fontSize.asString("%.0f")).concat("px;")); + Bindings.concat("-fx-font-size: ", fontSize.asString("%.0f")).concat("px;") + ); } @@ -126,7 +129,7 @@ public class MainWindowController implements Initializable { * Reset the handler for when next button is clicked */ public void resetNextButtonEventHandler(){ - System.out.println("ResetNextButtonEventHandler"); + logger.info("ResetNextButtonEventHandler()"); nextButton.setOnMouseClicked((MouseEvent event)->{ onNextBtnClick(); }); @@ -144,7 +147,7 @@ public class MainWindowController implements Initializable { * Load different group of controls depending of the current step (of whole process) */ public void loadSubScene(){ - System.out.println("loadSubScene("+currentSubRootId+")"); + logger.info("loadSubScene("+currentSubRootId+")"); if(currentSubRootId == null || currentSubRootId.isEmpty()){ currentSubRootId =loadSubUI("1-beforeYouBegin.fxml"); @@ -196,7 +199,7 @@ public class MainWindowController implements Initializable { Platform.exit(); break; default: - System.out.println("Invalid currentSubRootId"); + logger.error("Invalid currentSubRootId"); break; } } @@ -233,7 +236,6 @@ public class MainWindowController implements Initializable { * @return */ public FXMLLoader loadFXML(String fxmlName){ - System.out.println("loadFXML('"+fxmlName+"')"); FXMLLoader loader; try{ loader = new FXMLLoader(getClass().getResource(EasyInstaller.FXML_PATH+fxmlName)); @@ -242,7 +244,7 @@ public class MainWindowController implements Initializable { AbstractSubController ctrl = loader.getController(); if(ctrl != null) ctrl.setParentController(this); }catch(IOException e){ - e.printStackTrace(); + logger.error("fxmlName = {}, error = {}", fxmlName, e.toString()); return null; } return loader; @@ -253,7 +255,6 @@ public class MainWindowController implements Initializable { * @return subRoot. */ public String loadSubUI(String fxmlName){ - System.out.println("loadSubUI("+fxmlName+")"); FXMLLoader loader = loadFXML(fxmlName); Pane subRoot = (Pane) loader.getRoot(); root.getChildren().add(0, subRoot); //adding this element as first subNode, let other element like button to still be clickable on small screen @@ -289,7 +290,7 @@ public class MainWindowController implements Initializable { * It is in charge to close the opened flash or preparation Thread */ public void onStop(){ - System.out.println("onStop"); + logger.debug("onStop()"); if(this.thread != null){ thread.onCancelRequestRecieved(); } @@ -318,7 +319,7 @@ public class MainWindowController implements Initializable { throw new Exception("OS not supported"); //Not Supported OS } }catch(Exception e){ - e.printStackTrace(); + logger.error("url = {}, error = {}", url, e.toString()); } } diff --git a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/DeviceDetectedController.java b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/DeviceDetectedController.java index f922442756348dc751895b4d8b446dbf4cdca551..b6668c55b82adb8af6cfa77bec69565e4436db14 100644 --- a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/DeviceDetectedController.java +++ b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/DeviceDetectedController.java @@ -26,13 +26,14 @@ import javafx.concurrent.WorkerStateEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * * @author Vincent Bourgmayer */ public class DeviceDetectedController extends AbstractSubController{ - - + private final static Logger logger = LoggerFactory.getLogger(DeviceDetectedController.class); @FXML private Button buyNewDevice; @FXML private Button startDetectionButton; @FXML private Label detectionMsg; @@ -55,6 +56,7 @@ public class DeviceDetectedController extends AbstractSubController{ * Start the process of detection */ public void startDetection(){ + logger.info("startDetection()"); startDetectionButton.setManaged(false); startDetectionButton.setVisible(false); buyNewDevice.setVisible(false); @@ -92,7 +94,7 @@ public class DeviceDetectedController extends AbstractSubController{ new Thread(detectorTask).start(); } catch(Exception e){ - e.printStackTrace(); + logger.error("startDetection(), error: {}", e.toString()); //@TODO: handle Too many device Found Exception } } @@ -161,7 +163,7 @@ public class DeviceDetectedController extends AbstractSubController{ throw new Exception("OS not supported"); } }catch(Exception e){ - e.printStackTrace(); + logger.error("goToShop(), error: {}", e.toString()); } } } diff --git a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/DownloadSrcController.java b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/DownloadSrcController.java index 96db6c229efb9fa79c69d0038114902533c07566..698f80e0ae26e51701cf512d20fea3cbc6864ede 100644 --- a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/DownloadSrcController.java +++ b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/DownloadSrcController.java @@ -30,6 +30,8 @@ import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * FXML Controller class @@ -37,7 +39,7 @@ import javafx.scene.control.ProgressBar; * @author Vincent Bourgmayer */ public class DownloadSrcController extends AbstractSubController { - + private final static Logger logger = LoggerFactory.getLogger(DownloadSrcController.class); @FXML ProgressBar preparationProgressBar; @FXML Label progressLabel; @FXML Label progressTitle; @@ -66,7 +68,8 @@ public class DownloadSrcController extends AbstractSubController { private boolean startNextDownload(){ - System.out.println("taskIterator has next ? "+taskIterator.hasNext()); + logger.info("startNextDownload()"); + logger.debug("taskIterator has next ? {} "+taskIterator.hasNext()); if(taskIterator.hasNext()){ Map.Entry sources = taskIterator.next(); currentTask = new DownloadTask(sources.getKey(), sources.getValue(), i18n); @@ -93,9 +96,9 @@ public class DownloadSrcController extends AbstractSubController { progressLabel.textProperty().unbind(); progressTitle.textProperty().unbind(); preparationProgressBar.progressProperty().unbind(); - this.preparationProgressBar.getStyleClass().add("errorBar"); - System.out.println(eh.getSource().getException().toString()); - this.progressLabel.setText(i18n.getString("download_lbl_downloadError")); + preparationProgressBar.getStyleClass().add("errorBar"); + logger.error("startNextDownload(), error: {}", eh.getSource().getException().toString()); + progressLabel.setText(i18n.getString("download_lbl_downloadError")); restartDownloadBtn.setManaged(true); restartDownloadBtn.setVisible(true); }); diff --git a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/EAccountController.java b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/EAccountController.java index f55fde003c86895d2220d0f33b80d376c4f06607..7a7005ed29b4f3de5c279368f1c056213992176c 100644 --- a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/EAccountController.java +++ b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/EAccountController.java @@ -30,6 +30,8 @@ import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -37,6 +39,7 @@ import javafx.scene.layout.VBox; * This is the controller for eAccount.fxml */ public class EAccountController extends AbstractSubController{ + private static final Logger logger = LoggerFactory.getLogger(EAccountController.class); private static final String MAIL_REGEX="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"; private static final Pattern EMAIL_PATTERN = Pattern.compile(MAIL_REGEX); @@ -80,7 +83,7 @@ public class EAccountController extends AbstractSubController{ public void onCheckMailBtnClick(){ - System.out.println("Check Mail button clicked"); + logger.info("onCheckMailBtnClick"); final String userInput = mailInput.getText(); parentController.disableNextButton(true); if(!radioButton.isSelected()) radioButton.setSelected(true); diff --git a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/EnableADBController.java b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/EnableADBController.java index c5f7ce43ee001afe7fba81f4a13e986b05c0c981..44aab4a891b70e0f643867ce204db158bc88f93e 100644 --- a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/EnableADBController.java +++ b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/EnableADBController.java @@ -23,6 +23,8 @@ import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -31,7 +33,7 @@ import javafx.scene.image.ImageView; * @author Vincent */ public class EnableADBController extends AbstractSubSteppedController { - + private final static Logger logger = LoggerFactory.getLogger(EnableADBController.class); @FXML private Label firstSubStep; @FXML private Label secondSubStep; @FXML private Label thirdSubStep; @@ -52,11 +54,14 @@ public class EnableADBController extends AbstractSubSteppedController { } private void updateImage(){ - System.out.println("currentStepId= "+currentSubStepId); + logger.info("updateImage()"); + logger.debug("currentStepId= {}", currentSubStepId); + Image image; try{ image = new Image(this.parentController.getClass().getResourceAsStream("/images/enableADB"+(currentSubStepId+2)+".png")); }catch(Exception e){ + logger.warn("imageName = {}, error = {}", "/images/enableADB"+(currentSubStepId+2), e.toString()); image = null; } this.enableADBImg.setImage(image); diff --git a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/FeedbackController.java b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/FeedbackController.java index a8b3919bbadbb21848314aa1b4885aceb82cb968..fbd2ade97687a9ba864ae8695c435b812145ece4 100644 --- a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/FeedbackController.java +++ b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/FeedbackController.java @@ -30,6 +30,8 @@ import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.input.MouseEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -38,7 +40,7 @@ import javafx.scene.input.MouseEvent; * @author Vincent Bourgmayer */ public class FeedbackController extends AbstractSubController { - + private final static Logger logger = LoggerFactory.getLogger(FeedbackController.class); private @FXML Button sendAnswerBtn; private @FXML TextArea commentArea; private @FXML Label thanksLabel; @@ -54,10 +56,12 @@ public class FeedbackController extends AbstractSubController { parentController.setNextButtonText("feedback_btn_leave"); Device device = parentController.getDevice(); if(device != null){ - System.out.println("Device not null!"); + logger.debug("setParentController(), ParentController.getDevice() != null"); deviceModel = device.getModel()+", "+device.getDevice(); - }else - System.out.println("device is null"); + }else{ + logger.warn("setParentController(), parentController.getDevice() == null"); + } + } @@ -70,7 +74,7 @@ public class FeedbackController extends AbstractSubController { Button clickedButton = (Button) event.getSource(); if(clickedButton.equals(selectedFeelings)) { - System.out.println("Deselect: "+selectedFeelings.getId()); + logger.debug("onFeelingsSelected(), Deselect: {}", selectedFeelings.getId()); selectedFeelings.getStyleClass().remove(SELECTED_STYLE); selectedFeelings = null; } @@ -80,7 +84,7 @@ public class FeedbackController extends AbstractSubController { clickedButton.getStyleClass().add(SELECTED_STYLE); selectedFeelings = clickedButton; - System.out.println("Select:" +selectedFeelings.getId()); + logger.debug("onFeelingsSelected(), select: {}", selectedFeelings.getId()); } } @@ -99,19 +103,19 @@ public class FeedbackController extends AbstractSubController { sendAnswerBtn.setVisible(false); thanksLabel.setVisible(true); thanksLabel.setManaged(true); - System.out.println("sending feedback: success"); + logger.debug("onSendBtnClicked(), sending feedback: success"); } else{ //if failure sendAnswerBtn.setText(i18n.getString("feedback_btn_sendTryAgain")); sendAnswerBtn.setDisable(false); - System.out.println("sending feedback: failed"); + logger.error("onSendBtnClicked(), sending feedback: failure"); } }); uploadTask.setOnFailed(eh->{ sendAnswerBtn.setDisable(false); sendAnswerBtn.setText(i18n.getString("feedback_btn_sendTryAgain")); - System.out.println("sending feedback error: "+eh.getSource().getException().toString()); + logger.error("onSendBtnClicked(), sending feedback: failure, error: {}", eh.getSource().getException().toString()); }); new Thread(uploadTask).start(); @@ -133,7 +137,7 @@ public class FeedbackController extends AbstractSubController { out.write("\nComment: \n"+this.commentArea.getText()); } catch (IOException e) { - System.err.println(e); + logger.error("createAnswerFile()\n answerFilePath = {}\n error: {}", answerFilePath, e.toString()); return null; } return answerFilePath; diff --git a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/FlashSceneController.java b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/FlashSceneController.java index 5ddb8c28eca790c544e8f36267383f9018a952d2..bc10744aa68d0944e5e992349f4c7768648af86d 100644 --- a/src/main/java/ecorp/easy/installer/controllers/subcontrollers/FlashSceneController.java +++ b/src/main/java/ecorp/easy/installer/controllers/subcontrollers/FlashSceneController.java @@ -16,10 +16,13 @@ */ package ecorp.easy.installer.controllers.subcontrollers; +import ch.qos.logback.classic.LoggerContext; import ecorp.easy.installer.AppConstants; import ecorp.easy.installer.controllers.MainWindowController; import ecorp.easy.installer.graphics.FlashGlobalProgressManager; import ecorp.easy.installer.helpers.DeviceHelper; +import ecorp.easy.installer.logger.GUIAppender; +import ecorp.easy.installer.logger.LogPathPropertyDefiner; import ecorp.easy.installer.models.DataBundle; import ecorp.easy.installer.threads.EasilyCancelable; import ecorp.easy.installer.threads.FlashThread; @@ -44,6 +47,8 @@ import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.TextFlow; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * FXML Controller class @@ -76,12 +81,13 @@ public class FlashSceneController extends AbstractSubSteppedController implement ResourceBundle instructionsImagesBundle; //Give access to image to loads with instructionsKey private FlashThread thread; private Object pauseLock; //lock used for pausing the FlashThread - + private final static Logger logger = LoggerFactory.getLogger(FlashSceneController.class); @Override public void initialize(URL location, ResourceBundle resources) { super.initialize(location, resources); + logger.debug("Initialize FlashSceneController.java"); sendLogBtn.managedProperty().bind(sendLogBtn.visibleProperty()); loadStepProgressIndicator.managedProperty().bind(loadStepProgressIndicator.visibleProperty()); @@ -153,7 +159,8 @@ public class FlashSceneController extends AbstractSubSteppedController implement */ @Override public void onStepStart(DataBundle db) { - System.out.println("onStepStart"); + logger.info("onStepStart()"); + logger.debug(" DataBundle = {}", db.toString()); if(db == null)return; if(timer != null){ @@ -177,6 +184,7 @@ public class FlashSceneController extends AbstractSubSteppedController implement try{ this.instructionImage.setImage(new Image(getClass().getResourceAsStream("/images/"+instructionsImagesBundle.getString(instructionImgName)))); }catch (Exception e) { + logger.warn("onStepStart(), image key = {}, error = {}", instructionImgName, e.toString()); this.instructionImage.setImage(null); } } @@ -225,10 +233,11 @@ public class FlashSceneController extends AbstractSubSteppedController implement * @param db */ private void onLoadStepType(DataBundle db){ + logger.info("onLoadStepType()"); instructionsVBox.setAlignment(Pos.CENTER); parentController.setNextButtonVisible(false); int averageTime = db.getInt("averageTime"); - System.out.println("averageTime is: "+averageTime); + logger.debug("averageTime = {} ", averageTime); if(averageTime > -1){ //Or > 0 ? timer = new TimerTask(averageTime, this); loadStepProgressIndicator.setProgress(0.0); //Reset to prevent showing last value @@ -271,13 +280,15 @@ public class FlashSceneController extends AbstractSubSteppedController implement */ @Override public void onFlashError(DataBundle db) { - System.out.println("onFlashError"); - + logger.warn("onFlashError()"); String errorMsgKey = db.getString("errorMsgKey"); + if(errorMsgKey == null || errorMsgKey.isEmpty() || !i18n.containsKey(errorMsgKey)) errorMsgKey ="script_error_unknown"; stepTitleLabel.setText(i18n.getString(errorMsgKey)); + logger.debug("errorMsgKey = {}", errorMsgKey); + instructionsFlow.setManaged(false); instructionsFlow.setVisible(false); sendLogBtn.setVisible(true); @@ -296,7 +307,7 @@ public class FlashSceneController extends AbstractSubSteppedController implement */ @Override public void onFlashThreadEnd(DataBundle db) { - System.out.println("onFlashThreadEnd"); + logger.info("onFlashThreadEnd()"); stepTitleLabel.setText("FlashEnd"); } @@ -307,7 +318,7 @@ public class FlashSceneController extends AbstractSubSteppedController implement */ @Override public void onFlashStop(DataBundle db) { - System.out.println("onFlashStop"); + logger.info("onFlashStop()"); //flashStepTitleLabel.setText("Stopped"); if(timer != null){ timer.cancel(); @@ -339,13 +350,23 @@ public class FlashSceneController extends AbstractSubSteppedController implement * enable/disable log displaying */ public void showHideLog(){ + ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + GUIAppender appender = (GUIAppender) rootLogger.getAppender("GUI"); + + String text = showHideLogBtn.getText(); if(text.equals(">")){ showHideLogBtn.setText("V"); logScrollPane.setVisible(false); + + logFlow.getChildren().clear(); + appender.setContainer(null); }else{ showHideLogBtn.setText(">"); logScrollPane.setVisible(true); + + logFlow.getChildren().addAll(appender.getLogsList()); + appender.setContainer(logFlow); } } @@ -355,7 +376,7 @@ public class FlashSceneController extends AbstractSubSteppedController implement */ public boolean sendLogToSupport(){ if(thread != null){ - String filePath = thread.createLogFile(); + String filePath = LogPathPropertyDefiner.getLogFilePath(); if(filePath != null){ UploadToEcloudTask uploadTask = new UploadToEcloudTask(AppConstants.LOG_STORAGE_URL, filePath); @@ -363,17 +384,17 @@ public class FlashSceneController extends AbstractSubSteppedController implement if( (Boolean) eh.getSource().getValue() ){ //if success sendLogBtn.setDisable(true); sendLogBtn.setText(i18n.getString("install_btn_sendLogSuccess")); - System.out.println("sending log: success"); + logger.info("sendLogToSupport(), sending log: success"); } else{ sendLogBtn.setText(i18n.getString("install_btn_sendLogAgain")); - System.out.println("sending log: failed"); + logger.warn("sendLogToSupport(), sending log: failure"); } }); uploadTask.setOnFailed(eh->{ sendLogBtn.setText(i18n.getString("install_btn_sendLogAgain")); - System.out.println("sending log error: "+eh.getSource().getException().toString()); + logger.warn("sendLogToSupport(), sending log: failure, error = {}",eh.getSource().getException().toString() ); }); new Thread(uploadTask).start(); @@ -426,7 +447,10 @@ public class FlashSceneController extends AbstractSubSteppedController implement Image img; try{ img = new Image(getClass().getResourceAsStream("/images/"+instructionsImagesBundle.getString(instruction))); - }catch(Exception e){ img = null; } + }catch(Exception e){ + logger.warn("onNextButtonClicked(), image key = {}, error = {}", instruction, e.toString()); + img = null; + } instructionImage.setImage(img); break; diff --git a/src/main/java/ecorp/easy/installer/logger/FlashLogger.java b/src/main/java/ecorp/easy/installer/logger/FlashLogger.java deleted file mode 100644 index cc16fa15afc5de7ee259729b240e19848995a756..0000000000000000000000000000000000000000 --- a/src/main/java/ecorp/easy/installer/logger/FlashLogger.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2019-2020 - ECORP SAS - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package ecorp.easy.installer.logger; - -import ecorp.easy.installer.AppConstants; -import ecorp.easy.installer.utils.IFlashHandler; -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.UUID; -import javafx.application.Platform; - -/** - * - * @author vincent Bourgmayer - */ -public class FlashLogger{ - private final StringBuilder logs; - private final IFlashHandler displayOutput; - - public FlashLogger(IFlashHandler output){ - super(); - this.displayOutput = output; - this.logs = new StringBuilder(); - } - - - public void writeLine(String log) { - this.logs.append(log); - Platform.runLater( () -> { - displayOutput.onLogToDisplayRecieved(log); - }); - } - - /** - * Write all the log content into a file - * @return The absolute path to the file or null if there is an error during writing - */ - public String writeTofile() { - System.out.println("FlashLogger.writeLogToFile()"); - //generate unique file name thanks to UUID: - //https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/UUID.html#randomUUID() - String fileNameToHash=UUID.randomUUID()+".log"; - String logFilePath = AppConstants.getWritableFolder()+fileNameToHash; - try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(logFilePath, true)))) { - out.write(logs.toString()); - } catch (IOException e) { - System.err.println(e); - return null; - } - return logFilePath; - } - - /** - * Write content of log into a file. - * @param logFilePath path to the local file - * @param log the String to write into a file - */ - public void writeTofile(String logFilePath, String log) { - System.out.println("write log to file"); - try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(logFilePath, true)))) { - out.println(log); - } catch (IOException e) { - System.err.println(e); - } - } - - /** - * Write a String in the StringBuilder for specified API - * @param log The text to write in Log - */ - public void write(String log) { - if(log != null && ! log.isEmpty()) - this.logs.append(log); - } -} diff --git a/src/main/java/ecorp/easy/installer/logger/GUIAppender.java b/src/main/java/ecorp/easy/installer/logger/GUIAppender.java new file mode 100644 index 0000000000000000000000000000000000000000..9c9f99a596b19585c441eb869605008d2cfa47c2 --- /dev/null +++ b/src/main/java/ecorp/easy/installer/logger/GUIAppender.java @@ -0,0 +1,56 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ecorp.easy.installer.logger; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.ArrayList; +import javafx.scene.Node; +import javafx.scene.control.Label; +import javafx.scene.text.Text; +import javafx.scene.text.TextFlow; + +/** + * + * @author vincent + */ +public class GUIAppender extends AppenderBase{ + private ArrayList logsList= new ArrayList<>(); + private TextFlow container; + + @Override + protected void append(ILoggingEvent e) { + if(logsList.size() > 100){ + logsList.remove(0); + } + Text txt = buildLabel(e); + logsList.add(txt); + + //side effect + displayLog(txt); + } + + public synchronized void setContainer(TextFlow container){ + this.container = container; + } + + + private synchronized void displayLog(Text text){ + if(container != null){ + container.getChildren().add(text); + } + } + private Text buildLabel(ILoggingEvent e){ + + Text result = new Text(e.getFormattedMessage()+"\n"); + return result; + } + + + public ArrayList getLogsList() { + return logsList; + } +} diff --git a/src/main/java/ecorp/easy/installer/logger/LogPathPropertyDefiner.java b/src/main/java/ecorp/easy/installer/logger/LogPathPropertyDefiner.java new file mode 100644 index 0000000000000000000000000000000000000000..a3b32c4f98a6ab03a8eecea9c9f5fe5f5c3597fb --- /dev/null +++ b/src/main/java/ecorp/easy/installer/logger/LogPathPropertyDefiner.java @@ -0,0 +1,36 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ecorp.easy.installer.logger; + +import ch.qos.logback.core.PropertyDefinerBase; +import ecorp.easy.installer.AppConstants; +import java.util.UUID; + +/** + * + * @author vincent + */ +public class LogPathPropertyDefiner extends PropertyDefinerBase{ + private static final String logFilePath = AppConstants.getWritableFolder()+UUID.randomUUID()+".log"; + + + /** + * This is access for logback.xml + * @return + */ + @Override + public String getPropertyValue() { + return logFilePath; + } + + /** + * This is access for FlashSceneController.java + * @return + */ + public static String getLogFilePath(){ + return logFilePath; + } +} diff --git a/src/main/java/ecorp/easy/installer/models/Command.java b/src/main/java/ecorp/easy/installer/models/Command.java index 782947be6829e72c997daee74e0abf27cc601d81..5e6cf95c3f80b07d52de66c567a381ee7bfbe2a8 100644 --- a/src/main/java/ecorp/easy/installer/models/Command.java +++ b/src/main/java/ecorp/easy/installer/models/Command.java @@ -22,6 +22,8 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author Vincent Bourgmayer @@ -34,10 +36,11 @@ public class Command { private String shellOutput; //The shell text output of the execution of the script Process pc; //Process which run the command Step step; //Object which contain data about the command like next step, ... - + private final static Logger logger = LoggerFactory.getLogger(Command.class); /** * Constructor for instance in context of FlashThread + * @param runScriptCmd * @param step */ @@ -118,7 +121,7 @@ public class Command { }); } - System.out.println("Splitted command: "+sb.toString()); + logger.debug("getFinalCmd(), Splitted command = {}", sb.toString()); return sb.toString().split(" "); } @@ -129,13 +132,13 @@ public class Command { */ public void execAndReadOutput() throws IOException, InterruptedException{ - System.out.println("execAndReadOutput() : "+this.command); + logger.debug("execAndReadOutput(), command string = {} ", this.command); ProcessBuilder pb = new ProcessBuilder(getFinalCmd()); pb.redirectErrorStream(true); pc= pb.start(); - System.out.println("Process started"); + logger.info("Command's Process started"); InputStream stdout = pc.getInputStream(); InputStreamReader isr = new InputStreamReader (stdout); BufferedReader br = new BufferedReader(isr); @@ -147,12 +150,12 @@ public class Command { line = br.readLine(); if( line != null && !line.equals("null") ){ sb.append("\n\n").append(line); - System.out.println("\n"+line); + logger.debug("\n (debug)"+line); } } this.exitValue = pc.exitValue(); }catch(IOException e){ - System.out.println(e.toString() ); + logger.error("execAndReadOutput(), error = {}", e.toString() ); this.exitValue = -1; } br.close(); @@ -165,7 +168,7 @@ public class Command { } public void cancel(){ - System.out.println("Command.cancel()"); + logger.info("cancel()"); this.cancelled = true; if(pc != null && pc.isAlive()) pc.destroy(); diff --git a/src/main/java/ecorp/easy/installer/models/Step.java b/src/main/java/ecorp/easy/installer/models/Step.java index fcff86ae231e52e96665326a6dabae728d40829b..067200d0ca15b38540cf13d31d9984468064c03d 100644 --- a/src/main/java/ecorp/easy/installer/models/Step.java +++ b/src/main/java/ecorp/easy/installer/models/Step.java @@ -24,7 +24,7 @@ import java.util.Map; */ public class Step { private StepUi ui; - private boolean startNewThread = false; //define if a new thread should be started if this command succeeds + private boolean startNewThread = false; //@TODO REMOVE! define if a new thread should be started if this command succeeds private String script; //script's file script private String output; //Key of output to store as common parameter private String afterSuccess; // index of next script if succeed diff --git a/src/main/java/ecorp/easy/installer/threads/AskAccountTask.java b/src/main/java/ecorp/easy/installer/threads/AskAccountTask.java index 21a1828f7ff030e82c7d265aadf0f9fc956236eb..dc9245981cb9d7de8f821f34e512034a2e136776 100644 --- a/src/main/java/ecorp/easy/installer/threads/AskAccountTask.java +++ b/src/main/java/ecorp/easy/installer/threads/AskAccountTask.java @@ -27,12 +27,14 @@ import java.net.http.HttpResponse; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * * @author vincent Bourgmayer */ public class AskAccountTask extends Task{ - + private final static Logger logger = LoggerFactory.getLogger(AskAccountTask.class); String email; String sugar; /** @@ -58,7 +60,7 @@ public class AskAccountTask extends Task{ HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - System.out.println(response.body()); + logger.debug("call(), response.body() = {}",response.body() ); return response.body(); } diff --git a/src/main/java/ecorp/easy/installer/threads/DeviceDetectionTask.java b/src/main/java/ecorp/easy/installer/threads/DeviceDetectionTask.java index 435522e8aff5ce10bd1ff9fab9714bc3a55ed7e1..47b913fcca26ba2ce7aa03968370999626476f58 100644 --- a/src/main/java/ecorp/easy/installer/threads/DeviceDetectionTask.java +++ b/src/main/java/ecorp/easy/installer/threads/DeviceDetectionTask.java @@ -22,6 +22,8 @@ import ecorp.easy.installer.models.Command; import ecorp.easy.installer.models.Device; import javafx.concurrent.Task; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -29,6 +31,8 @@ import javafx.concurrent.Task; */ public class DeviceDetectionTask extends Task{ final String CMD_adbDevices = "devices"; + private final static Logger logger = LoggerFactory.getLogger(DeviceDetectionTask.class); + @Override protected Device call() throws Exception{ @@ -37,7 +41,7 @@ public class DeviceDetectionTask extends Task{ detectedDevice = runAdbDevicesCmd(AppConstants.getADBFolderPath()+"adb"); if(detectedDevice != null){ - System.out.println("Device found"); + logger.debug("call(), result: Device found"); } return detectedDevice; } @@ -49,7 +53,7 @@ public class DeviceDetectionTask extends Task{ * @throws Exception */ private Device runAdbDevicesCmd(String baseCmdString) throws Exception{ - System.out.println("runADBDevicesCmd()"); + logger.info("runADBDevicesCmd({})", baseCmdString); Command cmd = new Command(baseCmdString); cmd.addParameter("1", CMD_adbDevices); @@ -59,9 +63,9 @@ public class DeviceDetectionTask extends Task{ Device detectedDevice = null; String[] outputs = cmd.getShellOutput().split("\\R"); - System.out.println("raw shell outputs: "+cmd.getShellOutput()); + logger.debug(" raw shell outputs = {} ", cmd.getShellOutput()); if(outputs.length <=1){ - System.out.println("Waiting"); + logger.info(" Waiting"); Thread.sleep(2250); return null; } @@ -74,11 +78,11 @@ public class DeviceDetectionTask extends Task{ } } if(counter > 1){ - System.out.println("Too many devices detected"); + logger.info(" Too many devices detected"); throw new TooManyDevicesException(counter); } if(detectedDevice==null) { - System.out.println("waiting"); + logger.info(" waiting"); Thread.sleep(2250); } return detectedDevice; @@ -92,7 +96,7 @@ public class DeviceDetectionTask extends Task{ * @return the adb's device's id if found else it return empty string */ private Device checkAdbDevicesResult(String resultLine){ - System.out.println("checkAdbDevicesResult("+resultLine+")"); + logger.debug("checkAdbDevicesResult({})", resultLine); boolean deviceFound = false; Device result = null; @@ -101,24 +105,24 @@ public class DeviceDetectionTask extends Task{ //loop over each subString for(String stringPart : datas){ - System.out.println("Current subString : "+stringPart); + logger.debug(" Current subString : "+stringPart); //Detect the line that says that device is found if(!stringPart.isEmpty() && (stringPart.endsWith("device") ||stringPart.endsWith("recovery") ) ){ - System.out.println("Device has been found"); + logger.info(" Device has been found"); deviceFound = true; result = new Device(datas[0]); //get adb id } //Read data and store them in Device object if(deviceFound){ if(stringPart.contains("product:")){ - System.out.println("\"product\" keyword has been found"); + logger.debug(" \"product\" keyword has been found"); result.setName(stringPart.substring("product:".length() )); }else if(stringPart.contains("model:")){ - System.out.println("\"model\" keyword has been found"); - result.setModel(stringPart.substring("model:".length() )); + logger.debug(" \"model\" keyword has been found"); + result.setModel(stringPart.substring("model:".length() )); }else if(stringPart.contains("device:")){ - System.out.println("\"device\" keyword has been found"); - result.setDevice(stringPart.substring("device:".length() )); + logger.debug(" \"device\" keyword has been found"); + result.setDevice(stringPart.substring("device:".length() )); } } } diff --git a/src/main/java/ecorp/easy/installer/threads/DownloadTask.java b/src/main/java/ecorp/easy/installer/threads/DownloadTask.java index 9ea77e47355bca6a61803151c3e28fae3e0e96ea..158686209790c779bfee71fd84a997226e7af35c 100644 --- a/src/main/java/ecorp/easy/installer/threads/DownloadTask.java +++ b/src/main/java/ecorp/easy/installer/threads/DownloadTask.java @@ -35,12 +35,15 @@ import java.text.DecimalFormat; import java.util.ResourceBundle; import java.util.Scanner; import javafx.concurrent.Task; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * this class verify the checksum of a file and download it * @author vincent Bourgmayer */ public class DownloadTask extends Task{ + private final static Logger logger = LoggerFactory.getLogger(DownloadTask.class); /** * Constante taille */ @@ -215,7 +218,7 @@ public class DownloadTask extends Task{ * @throws IOException */ private boolean validChecksum( String fileChecksum) throws NoSuchAlgorithmException, IOException{ - System.out.println("ValidChecksum("+fileChecksum+")"); + logger.debug("validChecksum("+fileChecksum+")"); updateMessage(i18n.getString("download_lbl_checkingIntegrity")); //get file containing checksum File sumFile = new File(fileChecksum); @@ -227,9 +230,8 @@ public class DownloadTask extends Task{ } //read content of file containing checksum to extract hash and filename - System.out.println("fileChecksum: "+fileChecksum); String checksumLine = readChecksumFile(fileChecksum); - System.out.println("ChecksumLine : "+checksumLine); + logger.debug(" ChecksumLine = "+checksumLine); String[] splittedLine = checksumLine.split("\\s+"); //get file of the hash @@ -237,7 +239,7 @@ public class DownloadTask extends Task{ File file = new File(AppConstants.getSourcesFolderPath()+splittedLine[1]); if(!file.exists()){ updateMessage(i18n.getString("download_lbl_localFileNotFound")); - System.out.println(splittedLine[1]+" do not exists"); + logger.debug(" "+splittedLine[1]+" do not exists"); return false; } @@ -258,7 +260,7 @@ public class DownloadTask extends Task{ String fileHash = sb.toString(); - System.out.println(fileHash+" vs "+splittedLine[0]); + logger.debug("compare hash: "+fileHash+" vs "+splittedLine[0]); return fileHash.equals(splittedLine[0]); } @@ -287,17 +289,17 @@ public class DownloadTask extends Task{ try{ Thread.sleep(timeout); if(!stop && currentTime == previousTime){ - System.out.println("No updates"); + logger.info("No updates"); //updateProgress & updateMessage are methos of DownloadTask.java updateProgress(-1, 1); updateMessage(i18n.getString("download_lbl_connectionLost")); } }catch(Exception e){ stop = true; - System.out.println("TimeoutThread crashed: "+e.toString()); + logger.error("TimeoutThread crashed: "+e.toString()); } } - System.out.println("timeoutThread is over!"); + logger.debug("timeoutThread is over!"); } //Signal that an amount was increased synchronized private void amountIncreased(){ diff --git a/src/main/java/ecorp/easy/installer/threads/FlashThread.java b/src/main/java/ecorp/easy/installer/threads/FlashThread.java index 6ad3752d0256c478129da8432cb2c73ed3483d15..8264be0f05123299072ae70ff9f25c2b270bc94e 100644 --- a/src/main/java/ecorp/easy/installer/threads/FlashThread.java +++ b/src/main/java/ecorp/easy/installer/threads/FlashThread.java @@ -17,7 +17,6 @@ package ecorp.easy.installer.threads; import ecorp.easy.installer.AppConstants; -import ecorp.easy.installer.logger.FlashLogger; import ecorp.easy.installer.models.Device; import ecorp.easy.installer.models.Command; import ecorp.easy.installer.models.DataBundle; @@ -29,6 +28,8 @@ import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -38,8 +39,8 @@ import java.util.regex.Pattern; public class FlashThread extends Thread implements EasilyCancelable{ final protected static char COMMON_PARAM_IDENTIFIER = '$';//allow to identify when an param of a step is to load from common parameter final protected static Pattern REGEX_FIND_PARAM = Pattern.compile("\\$\\{(.*?)\\}"); - - private final FlashLogger logger; + private final static Logger logger = LoggerFactory.getLogger(FlashThread.class); + //private final FlashLogger logger; boolean running = false; boolean cancelled = false; boolean sendIssueLog = false; //if true then the app must write the file for issue. @TODO replace the word "send" by a word more accurate. @@ -66,7 +67,6 @@ public class FlashThread extends Thread implements EasilyCancelable{ this.commands = new HashMap<>(); this.commonParameters = new HashMap<>(); this.firstCommandKey = firstCommandKey; - this.logger = new FlashLogger(controller); this.application = controller; this.pauseLock = pauseLock; this.device = device; @@ -99,13 +99,13 @@ public class FlashThread extends Thread implements EasilyCancelable{ * @return boolean true is success false either */ private boolean handleResult(final Command command){ - System.out.println("FlashThread.handleResult()"); + logger.info("handleResult()"); //read result from command object final int exitValue = command.getExitValue(); final String shellOutput = command.getShellOutput(); - this.logger.writeLine("Shell output: \n``` \n"+shellOutput); - this.logger.writeLine("Exit value: "+exitValue+"\n```"); + logger.debug(" Shell output= {}\nexit value = {}\n", shellOutput, exitValue); + if(command.isSuccess()){ String outputKey = command.getOutputKey(); @@ -114,7 +114,7 @@ public class FlashThread extends Thread implements EasilyCancelable{ final int lastIndex = shellOutput.lastIndexOf("\n"); final int length = shellOutput.length(); final String shellOutputCleaned = shellOutput.substring(lastIndex+1, length); - System.out.println("shell output cleaned : "+shellOutputCleaned); + logger.debug("shell output cleaned : "+shellOutputCleaned); this.commonParameters.put(outputKey.replace("${","").replace("}", ""), shellOutputCleaned); } @@ -124,8 +124,7 @@ public class FlashThread extends Thread implements EasilyCancelable{ if(errorMsgKey == null || errorMsgKey.isEmpty()){ errorMsgKey = "script_error_unknown"; } - logger.write( "Exit value means: "+errorMsgKey ); - System.out.println(errorMsgKey); + logger.warn("Exit value means: "+errorMsgKey ); showError(errorMsgKey); return false; } @@ -144,21 +143,13 @@ public class FlashThread extends Thread implements EasilyCancelable{ application.onFlashError(bundle); }); } - - /** - * Ask logger to create a log file and return its path - * @return - */ - public String createLogFile(){ - return ((FlashLogger) logger).writeTofile(); - } /** * stop the thread * @param sendLog if true, Logger will send data in logger */ synchronized public void cancel(boolean sendLog){ - System.out.println("FlashThread.cancel()"); + logger.info("cancel()"); if(running && commands.containsKey(currentStepCode)){ //@TODO the second part of the test won't work, as we include some "error" steps. So the commands.size isn't good. Command cmd = commands.get(currentStepCode); if(cmd != null) cmd.cancel(); @@ -212,14 +203,16 @@ public class FlashThread extends Thread implements EasilyCancelable{ bundle.putString("stepType", AppConstants.ASK_ACCOUNT_KEY); //@TODO: Tell UI To update Platform.runLater(()->{ - System.out.println("Update UI for"+cmd.getCommand()); + logger.debug("runLater-> Update UI for"+cmd.getCommand()); application.onStepStart(bundle); }); try{ synchronized(pauseLock){ pauseLock.wait(); } - }catch (InterruptedException e) {} //Ignore the issue + }catch (InterruptedException e) { + logger.error("error = "+e.toString()); + } //Ignore the issue //@TODO Find a way to prevent end the run process of this command before to try to run a script //A posibility is to add a (cmd != null) ? cmd.execAndReadOutput : ; in AbsttractThread class and then here: se cmd to null. }else{ @@ -237,7 +230,7 @@ public class FlashThread extends Thread implements EasilyCancelable{ } bundle.putInteger("averageTime", newUIValues.getAverageTime()); Platform.runLater(()->{ - System.out.println("Update UI for"+cmd.getCommand()); + logger.debug("runLater-> Update UI for"+cmd.getCommand()); application.onStepStart(bundle); }); } @@ -263,11 +256,10 @@ public class FlashThread extends Thread implements EasilyCancelable{ */ protected void onErrorRaised(Exception e) { showError("java_error_unknow"); - System.out.println("catched exception "+e.toString()); //send error in log rather that in UI sendIssueLog = true; atLeastOneError = true; - logger.writeLine("Java exception: "+ e.toString()); + logger.error("Java exception: "+ e.toString()); } /** @@ -315,7 +307,7 @@ public class FlashThread extends Thread implements EasilyCancelable{ doBeforeToRunCommand(); if(! cmd.getCommand().contains(AppConstants.ASK_ACCOUNT_KEY)){ //write into logger - this.logger.write("\n\n### Command : "+cmd.getCommand()); + logger.debug("Run(), Command = "+cmd.getCommand()); //run command cmd.execAndReadOutput(); success = handleResult(cmd); @@ -358,7 +350,7 @@ public class FlashThread extends Thread implements EasilyCancelable{ } }); - this.logger.write("\n\nParameters : "+cmd.getParameters().toString()); + logger.debug("updateParameters(), Parameters = "+cmd.getParameters().toString()); } } } diff --git a/src/main/java/ecorp/easy/installer/threads/ThreadFactory.java b/src/main/java/ecorp/easy/installer/threads/ThreadFactory.java index 3c0e062a21895dd2c04d8ebb28e42364a5ea5ec3..bf8d441581df10a9d8419e63b40cc85b35519c3e 100644 --- a/src/main/java/ecorp/easy/installer/threads/ThreadFactory.java +++ b/src/main/java/ecorp/easy/installer/threads/ThreadFactory.java @@ -30,6 +30,8 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.HashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; /** @@ -40,6 +42,7 @@ import org.yaml.snakeyaml.Yaml; * @author Vincent */ public class ThreadFactory { + private final static Logger logger = LoggerFactory.getLogger(ThreadFactory.class); private ProcessMould flashMould; private final HashMap sourcesToDownload; private Device device; @@ -69,15 +72,15 @@ public class ThreadFactory { * @return false if there is an issue or if no flashMould is built */ private boolean loadYAMLFile(){ - System.out.println("loadYAMLFile"); + logger.info("loadYAMLFile()"); + final String modelName = device.getDevice(); //Do not use device.getModel as it doesn't return the expected value + if(modelName == null || modelName.isEmpty()){ + return false; + } + try{ Yaml yaml = new Yaml (); - final String modelName = device.getDevice(); //Do not use device.getModel as it doesn't return the expected value - if(modelName == null || modelName.isEmpty()){ - return false; - } - //load config file InputStream is = getClass().getResourceAsStream(yamlFolderPath+modelName+".yml"); Map yamLContent= (Map)yaml.load(is); @@ -102,7 +105,8 @@ public class ThreadFactory { is.close(); }catch(IOException | NullPointerException e){ - e.printStackTrace(); + logger.error("modelName = {}, error= {}", modelName, e.toString()); + return false; } return true; @@ -113,7 +117,7 @@ public class ThreadFactory { * @param steps Map containing data from YAML */ protected void loadFlashProcess( Map steps){ - System.out.println("loadFlashProcess( ...) "); + logger.info("loadFlashProcess( ... ) "); if(steps == null || steps.isEmpty()){ throw new InvalidParameterException("Flash steps loaded from YAML are invalid"); } @@ -122,7 +126,7 @@ public class ThreadFactory { String scriptExtension = AppConstants.OsName.toLowerCase().contains("windows") ? ".bat" : ".sh"; for(String key: keys){ - System.out.println("Key: "+key); + logger.debug("Key = "+key); Map stepData = (Map) steps.get(key); Step step = new Step(); @@ -148,7 +152,7 @@ public class ThreadFactory { * @param steps Map Loaded from YAML */ protected void loadFlashExtra( Map steps){ - System.out.println("loadFlashExtra(...)"); + logger.info("loadFlashExtra(...)"); if(steps == null || steps.isEmpty()){ throw new InvalidParameterException("Flash steps's extra loaded from YAML are invalid"); } @@ -183,7 +187,7 @@ public class ThreadFactory { * @param sources Map containing steps of preparation */ protected void loadSourcesToDownload( Map sources){ - System.out.println("loadPreparationProcess(...)"); + logger.info("loadSourcesToDownload(...)"); if(sources == null || sources.isEmpty()){ throw new InvalidParameterException("Preparation steps loaded from YAML are invalid"); } diff --git a/src/main/java/ecorp/easy/installer/threads/UploadToEcloudTask.java b/src/main/java/ecorp/easy/installer/threads/UploadToEcloudTask.java index 40468b0b710d4200bff8020820ef13d5c971ad20..f46a7cdb528cfdf25d0fa27cb9060451efc346e4 100644 --- a/src/main/java/ecorp/easy/installer/threads/UploadToEcloudTask.java +++ b/src/main/java/ecorp/easy/installer/threads/UploadToEcloudTask.java @@ -25,12 +25,15 @@ import java.net.http.HttpResponse; import java.nio.file.Paths; import java.util.Base64; import javafx.concurrent.Task; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The goal of this task is to push the specified file on ecloud folder * @author vincent Bourgmayer */ public class UploadToEcloudTask extends Task{ + private final static Logger logger = LoggerFactory.getLogger(UploadToEcloudTask.class); String URL; String filePath; @@ -41,6 +44,7 @@ public class UploadToEcloudTask extends Task{ @Override protected Boolean call() throws Exception { + logger.info("call(), url = {}, filepath = {}", URL, filePath); File file = new File(filePath); if(!file.exists()) return false; @@ -56,7 +60,7 @@ public class UploadToEcloudTask extends Task{ var httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build(); var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - System.out.println("Response code of log's upload : "+response.statusCode()); + logger.debug("Response code of log's upload : "+response.statusCode()); if(response.statusCode()>= 200 && response.statusCode() < 300){ file.delete(); return true; diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index b8c0b624b4e581fa20fcbd98caac5387f5c7785a..420afa7e35be357b58155235a68b09efa6ea1323 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -23,9 +23,11 @@ module ecorp.easy.installer { requires javafx.base; requires jdk.crypto.ec; //REQUIRED TO DOWNLOAD OVER HTTPS requires org.yaml.snakeyaml; + requires org.slf4j; opens ecorp.easy.installer to javafx.fxml; opens ecorp.easy.installer.controllers to javafx.fxml; opens ecorp.easy.installer.controllers.subcontrollers to javafx.fxml; - + + exports ecorp.easy.installer.logger; exports ecorp.easy.installer; } diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000000000000000000000000000000000000..562e2fa25b60edffc7f54d8da443ac05f1f27166 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,45 @@ + + + + + + ${LOG_PATH} + + %date %level [%thread] %logger{10} [%file:%line] %msg%n + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + %d{HH:mm:ss} [%thread] %logger{36} - %msg%n + + /> + + + + + + +