java.util.Optional#ofNullable ( )源码实例Demo

下面列出了java.util.Optional#ofNullable ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cloudbreak   文件: StackBasedExitCriteria.java
@Override
public boolean isExitNeeded(ExitCriteriaModel exitCriteriaModel) {
    StackBasedExitCriteriaModel model = (StackBasedExitCriteriaModel) exitCriteriaModel;
    LOGGER.debug("Check isExitNeeded for model: {}", model);

    Optional<Long> stackIdOpt = model.getStackId();
    if (stackIdOpt.isPresent()) {
        Optional<PollGroup> stackPollGroup = Optional.ofNullable(InMemoryStateStore.getStack(stackIdOpt.get()));
        if (stackPollGroup.isPresent() && CANCELLED.equals(stackPollGroup.get())) {
            LOGGER.debug("Stack is getting terminated, polling is cancelled.");
            return true;
        } else if (stackPollGroup.isEmpty()) {
            LOGGER.debug("No InMemoryState found, cancel polling");
            return true;
        }
    }
    return false;
}
 
源代码2 项目: gsc-core   文件: SuperWitnessAllowance.java
@Test(enabled = false)
public void testQueryAllowance() {
  WitnessList witnesslist = blockingStubFull
      .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build());
  Optional<WitnessList> result = Optional.ofNullable(witnesslist);
  WitnessList witnessList = result.get();
  Integer allowanceNum = 0;
  for (Integer i = 0; i < witnessList.getWitnessesCount(); i++) {
    /*      witnessList.getWitnesses(i).getAddress();
    witnessList.getWitnesses(i).getAddress();
    witnessList.getWitnesses(i).getAddress();
    witnessList.getWitnesses(i).getAddress();*/
    ByteString addressBs = witnessList.getWitnesses(i).getAddress();
    Account request = Account.newBuilder().setAddress(addressBs).build();
    request = blockingStubFull.getAccount(request);
    if (request.getAllowance() > 0) {
      allowanceNum++;
    }
    logger.info("Account " + Integer.toString(i) + " allowance is " + Long.toString(request
        .getAllowance()));

  }
  logger.info("Allowance num is " + Integer.toString(allowanceNum));


}
 
源代码3 项目: tcases   文件: DecimalDomain.java
/**
 * Defines the value range for this domain.
 */
public void setRange( Range range)
  {
  Optional<Range> ifRange = Optional.ofNullable( range);

  setExcluded(
    ifRange.map( Range::getExcluded).orElse( emptySet())
    .stream()
    .map( BigDecimal::new)
    .collect( toSet()));

  BigDecimal min = 
    Optional.ofNullable( ifRange.map( Range::getMin).orElse( null))
    .map( BigDecimal::new)
    .orElse( new BigDecimal( -getMaxRange()));

  BigDecimal max = 
    Optional.ofNullable( ifRange.map( Range::getMax).orElse( null))
    .map( BigDecimal::new)
    .orElse( new BigDecimal( getMaxRange()));

  int unitScale = Math.max( 1, Math.max( min.scale(), max.scale()));
  BigDecimal unit = new BigDecimal( BigInteger.ONE, unitScale);
  
  setRange(
    ifRange.map( Range::isMinExclusive).orElse( false)? min.add( unit) : min,
    ifRange.map( Range::isMaxExclusive).orElse( false)? max.subtract( unit) : max);
  }
 
@Override
public Optional<Point> findParkingPosition(final Vehicle vehicle) {
  requireNonNull(vehicle, "vehicle");

  if (vehicle.getCurrentPosition() == null) {
    return Optional.empty();
  }

  int currentPriority = priorityOfCurrentPosition(vehicle);
  Set<Point> parkingPosCandidates = findUsableParkingPositions(vehicle).stream()
      .filter(point -> hasHigherPriorityThan(point, currentPriority))
      .collect(Collectors.toSet());

  if (parkingPosCandidates.isEmpty()) {
    LOG.debug("{}: No parking position candidates found.", vehicle.getName());
    return Optional.empty();
  }

  LOG.debug("{}: Selecting parking position from candidates {}.",
            vehicle.getName(),
            parkingPosCandidates);

  parkingPosCandidates = filterPositionsWithHighestPriority(parkingPosCandidates);
  Point parkingPos = nearestPoint(vehicle, parkingPosCandidates);

  LOG.debug("{}: Selected parking position {}.", vehicle.getName(), parkingPos);

  return Optional.ofNullable(parkingPos);
}
 
源代码5 项目: inception   文件: MtasDocumentIndex.java
@Override
public Optional<String> getTimestamp(AnnotationDocument aDocument) throws IOException
{
    Optional<String> result = Optional.empty();

    // Prepare index searcher for accessing index
    Directory directory = FSDirectory.open(getIndexDir().toPath());
    IndexReader indexReader = DirectoryReader.open(directory);
    IndexSearcher indexSearcher = new IndexSearcher(indexReader);

    // Prepare query for the annotation document for this annotation document
    Term term = new Term(FIELD_ID,
            String.format("%d/%d", aDocument.getDocument().getId(), aDocument.getId()));
    
    TermQuery query = new TermQuery(term);

    // Do query
    TopDocs docs = indexSearcher.search(query, 1);

    if (docs.scoreDocs.length > 0) {
        // If there are results, retrieve first document, since all results should come
        // from the same document
        Document document = indexSearcher.doc(docs.scoreDocs[0].doc);

        // Retrieve the timestamp field if it exists
        if (document.getField(FIELD_TIMESTAMP) != null) {
            result = Optional.ofNullable(StringUtils
                    .trimToNull(document.getField(FIELD_TIMESTAMP).stringValue()));
        }
    }
    
    return result;
}
 
源代码6 项目: smallrye-jwt   文件: ClaimValueWrapper.java
@Override
@SuppressWarnings("unchecked")
public T getValue() {
    Object value = JsonUtils.convert(klass, producer.getValue(getName(), false));

    if (optional) {
        /*
         * Wrap the raw value in Optional based on type parameter of the
         * ClaimValue checked during construction.
         */
        return (T) Optional.ofNullable(value);
    }

    return (T) value;
}
 
public Optional<Integer> getLimitClause() {
  return Optional.ofNullable(limitClause);
}
 
源代码8 项目: vespa   文件: InternalStepRunner.java
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
    return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
 
源代码9 项目: openapi-generator   文件: FakeApiController.java
@Override
public Optional<NativeWebRequest> getRequest() {
    return Optional.ofNullable(request);
}
 
源代码10 项目: netcdf-java   文件: Nccopy.java
public static void main(String[] args) {
  String progName = Nccopy.class.getName();
  CommandLine cmdLine;
  try {
    cmdLine = new CommandLine(progName, args);
    if (cmdLine.help) {
      cmdLine.printUsage();
      return;
    }
  } catch (ParameterException e) {
    System.err.println(e.getMessage());
    System.err.printf("Try \"%s --help\" for more information.%n", progName);
    return;
  }

  String datasetIn = cmdLine.inputFile;
  String datasetOut = cmdLine.outputFile.getAbsolutePath();
  System.out.printf("NetcdfDatataset read from %s write %s to %s ", datasetIn, cmdLine.format, datasetOut);

  Optional<File> diskCacheDir = Optional.ofNullable(cmdLine.diskCacheRoot);
  if (diskCacheDir.isPresent()) {
    DiskCache.setRootDirectory(diskCacheDir.get().getAbsolutePath());
    // if user has set the diskCacheRootDir, then always use it over trying the "normal" locations first.
    // Was seeing an issue on cloud-mounted drives in which the I/O error generated by even trying to write data next
    // to the original file
    // caused the the JVM to close out (not the case on a local write protected directory).
    DiskCache.setCachePolicy(true);
  }

  CancelTask cancel = CancelTask.create();
  try (NetcdfFile ncfileIn = ucar.nc2.dataset.NetcdfDatasets.openFile(datasetIn, cancel)) {

    NetcdfFormatWriter.Builder builder = NetcdfFormatWriter.builder().setNewFile(true).setFormat(getFormat(cmdLine))
        .setLocation(datasetOut).setChunker(cmdLine.getNc4Chunking()).setUseJna(cmdLine.useJna);
    NetcdfCopier copier = NetcdfCopier.create(ncfileIn, builder);

    try (NetcdfFile ncfileOut = copier.write(cancel)) {

    } finally {
      cancel.setDone(true);
      System.out.printf("%s%n", cancel);
    }

  } catch (Exception ex) {
    System.out.printf("%s = %s %n", ex.getClass().getName(), ex.getMessage());
  }
}
 
源代码11 项目: clava   文件: ClavaId.java
public Optional<ClavaId> getNext() {
    return Optional.ofNullable(next);
}
 
源代码12 项目: nifi   文件: StandardFunnel.java
@Override
public Optional<String> getVersionedComponentId() {
    return Optional.ofNullable(versionedComponentId.get());
}
 
源代码13 项目: swaggy-jenkins   文件: JobApiController.java
@Override
public Optional<NativeWebRequest> getRequest() {
    return Optional.ofNullable(request);
}
 
源代码14 项目: smithy   文件: Schema.java
public Optional<Number> getMultipleOf() {
    return Optional.ofNullable(multipleOf);
}
 
源代码15 项目: mnIMAPSync   文件: IMAPUtils.java
private static Optional<String> translateInbox(String folderName, String inboxName) {
  if (INBOX_MAILBOX.equalsIgnoreCase(folderName)) {
    return Optional.ofNullable(inboxName);
  }
  return Optional.empty();
}
 
源代码16 项目: Javacord   文件: ActivityPartyImpl.java
@Override
public Optional<String> getId() {
    return Optional.ofNullable(id);
}
 
源代码17 项目: Bytecoder   文件: ModuleDescriptor.java
/**
 * Returns the string with the possibly-unparseable version of the module
 * if recorded at compile-time.
 *
 * @return The string containing the version of the module if recorded
 *         at compile-time, or an empty {@code Optional} if no version
 *         was recorded
 *
 * @see #compiledVersion()
 */
public Optional<String> rawCompiledVersion() {
    if (compiledVersion != null) {
        return Optional.of(compiledVersion.toString());
    } else {
        return Optional.ofNullable(rawCompiledVersion);
    }
}
 
源代码18 项目: openemm   文件: LoginData.java
/**
 * Instantiates a new login data.
 *
 * @param trackId ID of tracking record
 * @param loginTime the login time
 * @param loginIP the login IP
 * @param loginStatus the login status
 * @param usernameOrNull user name or <code>null</code>
 */
public LoginData(final int trackId, final Date loginTime, final String loginIP, final LoginStatus loginStatus, final String usernameOrNull) {
	this.trackId = trackId;
	this.loginTime = Objects.requireNonNull(loginTime);
	this.loginIP = Objects.requireNonNull(loginIP);
	this.loginStatus = Objects.requireNonNull(loginStatus);
	this.username = Optional.ofNullable(usernameOrNull);
}
 
/**
 * Gets the name of the publisher that registered the schema, {@code null} if published independently.
 *
 * @return the publisher name, or null
 */
public Optional<String> getPublisherId() {
    return Optional.ofNullable(record.getMetadata().getString("publisherId"));
}
 
源代码20 项目: Strata   文件: PaymentSchedule.java
/**
 * Gets the optional start date of the first regular payment schedule period, which is the end date of the initial stub.
 * <p>
 * This is used to identify the boundary date between the initial stub and the first regular period.
 * In most cases there is no need to specify this as it can be worked out from other information.
 * It must be used when there is a need to produce a payment schedule with an initial stub that combines
 * an initial stub from the accrual schedule with the first regular period of the accrual schedule.
 * <p>
 * This is an unadjusted date, and as such it might not be a valid business day.
 * It must equal one of the unadjusted dates on the accrual schedule.
 * <p>
 * If {@linkplain #getPaymentRelativeTo() paymentRelativeTo} is 'PeriodEnd' then this field
 * corresponds to {@code firstPaymentDate} in FpML.
 * @return the optional value of the property, not null
 */
public Optional<LocalDate> getFirstRegularStartDate() {
  return Optional.ofNullable(firstRegularStartDate);
}