Java Code Examples for java.util.Optional#ofNullable()

The following examples show how to use java.util.Optional#ofNullable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StackBasedExitCriteria.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: SuperWitnessAllowance.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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));


}
 
Example 3
Source File: ClaimValueWrapper.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 4
Source File: DecimalDomain.java    From tcases with MIT License 5 votes vote down vote up
/**
 * 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);
  }
 
Example 5
Source File: PrioritizedParkingPositionSupplier.java    From openAGV with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 6
Source File: MtasDocumentIndex.java    From inception with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 7
Source File: ClavaId.java    From clava with Apache License 2.0 4 votes vote down vote up
public Optional<ClavaId> getNext() {
    return Optional.ofNullable(next);
}
 
Example 8
Source File: ActivityPartyImpl.java    From Javacord with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<String> getId() {
    return Optional.ofNullable(id);
}
 
Example 9
Source File: IMAPUtils.java    From mnIMAPSync with Apache License 2.0 4 votes vote down vote up
private static Optional<String> translateInbox(String folderName, String inboxName) {
  if (INBOX_MAILBOX.equalsIgnoreCase(folderName)) {
    return Optional.ofNullable(inboxName);
  }
  return Optional.empty();
}
 
Example 10
Source File: Schema.java    From smithy with Apache License 2.0 4 votes vote down vote up
public Optional<Number> getMultipleOf() {
    return Optional.ofNullable(multipleOf);
}
 
Example 11
Source File: JobApiController.java    From swaggy-jenkins with MIT License 4 votes vote down vote up
@Override
public Optional<NativeWebRequest> getRequest() {
    return Optional.ofNullable(request);
}
 
Example 12
Source File: StandardFunnel.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<String> getVersionedComponentId() {
    return Optional.ofNullable(versionedComponentId.get());
}
 
Example 13
Source File: Nccopy.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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());
  }
}
 
Example 14
Source File: FakeApiController.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<NativeWebRequest> getRequest() {
    return Optional.ofNullable(request);
}
 
Example 15
Source File: InternalStepRunner.java    From vespa with Apache License 2.0 4 votes vote down vote up
/** 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())));
}
 
Example 16
Source File: Analysis.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 4 votes vote down vote up
public Optional<Integer> getLimitClause() {
  return Optional.ofNullable(limitClause);
}
 
Example 17
Source File: LoginData.java    From openemm with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * 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);
}
 
Example 18
Source File: ModuleDescriptor.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * 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);
    }
}
 
Example 19
Source File: SchemaRegistration.java    From vertx-graphql-service-discovery with Apache License 2.0 2 votes vote down vote up
/**
 * 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"));
}
 
Example 20
Source File: PaymentSchedule.java    From Strata with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}