Exemple #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) {

    }
  }
  @SuppressWarnings("unchecked")
  public static Predicate[] deviceListPredicates(
      CriteriaBuilder cb,
      Root<Device> from,
      Optional<String> name,
      Optional<String> namePattern,
      Optional<String> status,
      Optional<Long> networkId,
      Optional<String> networkName,
      Optional<Long> deviceClassId,
      Optional<String> deviceClassName,
      Optional<String> deviceClassVersion,
      Optional<HivePrincipal> principal) {
    final List<Predicate> predicates = new LinkedList<>();

    name.ifPresent(n -> predicates.add(cb.equal(from.<String>get("name"), n)));
    namePattern.ifPresent(np -> predicates.add(cb.like(from.<String>get("name"), np)));
    status.ifPresent(s -> predicates.add(cb.equal(from.<String>get("status"), s)));

    final Join<Device, Network> networkJoin = (Join) from.fetch("network", JoinType.LEFT);
    networkId.ifPresent(nId -> predicates.add(cb.equal(networkJoin.<Long>get("id"), nId)));
    networkName.ifPresent(
        nName -> predicates.add(cb.equal(networkJoin.<String>get("name"), nName)));

    final Join<Device, DeviceClass> dcJoin = (Join) from.fetch("deviceClass", JoinType.LEFT);
    deviceClassId.ifPresent(dcId -> predicates.add(cb.equal(dcJoin.<Long>get("id"), dcId)));
    deviceClassName.ifPresent(
        dcName -> predicates.add(cb.equal(dcJoin.<String>get("name"), dcName)));
    deviceClassVersion.ifPresent(
        dcVersion -> predicates.add(cb.equal(dcJoin.<String>get("version"), dcVersion)));

    predicates.addAll(deviceSpecificPrincipalPredicates(cb, from, principal));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
  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();
              });
        });
  }
 public static void respond(
     HttpExchange exchange, String redirectUrl, String name, Optional<String> message)
     throws IOException {
   LOG.finer(
       () ->
           "Redirecting to "
               + name
               + " ["
               + redirectUrl
               + "]"
               + message.map(m -> ": " + m).orElse(""));
   exchange.getResponseHeaders().set("Location", redirectUrl);
   exchange.sendResponseHeaders(302, 0);
   if ("HEAD".equals(exchange.getRequestMethod())) return;
   try (PrintStream out = new PrintStream(exchange.getResponseBody())) {
     HeaderResponse.send(out, SessionFilter.getSession(exchange), "Redirection to " + name);
     out.println("<DIV>");
     message.ifPresent(m -> out.printf("%s<BR>\n", m));
     out.printf("Go to: <A href=\"%s\"><B>%s</B></A>", redirectUrl, name);
     out.println("</DIV>");
   } catch (Exception e) {
     LOG.log(Level.SEVERE, e, () -> "Failed generating redirection to '" + name + "': ");
     throw (e);
   }
 }
Exemple #6
0
 private Map<String, T> mapToCode(String prefix) {
   Map<String, T> result = Maps.newHashMap();
   value.ifPresent((v) -> result.put(prefix, v));
   leftNode.ifPresent((v) -> result.putAll(v.mapToCode(prefix + "0")));
   rightNode.ifPresent((v) -> result.putAll(v.mapToCode(prefix + "1")));
   return result;
 }
  @Override
  @SuppressWarnings("unchecked")
  public <T> T getBean(Class<T> clazz) {
    Object bean = beans.get(clazz);
    if (bean != null) {
      return (T) bean;
    }

    BeanDefinition beanDefinition = beanDefinitions.get(clazz);
    if (beanDefinition != null && beanDefinition instanceof AnnotatedBeanDefinition) {
      Optional<Object> optionalBean = createAnnotatedBean(beanDefinition);
      optionalBean.ifPresent(b -> beans.put(clazz, b));
      initialize(bean, clazz);
      return (T) optionalBean.orElse(null);
    }

    Optional<Class<?>> concreteClazz = BeanFactoryUtils.findConcreteClass(clazz, getBeanClasses());
    if (!concreteClazz.isPresent()) {
      return null;
    }

    beanDefinition = beanDefinitions.get(concreteClazz.get());
    bean = inject(beanDefinition);
    beans.put(concreteClazz.get(), bean);
    initialize(bean, concreteClazz.get());
    return (T) bean;
  }
Exemple #8
0
  private void addEadLevel(
      XMLStreamWriter sw,
      int num,
      DocumentaryUnit subUnit,
      Optional<Description> priorDescOpt,
      String langCode) {
    logger.trace("Adding EAD sublevel: c" + num);
    Optional<Description> descOpt =
        LanguageHelpers.getBestDescription(subUnit, priorDescOpt, langCode);
    String levelTag = String.format("c%02d", num);
    tag(
        sw,
        levelTag,
        getLevelAttrs(descOpt, null),
        () -> {
          descOpt.ifPresent(
              desc -> {
                addDataSection(sw, null, subUnit, desc, langCode);
                addPropertyValues(sw, desc);
                addControlAccess(sw, desc);
              });

          for (DocumentaryUnit child : getOrderedChildren(subUnit)) {
            addEadLevel(sw, num + 1, child, descOpt, langCode);
          }
        });
  }
 /** Pauses current playback. */
 public void pause() {
   optionalMediaPlayer.ifPresent(
       player -> {
         state = MediaPlayerState.PAUSED;
         player.pause();
       });
 }
  void migrateEventToCurrentVersion(Event event) {
    Optional<EventMigration> optional =
        optionally(() -> eventMigrationRepository.loadEventMigration(event.getId()));
    boolean alreadyDefined = optional.isPresent();
    if (!alreadyDefined || optional.filter(this::needsFixing).isPresent()) {
      transactionTemplate.execute(
          s -> {
            optional.ifPresent(
                eventMigration ->
                    eventMigrationRepository.lockEventMigrationForUpdate(eventMigration.getId()));
            createMissingTickets(event);
            fillDescriptions(event);
            if (alreadyDefined) {
              EventMigration eventMigration = optional.get();
              int result =
                  eventMigrationRepository.updateMigrationData(
                      eventMigration.getId(),
                      currentVersionAsString,
                      buildTimestamp,
                      EventMigration.Status.COMPLETE.name());
              Validate.isTrue(result == 1, "error during update " + result);
            } else {
              eventMigrationRepository.insertMigrationData(
                  event.getId(),
                  currentVersionAsString,
                  buildTimestamp,
                  EventMigration.Status.COMPLETE.name());
            }

            return null;
          });
    }
  }
Exemple #11
0
  private void showBoardPicker(List<String> boards) {
    BoardPickerDialog boardPickerDialog = new BoardPickerDialog(boards, stage);
    Optional<String> result = boardPickerDialog.showAndWait();
    stage.show();

    result.ifPresent(res -> ui.getMenuControl().switchBoard(res));
  }
Exemple #12
0
 /**
  * Returns if the {@link de.mki.jchess.server.implementation.threePersonChess.figures.King} of a
  * {@link de.mki.jchess.server.model.Client} is checked with a hypothetical figure layout.0 Used
  * for predetermination if a movement is valid.
  *
  * @param clientId The ID of the {@link de.mki.jchess.server.model.Client}.
  * @return Returns true if the {@link
  *     de.mki.jchess.server.implementation.threePersonChess.figures.King} would be checked.
  */
 @Override
 public boolean willKingBeChecked(String clientId) {
   // The king
   final boolean[] output = {false};
   Optional<King> king =
       getFigures()
           .stream()
           .filter(hexagonFigure -> hexagonFigure.getClient().getId().equals(clientId))
           .filter(hexagonFigure -> hexagonFigure instanceof King)
           .map(hexagonFigure -> (King) hexagonFigure)
           .findFirst();
   // Check if any figure could attack our kings hexagon
   king.ifPresent(
       king1 ->
           getFigures()
               .stream()
               .parallel()
               // Only active figures
               .filter(hexagonFigure -> !hexagonFigure.getHypotheticalRemoved())
               // Enemy players figures
               .filter(hexagonFigure -> !hexagonFigure.getClient().getId().equals(clientId))
               // Go through all attackable fields
               .forEach(
                   hexagonFigure ->
                       hexagonFigure
                           .getHypotheticalAttackableFields(this)
                           .forEach(
                               hexagon -> {
                                 if (hexagon
                                     .getNotation()
                                     .equals(king1.getHypotheticalPosition().getNotation()))
                                   output[0] = true;
                               })));
   return output[0];
 }
 /**
  * Jums into given timestamp of the track.
  *
  * @param value timestamp
  */
 public void seek(double value) {
   optionalMediaPlayer.ifPresent(
       player -> {
         Duration duration = new Duration(value);
         player.seek(duration);
       });
 }
 /** Plays/resumes current playback. */
 public void play() {
   optionalMediaPlayer.ifPresent(
       player -> {
         state = MediaPlayerState.RUNNING;
         player.play();
       });
 }
  public static Predicate[] deviceClassListPredicates(
      CriteriaBuilder cb,
      Root<DeviceClass> from,
      Optional<String> name,
      Optional<String> namePattern,
      Optional<String> version) {
    final List<Predicate> predicates = new LinkedList<>();
    if (namePattern.isPresent()) {
      namePattern.ifPresent(np -> predicates.add(cb.like(from.get("name"), np)));
    } else {
      name.ifPresent(n -> predicates.add(cb.equal(from.get("name"), n)));
    }

    version.ifPresent(v -> predicates.add(cb.equal(from.get(DeviceClass.VERSION_COLUMN), v)));
    return predicates.toArray(new Predicate[predicates.size()]);
  }
 /** Rewinds 10 seconds of song. */
 public void rewind() {
   optionalMediaPlayer.ifPresent(
       player -> {
         Duration pushedTime =
             new Duration(getCurrentTime() - AudioModel.FORWARD_REVIND_MOVE_STEP_MILLIS);
         player.seek(pushedTime);
       });
 }
 @Override
 public void positionUpdated(long position) {
   // Cache the operation to avoid too many file writes
   if (currentPosition == null || position != currentPosition) {
     positionStoreOption.ifPresent(store -> store.setFilePosition(tailingFile.toPath(), position));
     currentPosition = position;
   }
 }
Exemple #18
0
 private Optional<BibEntry> createNewBlankEntry(String fileName) {
   Optional<BibEntry> newEntry = createNewEntry();
   newEntry.ifPresent(
       bibEntry -> {
         DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
         dfh.linkPdfToEntry(fileName, bibEntry);
       });
   return newEntry;
 }
Exemple #19
0
 private void updateItem(ODocument item) {
   projectOptional.ifPresent(
       project -> {
         Issue issue = createIssueFromWorkItem(item, project);
         persistIssue(item, issue);
         persistNewComments(item, issue);
         persistAttachments(item, issue);
       });
 }
 private List<Expression> getCaseResultExpressions(
     List<WhenClause> whenClauses, Optional<Expression> defaultValue) {
   List<Expression> resultExpressions = new ArrayList<>();
   for (WhenClause whenClause : whenClauses) {
     resultExpressions.add(whenClause.getResult());
   }
   defaultValue.ifPresent(resultExpressions::add);
   return resultExpressions;
 }
Exemple #21
0
  public void setEntry(BibEntry newEntry) {

    entry.filter(e -> e != newEntry).ifPresent(e -> e.unregisterListener(this));
    entry = Optional.ofNullable(newEntry);
    entry.ifPresent(e -> e.registerListener(this));

    updateLayout();
    update();
  }
Exemple #22
0
 @Override
 public List<Symbol> getOutputSymbols() {
   ImmutableList.Builder<Symbol> outputSymbolsBuilder =
       ImmutableList.<Symbol>builder()
           .addAll(replicateSymbols)
           .addAll(Iterables.concat(unnestSymbols.values()));
   ordinalitySymbol.ifPresent(outputSymbolsBuilder::add);
   return outputSymbolsBuilder.build();
 }
 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));
 }
  private void setCSSContextVariables(
      IApplicationContext applicationContext, IEclipseContext context) {
    boolean highContrastMode = getApplicationDisplay().getHighContrast();

    Optional<String> cssURI =
        highContrastMode
            ? Optional.empty()
            : getArgValue(IWorkbench.CSS_URI_ARG, applicationContext, false);

    cssURI.ifPresent(
        cssURIValue -> {
          context.set(IWorkbench.CSS_URI_ARG, cssURIValue);
        });

    Optional<String> themeId =
        highContrastMode
            ? Optional.of(HIGH_CONTRAST_THEME_ID)
            : getArgValue(E4Application.THEME_ID, applicationContext, false);

    if (!themeId.isPresent() && !cssURI.isPresent()) {
      context.set(E4Application.THEME_ID, DEFAULT_THEME_ID);
    } else {
      context.set(E4Application.THEME_ID, themeId.orElseGet(() -> null));
    }

    // validate static CSS URI
    cssURI
        .filter(cssURIValue -> !cssURIValue.startsWith("platform:/plugin/"))
        .ifPresent(
            cssURIValue -> {
              System.err.println(
                  "Warning. Use the \"platform:/plugin/Bundle-SymbolicName/path/filename.extension\" URI for the  parameter:   "
                      + IWorkbench.CSS_URI_ARG); // $NON-NLS-1$
              context.set(E4Application.THEME_ID, cssURIValue);
            });

    Optional<String> cssResourcesURI =
        getArgValue(IWorkbench.CSS_RESOURCE_URI_ARG, applicationContext, false);
    cssResourcesURI.ifPresent(
        cssResourcesURIValue -> {
          context.set(IWorkbench.CSS_RESOURCE_URI_ARG, cssResourcesURIValue);
        });
  }
  public static Predicate[] oAuthClientListPredicates(
      CriteriaBuilder cb,
      Root<OAuthClient> from,
      Optional<String> nameOpt,
      Optional<String> namePattern,
      Optional<String> domainOpt,
      Optional<String> oauthIdOpt) {
    List<Predicate> predicates = new LinkedList<>();

    if (namePattern.isPresent()) {
      namePattern.ifPresent(pattern -> predicates.add(cb.like(from.get("name"), pattern)));
    } else {
      nameOpt.ifPresent(name -> predicates.add(cb.equal(from.get("name"), name)));
    }
    domainOpt.ifPresent(domain -> predicates.add(cb.equal(from.get("domain"), domain)));
    oauthIdOpt.ifPresent(id -> predicates.add(cb.equal(from.get("oauthId"), id)));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
  public static Predicate[] userListPredicates(
      CriteriaBuilder cb,
      Root<User> from,
      Optional<String> loginOpt,
      Optional<String> loginPattern,
      Optional<Integer> roleOpt,
      Optional<Integer> statusOpt) {
    List<Predicate> predicates = new LinkedList<>();

    if (loginPattern.isPresent()) {
      loginPattern.ifPresent(pattern -> predicates.add(cb.like(from.get("login"), pattern)));
    } else {
      loginOpt.ifPresent(login -> predicates.add(cb.equal(from.get("login"), login)));
    }

    roleOpt.ifPresent(role -> predicates.add(cb.equal(from.get("role"), role)));
    statusOpt.ifPresent(status -> predicates.add(cb.equal(from.get("status"), status)));

    return predicates.toArray(new Predicate[predicates.size()]);
  }
Exemple #27
0
  public void update() {
    StringBuilder sb = new StringBuilder();
    ExportFormats.entryNumber =
        1; // Set entry number in case that is included in the preview layout.
    entry.ifPresent(
        entry ->
            layout.ifPresent(
                layout ->
                    sb.append(
                        layout.doLayout(
                            entry,
                            databaseContext.map(BibDatabaseContext::getDatabase).orElse(null),
                            highlightPattern))));
    String newValue = sb.toString();

    previewPane.setText(newValue);
    previewPane.revalidate();

    // Scroll to top:
    scrollToTop();
  }
Exemple #28
0
 private Described validatePublisher(Optional<String> publisher, Optional<Identified> identified) {
   Described described = (Described) identified.get();
   publisher.ifPresent(
       key -> {
         if (!key.equals(described.getPublisher().key())) {
           throw new RuntimeException(
               (String.format(
                   "Described %d is not published by '%s'", described.getId(), publisher)));
         }
       });
   return described;
 }
 /**
  * Adds ORDER BY ... ASC/DESC to query Mutates provided criteria query
  *
  * @param sortFieldOpt - field to sort by (field name in JPA Entity class)
  * @param asc - true if order should be ASC, false otherwise
  */
 public static void order(
     CriteriaBuilder cb,
     CriteriaQuery<?> cq,
     Root<?> from,
     Optional<String> sortFieldOpt,
     boolean asc) {
   sortFieldOpt.ifPresent(
       sortField -> {
         Order order = asc ? cb.asc(from.get(sortField)) : cb.desc(from.get(sortField));
         cq.orderBy(order);
       });
 }
  public static Predicate[] oAuthGrantsListPredicates(
      CriteriaBuilder cb,
      Root<OAuthGrant> from,
      User user,
      Optional<Date> startOpt,
      Optional<Date> endOpt,
      Optional<String> oAuthIdOpt,
      Optional<Integer> typeOpt,
      Optional<String> scopeOpt,
      Optional<String> redirectUri,
      Optional<Integer> accessType) {
    List<Predicate> predicates = new LinkedList<>();

    if (!user.isAdmin()) {
      predicates.add(from.join("user").in(user));
    }

    startOpt.ifPresent(start -> predicates.add(cb.greaterThan(from.get("timestamp"), start)));
    endOpt.ifPresent(end -> predicates.add(cb.lessThan(from.get("timestamp"), end)));
    oAuthIdOpt.ifPresent(id -> predicates.add(cb.equal(from.join("client").get("oauthId"), id)));
    typeOpt.ifPresent(type -> predicates.add(cb.equal(from.get("type"), type)));
    scopeOpt.ifPresent(scope -> predicates.add(cb.equal(from.get("scope"), scope)));
    redirectUri.ifPresent(uri -> predicates.add(cb.equal(from.get("redirectUri"), uri)));
    accessType.ifPresent(at -> predicates.add(cb.equal(from.get("accessType"), at)));

    return predicates.toArray(new Predicate[predicates.size()]);
  }