Example usage for java.util Optional of

List of usage examples for java.util Optional of

Introduction

In this page you can find the example usage for java.util Optional of.

Prototype

public static <T> Optional<T> of(T value) 

Source Link

Document

Returns an Optional describing the given non- null value.

Usage

From source file:com.github.horrorho.inflatabledonkey.cloud.clients.BackupAccountClient.java

public static Optional<BackupAccount> backupAccount(HttpClient httpClient, CloudKitty kitty,
        ProtectionZone zone) throws IOException {

    List<CloudKit.RecordRetrieveResponse> responses = kitty.recordRetrieveRequest(httpClient, "mbksync",
            "BackupAccount");
    logger.debug("-- backupAccount() - responses: {}", responses);

    if (responses.size() != 1) {
        logger.warn("-- backupAccount() - bad response list size: {}", responses);
        return Optional.empty();
    }//from   w  ww .  j  a va2s .c om

    CloudKit.ProtectionInfo protectionInfo = responses.get(0).getRecord().getProtectionInfo();

    Optional<ProtectionZone> optionalNewZone = zone.newProtectionZone(protectionInfo);
    if (!optionalNewZone.isPresent()) {
        logger.warn("-- backupAccount() - failed to retrieve protection info");
        return Optional.empty();
    }
    ProtectionZone newZone = optionalNewZone.get();

    BackupAccount backupAccount = BackupAccountFactory.from(responses.get(0).getRecord(),
            (bs, id) -> newZone.decrypt(bs, id).get()); // TODO rework BackupAccount
    logger.debug("-- backupAccount() - backup account: {}", backupAccount);

    return Optional.of(backupAccount);
}

From source file:com.uber.hoodie.common.util.ParquetUtils.java

/**
 * Read the rowKey list matching the given filter, from the given parquet file. If the filter is empty,
 * then this will return all the rowkeys.
 *
 * @param filePath              The parquet file path.
 * @param configuration         configuration to build fs object
 * @param filter                record keys filter
 * @return Set                  Set of row keys matching candidateRecordKeys
 *//*from  w w w.j a v  a2s.  c  o  m*/
public static Set<String> filterParquetRowKeys(Configuration configuration, Path filePath, Set<String> filter) {
    Optional<RecordKeysFilterFunction> filterFunction = Optional.empty();
    if (CollectionUtils.isNotEmpty(filter)) {
        filterFunction = Optional.of(new RecordKeysFilterFunction(filter));
    }
    Configuration conf = new Configuration(configuration);
    conf.addResource(getFs(filePath.toString(), conf).getConf());
    Schema readSchema = HoodieAvroUtils.getRecordKeySchema();
    AvroReadSupport.setAvroReadSchema(conf, readSchema);
    AvroReadSupport.setRequestedProjection(conf, readSchema);
    ParquetReader reader = null;
    Set<String> rowKeys = new HashSet<>();
    try {
        reader = AvroParquetReader.builder(filePath).withConf(conf).build();
        Object obj = reader.read();
        while (obj != null) {
            if (obj instanceof GenericRecord) {
                String recordKey = ((GenericRecord) obj).get(HoodieRecord.RECORD_KEY_METADATA_FIELD).toString();
                if (!filterFunction.isPresent() || filterFunction.get().apply(recordKey)) {
                    rowKeys.add(recordKey);
                }
            }
            obj = reader.read();
        }
    } catch (IOException e) {
        throw new HoodieIOException("Failed to read row keys from Parquet " + filePath, e);

    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return rowKeys;
}

From source file:org.openmhealth.shim.fitbit.mapper.FitbitStepCountDataPointMapper.java

@Override
protected Optional<DataPoint<StepCount>> asDataPoint(JsonNode node) {

    int stepCountValue = Integer.parseInt(asRequiredString(node, "value"));

    if (stepCountValue == 0) {
        return Optional.empty();
    }/*w  ww  .  j a v  a  2  s. co  m*/

    StepCount.Builder builder = new StepCount.Builder(stepCountValue);

    Optional<LocalDate> stepDate = asOptionalLocalDate(node, "dateTime");

    if (stepDate.isPresent()) {
        LocalDateTime startDateTime = stepDate.get().atTime(0, 0, 0, 0);

        builder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(
                combineDateTimeAndTimezone(startDateTime), new DurationUnitValue(DAY, 1)));
    }

    StepCount measure = builder.build();
    Optional<Long> externalId = asOptionalLong(node, "logId");

    return Optional.of(newDataPoint(measure, externalId.orElse(null)));
}

From source file:com.uber.hoodie.common.TestRawTripPayload.java

public TestRawTripPayload(String jsonData, String rowKey, String partitionPath, String schemaStr)
        throws IOException {
    this(Optional.of(jsonData), rowKey, partitionPath, schemaStr, false);
}

From source file:net.hamnaberg.json.Property.java

public Optional<String> getPrompt() {
    return delegate.has("prompt") ? Optional.of(delegate.get("prompt").asText()) : Optional.<String>empty();
}

From source file:se.sawano.eureka.legacyregistrar.boot.LegacyInstances.java

public Optional<SpringBootInstanceConfig> withInstanceId(final String instanceId) {
    notNull(instanceId);/*from  w  w w. j av  a  2  s.  com*/

    final List<SpringBootInstanceConfig> found = instances.stream()
            .filter(conf -> instanceId.equals(conf.getInstanceId())).collect(toList());
    if (found.isEmpty()) {
        return Optional.empty();
    }

    isTrue(1 == found.size(), "Instance id must be unique. Found %d with id '%s'", found.size(), instanceId);

    return Optional.of(found.get(0));
}

From source file:io.kamax.mxisd.lookup.provider.DnsLookupProvider.java

private Optional<String> getDomain(String email) {
    int atIndex = email.lastIndexOf("@");
    if (atIndex == -1) {
        return Optional.empty();
    }// ww  w .  ja v a 2  s . c o  m

    return Optional.of(email.substring(atIndex + 1));
}

From source file:com.poc.restfulpoc.service.CustomerServiceTest.java

License:asdf

@BeforeAll
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.customerService = new CustomerServiceImpl(this.customerRepository, this.jmsTemplate);
    given(this.customerRepository.findAll()).willReturn(Arrays.asList(this.customer));
    given(this.customerRepository.findById(ArgumentMatchers.anyLong())).willReturn(Optional.of(this.customer));
    given(this.customerRepository.save(ArgumentMatchers.any(Customer.class))).willReturn(this.customer);
    given(this.customerRepository.findByFirstName(ArgumentMatchers.anyString()))
            .willReturn(Arrays.asList(this.customer));
    given(this.customerRepository.findByFirstName(ArgumentMatchers.eq("asdfg"))).willReturn(new ArrayList<>());

    given(this.customerRepository.findById(ArgumentMatchers.eq(0L))).willReturn(Optional.empty());

    BDDMockito.willDoNothing().given(this.jmsTemplate)
            .convertAndSend(ArgumentMatchers.eq("jms.message.endpoint"), ArgumentMatchers.anyLong());
}

From source file:com.okta.scim.SingleUserController.java

/**
 * Queries database for {@link User} with identifier
 * Updates response code with '404' if unable to locate {@link User}
 *
 * @param id {@link User#id}//w w  w  .ja  va  2 s .c  o  m
 * @param response HTTP Response
 * @return {@link #scimError(String, Optional)} / JSON {@link Map} of {@link User}
 *
 */
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody Map singeUserGet(@PathVariable String id, HttpServletResponse response) {

    try {
        User user = db.findById(id).get(0);
        return user.toScimResource();

    } catch (Exception e) {
        response.setStatus(404);
        return scimError("User not found", Optional.of(404));
    }
}

From source file:org.zalando.logbook.httpclient.Response.java

@Override
public Charset getCharset() {
    return Optional.of(response).map(request -> request.getFirstHeader("Content-Type")).map(Header::getValue)
            .map(ContentType::parse).map(ContentType::getCharset).orElse(StandardCharsets.UTF_8);
}