Example usage for java.util Optional orElse

List of usage examples for java.util Optional orElse

Introduction

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

Prototype

public T orElse(T other) 

Source Link

Document

If a value is present, returns the value, otherwise returns other .

Usage

From source file:edu.jhu.hlt.concrete.ingesters.alnc.ALNCIngester.java

public ALNCIngester(Path path) throws IngestException {
    this.ts = Timing.currentLocalTime();
    this.path = path;
    try {/*from   w w w .  j  av  a 2 s . co m*/
        Optional<String> inferredType = Optional.ofNullable(Files.probeContentType(this.path));
        String ft = inferredType.orElse("unk");
        if (ft.contains("bzip"))
            this.conv = new ALNCFileConverter(new BZip2CompressorInputStream(Files.newInputStream(this.path)));
        else
            this.conv = new ALNCFileConverter(Files.newInputStream(this.path));
    } catch (IOException e) {
        throw new IngestException(e);
    }
}

From source file:com.blackducksoftware.integration.hub.detect.detector.clang.DependenciesListFileManager.java

public Set<String> generateDependencyFilePaths(final File workingDir, final CompileCommand compileCommand,
        final boolean cleanup) {
    final Set<String> dependencyFilePaths = new HashSet<>();
    final Optional<File> depsMkFile = generate(workingDir, compileCommand);
    dependencyFilePaths.addAll(parse(depsMkFile.orElse(null)));
    if (cleanup) {
        depsMkFile.ifPresent(File::delete);
    }//from   w  w w . j  av a2s. c  o m
    return dependencyFilePaths;
}

From source file:org.jbb.system.impl.logging.AppenderBrowser.java

public Optional<LogAppender> searchForAppenderWithName(LoggingConfiguration loggingConfiguration, String name) {
    Validate.notNull(loggingConfiguration);

    if (StringUtils.isBlank(name)) {
        return Optional.empty();
    }/*from ww  w .  ja v a 2 s.c o m*/

    List<LogConsoleAppender> consoleAppenders = loggingConfiguration.getConsoleAppenders();
    Optional<LogConsoleAppender> matchedConsoleAppender = consoleAppenders.stream()
            .filter(consoleAppender -> consoleAppender.getName().equals(name)).findFirst();
    if (matchedConsoleAppender.isPresent()) {
        return Optional.of(matchedConsoleAppender.get());
    }

    List<LogFileAppender> fileAppenders = loggingConfiguration.getFileAppenders();
    Optional<LogFileAppender> matchedFileAppender = fileAppenders.stream()
            .filter(fileAppender -> fileAppender.getName().equals(name)).findFirst();
    return Optional.ofNullable(matchedFileAppender.orElse(null));
}

From source file:org.apache.nifi.csv.CSVSchemaInference.java

private DataType getDataType(final String value) {
    if (value == null || value.isEmpty()) {
        return null;
    }//from   w w w .  ja v a 2s.co m

    if (NumberUtils.isParsable(value)) {
        if (value.contains(".")) {
            try {
                final double doubleValue = Double.parseDouble(value);
                if (doubleValue > Float.MAX_VALUE || doubleValue < Float.MIN_VALUE) {
                    return RecordFieldType.DOUBLE.getDataType();
                }

                return RecordFieldType.FLOAT.getDataType();
            } catch (final NumberFormatException nfe) {
                return RecordFieldType.STRING.getDataType();
            }
        }

        try {
            final long longValue = Long.parseLong(value);
            if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) {
                return RecordFieldType.LONG.getDataType();
            }

            return RecordFieldType.INT.getDataType();
        } catch (final NumberFormatException nfe) {
            return RecordFieldType.STRING.getDataType();
        }
    }

    if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
        return RecordFieldType.BOOLEAN.getDataType();
    }

    final Optional<DataType> timeDataType = timeValueInference.getDataType(value);
    return timeDataType.orElse(RecordFieldType.STRING.getDataType());
}

From source file:org.jamocha.filter.SymbolCollector.java

public Map<SingleFactVariable, Pair<VariableSymbol, List<Pair<VariableSymbol, SingleSlotVariable>>>> toSlotVariablesByFactVariable() {
    final Map<SingleFactVariable, List<Pair<VariableSymbol, SingleSlotVariable>>> fvToSv = getSlotVariableStream()
            .collect(groupingBy(pvs -> pvs.getRight().getFactVariable()));
    final Map<SingleFactVariable, Pair<VariableSymbol, List<Pair<VariableSymbol, SingleSlotVariable>>>> map = new HashMap<>();
    for (final Map.Entry<SingleFactVariable, List<Pair<VariableSymbol, SingleSlotVariable>>> entry : fvToSv
            .entrySet()) {/*ww w  . ja  v a 2 s .c  o m*/
        final SingleFactVariable fv = entry.getKey();
        final Optional<VariableSymbol> symbol = symbols.stream()
                .filter(vs -> vs.getEqual().getFactVariables().contains(fv)).findAny();
        map.put(fv, Pair.of(symbol.orElse(null), fvToSv.get(fv)));
    }
    return map;
}

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderMetadata.java

@ExtDirectMethod(value = ExtDirectMethodType.STORE_READ, group = "metadata")
public List<Row> method4(@MetadataParam(value = "id") Optional<Integer> id) {
    if (!id.isPresent()) {
        assertThat(id.orElse(null)).isNull();
    } else {//  ww w.  java  2s  . c  o m
        assertThat(id.get()).isEqualTo(Integer.valueOf(13));
    }
    return RemoteProviderStoreRead.createRows(":" + id);
}

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

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

    String activityName = asRequiredString(node, "name");
    PhysicalActivity.Builder activityBuilder = new PhysicalActivity.Builder(activityName);

    Boolean hasStartTime = asRequiredBoolean(node, "hasStartTime");

    /*/*from   w w  w  .  j a v a 2s .c o  m*/
     * hasStartTime is true if the startTime value has been set, which is required of entries through the user
     * GUI and from sensed data, however some of their data import workflows may set dummy values for these
     * (00:00:00), in which case hasStartTime is false and the time shouldn't be used
     */
    if (hasStartTime) {

        Optional<LocalDateTime> localStartDateTime = asOptionalLocalDateTime(node, "startDate", "startTime");
        Optional<Long> duration = asOptionalLong(node, "duration");

        if (localStartDateTime.isPresent()) {

            OffsetDateTime offsetStartDateTime = combineDateTimeAndTimezone(localStartDateTime.get());
            if (duration.isPresent()) {
                activityBuilder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(
                        offsetStartDateTime, new DurationUnitValue(MILLISECOND, duration.get())));
            } else {
                activityBuilder.setEffectiveTimeFrame(offsetStartDateTime);
            }
        }
    } else {
        Optional<LocalDate> localStartDate = asOptionalLocalDate(node, "startDate");

        if (localStartDate.isPresent()) {
            // in this case we have a date, but no time, so we set the startTime to beginning of day on the
            // startDate, add the offset, then set the duration as the entire day
            LocalDateTime localStartDateTime = localStartDate.get().atStartOfDay();
            OffsetDateTime offsetStartDateTime = combineDateTimeAndTimezone(localStartDateTime);
            activityBuilder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(offsetStartDateTime,
                    new DurationUnitValue(DAY, 1)));
        }
    }

    Optional<Double> distance = asOptionalDouble(node, "distance");

    if (distance.isPresent()) {
        // by default fitbit returns metric unit values (https://wiki.fitbit.com/display/API/API+Unit+System), so
        // this assumes that the response is using the default for distance (KM)
        activityBuilder.setDistance(new LengthUnitValue(KILOMETER, distance.get()));
    }

    asOptionalDouble(node, "calories")
            .ifPresent(calories -> activityBuilder.setCaloriesBurned(new KcalUnitValue(KILOCALORIE, calories)));

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

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

From source file:org.openmhealth.shim.googlefit.mapper.GoogleFitBodyWeightDataPointMapper.java

@Override
public Optional<DataPoint<BodyWeight>> asDataPoint(JsonNode listNode) {

    JsonNode valueList = asRequiredNode(listNode, getValueListNodeName());

    Double bodyWeightValue = asRequiredDouble(valueList.get(0), "fpVal");
    if (bodyWeightValue == 0) {
        return Optional.empty();
    }// w  w w  .j  a  v  a 2s  .co  m

    BodyWeight.Builder bodyWeightBuilder = new BodyWeight.Builder(new MassUnitValue(KILOGRAM, bodyWeightValue));
    setEffectiveTimeFrameIfPresent(bodyWeightBuilder, listNode);

    Optional<String> originDataSourceId = asOptionalString(listNode, "originDataSourceId");

    BodyWeight bodyWeight = bodyWeightBuilder.build();
    return Optional.of(newDataPoint(bodyWeight, originDataSourceId.orElse(null)));
}

From source file:spring.travel.site.model.user.User.java

public User(String id, String firstName, String lastName, String username, Optional<Address> address) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.username = username;
    this.a = address.orElse(null);
}

From source file:com.netflix.spinnaker.orca.clouddriver.utils.TrafficGuard.java

@Autowired
public TrafficGuard(OortHelper oortHelper, Optional<Front50Service> front50Service) {
    this.oortHelper = oortHelper;
    this.front50Service = front50Service.orElse(null);
}