Esempio n. 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();
    }
  }
  /**
   * Returns the target types that need to have conversion. The types contain first as many
   * constructor parameter types as we have and then the types of properties of object as given by
   * names of result-set.
   */
  @NotNull
  private static Optional<List<Type>> findTargetTypes(
      @NotNull Constructor<?> ctor, @NotNull List<String> resultSetColumns) {
    List<Type> constructorParameterTypes = asList(ctor.getGenericParameterTypes());

    int constructorParameterCount = constructorParameterTypes.size();

    if (constructorParameterCount > resultSetColumns.size()) {
      // We don't have enough columns in ResultSet to instantiate this constructor, discard it.
      return Optional.empty();

    } else if (constructorParameterCount == resultSetColumns.size()) {
      // We have exactly enough column in ResultSet. Use the constructor as it is.
      return Optional.of(constructorParameterTypes);

    } else {
      // Get the types of remaining properties
      ArrayList<Type> result = new ArrayList<>(resultSetColumns.size());
      result.addAll(constructorParameterTypes);

      List<String> propertyNames =
          resultSetColumns.subList(constructorParameterCount, resultSetColumns.size());
      for (String name : propertyNames) {
        Type type = PropertyAccessor.findPropertyType(ctor.getDeclaringClass(), name).orElse(null);
        if (type != null) result.add(type);
        else return Optional.empty();
      }

      return Optional.of(result);
    }
  }
Esempio n. 3
0
  /**
   * Search the tree for the first instance of `pattern`, giving preference to the left child.
   *
   * <p>`pattern` is a tree, representing a pattern of nodes. `NilNode`s should be considered
   * wildcards.
   *
   * <p>Example patterns ---------------- `Tree()` Matches any tree.
   *
   * <p>`Tree(3)` Matches any tree where the root node has a value of `3`.
   *
   * <p>`Tree(3, Tree(2), Tree())` Matches any tree where the root node has a value of `3`, and a
   * left sub-tree with a root value of `2`, and any (or no) right sub-tree.
   */
  static Optional<Tree> find(Tree target, Tree pattern) {
    if (pattern.isEmpty()) return Optional.of(target);
    if (target.isEmpty()) return Optional.empty();
    if (prefixMatches(target, pattern)) return Optional.of(target);

    Optional<Tree> leftMatch = find(target.left(), pattern);
    if (leftMatch.isPresent()) return leftMatch;
    return find(target.right(), pattern);
  }
Esempio n. 4
0
  @Test
  public void _07_옵션값_생성() {
    assertThat(inverse(0d), is(Optional.empty()));
    assertThat(inverse(10d), is(Optional.of(0.1d)));

    // ofNullalbe -> null 값 처리
    assertThat(Optional.ofNullable(null), is(Optional.empty()));
    assertThat(Optional.ofNullable("test"), is(Optional.of("test")));
  }
Esempio n. 5
0
  @Test
  public void _07_옵션값_합성() {
    Optional<Double> result = inverse(4.0d).flatMap(Ch02ExampleTest::squareRoot);
    assertThat(result, is(Optional.of(0.5d)));

    Optional<Double> result2 =
        Optional.of(-4.0d).flatMap(Ch02ExampleTest::inverse).flatMap(Ch02ExampleTest::squareRoot);
    assertThat(
        "inverse, squareRoot중 하나라도 empty 리턴하면, 결과는 empty", result2, is(Optional.<Double>empty()));
  }
Esempio n. 6
0
 public Optional<List<Response>> getBatch(Optional<List<Request>> requests) {
   if (!valid) {
     Logger.error("CANNOT GET! NO VALID CONNECTION");
     return Optional.empty();
   }
   List<Response> responses = new ArrayList<>();
   requests.ifPresent(
       reqs ->
           reqs.forEach(r -> get(Optional.of(r)).ifPresent(response -> responses.add(response))));
   return Optional.of(responses);
 }
Esempio n. 7
0
  public void testGetIfPresent() {
    assertEquals(Optional.of(TestEnum.CHEETO), Enums.getIfPresent(TestEnum.class, "CHEETO"));
    assertEquals(Optional.of(TestEnum.HONDA), Enums.getIfPresent(TestEnum.class, "HONDA"));
    assertEquals(Optional.of(TestEnum.POODLE), Enums.getIfPresent(TestEnum.class, "POODLE"));

    assertTrue(Enums.getIfPresent(TestEnum.class, "CHEETO").isPresent());
    assertTrue(Enums.getIfPresent(TestEnum.class, "HONDA").isPresent());
    assertTrue(Enums.getIfPresent(TestEnum.class, "POODLE").isPresent());

    assertEquals(TestEnum.CHEETO, Enums.getIfPresent(TestEnum.class, "CHEETO").get());
    assertEquals(TestEnum.HONDA, Enums.getIfPresent(TestEnum.class, "HONDA").get());
    assertEquals(TestEnum.POODLE, Enums.getIfPresent(TestEnum.class, "POODLE").get());
  }
Esempio n. 8
0
  /** Unit tests */
  public static void main(String[] args) {
    final Tree targetTree =
        tree(
            1,
            tree(
                2,
                tree(3, tree(4), tree(3, tree(4), tree(5))),
                tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree()))),
            tree(12));

    System.out.println("    Test Pattern");
    checkPattern(targetTree, tree(), Optional.of(targetTree));

    checkPattern(targetTree, tree(9), Optional.of(tree(9)));
    checkPattern(targetTree, tree(12), Optional.of(tree(12)));
    checkPattern(targetTree, tree(13), Optional.empty());
    checkPattern(targetTree, tree(1), Optional.of(targetTree));

    checkPattern(targetTree, tree(2, tree(3), tree(5)), Optional.of(targetTree.left()));
    checkPattern(
        targetTree, tree(3, tree(4), tree(5)), Optional.of(targetTree.left().left().right()));
    checkPattern(
        targetTree, tree(6, tree(), tree(8)), Optional.of(targetTree.left().right().left()));
    checkPattern(targetTree, tree(6, tree(), tree(7)), Optional.empty());

    checkPattern(
        targetTree,
        tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree())),
        Optional.of(targetTree.left().right()));
  }
Esempio n. 9
0
 @Override
 public Optional<Class<?>> find(String name) {
   Class<?> found = cache.get(name);
   if (found != null) {
     return Optional.of(found);
   }
   try {
     String className = name.indexOf('+') != -1 ? name.replace('+', '$') : name;
     Class<?> manifest = Class.forName(namespace + className, true, loader);
     cache.put(name, manifest);
     return Optional.of(manifest);
   } catch (ClassNotFoundException ignore) {
     return Optional.empty();
   }
 }
Esempio n. 10
0
 /** PUT /users -> Updates an existing User. */
 @RequestMapping(
     value = "/users",
     method = RequestMethod.PUT,
     produces = MediaType.APPLICATION_JSON_VALUE)
 @Timed
 @Transactional
 @Secured(AuthoritiesConstants.ADMIN)
 public ResponseEntity<ManagedUserDTO> updateUser(@RequestBody ManagedUserDTO managedUserDTO)
     throws URISyntaxException {
   log.debug("REST request to update User : {}", managedUserDTO);
   return Optional.of(userRepository.findOne(managedUserDTO.getId()))
       .map(
           user -> {
             user.setLogin(managedUserDTO.getLogin());
             user.setFirstName(managedUserDTO.getFirstName());
             user.setLastName(managedUserDTO.getLastName());
             user.setEmail(managedUserDTO.getEmail());
             user.setActivated(managedUserDTO.isActivated());
             user.setLangKey(managedUserDTO.getLangKey());
             Set<Authority> authorities = user.getAuthorities();
             authorities.clear();
             managedUserDTO
                 .getAuthorities()
                 .stream()
                 .forEach(authority -> authorities.add(authorityRepository.findOne(authority)));
             return ResponseEntity.ok()
                 .headers(HeaderUtil.createEntityUpdateAlert("user", managedUserDTO.getLogin()))
                 .body(new ManagedUserDTO(userRepository.findOne(managedUserDTO.getId())));
           })
       .orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
 }
 private Optional<MediaType> getContentType(HttpServletRequest request) {
   String contentType = request.getContentType();
   if (contentType != null) {
     return Optional.of(MediaType.parseMediaType(contentType));
   }
   return Optional.empty();
 }
  /** @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;
  }
  public ProjectDto getProject(String id) {
    if (cache.isCached(id)) {
      return cache.tryGetCached(id);
    }

    ProjectInfo info = null;

    try {
      info = caller.waitOrCall(() -> api.projects().name(id).get());
    } catch (Exception e) {

      logger.error(Logging.prepare("getProject", id), e);
    }

    if (info != null) {
      ProjectDto project = new ProjectDto(info.id, info.name);

      if (info.parent != null && downloadParents) {
        ProjectDto parent = getProject(info.parent);
        project.parentId = Optional.of(parent.id);
      }

      project = repo.add(project);

      // getProjectBranches(project);
      // getApprovals(project);

      cache.cache(project);

      return project;
    }

    return null;
  }
Esempio n. 14
0
  @Override
  public Optional<Suggestion> requestPlayerSuggestion(Player player, Room room) {
    char userWantsToMakeSuggestion = '\0';

    while (userWantsToMakeSuggestion != 'Y' && userWantsToMakeSuggestion != 'N') {
      this.out.println("Do you want to make an suggestion (Y/N)?");
      this.out.println("Your cards are: " + player.cards);
      userWantsToMakeSuggestion = this.scanner.next().charAt(0);
    }

    if (userWantsToMakeSuggestion == 'Y') {
      this.out.printf("You suggest it was done in the %s, by: \n", room);

      Stream<String> suspects =
          Arrays.stream(CluedoCharacter.values()).map(CluedoCharacter::toString);
      CluedoCharacter suspect = CluedoCharacter.values()[this.selectOptionFromList(suspects)];

      this.out.println("with the ");

      Stream<String> weapons = Arrays.stream(Weapon.values()).map(Weapon::toString);
      Weapon weapon = Weapon.values()[this.selectOptionFromList(weapons)];

      return Optional.of(new Suggestion(suspect, weapon, room));

    } else {
      return Optional.empty();
    }
  }
Esempio n. 15
0
  /**
   * Perform one setter operation with the provided value.
   *
   * @param instance Instance of class under test to operate on.
   * @param property Property being tested
   * @param field Field being tested
   * @param testVal Test value to use.
   * @return Optional that will contain an error message if the test failed, otherwise empty.
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   */
  private Optional<String> testSetterWithVal(
      T instance, PropertyDescriptor property, Field field, Object testVal)
      throws InvocationTargetException, IllegalAccessException {

    Objects.requireNonNull(instance, "Instance of target class required.");
    boolean status = true;
    property.getWriteMethod().invoke(instance, testVal);

    Object expected, actual;
    if (property.getPropertyType().isPrimitive()) {
      expected = String.valueOf(testVal);
      actual = String.valueOf(field.get(instance));
      status = expected.equals(actual);
    } else {

      expected = testVal;
      actual = field.get(instance);

      if (expected == null) {
        status = actual == null;
      } else {
        status = expected.equals(actual);
      }
    }
    if (status == false) {
      return Optional.of(
          String.format(
              "Failed during setter test: %s.  Expected: %s  Actual: %s",
              property.getWriteMethod(), expected, actual));
    }
    return Optional.empty();
  }
Esempio n. 16
0
 private static Optional<PredictionBatch> asOptional(PredictionBatch pb) {
   if (pb == null || pb.predictions.isEmpty()) {
     return Optional.empty();
   } else {
     return Optional.of(pb);
   }
 }
Esempio n. 17
0
 public Optional<Response> get(Optional<Request> request) {
   if (!valid) {
     Logger.error("CANNOT GET! NO VALID CONNECTION");
     return Optional.empty();
   }
   Response response = new Response();
   if (request.isPresent()) {
     Request r = request.get();
     response.key = r.key;
     response.table = r.table;
     try {
       final Table htable = connection.getTable(TableName.valueOf(r.table));
       Result result = htable.get(new Get(r.key));
       if (result == null || result.isEmpty()) {
         return Optional.empty();
       }
       r.columns.forEach(
           c ->
               response.columns.add(
                   new Request.Column(
                       c.family,
                       c.qualifier,
                       result.getValue(c.family.getBytes(), c.qualifier.getBytes()))));
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return Optional.of(response);
 }
Esempio n. 18
0
 public static Container setup(
     DataSource dataSource,
     Properties properties,
     Optional<File> pluginsPath,
     Optional<ClassLoader> classLoader)
     throws IOException {
   ClassLoader loader;
   if (pluginsPath.isPresent()) {
     File[] jars = pluginsPath.get().listFiles(f -> f.getPath().toLowerCase().endsWith(".jar"));
     List<URL> urls = new ArrayList<>(jars.length);
     for (File j : jars) {
       try {
         urls.add(j.toURI().toURL());
       } catch (MalformedURLException ex) {
         throw new IOException(ex);
       }
     }
     loader =
         classLoader.isPresent()
             ? new URLClassLoader(urls.toArray(new URL[urls.size()]), classLoader.get())
             : new URLClassLoader(urls.toArray(new URL[urls.size()]));
   } else if (classLoader.isPresent()) {
     loader = classLoader.get();
   } else {
     loader = Thread.currentThread().getContextClassLoader();
   }
   ServiceLoader<SystemAspect> aspects = ServiceLoader.load(SystemAspect.class, loader);
   return setup(dataSource, properties, Optional.of(loader), aspects.iterator());
 }
Esempio n. 19
0
  @Test
  public void _08_리덕션() {
    Stream<Integer> values = Stream.of(digits);
    // x 이전값, y 지금 요소 (v0 + v1 + v2.....)
    Optional<Integer> sum = values.reduce((x, y) -> x + y);

    assertThat(sum, is(Optional.of(366)));
  }
Esempio n. 20
0
 public Optional<Put> getPut() {
   if (valid()) {
     Put p = new Put(key);
     columns.forEach(c -> p.addColumn(c.family.getBytes(), c.qualifier.getBytes(), c.value));
     return Optional.of(p);
   }
   return Optional.empty();
 }
Esempio n. 21
0
 /**
  * Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the
  * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
  * user input or falling back to a default enum constant. For example, {@code
  * Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
  *
  * @since 12.0
  */
 public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) {
   checkNotNull(enumClass);
   checkNotNull(value);
   try {
     return Optional.of(Enum.valueOf(enumClass, value));
   } catch (IllegalArgumentException iae) {
     return Optional.absent();
   }
 }
  /**
   * Update the items to display. If this tab is currently selected the content will be refreshed.
   * Else it will be refreshed whenever this tab becomes active
   *
   * @param timereportContext The TaskWithWorklogs to show in this tab
   */
  public void updateItems(FetchTimereportContext timereportContext) {
    this.fetchTimereportContext = Optional.of(timereportContext);

    resultToDisplayChangedSinceLastRender = true;

    if (isSelected()) {
      refreshWorklogTableViewAndResults();
    }
  }
Esempio n. 23
0
 @Override
 public Optional<Point2D[]> findIntersection(Parabola thatParabola) {
   final double temp =
       Math.pow(thatParabola.getB(), 2) - 4 * thatParabola.getA() * (thatParabola.getC() - yValue);
   if (temp < 0) {
     return Optional.empty();
   } else if (temp == 0) {
     final double xRes = -1.0 * thatParabola.getB() / (2.0 * thatParabola.getA());
     final Point2D[] result = {new Point2D(xRes, this.yValue)};
     return Optional.of(result);
   } else {
     final double xRes1 =
         (-1.0 * thatParabola.getB() - Math.sqrt(temp)) / (2.0 * thatParabola.getA());
     final double xRes2 =
         (-1.0 * thatParabola.getB() + Math.sqrt(temp)) / (2.0 * thatParabola.getA());
     final Point2D[] result = {new Point2D(xRes1, this.yValue), new Point2D(xRes2, this.yValue)};
     return Optional.of(result);
   }
 }
 @Override
 public Optional<InternalConstructorDefinition> findConstructor(List<ActualParam> actualParams) {
   ensureIsInitialized(symbolResolver());
   for (InternalConstructorDefinition constructor : constructors) {
     if (constructor.match(symbolResolver(), actualParams)) {
       return Optional.of(constructor);
     }
   }
   return Optional.empty();
 }
Esempio n. 25
0
 @RequestMapping(value = "/events/{id}/prices/update", method = POST)
 public ValidationResult updatePrices(
     @PathVariable("id") int id,
     @RequestBody EventModification eventModification,
     Errors errors,
     Principal principal) {
   Event event = eventManager.getSingleEventById(id, principal.getName());
   return validateEventPrices(Optional.of(event), eventModification, errors)
       .ifSuccess(
           () -> eventManager.updateEventPrices(event, eventModification, principal.getName()));
 }
  @Override
  public Optional<Symbol> findSymbol(String name, SymbolResolver resolver) {
    // TODO support references to methods
    for (Property property : this.getAllProperties(resolver)) {
      if (property.getName().equals(name)) {
        return Optional.of(property);
      }
    }

    return super.findSymbol(name, resolver);
  }
 public <T> Optional<T> execSelectSqlAsPojoOpt(String sql, Object... args) {
   try {
     @SuppressWarnings("unchecked")
     T t = (T) jdbcTemplate.queryForObject(sql, makeRowMapperInstance(), args);
     if (log.isDebugEnabled()) log.debug("查找到记录:" + t);
     return Optional.of(t);
   } catch (EmptyResultDataAccessException e) {
     if (log.isDebugEnabled()) log.debug("没有查找到数据");
     return Optional.empty();
   }
 }
Esempio n. 28
0
  @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) {

    }
  }
Esempio n. 29
0
 @Override
 public Optional<Point2D[]> findIntersection(Parabola thatParabola) {
   final double aDiff = this.getParabola().getA() - thatParabola.getA();
   final double bDiff = this.getParabola().getB() - thatParabola.getB();
   final double cDiff = this.getParabola().getC() - thatParabola.getC();
   final double d = bDiff / (2.0 * aDiff);
   final double temp = Math.pow(d, 2) - cDiff / aDiff;
   if (temp < 0) {
     return Optional.empty();
   } else if (temp == 0) {
     final Point2D[] result = {new Point2D(d, this.getParabola().apply(d))};
     return Optional.of(result);
   } else {
     final double e = Math.sqrt(temp);
     final double deSum = -d + e;
     final double deDif = -d - e;
     final Point2D[] result = {
       new Point2D(deDif, this.getParabola().apply(deDif)),
       new Point2D(deSum, this.getParabola().apply(deSum))
     };
     return Optional.of(result);
   }
 }
Esempio n. 30
0
  /**
   * Tests that replaceIssueMilestone finds issue with the right id and successfully modify the
   * issue's milestone
   */
  @Test
  public void replaceIssueMilestone_successful() {
    Optional<Integer> milestoneIdReplacement = Optional.of(1);
    String repoId = "testowner/testrepo";

    TurboIssue issue1 = LogicTests.createIssueWithMilestone(1, Optional.of(0));
    TurboIssue issue2 = LogicTests.createIssueWithMilestone(2, Optional.of(1));
    TurboIssue issue3 = LogicTests.createIssueWithMilestone(3, Optional.of(1));
    List<TurboIssue> issues = Arrays.asList(issue3, issue2, issue1);

    Model model =
        new Model(
            repoId,
            issues,
            new ArrayList<TurboLabel>(),
            new ArrayList<TurboMilestone>(),
            new ArrayList<TurboUser>());
    Optional<TurboIssue> result =
        model.replaceIssueMilestone(issue1.getId(), milestoneIdReplacement);
    assertEquals(1, result.get().getId());
    assertTrue(result.get().getMilestone().isPresent());
    assertEquals(milestoneIdReplacement, result.get().getMilestone());
  }