io.vavr.control.Try.withResources()方法的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(8.3k)|赞(0)|评价(0)|浏览(169)

本文整理了Java中io.vavr.control.Try.withResources()方法的一些代码示例,展示了Try.withResources()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Try.withResources()方法的具体详情如下:
包路径:io.vavr.control.Try
类名称:Try
方法名:withResources

Try.withResources介绍

[英]Creates a Try-with-resources builder that operates on one AutoCloseable resource.
[中]创建在一个可自动关闭的资源上运行的“资源试用生成器”。

代码示例

代码示例来源:origin: RoboZonky/robozonky

@Override
  protected String getLatestSource() {
    logger.debug("Reading notification configuration from '{}'.", source);
    return Try.withResources(() -> new BufferedReader(new InputStreamReader(source.openStream(), Defaults.CHARSET)))
        .of(r -> r.lines().collect(Collectors.joining(System.lineSeparator())))
        .getOrElseGet(t -> {
          logger.warn("Failed reading notification configuration from '{}' due to '{}'.", source,
                t.getMessage());
          return null;
        });
  }
}

代码示例来源:origin: com.github.robozonky/robozonky-notifications

@Override
  protected String getLatestSource() {
    LOGGER.debug("Reading notification configuration from '{}'.", source);
    return Try.withResources(() -> new BufferedReader(new InputStreamReader(source.openStream(), Defaults.CHARSET)))
        .of(r -> r.lines().collect(Collectors.joining(System.lineSeparator())))
        .getOrElseGet(t -> {
          LOGGER.warn("Failed reading notification configuration from '{}' due to '{}'.", source,
                t.getMessage());
          return null;
        });
  }
}

代码示例来源:origin: com.github.robozonky/robozonky-installer

public static void writeOutProperties(final Properties properties, final File target) {
  Try.withResources(() -> Files.newBufferedWriter(target.toPath(), Defaults.CHARSET))
      .of(w -> {
        properties.store(w, Defaults.ROBOZONKY_USER_AGENT);
        LOGGER.debug("Written properties to {}.", target);
        return null;
      })
      .getOrElseThrow((Function<Throwable, IllegalStateException>) IllegalStateException::new);
}

代码示例来源:origin: RoboZonky/robozonky

public static void writeOutProperties(final Properties properties, final File target) {
  Try.withResources(() -> Files.newBufferedWriter(target.toPath(), Defaults.CHARSET))
      .of(w -> {
        properties.store(w, Defaults.ROBOZONKY_USER_AGENT);
        LOGGER.debug("Written properties to {}.", target);
        return null;
      })
      .getOrElseThrow((Function<Throwable, IllegalStateException>) IllegalStateException::new);
}

代码示例来源:origin: com.github.robozonky/robozonky-integration-stonky

static Optional<File> download(final URL url) {
  return Try.withResources(url::openStream)
      .of(Util::download)
      .getOrElseGet(t -> {
        LOGGER.warn("Failed downloading file.", t);
        return Optional.empty();
      });
}

代码示例来源:origin: RoboZonky/robozonky

@Override
protected Optional<ConfigStorage> transform(final String source) {
  return Try.withResources(() -> new ByteArrayInputStream(source.getBytes(Defaults.CHARSET)))
      .of(baos -> Optional.of(ConfigStorage.create(baos)))
      .getOrElseGet(ex -> {
        logger.warn("Failed transforming source.", ex);
        return Optional.empty();
      });
}

代码示例来源:origin: com.github.robozonky/robozonky-integration-stonky

private URL download(final Zonky zonky, final Function<Zonky, Response> delegate) {
  return Try.withResources(() -> delegate.apply(zonky))
      .of(response -> {
        final int status = response.getStatus();
        LOGGER.debug("Download endpoint returned HTTP {}.", status);
        if (status != 302) {
          throw new IllegalStateException("Download not yet ready: " + this);
        }
        final String s = response.getHeaderString("Location");
        return new URL(s);
      }).get();
}

代码示例来源:origin: com.github.robozonky/robozonky-app

@Override
  protected Optional<VersionIdentifier> transform(final String source) {
    return Try.withResources(() -> new ByteArrayInputStream(source.getBytes(Defaults.CHARSET)))
        .of(s -> Optional.of(UpdateMonitor.parseVersionString(s)))
        .getOrElseGet(ex -> {
          LOGGER.debug("Failed parsing source.", ex);
          return Optional.empty();
        });
  }
}

代码示例来源:origin: RoboZonky/robozonky

public static Optional<File> findFolder(final String folderName) {
  final Path root = new File(System.getProperty("user.dir")).toPath();
  return Try.withResources(() -> Files.find(root, 1, (path, attr) -> attr.isDirectory()))
      .of(s -> s.map(Path::toFile)
          .filter(f -> Objects.equals(f.getName(), folderName))
          .findFirst())
      .getOrElseGet(ex -> {
        LOGGER.warn("Exception while walking file tree.", ex);
        return Optional.empty();
      });
}

代码示例来源:origin: RoboZonky/robozonky

static Optional<File> download(final URL url) {
  return Try.withResources(url::openStream)
      .of(Util::download)
      .getOrElseGet(t -> {
        LOGGER.warn("Failed downloading file.", t);
        return Optional.empty();
      });
}

代码示例来源:origin: com.github.robozonky/robozonky-app

@Override
protected String getLatestSource() {
  return Try.withResources(url::openStream)
      .of(s -> IOUtils.toString(s, Defaults.CHARSET))
      .getOrElseThrow((Function<Throwable, IllegalStateException>) IllegalStateException::new);
}

代码示例来源:origin: com.github.robozonky/robozonky-common

public static Optional<File> findFolder(final String folderName) {
  final Path root = new File(System.getProperty("user.dir")).toPath();
  return Try.withResources(() -> Files.find(root, 1, (path, attr) -> attr.isDirectory()))
      .of(s -> s.map(Path::toFile)
          .filter(f -> Objects.equals(f.getName(), folderName))
          .findFirst())
      .getOrElseGet(ex -> {
        FileUtil.LOGGER.warn("Exception while walking file tree.", ex);
        return Optional.empty();
      });
}

代码示例来源:origin: RoboZonky/robozonky

@Override
  protected Optional<VersionIdentifier> transform(final String source) {
    return Try.withResources(() -> new ByteArrayInputStream(source.getBytes(Defaults.CHARSET)))
        .of(s -> Optional.of(UpdateMonitor.parseVersionString(s)))
        .getOrElseGet(ex -> {
          logger.debug("Failed parsing source.", ex);
          return Optional.empty();
        });
  }
}

代码示例来源:origin: RoboZonky/robozonky

ReturnCode execute(final InvestmentMode mode) {
  return Try.withResources(() -> mode)
      .of(this::executeSafe)
      .getOrElseGet(t -> {
        LOGGER.error("Caught unexpected exception, terminating daemon.", t);
        return ReturnCode.ERROR_UNEXPECTED;
      });
}

代码示例来源:origin: com.github.robozonky/robozonky-app

ReturnCode execute(final InvestmentMode mode) {
  return Try.withResources(() -> mode)
      .of(this::executeSafe)
      .getOrElseGet(t -> {
        LOGGER.error("Caught unexpected exception, terminating daemon.", t);
        return ReturnCode.ERROR_UNEXPECTED;
      });
}

代码示例来源:origin: com.github.robozonky/robozonky-notifications

@Override
protected Optional<ConfigStorage> transform(final String source) {
  return Try.withResources(() -> new ByteArrayInputStream(source.getBytes(Defaults.CHARSET)))
      .of(baos -> Optional.of(ConfigStorage.create(baos)))
      .getOrElseGet(ex -> {
        LOGGER.warn("Failed transforming source.", ex);
        return Optional.empty();
      });
}

代码示例来源:origin: com.github.robozonky/robozonky-integration-stonky

private GoogleClientSecrets createClientSecrets() {
  final byte[] key = secrets.get();
  return Try.withResources(() -> new ByteArrayInputStream(key))
      .of(s -> GoogleClientSecrets.load(Util.JSON_FACTORY, new InputStreamReader(s)))
      .getOrElseThrow((Function<Throwable, IllegalStateException>) IllegalStateException::new);
}

代码示例来源:origin: com.github.robozonky/robozonky-app

@Override
protected String getLatestSource() {
  return Try.withResources(() -> UpdateMonitor.getMavenCentralData(this.groupId, this.artifactId,
                                   this.mavenCentralHostname))
      .of(s -> IOUtils.toString(s, Defaults.CHARSET))
      .getOrElseThrow((Function<Throwable, IllegalStateException>) IllegalStateException::new);
}

代码示例来源:origin: com.github.robozonky/robozonky-integration-zonkoid

private static boolean requestConfirmation(final RequestId requestId, final int loanId, final int amount,
                      final String rootUrl, final String protocol) {
  return Try.withResources(HttpClients::createDefault)
      .of(httpClient -> {
        LOGGER.debug("Requesting notification of {} CZK for loan #{}.", amount, loanId);
        final HttpPost post = getRequest(requestId, loanId, amount, protocol, rootUrl);
        return httpClient.execute(post, ZonkoidConfirmationProvider::respond);
      })
      .getOrElseGet(t -> handleError(requestId, loanId, amount, rootUrl, protocol, t));
}

代码示例来源:origin: RoboZonky/robozonky

private static boolean requestConfirmation(final RequestId requestId, final int loanId, final int amount,
                      final String rootUrl, final String protocol) {
  return Try.withResources(HttpClients::createDefault)
      .of(httpClient -> {
        LOGGER.debug("Requesting notification of {} CZK for loan #{}.", amount, loanId);
        final HttpPost post = getRequest(requestId, loanId, amount, protocol, rootUrl);
        return httpClient.execute(post, ZonkoidConfirmationProvider::respond);
      })
      .getOrElseGet(t -> handleError(requestId, loanId, amount, rootUrl, protocol, t));
}

相关文章