/** @return True if the backup location was created successfully */
  private boolean handleBackupLocation() {

    try {
      // Locate the installation directory
      File applicationDataDirectory = InstallationManager.getOrCreateApplicationDataDirectory();

      log.debug("Cloud backup...");
      File cloudBackupLocation = null;
      if (Configurations.currentConfiguration != null) {
        String cloudBackupLocationString =
            Configurations.currentConfiguration.getAppearance().getCloudBackupLocation();
        if (cloudBackupLocationString != null && !"".equals(cloudBackupLocationString)) {
          cloudBackupLocation = new File(cloudBackupLocationString);
        }
      }

      log.debug("Backup manager...");
      // Initialise backup (must be before Bitcoin network starts and on the main thread)
      BackupManager.INSTANCE.initialise(
          applicationDataDirectory,
          cloudBackupLocation == null ? Optional.<File>absent() : Optional.of(cloudBackupLocation));

      return true;

    } catch (Exception e) {
      log.error("Failed to create backup location.", e);
    }

    // Must have failed to be here
    return false;
  }
示例#2
0
  void renameTrack() {
    if (interfaceDisabled) return;
    Playlist p = getSelectedPlaylist();
    if (p == null) return;
    Track t = getSelectedTrack();
    if (t == null) return;

    TextInputDialog dialog = new TextInputDialog(t.getTitle());
    dialog.setTitle(res.getString("rename_track"));
    dialog.setHeaderText(res.getString("rename_track"));
    dialog.setContentText(res.getString("enter_new_title"));
    dialog.getDialogPane().getStylesheets().add("/styles/dialogs.css");
    ((Stage) dialog.getDialogPane().getScene().getWindow()).getIcons().addAll(logoImages);
    Optional<String> result = dialog.showAndWait();
    result.ifPresent(
        title -> {
          if (StringUtils.isEmpty(title)) {
            return;
          }
          Cache.renameTrack(t, p, title);
          Platform.runLater(
              () -> {
                loadSelectedPlaylist();
              });
        });
  }
示例#3
0
 void menuAddToPlaylist() {
   Track t = getSelectedTrack();
   if (t == null) {
     return;
   }
   ChoiceDialog<Playlist> dialog = playlistSelectionDialog(playlistsView.getItems());
   Optional<Playlist> result = dialog.showAndWait();
   result.ifPresent(playlist -> addToPlaylist(t, playlist));
 }
示例#4
0
 @Nullable
 public static <T> T getIfSingle(@Nullable Stream<T> items) {
   return items == null
       ? null
       : items
           .limit(2)
           .map(Optional::ofNullable)
           .reduce(
               Optional.empty(), (a, b) -> a.isPresent() ^ b.isPresent() ? b : Optional.empty())
           .orElse(null);
 }
示例#5
0
 void createOfflinePlaylist() {
   if (interfaceDisabled) return;
   TextInputDialog dialog = new TextInputDialog(res.getString("new_offline_playlist"));
   dialog.setTitle(res.getString("create_new_offline_playlist"));
   dialog.setHeaderText(res.getString("create_new_playlist"));
   dialog.setContentText(res.getString("enter_playlist_name"));
   dialog.getDialogPane().getStylesheets().add("/styles/dialogs.css");
   ((Stage) dialog.getDialogPane().getScene().getWindow()).getIcons().addAll(logoImages);
   Optional<String> result = dialog.showAndWait();
   result.ifPresent(
       title -> {
         Platform.runLater(
             () -> {
               Playlist newPlaylist = Cache.createPlaylist(title);
               Platform.runLater(
                   () -> {
                     playlistsView.getItems().add(newPlaylist);
                     playlistsView.getSelectionModel().select(newPlaylist);
                   });
             });
       });
 }
  /**
   * Create a Trezor hard wallet from a backup summary, decrypting it with a password created from
   * the Trezor supplied entropy
   */
  private boolean createTrezorHardWallet() {

    // Get the model that contains the selected wallet backup to use
    SelectBackupSummaryModel selectedBackupSummaryModel =
        getWizardModel().getSelectBackupSummaryModel();

    if (selectedBackupSummaryModel == null
        || selectedBackupSummaryModel.getValue() == null
        || selectedBackupSummaryModel.getValue().getFile() == null) {
      log.debug("No wallet backup to use from the model");
      return false;
    }

    log.debug(
        "Loading hard wallet backup '" + selectedBackupSummaryModel.getValue().getFile() + "'");
    try {
      // For Trezor hard wallets the backups are encrypted with the entropy derived password
      String walletPassword = null;
      Optional<HardwareWalletService> hardwareWalletService =
          CoreServices.getOrCreateHardwareWalletService();
      if (hardwareWalletService.isPresent()
          && hardwareWalletService.get().getContext().getEntropy().isPresent()) {
        walletPassword =
            Hex.toHexString(hardwareWalletService.get().getContext().getEntropy().get());
      }

      // Check there is a wallet password - if not then cannot decrypt backup
      if (walletPassword == null) {
        log.debug(
            "Cannot work out the password to decrypt the backup - there is no entropy from the Trezor");
        return false;
      }
      KeyParameter backupAESKey =
          AESUtils.createAESKey(
              walletPassword.getBytes(Charsets.UTF_8), WalletManager.scryptSalt());

      WalletId loadedWalletId =
          BackupManager.INSTANCE.loadZipBackup(
              selectedBackupSummaryModel.getValue().getFile(), backupAESKey);

      // Attempt to open the wallet
      final Optional<WalletSummary> walletSummaryOptional =
          WalletManager.INSTANCE.openWalletFromWalletId(
              InstallationManager.getOrCreateApplicationDataDirectory(),
              loadedWalletId,
              walletPassword);

      // If the wallet is present then it was opened successfully
      return walletSummaryOptional.isPresent();

    } catch (Exception e) {
      log.error("Failed to restore Trezor hard wallet.", e);
    }

    // Must have failed to be here
    return false;
  }
示例#7
0
  void deletePlaylist() {
    if (interfaceDisabled) return;
    Playlist p = getSelectedPlaylist();
    if (p == null) return;
    Alert alert = new Alert(AlertType.CONFIRMATION);
    ButtonType btYes = new ButtonType(res.getString("yes"), ButtonBar.ButtonData.YES);
    ButtonType btCancel =
        new ButtonType(res.getString("cancel"), ButtonBar.ButtonData.CANCEL_CLOSE);
    alert.getButtonTypes().setAll(btYes, btCancel);
    alert.setTitle(res.getString("delete_playlist"));
    alert.setHeaderText(res.getString("delete_playlist"));
    alert.setContentText(String.format(res.getString("delete_confirm"), p.getTitle()));
    alert.getDialogPane().getStylesheets().add("/styles/dialogs.css");
    ((Stage) alert.getDialogPane().getScene().getWindow()).getIcons().addAll(logoImages);

    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == btYes) {
      Cache.deletePlaylist(p);
      Platform.runLater(
          () -> {
            updatePlaylists();
          });
    }
  }
  public void update(List<Client> clientSet, List<Payment> payments) {
    Object[] columnNames =
        new Object[] {
          "#Cliente",
          "Nombre",
          "Apellido",
          "Celular",
          "Inscripción",
          "Domicilio",
          "Correo electrónico",
          "Próxima cuota"
        };

    Map<Integer, List<Payment>> paymentsByIds = new HashMap<>(clientSet.size());
    for (Payment payment : payments) {
      paymentsByIds.getOrDefault(payment.getClientId(), new ArrayList<>()).add(payment);

      List<Payment> idPayments = paymentsByIds.get(payment.getClientId());
      if (idPayments == null) {
        idPayments = new ArrayList<>();
        paymentsByIds.put(payment.getClientId(), idPayments);
      }
      idPayments.add(payment);
    }

    Object[][] data = new Object[clientSet.size()][columnNames.length];
    int i = 0;
    for (Client client : clientSet) {
      data[i][COLUMN_CLIENT] = client;
      data[i][COLUMN_FIRSTNAME] = client.getFirstName();
      data[i][COLUMN_LASTNAME] = client.getLastName();
      data[i][COLUMN_PHONENUMBER] = client.getPhoneNumber();
      data[i][COLUMN_INSCRIPTIONDATE] = client.getInscriptionDate().format(Utils.DATE_FORMATTER);
      data[i][COLUMN_HOMEADDRESS] = client.getHomeAddress();
      data[i][COLUMN_MAIL] = client.getMail();

      String finalString = "Nunca";
      Optional<Payment> lastPayment = getClientLastPayment(client, paymentsByIds);
      if (lastPayment.isPresent()) {
        LocalDate nextMonthToPay = lastPayment.get().getMonthDate().plusMonths(1);
        Period periodBetweenNowAndNextMonthToPay = Period.between(LocalDate.now(), nextMonthToPay);
        finalString = readablePeriod(periodBetweenNowAndNextMonthToPay);
      }
      data[i][COLUMN_NEXTPAYMENT] = finalString;
      i++;
    }
    TableModel tableModel = new DefaultTableModel(data, columnNames);
    setModel(tableModel);

    RowFilter<Object, Object> filter =
        new RowFilter<Object, Object>() {
          @Override
          public boolean include(Entry entry) {
            Client client = (Client) entry.getValue(COLUMN_CLIENT);
            if (!inactiveClientsVisible && client.isInactive()) {
              return false;
            }

            if (filteringWords == null) {
              return true;
            }

            for (String word : filteringWords) {
              if (!entryContainsWord(entry, word)) {
                return false;
              }
            }
            return true;
          }
        };

    TableRowSorter<TableModel> sorter = new TableRowSorter<>(tableModel);
    sorter.setRowFilter(filter);
    setRowSorter(sorter);
  }
  /** Create a wallet from a seed phrase and a backup summary (chosen by the user) */
  private boolean createWalletFromSeedPhrase(List<String> seedPhrase) {

    if (!verifySeedPhrase(seedPhrase)) {
      return false;
    }

    // Get the model that contains the selected wallet backup to use
    SelectBackupSummaryModel selectedBackupSummaryModel =
        getWizardModel().getSelectBackupSummaryModel();

    if (selectedBackupSummaryModel == null
        || selectedBackupSummaryModel.getValue() == null
        || selectedBackupSummaryModel.getValue().getFile() == null) {
      log.debug("No wallet backup to use from the model");
      return false;
    }

    log.debug(
        "Loading soft wallet backup '" + selectedBackupSummaryModel.getValue().getFile() + "'");
    try {

      WalletId loadedWalletId =
          BackupManager.INSTANCE.loadZipBackup(
              selectedBackupSummaryModel.getValue().getFile(), seedPhrase);

      // Locate the installation directory
      File applicationDataDirectory = InstallationManager.getOrCreateApplicationDataDirectory();

      // Work out what the wallet credentials was from the encrypted value stored in the
      // WalletSummary
      SeedPhraseGenerator seedPhraseGenerator = new Bip39SeedPhraseGenerator();
      byte[] seed = seedPhraseGenerator.convertToSeed(seedPhrase);

      String walletRoot =
          applicationDataDirectory.getAbsolutePath()
              + File.separator
              + WalletManager.createWalletRoot(loadedWalletId);
      WalletSummary walletSummary =
          WalletManager.getOrCreateWalletSummary(new File(walletRoot), loadedWalletId);

      KeyParameter backupAESKey = AESUtils.createAESKey(seed, WalletManager.scryptSalt());
      byte[] decryptedPaddedWalletPasswordBytes =
          org.multibit.commons.crypto.AESUtils.decrypt(
              walletSummary.getEncryptedPassword(),
              backupAESKey,
              WalletManager.aesInitialisationVector());
      byte[] decryptedWalletPasswordBytes =
          WalletManager.unpadPasswordBytes(decryptedPaddedWalletPasswordBytes);
      String decryptedWalletPassword = new String(decryptedWalletPasswordBytes, "UTF8");

      // Attempt to open the wallet
      final Optional<WalletSummary> walletSummaryOptional =
          WalletManager.INSTANCE.openWalletFromWalletId(
              InstallationManager.getOrCreateApplicationDataDirectory(),
              loadedWalletId,
              decryptedWalletPassword);

      // If the wallet is present then it was opened successfully
      return walletSummaryOptional.isPresent();

    } catch (Exception e) {
      log.error("Failed to restore wallet from seed phrase.", e);
    }

    // Must have failed to be here
    return false;
  }
  public static EventHandler<ActionEvent> getUploadHandler(
      FXController controller, ProgressBar progressBar, CheckBox stem) {
    return e -> {
      Alert a;
      if (selectedFiles != null) {
        controller.selectedFiles = new File[selectedFiles.size()];
        for (int i = 0; i < selectedFiles.size(); i++) {
          String filepath = selectedFiles.get(i).getAbsolutePath();
          if (lastUpload.contains(filepath)) {
            a = new Alert(Alert.AlertType.CONFIRMATION);
            a.setTitle("Are you sure?");
            a.setContentText(
                "You just uploaded " + filepath + ", are you sure you want to upload it again?");
            Optional<ButtonType> result = a.showAndWait();
            if (result.get() != ButtonType.OK) {
              return;
            }
          }
          if (selectedFiles.get(i).isAbsolute() && selectedFiles.get(i).exists()) {
            controller.selectedFiles[i] = selectedFiles.get(i);
          } else {
            a = new Alert(Alert.AlertType.INFORMATION, "Invalid path to file.", ButtonType.OK);
            a.setTitle("Information");
            a.showAndWait();
            return;
          }
        }
      } else {
        a = new Alert(Alert.AlertType.INFORMATION, "Please select a file.", ButtonType.OK);
        a.initStyle(StageStyle.UTILITY);
        a.setTitle("Information");
        a.showAndWait();
        return;
      }

      progressBar.setProgress(0);
      controller.writeLog("Uploading file(s)...");
      Button source = (Button) e.getSource();
      source.setDisable(true);

      SwingWorker<Boolean, Double> worker =
          new SwingWorker<Boolean, Double>() {
            @Override
            protected Boolean doInBackground() throws Exception {
              String[] key = new String[FXController.selectedFiles.length];
              publish(0.05);

              for (int i = 0; i < FXController.selectedFiles.length; i++) {
                key[i] = UUID.randomUUID().toString();
                FileUtils.uploadFile(FXController.selectedFiles[i], key[i], AESCTR.secretKey);
              }
              publish(0.4);

              Map<String, ArrayList<StringPair>> map =
                  SSE.EDBSetup(
                      FXController.selectedFiles, AESCTR.secretKey, key, stem.isSelected());
              publish(0.6);

              ObjectMapper mapper = new ObjectMapper();
              try {
                String json = mapper.writeValueAsString(map);
                publish(0.8);
                HttpUtil.HttpPost(json);
              } catch (JsonProcessingException e1) {
                e1.printStackTrace();
                return false;
              }

              publish(1.0);
              return true;
            }

            @Override
            protected void done() {
              Platform.runLater(
                  new TimerTask() {
                    @Override
                    public void run() {
                      Alert a;
                      try {
                        if (get()) {
                          controller.writeLog("Upload successful!");
                          a =
                              new Alert(
                                  Alert.AlertType.INFORMATION, "Upload successful!", ButtonType.OK);
                          a.setTitle("Success!");
                          a.showAndWait();
                          lastUpload.clear();
                          for (File f : FXController.selectedFiles) {
                            lastUpload.add(f.getAbsolutePath());
                          }
                        } else {
                          controller.writeLog("Upload failed!");
                          a = new Alert(Alert.AlertType.ERROR, "Upload failed!", ButtonType.OK);
                          a.setTitle("Error!");
                          a.showAndWait();
                        }
                      } catch (Exception ex) {
                        a = new Alert(Alert.AlertType.ERROR, "Upload error!", ButtonType.OK);
                        a.setTitle("Error!");
                        a.showAndWait();
                        ex.printStackTrace();
                      }
                      source.setDisable(false);
                    }
                  });
            }

            @Override
            protected void process(List<Double> n) {
              progressBar.setProgress(n.get(n.size() - 1));
            }
          };

      worker.execute();
    };
  }