/**
   * Map a ComputerDTo to a Computer.
   *
   * @param dto the ComputerDTO to map
   * @return the dto as a computer
   */
  public Computer toComputer(ComputerDto dto) {

    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, Locale.getDefault()));
    LocalDate introduced = null;
    LocalDate discontinued = null;

    if (null != dto.getIntroduced() && !dto.getIntroduced().isEmpty()) {
      introduced = LocalDate.parse(dto.getIntroduced(), formatter);
    }
    if (null != dto.getDiscontinued() && !dto.getDiscontinued().isEmpty()) {
      discontinued = LocalDate.parse(dto.getDiscontinued(), formatter);
    }
    Company company = null;
    if (dto.getCompanyId() != 0) {
      company = new Company(dto.getCompanyId(), dto.getCompanyName());
    }

    return new Computer.ComputerBuilder(dto.getName())
        .id(dto.getId())
        .company(company)
        .introduced(introduced)
        .discontinued(discontinued)
        .build();
  }
Пример #2
0
  public static void main(String args[]) {
    // Création sur une ligne

    /*
     * Personnel p1 = new Personnel.Builder("D", "Jacques", LocalDate.parse("2015-01-03")).build();
     * Personnel p2 = new Personnel.Builder("M", "Bob", LocalDate.parse("2011-03-07")).build();
     * Personnel p3 = new Personnel.Builder("S", "John", LocalDate.parse("2006-11-18")).build();
     */

    // Création sur plusieurs lignes
    Personnel.Builder b = new Personnel.Builder("D", "Jacques", LocalDate.parse("2015-01-03"));
    b.fonction("Directeur");
    Personnel p1 = b.build();
    b = new Personnel.Builder("M", "Bob", LocalDate.parse("2011-03-07"));
    b.fonction("Chargé de mission");
    Personnel p2 = b.build();
    b = new Personnel.Builder("S", "John", LocalDate.parse("2006-11-18"));
    b.fonction("Assistant administratif");
    Personnel p3 = b.build();

    Groupe g1 = new Groupe();
    Groupe g2 = new Groupe();

    g1.ajouter(p1);
    g1.ajouter(p3);
    g2.ajouter(p2);

    System.out.println("GROUPE 1");
    System.out.println();
    g1.afficher();

    System.out.println("GROUPE 2");
    System.out.println();
    g2.afficher();
  }
  @Test
  public void testCreateHtml() throws Exception {
    List<Transaction> result =
        new CsvImporter()
            .importCsv(new FileInputStream("src/test/resources/transactions_example6.csv"), null);

    LocalDate beginPeriod =
        LocalDate.parse("04-02-2016", DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate endPeriod = LocalDate.parse("05-03-2016", DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    /*ByteArrayInputStream bStream = new HtmlGenerator().createHtml(result, "134567890", beginPeriod, endPeriod);
    try (OutputStream os = new FileOutputStream("src/test/resources/testHtmlGenerator.html")) {
        IOUtils.copy(bStream, os);
    }*/

  }
  @Test
  public void simulationStatusShouldBeSimulationFinishedAfterInitialising()
      throws DateTimeParseException, FileNotFoundException, IOException {
    // given
    Mockito.doNothing().when(dataProvider).readDataFromFile(Mockito.anyString());
    Mockito.when(dataProvider.getEarliestDate()).thenReturn(LocalDate.parse("2013-12-30"));
    Mockito.when(dataProvider.getLatestDate()).thenReturn(LocalDate.parse("2013-01-02"));

    // when
    stockExchange.initialise("Test");

    // then
    Mockito.verify(dataProvider).readDataFromFile(Mockito.anyString());
    assertEquals(SimulationStatus.SIMULATION_FINISHED, stockExchange.getSimulationStatus());
  }
  @Test
  public void splitJobsByDateTest() throws FileNotFoundException {
    List<JobDetail> jobs = LogFiles.getJobsFromFile(folderPath + "../threedaysjobs.csv");

    TreeMap<LocalDate, List<JobDetail>> sortedJobs = LogFiles.splitJobsByDate(jobs);

    assertEquals(3, sortedJobs.size());

    assertEquals(
        4, sortedJobs.get(LocalDate.parse("2015-11-23", LogFiles.filenameDateFormatter)).size());
    assertEquals(
        3, sortedJobs.get(LocalDate.parse("2015-11-24", LogFiles.filenameDateFormatter)).size());
    assertEquals(
        2, sortedJobs.get(LocalDate.parse("2015-11-25", LogFiles.filenameDateFormatter)).size());
  }
Пример #6
0
  private List<Student> rearFromTextFileToList(String fileName) throws FileNotFoundException {
    List<Student> students = new ArrayList<>();

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
      int n = Integer.parseInt(reader.readLine());
      for (int i = 0; i < n; i++) {
        int id = Integer.parseInt(reader.readLine());
        String firstName = reader.readLine();
        String secondName = reader.readLine();
        String lastName = reader.readLine();
        LocalDate birthday = LocalDate.parse(reader.readLine());
        String address = reader.readLine();
        String phone = reader.readLine();
        String faculty = reader.readLine();
        int year = Integer.parseInt(reader.readLine());
        String group = reader.readLine();
        students.add(
            new Student(
                id,
                firstName,
                secondName,
                lastName,
                birthday,
                address,
                phone,
                faculty,
                year,
                group));
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
    return students;
  }
Пример #7
0
  // -------------------------------------------------------------------------
  // loads a single fixing series CSV file
  private static ImmutableMap<ObservableId, LocalDateDoubleTimeSeries> parseSingle(
      CharSource resource) {
    Map<ObservableId, LocalDateDoubleTimeSeriesBuilder> builders = new HashMap<>();
    try {
      CsvFile csv = CsvFile.of(resource, true);
      for (CsvRow row : csv.rows()) {
        String referenceStr = row.getField(REFERENCE_FIELD);
        String dateStr = row.getField(DATE_FIELD);
        String valueStr = row.getField(VALUE_FIELD);

        Index index = LoaderUtils.findIndex(referenceStr);
        ObservableId id = IndexQuoteId.of(index);
        LocalDate date = LocalDate.parse(dateStr);
        double value = Double.parseDouble(valueStr);

        LocalDateDoubleTimeSeriesBuilder builder =
            builders.computeIfAbsent(id, k -> LocalDateDoubleTimeSeries.builder());
        builder.put(date, value);
      }
    } catch (RuntimeException ex) {
      throw new IllegalArgumentException(
          Messages.format("Error processing resource as CSV file: {}", resource), ex);
    }
    return MapStream.of(builders).mapValues(builder -> builder.build()).toMap();
  }
Пример #8
0
  private Client createClient(double[] delta, long[] transferals) {
    Client client = new Client();

    AccountBuilder account = new AccountBuilder();

    LocalDate time = LocalDate.parse("2012-01-01");

    long valuation = 0;
    double quote = 1;
    for (int ii = 0; ii < delta.length; ii++) {
      long v = (long) Math.round((double) valuation * (delta[ii] + 1) / quote);
      long d = v - valuation;

      if (transferals[ii] > 0) account.deposit_(time, transferals[ii]);
      else if (transferals[ii] < 0) account.withdraw(time, Math.abs(transferals[ii]));

      if (v > 0) account.interest(time, d);
      else if (v < 0) account.fees____(time, Math.abs(d));

      valuation = v + transferals[ii];

      quote = 1 + delta[ii];

      time = time.plusDays(1);
    }

    account.addTo(client);
    return client;
  }
Пример #9
0
  public static void main(String[] args) {
    ZonedDateTime apollo11launch =
        ZonedDateTime.of(1969, 7, 16, 9, 32, 0, 0, ZoneId.of("America/New_York"));

    String formatted = DateTimeFormatter.ISO_DATE_TIME.format(apollo11launch);
    // 1969-07-16T09:32:00-05:00[America/New_York]
    System.out.println(formatted);

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
    formatted = formatter.format(apollo11launch);
    // July 16, 1969 9:32:00 AM EDT
    System.out.println(formatted);
    formatted = formatter.withLocale(Locale.FRENCH).format(apollo11launch);
    // 16 juillet 1969 09:32:00 EDT
    System.out.println(formatted);

    formatter = DateTimeFormatter.ofPattern("E yyyy-MM-dd HH:mm");
    formatted = formatter.format(apollo11launch);
    System.out.println(formatted);

    LocalDate churchsBirthday = LocalDate.parse("1903-06-14");
    System.out.println("churchsBirthday: " + churchsBirthday);
    apollo11launch =
        ZonedDateTime.parse(
            "1969-07-16 03:32:00-0400", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx"));
    System.out.println("apollo11launch: " + apollo11launch);
  }
Пример #10
0
 private void handleBirthDateChange() {
   String bdateStr = view.bDateFld.getText();
   if (bdateStr == null || bdateStr.trim().equals("")) {
     model.setBirthDate(null);
     view.syncBirthDate();
   } else {
     try {
       DateTimeFormatter formatter = DateTimeFormatter.ofPattern(view.dateFormat);
       LocalDate bdate = LocalDate.parse(bdateStr, formatter);
       List<String> errorList = new ArrayList<>();
       if (model.isValidBirthDate(bdate, errorList)) {
         model.setBirthDate(bdate);
         view.syncAgeCategory();
       } else {
         this.showError(errorList);
         view.syncBirthDate();
       }
     } catch (DateTimeParseException e) {
       // Birth date is not in the specified date format
       List<String> errorList = new ArrayList<>();
       errorList.add("Birth date must be in the " + view.dateFormat.toLowerCase() + " format.");
       this.showError(errorList);
       // Refresh the view
       view.syncBirthDate();
     }
   }
 }
  @Override
  public LocalDate deserialize(JsonParser parser, DeserializationContext context)
      throws IOException {
    switch (parser.getCurrentToken()) {
      case START_ARRAY:
        if (parser.nextToken() == JsonToken.END_ARRAY) {
          return null;
        }
        int year = parser.getIntValue();

        parser.nextToken();
        int month = parser.getIntValue();

        parser.nextToken();
        int day = parser.getIntValue();

        if (parser.nextToken() != JsonToken.END_ARRAY) {
          throw context.wrongTokenException(parser, JsonToken.END_ARRAY, "Expected array to end.");
        }
        return LocalDate.of(year, month, day);

      case VALUE_STRING:
        String string = parser.getText().trim();
        if (string.length() == 0) {
          return null;
        }
        return LocalDate.parse(string, ISO_DATE_OPTIONAL_TIME);
    }
    throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
  }
  @Test
  public void testErtragsgutschrift() throws IOException {
    DeutscheBankPDFExctractor extractor =
        new DeutscheBankPDFExctractor(new Client()) {
          @Override
          String strip(File file) throws IOException {
            return from("DeutscheBankErtragsgutschrift.txt");
          }
        };
    List<Exception> errors = new ArrayList<Exception>();

    List<Item> results = extractor.extract(Arrays.asList(new File("t")), errors);

    assertThat(errors, empty());
    assertThat(results.size(), is(2));
    new AssertImportActions().check(results, CurrencyUnit.EUR);

    // check security
    Security security = assertSecurity(results);

    // check transaction
    Optional<Item> item = results.stream().filter(i -> i instanceof TransactionItem).findFirst();
    assertThat(item.isPresent(), is(true));
    assertThat(item.get().getSubject(), instanceOf(AccountTransaction.class));
    AccountTransaction transaction = (AccountTransaction) item.get().getSubject();
    assertThat(transaction.getType(), is(AccountTransaction.Type.DIVIDENDS));
    assertThat(transaction.getSecurity(), is(security));
    assertThat(transaction.getDate(), is(LocalDate.parse("2014-12-15")));
    assertThat(transaction.getMonetaryAmount(), is(Money.of(CurrencyUnit.EUR, 1495L)));
    assertThat(transaction.getShares(), is(Values.Share.factorize(123)));
  }
Пример #13
0
  @RequestMapping(value = "/api/cacheFlightSearch", method = RequestMethod.GET)
  public String cacheFlightSearch(
      @RequestParam("departureDate") String departureDate,
      @RequestParam("departureAirport") String departureAirport) {

    DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ISO_DATE;

    LocalDate depDate = LocalDate.parse(departureDate, DATE_FORMAT);
    LocalDate returnDate = depDate.plusDays(7);

    String retDate = returnDate.format(DATE_FORMAT);

    List<Destination> destinations = new Destinations().getDestinations();

    for (Destination destination : destinations) {

      String arrivalAirportCode = destination.getAirportCodes().get(0);

      System.out.println(
          "Getting best flight price for destination: "
              + arrivalAirportCode
              + ","
              + destination.getCity());

      flightSearchService.getFlights(departureDate, departureAirport, arrivalAirportCode, retDate);

      System.out.println(
          "Finished processing best flight price for destination: "
              + arrivalAirportCode
              + ","
              + destination.getCity());
    }

    return "success";
  }
Пример #14
0
  public Post(String mensagem, String data) throws SystemException {
    this.valida = new Valida();
    if (!valida.conteudoPost(mensagem)) {
      throw new PostException("Conteudo do post nao pode ser nulo ou vazio.");
    }

    if (separaMensagem(mensagem, "#").length() >= MAXIMO_CARACTERES) {
      throw new PostException(
          "Nao eh possivel criar o post. O limite maximo da mensagem sao 200 caracteres.");
    }

    if (mensagem.contains("#")) {
      String hashtagErro = valida.hashtags(mensagem);
      if (hashtagErro != null) {
        throw new PostException(
            "Nao eh possivel criar o post. As hashtags devem comecar com '#'."
                + " Erro na hashtag: '"
                + hashtagErro
                + "'.");
      }
    }
    formatador = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    this.pops = 0;
    this.mensagem = separaMensagem(mensagem, ("#"));
    this.data = LocalDate.parse(data.substring(0, data.indexOf(" ")), formatador);
    this.hora = LocalTime.parse(data.substring(data.indexOf(" ") + 1));
    this.hashtags = separaHashtags(mensagem);
    this.curtidas = 0;
    adicionaMidia(mensagem);
  }
Пример #15
0
 public Exam(String name, String day, String hour, String color) {
   this.name = name;
   this.day = day;
   time =
       LocalTime.parse(hour, DateTimeFormatter.ofPattern("HH.mm"))
           .atDate(LocalDate.parse(day, DateTimeFormatter.ofPattern("dd/MM/yy")));
   this.color = color; // don't blame me they're all static methods ^^^		
   this.hour = hour;
 }
 /**
  * Java 8 / Hibernate Date
  *
  * @author <*****@*****.**><
  */
 @Test
 public void selectAllRecordAndPrint() {
   List<Blog> lstBlog = blogRepository.findAll();
   for (Blog blog : lstBlog) {
     System.out.println("Username is: " + blog.getAuthor() + " and Date: " + blog.getBlodate());
     assertThat(
         blog.getBlodate(),
         is(LocalDate.parse("2015-09-15"))); // Dia De La Independencia De México
   }
 }
Пример #17
0
  @Test
  public void vat_due_date_is_28_aug_if_low_turn_over() {
    LocalDate expected = LocalDate.parse("2016-08-28");

    VatRules vatRules = new VatRules();

    LocalDate actual = vatRules.getVatDueDate("8020120682");

    assertThat(actual, is(expected));
  }
Пример #18
0
 private static LocalDate parse(final DateTimeFormatter formatter, final String value) {
   try {
     Instant epoch = Instant.ofEpochMilli(Long.parseLong(value));
     ZonedDateTime zonedDate =
         epoch.atZone(Optional.ofNullable(formatter.getZone()).orElse(ZoneId.systemDefault()));
     return zonedDate.toLocalDate();
   } catch (NumberFormatException ex) {
     return LocalDate.parse(value, formatter);
   }
 }
Пример #19
0
 public Player nextPlayerResult() throws SQLException {
   Player player = new Player();
   player.setIdentifier(Integer.parseInt(resultSet.getString(Fields.IDENTIFIER.name())));
   player.setFirstName(resultSet.getString(Fields.FIRSTNAME.name()));
   player.setLastName(resultSet.getString(Fields.LASTNAME.name()));
   player.setEmailAddress(resultSet.getString(Fields.EMAILADDRESS.name()));
   player.setBirthdate(LocalDate.parse(resultSet.getString(Fields.BIRTHDATE.name())));
   player.setGamerTag(resultSet.getString(Fields.GAMERTAG.name()));
   return player;
 }
Пример #20
0
  @Test
  public void vat_due_date_is_28_feb_if_invoicing_in_eu() {
    LocalDate expected = LocalDate.parse("2016-02-28");

    VatRules vatRules = new VatRules();

    LocalDate actual = vatRules.getVatDueDate("5569215576");

    assertThat(actual, is(expected));
  }
Пример #21
0
  @RequestMapping(value = "/api/suggestion", method = RequestMethod.GET)
  public Map<String, FlightSuggestion> getFlight(
      @RequestParam("user") String userID,
      @RequestParam("departureAirportCode") String departureAirportCode,
      @RequestParam("departureAirportCity") String departureAirportCity,
      @RequestParam("departureDate") String date) {

    // The imageService and cruiseSuggestionService calls should happen from withing the
    // flightSuggestionService, but for now are here
    LocalDate departureDate = LocalDate.parse(date, DATE_FORMAT);
    LocalDate returnDate = departureDate.plusDays(7);

    String[] strArray = {"suggested", "followingIfLiked", "followingIfDisliked"};

    Map<String, FlightSuggestion> flightSuggestions = new LinkedHashMap<>();

    String depDate = departureDate.format(DATE_FORMAT);
    String retDate = returnDate.format(DATE_FORMAT);
    String displayDepDate = departureDate.format(DISPLAY_DATE_FORMAT);
    String displayRetDate = returnDate.format(DISPLAY_DATE_FORMAT);

    Map<String, Suggestion> suggestions =
        destinationSuggestionService.getNextDestination(userID, departureAirportCity);

    for (String key : suggestions.keySet()) {
      Suggestion suggestion = suggestions.get(key);

      Flights flights =
          flightSearchService.getFlights(
              depDate, departureAirportCode, suggestion.getAirportCodes().get(0), retDate);

      DestinationDetails destinationDetails = new DestinationDetails();
      //
      // destinationDetails.setDestinationImages(imageService.getCityImages(suggestionCurrent.getCityName(), suggestionCurrent.getLabels(), 3));

      CruiseSuggestion cruiseSuggestion =
          cruiseSuggestionService.getCruiseSuggestion(
              suggestion.getAirportCodes().get(0), departureDate, returnDate);

      FlightSuggestion flightSuggestion =
          new FlightSuggestion(
              flights.getPrice(),
              flights.getDepartureDate(),
              flights.getReturnDate(),
              new Airport(departureAirportCode, departureAirportCity),
              new Airport(suggestion.getAirportCodes().get(0), suggestion.getCityName()),
              destinationDetails,
              cruiseSuggestion,
              displayDepDate,
              displayRetDate);
      flightSuggestions.put(key, flightSuggestion);
    }

    return flightSuggestions;
  }
Пример #22
0
 public Configuration() {
   final Properties properties = new Properties();
   try {
     properties.load(new FileReader(getConfigurationFilePath()));
     username = properties.getProperty("username");
     password = properties.getProperty("password");
     from = LocalDate.parse(properties.getProperty("from"));
   } catch (IOException e) {
     System.out.println("No configuration file found.");
   }
 }
  @Test
  public void nextDayShouldIncrementDateAndCallGetStockByDate()
      throws DateTimeParseException, FileNotFoundException, IOException {
    // given
    Mockito.doNothing().when(dataProvider).readDataFromFile(Mockito.anyString());
    Mockito.when(dataProvider.getEarliestDate()).thenReturn(LocalDate.parse("2013-01-02"));
    Mockito.when(dataProvider.getLatestDate()).thenReturn(LocalDate.parse("2013-01-07"));
    Mockito.when(dataProvider.getStocksByDate(Mockito.any()))
        .thenReturn(
            Arrays.asList(
                new Stock("TPSA", LocalDate.parse("2013-01-03"), new BigDecimal("12.13"))));
    stockExchange.initialise("Test");

    // when
    stockExchange.nextDay();

    // then
    Mockito.verify(dataProvider).getStocksByDate(LocalDate.parse("2013-01-03"));
    assertEquals(SimulationStatus.SIMULATION_NOT_FINISHED, stockExchange.getSimulationStatus());
  }
Пример #24
0
  public static void menu2() {
    System.out.println("¿En qué tabla quieres añadir el elemento?");
    System.out.println(
        "1.Trabajador \n"
            + "2.Aerolínea \n"
            + "3.Modelo \n"
            + "4.Pista \n"
            + "5.Billete \n"
            + "6.Pasajero \n"
            + "7.Equipaje \n"
            + "8.Terminal \n"
            + "9.Vuelo \n"
            + "10.Avión");

    int a = sc.nextInt();
    sc.nextLine();
    switch (a) {
      case 1:
        System.out.println("¿A qué tripulación pertenece: ");
        String tripulacion = sc.nextLine();

        System.out.println("Nombre del trabajador: ");
        String nombre = sc.nextLine();

        System.out.println("Fecha de nacimiento (yyyy-MM-dd)");
        String fechaNacimiento1 = sc.nextLine();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate p = LocalDate.parse(fechaNacimiento1, formatter);
        Date fechaNacimiento = Date.valueOf(p);

        System.out.println("Fecha inicio contrato (yyyy-MM-dd");
        String fechaContrato1 = sc.nextLine();
        LocalDate p2 = LocalDate.parse(fechaContrato1, formatter);
        Date fechaContrato = Date.valueOf(p2);

        Trabajador trabajador1 =
            new Trabajador(tripulacion, nombre, fechaNacimiento, fechaContrato);
        gestor.insertTablaTripulacion(trabajador1);
      case 2:
    }
  }
  public static void main(String[] args) {

    try (Scanner input = new Scanner(System.in)) {

      System.out.println("Enter first date (day-month-year):");
      LocalDate firstDate =
          LocalDate.parse(input.nextLine(), DateTimeFormatter.ofPattern("d-M-yyyy"));

      System.out.println("Enter second date (day-month-year):");
      LocalDate secondDate =
          LocalDate.parse(input.nextLine(), DateTimeFormatter.ofPattern("d-M-yyyy"));

      long daysBetweenDates = ChronoUnit.DAYS.between(firstDate, secondDate);

      System.out.println(
          "Days between " + firstDate + " and " + secondDate + " : " + daysBetweenDates + " days");

    } catch (DateTimeParseException e) {
      System.out.println("Wrong format.");
    }
  }
 private String parseDate(String[] fields, int colIndex, boolean warnOnNull) {
   try {
     return LocalDate.parse(fields[colIndex], DATE_FORMATTER).toString();
   } catch (DateTimeParseException e) {
     if (warnOnNull) {
       LOGGER.warn(
           "Unparseable date '{}' in column %d of row {}",
           fields[colIndex], colIndex, fieldsToString(fields));
     }
     return null;
   }
 }
 private LocalDateTime parseDateOrDateTime(String val) {
   try {
     return LocalDateTime.parse(val);
   } catch (DateTimeParseException dtpe) {
     try {
       return LocalDate.parse(val).atStartOfDay();
     } catch (DateTimeParseException dpe) {
       throw new BadRequestException(
           "Bad dateTimeFormat for string " + val + ". Should be in ISO date format");
     }
   }
 }
Пример #28
0
  @Test(dataProvider = "LeapSeconds")
  public void test_leapSeconds(long mjd, int adjust, int offset, String checkDate) {
    assertEquals(
        mjd, LocalDate.parse(checkDate).getLong(JulianFields.MODIFIED_JULIAN_DAY), "Invalid test");

    assertEquals(rules.getLeapSecondAdjustment(mjd), adjust);
    assertEquals(rules.getTaiOffset(mjd), offset);
    if (adjust != 0) {
      long[] leaps = rules.getLeapSecondDates();
      Arrays.sort(leaps);
      assertEquals(Arrays.binarySearch(leaps, mjd) >= 0, true);
    }
  }
Пример #29
0
  @FXML
  public void btnSaveOnAction() {
    GuiMain.getWithdrawalsControl()
        .addWithdrawals(
            withdrawals
                .stream()
                .map(
                    with ->
                        new Withdraw(
                            with.getDetails(),
                            with.getValue(),
                            LocalDate.parse(with.getDate()),
                            GuiMain.getAccountControl()
                                .getAccountId(LocalDate.parse(with.getDate()))))
                .collect(Collectors.toList()));

    try {
      GuiMain.getWithdrawalsControl().saveChanges();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      GuiMain.getAddWithdrawalsWindow().close();
    }
  }
  @Test
  public void testErtragsgutschrift2() throws IOException {
    DeutscheBankPDFExctractor extractor =
        new DeutscheBankPDFExctractor(new Client()) {
          @Override
          String strip(File file) throws IOException {
            return from(file.getName());
          }
        };
    List<Exception> errors = new ArrayList<Exception>();

    List<Item> results =
        extractor.extract(Arrays.asList(new File("DeutscheBankErtragsgutschrift2.txt")), errors);

    assertThat(errors, empty());
    assertThat(results.size(), is(2));
    new AssertImportActions().check(results, CurrencyUnit.EUR);

    // check security
    Security security =
        results.stream().filter(i -> i instanceof SecurityItem).findFirst().get().getSecurity();
    assertThat(security.getName(), is("ISHS-MSCI N. AMERIC.UCITS ETF BE.SH.(DT.ZT.)"));
    assertThat(security.getIsin(), is("DE000A0J2060"));
    assertThat(security.getWkn(), is("A0J206"));
    assertThat(security.getCurrencyCode(), is("USD"));

    // check transaction
    Optional<Item> item = results.stream().filter(i -> i instanceof TransactionItem).findFirst();
    assertThat(item.isPresent(), is(true));
    assertThat(item.get().getSubject(), instanceOf(AccountTransaction.class));

    AccountTransaction transaction = (AccountTransaction) item.get().getSubject();
    assertThat(transaction.getType(), is(AccountTransaction.Type.DIVIDENDS));
    assertThat(transaction.getSecurity(), is(security));
    assertThat(transaction.getDate(), is(LocalDate.parse("2015-03-24")));
    assertThat(transaction.getMonetaryAmount(), is(Money.of(CurrencyUnit.EUR, 16_17L)));
    assertThat(transaction.getShares(), is(Values.Share.factorize(123)));

    Optional<Unit> grossValue = transaction.getUnit(Unit.Type.GROSS_VALUE);
    assertThat(grossValue.isPresent(), is(true));
    assertThat(grossValue.get().getAmount(), is(Money.of("EUR", 16_17L)));
    assertThat(grossValue.get().getForex(), is(Money.of("USD", 17_38L)));
    assertThat(
        grossValue.get().getExchangeRate().doubleValue(), IsCloseTo.closeTo(0.930578, 0.000001));
  }