Exemplo n.º 1
0
  public void onBtnDecrypt() {
    // Prompt for file name/location.
    File keyFile = Utils.pickFileRead("Public key");
    if (keyFile == null) {
      return;
    }
    File inputFile = Utils.pickFileRead("Input file");
    if (inputFile == null) {
      return;
    }
    File outputFile = Utils.pickFileWrite("Decrypted file", "decrypted.txt");
    if (outputFile == null) {
      return;
    }

    // Encrypt the file.
    try {
      // Read the public key.
      X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decode(Utils.readFromFile(keyFile)));
      PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);

      // Read the input file.
      byte[] input = Base64.decode(Utils.readFromFile(inputFile));
      int signatureLength = (int) (input[0] & (0xff));
      byte[] signature = new byte[signatureLength];
      byte[] ciphered = new byte[input.length - signatureLength - 1];
      System.arraycopy(input, 1, signature, 0, signature.length);
      System.arraycopy(input, signature.length + 1, ciphered, 0, ciphered.length);

      // Decrypt the file.
      Cipher cipher = Cipher.getInstance("RSA");
      cipher.init(Cipher.DECRYPT_MODE, publicKey);
      byte[] output = cipher.doFinal(ciphered);

      // Verify the signature of the document using the Signature class
      Signature s = Signature.getInstance("SHA1withRSA");
      s.initVerify(publicKey);
      s.update(output);
      if (s.verify(signature)) {
        Dialogs.create()
            .title("Signature is valid")
            .message("The signature of the file is valid.")
            .showInformation();
      } else {
        Dialogs.create()
            .title("Signature is invalid")
            .message("The signature of the file is not valid.")
            .showError();
        return;
      }

      // Write the file.
      Utils.writeToFile(outputFile, new String(output, "UTF-8"));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * handler for the Load Character event
   *
   * @param event
   * @throws IOException
   */
  @FXML
  private void handleLoadChatacterAction(ActionEvent event) throws IOException {
    FileChooser fileChooser = new FileChooser();

    // Set extension filter
    FileChooser.ExtensionFilter extFilter =
        new FileChooser.ExtensionFilter("CDF files (*.cdf)", "*.cdf");
    fileChooser.getExtensionFilters().add(extFilter);
    File chosenFile = new File(System.getProperty("user.dir") + "/characters");
    fileChooser.setInitialDirectory(chosenFile);

    // Show open file dialog
    File file = fileChooser.showOpenDialog(getInterface().getPrimaryStage());

    if (file != null) {
      ((RootController) getRoot()).setCharacter(Data.Read(file.getPath(), Character.class));
      Dialogs.create()
          .title("Character Loaded")
          .message(
              String.format(
                  "The Character:%s was successfully loaded!",
                  ((RootController) getRoot()).getCharacter().getName()))
          .styleClass(Dialog.STYLE_CLASS_UNDECORATED)
          .showInformation();
    }
  }
Exemplo n.º 3
0
  private void createMasterPane() {
    webView = new WebView();

    webViewAnchorPane = new AnchorPane(webView);
    AnchorPane.setBottomAnchor(webView, 0.0);
    AnchorPane.setTopAnchor(webView, 0.0);
    AnchorPane.setLeftAnchor(webView, 0.0);
    AnchorPane.setRightAnchor(webView, 0.0);

    webEngine = webView.getEngine();

    dialog = Dialogs.create().lightweight().modal().owner(webView);

    //        locals = new LocalJSObject(webEngine);
    //        globals = GlobalJSObject.getGlobalJSObject(webEngine);
    javaScriptHelpers = new BurpKitBridge(webEngine);
    originalUserAgent = webEngine.getUserAgent();
    webEngine.setJavaScriptEnabled(true);
    webEngine.setOnAlert(this::handleAlert);
    webEngine.setOnError(this::handleError);
    webEngine.setConfirmHandler(param -> true);
    webEngine.getLoadWorker().stateProperty().addListener(this::workerStateChanged);

    createToolBar();

    createStatusBar();

    webEngine.load("about:blank");

    masterPane = new BorderPane();
    masterPane.setTop(toolBar);
    masterPane.setCenter(webViewAnchorPane);
    masterPane.setBottom(statusBar);
  }
Exemplo n.º 4
0
  public void openImageFile(Resource resource) {
    Tab tab = new Tab();
    tab.setClosable(true);
    if (resource == null) {
      Dialogs.create()
          .owner(tabPane)
          .title("Datei nicht vorhanden")
          .message(
              "Die angeforderte Datei ist nicht vorhanden und kann deshalb nicht geöffnet werden.")
          .showError();
      return;
    }
    tab.setText(resource.getFileName());

    ImageResource imageResource = (ImageResource) resource;
    ImageViewerPane pane = new ImageViewerPane();
    pane.setImageResource(imageResource);

    ImageView imageView = pane.getImageView();
    imageView.setImage(imageResource.asNativeFormat());
    imageView.setFitHeight(-1);
    imageView.setFitWidth(-1);

    Label imagePropertiesLabel = pane.getImagePropertiesLabel();
    imagePropertiesLabel.setText(imageResource.getImageDescription());

    tab.setContent(pane);
    tab.setUserData(resource);
    tabPane.getTabs().add(tab);
    tabPane.getSelectionModel().select(tab);
  }
  /** This handles the deletion of a meter or multiple meters */
  @FXML
  private void handleDeleteMeter() {
    int selectedIndex = meterTable.getSelectionModel().getSelectedIndex();
    consumptionHeatMap.removeHeatMap();
    generationHeatMap.removeHeatMap();
    // if something is selected
    if (selectedIndex >= 0) {
      meterTable.getItems().remove(selectedIndex);
      meterTable.getSelectionModel().clearSelection(selectedIndex);

    } else {
      // nothing is selected
      Dialogs.create()
          .title("No selection")
          .masthead("No meter selected")
          .message("Please select a meter in the table")
          .showError();
    }

    // TODO: handles whenever there are no meters left, there is a glitch
    // with the columns being fixed

    intervalGraphPanel.removeMeter(selectedIndex);
    barChartPanel.removeMeter(selectedIndex);
  }
 public boolean isNotSoled(CurrentProduct currentProduct) {
   con = dbCon.geConnection();
   boolean isNotSoled = false;
   try {
     pst = con.prepareStatement("select * from Sell where ProductId=?");
     pst.setString(1, currentProduct.id);
     rs = pst.executeQuery();
     while (rs.next()) {
       Dialogs.create()
           .title("")
           .masthead("Error")
           .message("This product has been  soled you can't delete it")
           .styleClass(Dialog.STYLE_CLASS_UNDECORATED)
           .showError();
       return isNotSoled;
     }
     rs.close();
     pst.close();
     con.close();
     isNotSoled = true;
   } catch (SQLException ex) {
     Logger.getLogger(CurrentProductGetway.class.getName()).log(Level.SEVERE, null, ex);
   }
   return isNotSoled;
 }
Exemplo n.º 7
0
 /** Opens an about dialog. */
 @FXML
 private void handleAbout() {
   Dialogs.create()
       .title("AddressApp")
       .masthead("About")
       .message("Author: Marco Jakob\nWebsite: http://code.makery.ch")
       .showInformation();
 }
Exemplo n.º 8
0
  @Override
  public void duringSave(Void model) {
    List<EntityExportSource<? extends AbstractPersistentObject>> entityExportSources =
        PersistentWork.read(
            em -> {
              @SuppressWarnings("unchecked")
              List<Class<? extends AbstractPersistentObject>> entityClasses =
                  em.getEntityManagerFactory()
                      .getMetamodel()
                      .getEntities()
                      .stream()
                      .map(e -> (Class<? extends AbstractPersistentObject>) e.getJavaType())
                      .collect(Collectors.toList());
              List<EntityExportSource<? extends AbstractPersistentObject>> exportSources =
                  entityClasses
                      .stream()
                      .map(c -> new EntityExportSource<>(PersistentWork.idsFrom(c), c))
                      .collect(Collectors.toList());
              return exportSources;
            });

    XlsxExporter exporter = new XlsxExporter(controller.getExecutorService());

    File file = exportFile.get();
    try {
      if (file.exists()) {
        log.info("Deleting existing file {}", file);
        file.delete();
      }
      Files.createDirectories(file.toPath());
      file.createNewFile();
    } catch (IOException e) {
      log.error("Could not create file {}", file, e);
    }
    List<EntityExportSource<?>> bla = entityExportSources;
    exporter.export(file, bla);

    controller
        .getJavaFXExecutor()
        .submit(
            () -> {
              Dialogs.create()
                  .message(Localized.get("export.successfully", file))
                  .showInformation();
              if (openAfterExport.isSelected()) {
                controller
                    .getExecutorService()
                    .submit(
                        () -> {
                          try {
                            desktop.edit(file);
                          } catch (IOException e) {
                            log.error("Could not open {}", file, e);
                          }
                        });
              }
            });
  }
Exemplo n.º 9
0
 @FXML
 private void aboutDialog() {
   // put a real link to the source in the dialog
   // I saw a class somewhere called Hyperlink which may be useful
   Dialogs.create()
       .title("p2p-gui")
       .masthead("About") // this must be that '(i)' icon thing
       .message("By Ethan Petuchowski\n" + "github.com/ethanp/p2p-gui\n" + "December 2015")
       .showInformation();
 }
 @Override
 @FXML
 public void abrirModalEdit() {
   if (f.getFuncionarioLogado().getTipoDeFuncionario().equals(TipoDeFuncionario.Gerente)) {
     super.showDialog("dialogFuncionario", editar, DialogController.EDIT_MODAL);
   } else {
     Dialogs.create()
         .title("Funcionário não autorizado")
         .masthead("Por favor, entre com um usuário diferente")
         .showError();
   }
 }
Exemplo n.º 11
0
  public void workerStateChanged(
      ObservableValue<? extends Worker.State> observable,
      Worker.State oldValue,
      Worker.State newValue) {
    if (newValue == Worker.State.READY || newValue == Worker.State.SCHEDULED) {
      if (trafficBrowser != null) {
        trafficBrowser.setStartTime(Instant.now());
        trafficBrowser.getTraffic().clear();
      }
      numberOfAlerts.setValue("0");
    } else if (newValue == Worker.State.SUCCEEDED) {
      JSObject result = (JSObject) webEngine.executeScript("window");

      result.setMember(
          "burpCallbacks",
          new BurpExtenderCallbacksBridge(webEngine, BurpExtender.getBurpExtenderCallbacks()));

      result.setMember("burpKit", javaScriptHelpers);

      //            result.setMember("locals", locals);
      //
      //            result.setMember("globals", globals);

      if (controller != null) {
        result.setMember("burpController", controller);
      }
    } else if (newValue == Worker.State.FAILED) {
      dialog
          .title("Navigation Failed")
          .message(webEngine.getLoadWorker().getException().getMessage())
          .showInformation();
      resetParents();
    } else if (newValue == Worker.State.CANCELLED) {
      dialog
          .title("Navigation Cancelled")
          .message(webEngine.getLoadWorker().getMessage())
          .showInformation();
      resetParents();
    }
  }
Exemplo n.º 12
0
 private Player askForPlayer() {
   Optional<Player> player;
   do {
     player =
         Dialogs.create()
             .owner(null)
             .title("Double Jeopardy!")
             .masthead(null)
             .message("You have encountered a Double Jeopardy!\nWhich player are you?")
             .showChoices(Players.getPlayerList());
   } while (player == null);
   return player.get();
 }
Exemplo n.º 13
0
 private Integer askForWager(Player player) {
   final List<Integer> doubleJeopardyChoices = getDoubleJeopardyChoices(getFrame());
   Optional<Integer> wager;
   do {
     wager =
         Dialogs.create()
             .owner(null)
             .title("Double Jeopardy!")
             .masthead(null)
             .message("Player " + player + "!\nHow many points do you want to set?")
             .showChoices(doubleJeopardyChoices);
   } while (wager == null);
   return wager.get();
 }
Exemplo n.º 14
0
  private void handleAlert(WebEvent<String> event) {
    numberOfAlerts.setValue(Integer.toString(Integer.valueOf(numberOfAlerts.getValue()) + 1));
    String message = event.getData();

    /*
     * Handle all the external onAlert event handlers first.
     */
    for (EventHandler<WebEvent<String>> handler : alertListeners) handler.handle(event);

    /*
     * Finally display an alert box if the operator demands it.
     */
    if (showAlerts.getValue()) {
      dialog.title("JavaScript Alert").message(message).showInformation();
      resetParents();
    }
  }
  /**
   * Validates the user input in the text fields.
   *
   * @return true if the input is valid
   */
  private boolean isInputValid() {
    String errorMessage = "";

    if (firstNameField.getText() == null || firstNameField.getText().length() == 0) {
      errorMessage += "No valid first name!\n";
    }
    if (lastNameField.getText() == null || lastNameField.getText().length() == 0) {
      errorMessage += "No valid last name!\n";
    }
    if (streetField.getText() == null || streetField.getText().length() == 0) {
      errorMessage += "No valid street!\n";
    }

    if (postalCodeField.getText() == null || postalCodeField.getText().length() == 0) {
      errorMessage += "No valid postal code!\n";
    } else {
      // try to parse the postal code into an int.
      try {
        Integer.parseInt(postalCodeField.getText());
      } catch (NumberFormatException e) {
        errorMessage += "No valid postal code (must be an integer)!\n";
      }
    }

    if (cityField.getText() == null || cityField.getText().length() == 0) {
      errorMessage += "No valid city!\n";
    }

    if (birthdayField.getValue() == null) {
      errorMessage += "Mete una fecha\n";
    }

    if (errorMessage.length() == 0) {
      return true;
    } else {
      // Show the error message.
      Dialogs.create()
          .title("Invalid Fields")
          .masthead("Please correct invalid fields")
          .message(errorMessage)
          .showError();
      return false;
    }
  }
Exemplo n.º 16
0
  public void execute() {
    InstrumentModel instrument = order.getInstrument();

    // Show confirm dialog
    Action response =
        Dialogs.create()
            .owner(guiDialogOwner)
            .title("Delete order")
            .masthead("Delete order on " + instrument.getName())
            .message("Do you want to delete order id[" + order.getId() + "]")
            .showConfirm();

    if (response != Dialog.Actions.YES) {
      log.info("User click on [Cancel] or [No]");
      return;
    }

    // Send order delete
    log.info("sendDeleteOrder: {}", order);
    connector.sendDeleteOrder(order);
  }
Exemplo n.º 17
0
    public ImageViewerPane() {
      FXMLLoader loader =
          new FXMLLoader(
              getClass().getResource("/image_view.fxml"),
              null,
              new JavaFXBuilderFactory(),
              type -> BeanFactory.getInstance().getBean(type));
      loader.setRoot(this);
      loader.setController(this);

      try {
        loader.load();
      } catch (IOException e) {
        Dialogs.create()
            .owner(tabPane)
            .title("Bild anzeigen")
            .masthead(null)
            .message("Fehler beim Öffnen eines Bildes.")
            .showException(e);
        logger.error("", e);
      }
    }
Exemplo n.º 18
0
 private void beautifyOrRepairHTML(String mode) {
   logger.info("beautifying html");
   try {
     CodeEditor editor = currentEditor.getValue();
     EditorPosition currentCursorPosition = editor.getEditorCursorPosition();
     String code = editor.getCode();
     if (currentEditorIsXHTML.get()) {
       try {
         Resource resource = currentXHTMLResource.get();
         resource.setData(code.getBytes("UTF-8"));
         switch (mode) {
           case "format":
             code = formatAsXHTML(code);
             break;
           case "repair":
             code = repairXHTML(code);
             break;
         }
         resource.setData(code.getBytes("UTF-8"));
       } catch (UnsupportedEncodingException e) {
         // never happens
       }
     }
     editor.setCode(code);
     editor.setEditorCursorPosition(currentCursorPosition);
     editor.scrollTo(currentCursorPosition);
     book.setBookIsChanged(true);
   } catch (IOException | JDOMException e) {
     logger.error("", e);
     Dialogs.create()
         .owner(tabPane)
         .title("Formatierung nicht möglich")
         .message(
             "Kann Datei nicht formatieren. Bitte die Fehlermeldung an den Hersteller weitergeben.")
         .showException(e);
   }
 }
  public void update(CurrentProduct currentProduct) {
    con = dbCon.geConnection();

    try {
      pst =
          con.prepareStatement(
              "update Products set ProductId=?, ProductName=?, Quantity=?, Description=?, "
                  + "SupplyerId=?, BrandId=?, CatagoryId=?,"
                  + " UnitId=?, PursesPrice=?, SellPrice=?, RMAId=?, Date=?  where Id=?");
      pst.setString(1, currentProduct.productId);
      pst.setString(2, currentProduct.productName);
      pst.setString(3, currentProduct.quantity);
      pst.setString(4, currentProduct.description);
      pst.setString(5, currentProduct.supplierId);
      pst.setString(6, currentProduct.brandId);
      pst.setString(7, currentProduct.catagoryId);
      pst.setString(8, currentProduct.unitId);
      pst.setString(9, currentProduct.pursesPrice);
      pst.setString(10, currentProduct.sellPrice);
      pst.setString(11, currentProduct.rmaId);
      pst.setString(12, currentProduct.date);
      pst.setString(13, currentProduct.id);
      pst.executeUpdate();
      pst.close();
      con.close();
      rs.close();
      Dialogs.create()
          .lightweight()
          .title("Update")
          .masthead("Update Sucess")
          .message("Update Success")
          .showInformation();
    } catch (SQLException ex) {
      Logger.getLogger(CurrentProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemplo n.º 20
0
  public boolean splitXHTMLFile() {
    boolean result = false;
    if (currentEditor.getValue().getMediaType().equals(MediaType.XHTML)) {
      XHTMLCodeEditor xhtmlCodeEditor = (XHTMLCodeEditor) currentEditor.getValue();
      EditorPosition pos = xhtmlCodeEditor.getEditorCursorPosition();
      XMLTagPair pair =
          xhtmlCodeEditor.findSurroundingTags(
              token -> {
                String type = token.getType();
                if ("tag".equals(type)) {
                  String content = token.getContent();
                  if ("head".equals(content) || "body".equals(content) || "html".equals(content)) {
                    return true;
                  }
                }
                return false;
              });
      if (pair == null
          || "head".equals(pair.getTagName())
          || "html".equals(pair.getTagName())
          || StringUtils.isEmpty(pair.getTagName())) {
        Dialogs.create()
            .owner(tabPane)
            .title("Teilung nicht möglich")
            .message(
                "Kann Datei nicht an dieser Position teilen. Eine Teilung ist nur innerhalb des XHTML-Bodys möglich.")
            .showWarning();
        return false;
      }
      logger.debug("umgebendes pair " + pair);
      // wir sind innerhalb des Body
      int index = xhtmlCodeEditor.getIndexFromPosition(pos);
      try {
        String originalCode = xhtmlCodeEditor.getCode();
        org.jdom2.Document originalDocument = XHTMLUtils.parseXHTMLDocument(originalCode);
        List<Content> originalHeadContent = getOriginalHeadContent(originalDocument);

        byte[] frontPart = originalCode.substring(0, index).getBytes("UTF-8");
        Resource oldResource = currentXHTMLResource.getValue();
        oldResource.setData(frontPart);
        HtmlCleanerBookProcessor processor = new HtmlCleanerBookProcessor();
        processor.processResource(oldResource);
        xhtmlCodeEditor.setCode(new String(oldResource.getData(), "UTF-8"));

        byte[] backPart =
            originalCode.substring(index, originalCode.length() - 1).getBytes("UTF-8");
        String fileName = book.getNextStandardFileName(MediaType.XHTML);
        Resource resource = MediaType.XHTML.getResourceFactory().createResource("Text/" + fileName);
        byte[] backPartXHTML = XHTMLUtils.repairWithHead(backPart, originalHeadContent);
        resource.setData(backPartXHTML);

        int spineIndex = book.getSpine().getResourceIndex(oldResource);
        book.addSpineResource(resource, spineIndex + 1);
        openFileInEditor(resource, MediaType.XHTML);

        bookBrowserManager.refreshBookBrowser();
        needsRefresh.setValue(true);
        needsRefresh.setValue(false);
      } catch (IOException | JDOMException | ResourceDataException e) {
        logger.error("", e);
        Dialogs.create()
            .owner(tabPane)
            .title("Teilung nicht möglich")
            .message("Kann Datei nicht teilen. Bitte Fehlermeldung an den Hersteller übermitteln.")
            .showException(e);
      }

      result = true;
    }
    return result;
  }
Exemplo n.º 21
0
  public void openFileInEditor(Resource resource, MediaType mediaType)
      throws IllegalArgumentException {
    if (!isTabAlreadyOpen(resource)) {
      Tab tab = new Tab();
      tab.setClosable(true);
      if (resource == null) {
        Dialogs.create()
            .owner(tabPane)
            .title("Datei nicht vorhanden")
            .message(
                "Die angeforderte Datei ist nicht vorhanden und kann deshalb nicht geöffnet werden.")
            .showError();
        return;
      }
      tab.setText(resource.getFileName());
      resource
          .hrefProperty()
          .addListener(
              (observable, oldValue, newValue) -> {
                tab.setText(resource.getFileName());
              });

      String content = "";
      try {
        content = new String(resource.getData(), resource.getInputEncoding());
      } catch (IOException e) {
        logger.error("", e);
      }

      CodeEditor editor;
      if (mediaType.equals(MediaType.CSS)) {
        editor = new CssCodeEditor();
        editor.setContextMenu(contextMenuCSS);
      } else if (mediaType.equals(MediaType.XHTML)) {
        editor = new XHTMLCodeEditor();
        editor.setContextMenu(contextMenuXHTML);
      } else if (mediaType.equals(MediaType.XML)) {
        editor = new XMLCodeEditor();
        editor.setContextMenu(contextMenuXML);
      } else {
        throw new IllegalArgumentException("no editor for mediatype " + mediaType.getName());
      }

      tab.setContent((Node) editor);
      tab.setUserData(resource);
      tabPane.getTabs().add(tab);
      tabPane.getSelectionModel().select(tab);

      final String code = content;
      editor
          .stateProperty()
          .addListener(
              new ChangeListener<Worker.State>() {
                @Override
                public void changed(
                    ObservableValue<? extends Worker.State> observable,
                    Worker.State oldValue,
                    Worker.State newValue) {
                  if (newValue.equals(Worker.State.SUCCEEDED)) {
                    openingEditorTab = true;
                    editor.setCode(code);
                    editor.setCodeEditorSize(
                        ((AnchorPane) editor).getWidth() - 20,
                        ((AnchorPane) editor).getHeight() - 20);
                    ((AnchorPane) editor)
                        .widthProperty()
                        .addListener(
                            new ChangeListener<Number>() {
                              @Override
                              public void changed(
                                  ObservableValue<? extends Number> observable,
                                  Number oldValue,
                                  Number newValue) {
                                editor.setCodeEditorSize(
                                    newValue.doubleValue() - 20,
                                    ((AnchorPane) editor).getHeight() - 20);
                              }
                            });
                    ((AnchorPane) editor)
                        .heightProperty()
                        .addListener(
                            new ChangeListener<Number>() {
                              @Override
                              public void changed(
                                  ObservableValue<? extends Number> observable,
                                  Number oldValue,
                                  Number newValue) {
                                editor.setCodeEditorSize(
                                    ((AnchorPane) editor).getWidth() - 20,
                                    newValue.doubleValue() - 20);
                              }
                            });
                    editor.setCodeEditorSize(
                        ((AnchorPane) editor).getWidth() - 20,
                        ((AnchorPane) editor).getHeight() - 20);
                    ((AnchorPane) editor)
                        .widthProperty()
                        .addListener(
                            new ChangeListener<Number>() {
                              @Override
                              public void changed(
                                  ObservableValue<? extends Number> observable,
                                  Number oldValue,
                                  Number newValue) {
                                editor.setCodeEditorSize(
                                    newValue.doubleValue() - 20,
                                    ((AnchorPane) editor).getHeight() - 20);
                              }
                            });
                    ((AnchorPane) editor)
                        .heightProperty()
                        .addListener(
                            new ChangeListener<Number>() {
                              @Override
                              public void changed(
                                  ObservableValue<? extends Number> observable,
                                  Number oldValue,
                                  Number newValue) {
                                editor.setCodeEditorSize(
                                    ((AnchorPane) editor).getWidth() - 20,
                                    newValue.doubleValue() - 20);
                              }
                            });
                    openingEditorTab = false;
                  }
                }
              });

      editor
          .cursorPositionProperty()
          .addListener(
              (observable, oldValue, newValue) -> {
                cursorPosLabelProperty.set(newValue.getLine() + ":" + newValue.getColumn());
              });

      editor
          .codeProperty()
          .addListener(
              (observable1, oldValue, newValue) -> {
                if (openingEditorTab) {
                  return;
                }
                if (currentEditor.getValue().getMediaType().equals(MediaType.XHTML)) {
                  try {
                    currentXHTMLResource.get().setData(newValue.getBytes("UTF-8"));
                  } catch (UnsupportedEncodingException e) {
                    // never happens
                  }
                } else if (currentEditor.getValue().getMediaType().equals(MediaType.CSS)) {
                  try {
                    currentCssResource.get().setData(newValue.getBytes("UTF-8"));
                  } catch (UnsupportedEncodingException e) {
                    // never happens
                  }
                } else if (currentEditor.getValue().getMediaType().equals(MediaType.XML)) {
                  try {
                    currentXMLResource.get().setData(newValue.getBytes("UTF-8"));
                    if (((XMLResource) resource).isValidXML()
                        && MediaType.OPF.equals(resource.getMediaType())) {
                      PackageDocumentReader.read(resource, book);
                    }
                  } catch (JDOMException | IOException e) {
                    logger.error("", e);
                  }
                }

                if (scheduledService.getState().equals(Worker.State.READY)) {
                  scheduledService.start();
                } else {
                  scheduledService.restart();
                }
                book.setBookIsChanged(true);
              });
    }
  }