Example #1
0
  static void optionalTest() {
    // 不要这样,这与!=null没什么区别
    Optional<String> stringOptional = Optional.of("alibaba");
    if (stringOptional.isPresent()) {
      System.out.println(stringOptional.get().length());
    }
    Optional<String> optionalValue = Optional.of("alibaba");
    // 下面是推荐的常用操作
    optionalValue.ifPresent(s -> System.out.println(s + " contains red"));
    // 增加到集合汇总
    List<String> results = Lists.newArrayList();
    optionalValue.ifPresent(results::add);
    // 增加到集合中,并返回操作结果
    Optional<Boolean> added = optionalValue.map(results::add);

    // 无值的optional
    Optional<String> optionalString = Optional.empty();
    // 不存在值,返回“No word”
    String result = optionalValue.orElse("No word");
    // 没值,计算一个默认值
    result = optionalString.orElseGet(() -> System.getProperty("user.dir"));
    // 无值,抛一个异常
    try {
      result = optionalString.orElseThrow(NoSuchElementException::new);
    } catch (Throwable t) {
      t.getCause();
    }
  }
  @Test
  public void _07_옵션_다루기() {
    final Optional<String> optional = words.stream().filter(w -> w.contains("red")).findFirst();
    try {
      optional.ifPresent(
          v -> {
            throw new RuntimeException();
          });
      assert false; // 이 행은 실행되면 안됨.
    } catch (RuntimeException e) {

    }

    // 비어있는 경우는 실행되지 않음.
    Optional.empty()
        .ifPresent(
            v -> {
              throw new RuntimeException();
            });

    Set<String> results = new HashSet<>();
    optional.ifPresent(results::add);
    assertThat(results.contains("tired"), is(true));

    // 실행 결과를 받고 싶은 경우에는 map 사용.
    results = new HashSet<>();
    Optional<Boolean> added = optional.map(results::add);
    assertThat(added, is(Optional.of(Boolean.TRUE)));

    // 대상이 빈경우에는 empty Optional 반환
    Optional<Boolean> a = Optional.empty().map(v -> true);
    assertThat(a.isPresent(), is(false));

    Optional<String> emptyOptional = Optional.empty();

    // orElse로 기본값 지정 가능
    String result = emptyOptional.orElse("기본값");
    assertThat(result, is("기본값"));

    // 기본값 생성하는 코드 호출 가능
    result = emptyOptional.orElseGet(() -> System.getProperty("user.dir"));
    assertThat(result, is(System.getProperty("user.dir")));

    // 값이 없는 경우 예외 던지기
    try {
      emptyOptional.orElseThrow(NoSuchElementException::new);
      assert false;
    } catch (NoSuchElementException e) {

    }
  }
  /**
   * @param directoryWithUnpackedFiles Directory with unpacked files (should include BBIs and DBF)
   * @return Map of BBI files names to their corresponding verifications
   * @throws SQLException
   * @throws ClassNotFoundException
   * @throws FileNotFoundException
   * @implNote Uses sqlite to open DBF
   */
  private Map<String, Map<String, String>> getVerificationMapFromUnpackedFiles(
      File directoryWithUnpackedFiles)
      throws SQLException, ClassNotFoundException, FileNotFoundException {

    Map<String, Map<String, String>> bbiFilesToVerification = new LinkedHashMap<>();
    Map<String, String> verificationMap;
    Optional<File> foundDBFile =
        FileUtils.listFiles(directoryWithUnpackedFiles, dbfExtensions, true).stream().findFirst();
    File dbFile = foundDBFile.orElseThrow(() -> new FileNotFoundException("DBF not found"));
    Class.forName("org.sqlite.JDBC");

    try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile)) {
      Statement statement = connection.createStatement();
      ResultSet rs = statement.executeQuery("SELECT * FROM Results");
      while (rs.next()) {
        verificationMap = new LinkedHashMap<>();
        verificationMap.put(Constants.VERIFICATION_ID, rs.getString("Id_pc"));
        verificationMap.put(Constants.PROVIDER, rs.getString("Customer"));
        verificationMap.put(Constants.DATE, rs.getString("Date"));
        verificationMap.put(Constants.COUNTER_NUMBER, rs.getString("CounterNumber"));
        verificationMap.put(Constants.COUNTER_SIZE_AND_SYMBOL, rs.getString("Type"));
        verificationMap.put(Constants.YEAR, rs.getString("Year"));
        verificationMap.put(Constants.STAMP, rs.getString("Account"));
        verificationMap.put(Constants.LAST_NAME, rs.getString("Surname"));
        verificationMap.put(Constants.FIRST_NAME, rs.getString("Name"));
        verificationMap.put(Constants.MIDDLE_NAME, rs.getString("Middlename"));
        verificationMap.put(Constants.PHONE_NUMBER, rs.getString("TelNumber"));
        verificationMap.put(Constants.REGION, rs.getString("District"));
        verificationMap.put(Constants.CITY, rs.getString("City"));
        verificationMap.put(Constants.STREET, rs.getString("Street"));
        verificationMap.put(Constants.BUILDING, rs.getString("Building"));
        verificationMap.put(Constants.FLAT, rs.getString("Apartment"));
        bbiFilesToVerification.put(rs.getString("FileNumber"), verificationMap);
      }
    }
    return bbiFilesToVerification;
  }