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:be.i8c.codequality.sonar.plugins.sag.webmethods.flow.FlowLanguage.java

/**
 * This methods returns the configured pattern for node files.
 * s/*from   w  w w.  ja v  a  2  s.  c o m*/
 * @return Pattern for node files
 */
public static String[] getNodeFilePatterns() {
    Optional<String> suffix = config.get(FlowLanguageProperties.NODE_FILE_FILTER_KEY);
    return new String[] { suffix.orElse(".*") };
}

From source file:com.joyent.manta.client.FindForkJoinPoolFactory.java

/**
 * Calculates the system parallelism setting by choosing the default value
 * generated based on the number of processors or by choosing the user
 * supplied system property./*w w w. j a  va  2s  .c om*/
 *
 * @return integer representing the parallelism value for a {@link ForkJoinPool}
 */
private static int calculateSystemParallelism() {
    final Optional<Integer> systemParallelism = readSystemForkJoinPoolParallelismSetting();
    return systemParallelism.orElse(Runtime.getRuntime().availableProcessors());
}

From source file:org.sakuli.services.cipher.AesCbcCipher.java

public static IvParameterSpec createIV(final int ivSizeBytes, final Optional<SecureRandom> rng) {
    final byte[] iv = new byte[ivSizeBytes];
    final SecureRandom theRNG = rng.orElse(new SecureRandom());
    theRNG.nextBytes(iv);//from   w  w  w.  j  a va 2 s . c o m
    return new IvParameterSpec(iv);
}

From source file:com.wormsim.data.SimulationConditions.java

public static SimulationConditions read(String str) throws IOException {
    RealDistribution food = null;/*from w  w  w.  j a  va  2 s .  c om*/
    HashMap<Integer, RealDistribution> pheromones = new HashMap<>();
    HashMap<String, IntegerDistribution> groups = new HashMap<>();

    if (Utils.MULTIBRACKET_VALIDITY_PATTERN.matcher(str).matches()) {
        Matcher m = Utils.SAMPLER_PATTERN.matcher(str);
        while (m.find()) {
            String match = m.group();
            String[] keyvalue = match.split("~");
            if (keyvalue[0].matches("\\s*food\\s*")) {
                food = Utils.readRealDistribution(keyvalue[1].trim());
            } else if (keyvalue[0].matches("\\s*pheromone\\[\\d+\\]\\s*")) {
                int leftbracket = keyvalue[0].indexOf('[') + 1;
                int rightbracket = keyvalue[0].indexOf(']');
                int id = 0;
                try {
                    id = Integer.valueOf(keyvalue[0].substring(leftbracket, rightbracket));
                    if (id < 0) {
                        throw new IOException("Invalid pheromone reference " + id + ", must be positive!");
                    }
                } catch (NumberFormatException ex) {
                    throw new IOException(ex);
                }
                if (pheromones.putIfAbsent(id, Utils.readRealDistribution(keyvalue[1].trim())) != null) {
                    throw new IOException("Duplicate pheromone id " + id);
                }
            } else { // Group Distribution
                groups.put(keyvalue[0].trim(), Utils.readIntegerDistribution(keyvalue[1].trim()));
            }
        }
    } else {
        throw new IOException("Brackets are missing on simulation conditions definition.");
    }
    if (food == null || groups.isEmpty()) {
        throw new IOException("Incomplete Data! Missing food or groups.");
    }

    // Convert pheromones into array
    Optional<Integer> max = pheromones.keySet().stream().max(Integer::max);

    RealDistribution[] pheromone_arr = new RealDistribution[max.orElse(0)];
    pheromones.forEach((k, v) -> pheromone_arr[k - 1] = v);
    for (int i = 0; i < pheromone_arr.length; i++) {
        if (pheromone_arr[i] == null) {
            pheromone_arr[i] = Utils.ZERO_REAL_DISTRIBUTION;
        }
    }

    return new SimulationConditions(food, pheromone_arr, groups);
}

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** Returns a date from a human readable date - can only be in the future
 * @param human_readable_date - the date expressed in words, eg "next wednesday".. Uses some simple regexes (1h,d, 1month etc), and Natty (try examples http://natty.joestelmach.com/try.jsp#)
 * @param base_date - for relative date, locks the date to this origin
 * @return the machine readable date, or an error
 *///from  ww w  .  j ava2s.c  o  m
public static Validation<String, Date> getForwardSchedule(final String human_readable_date,
        Optional<Date> base_date) {
    final Date adjusted_date = base_date.orElse(new Date());
    return _adjustments.stream()
            .map(adjust -> Date.from(adjusted_date.toInstant().plus(adjust._1(), adjust._2()))) // (adjust the date by the increasing adjustment)
            .map(adjusted -> getSchedule(human_readable_date, Optional.of(adjusted)))
            .filter(parsed -> parsed.isSuccess())
            .filter(parsed -> parsed.success().getTime() >= adjusted_date.getTime()).findFirst()
            .orElse(Validation
                    .fail(ErrorUtils.get(ErrorUtils.INVALID_DATETIME_FORMAT_PAST, human_readable_date)));
}

From source file:org.ballerinalang.composer.service.ballerina.swagger.service.SwaggerConverterUtils.java

/**
 * Generate ballerina fine from the String definition.
 *
 * @param bFile ballerina string definition
 * @return ballerina file created from ballerina string definition
 * @throws IOException IO exception/*ww  w.ja  v a  2s.  c om*/
 */
public static BLangCompilationUnit getTopLevelNodeFromBallerinaFile(BFile bFile) throws IOException {

    String filePath = bFile.getFilePath();
    String fileName = bFile.getFileName();
    String content = bFile.getContent();

    org.wso2.ballerinalang.compiler.tree.BLangPackage model;

    // Sometimes we are getting Ballerina content without a file in the file-system.
    if (!Files.exists(Paths.get(filePath, fileName))) {
        BallerinaFile ballerinaFile = ParserUtils.getBallerinaFileForContent(fileName, content,
                CompilerPhase.CODE_ANALYZE);
        model = ballerinaFile.getBLangPackage();

    } else {
        BallerinaFile ballerinaFile = ParserUtils.getBallerinaFile(filePath, fileName);
        model = ballerinaFile.getBLangPackage();
    }

    final Map<String, ModelPackage> modelPackage = new HashMap<>();
    ParserUtils.loadPackageMap("Current Package", model, modelPackage);

    Optional<BLangCompilationUnit> compilationUnit = model.getCompilationUnits().stream()
            .filter(compUnit -> fileName.equals(compUnit.getName())).findFirst();
    return compilationUnit.orElse(null);
}

From source file:org.exist.launcher.ServiceManager.java

static void run(List<String> args, BiConsumer<Integer, String> consumer) {
    final ProcessBuilder pb = new ProcessBuilder(args);
    final Optional<Path> home = ConfigurationHelper.getExistHome();

    pb.directory(home.orElse(Paths.get(".")).toFile());
    pb.redirectErrorStream(true);/*w  w  w .  j a v a2s  .c o  m*/
    if (consumer == null) {
        pb.inheritIO();
    }
    try {
        final Process process = pb.start();
        if (consumer != null) {
            final StringBuilder output = new StringBuilder();
            try (final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "UTF-8"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append('\n').append(line);
                }
            }
            final int exitValue = process.waitFor();
            consumer.accept(exitValue, output.toString());
        }
    } catch (IOException | InterruptedException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error Running Process", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.egov.infra.utils.ImageUtils.java

public static double[] findGeoCoordinates(File jpegImage) {
    Optional<double[]> coordinates = Optional.empty();
    if (JPG_FORMAT_NAME.equalsIgnoreCase(imageFormat(jpegImage))) {
        Image image = new Image(jpegImage);
        coordinates = Optional.ofNullable(image.getGPSCoordinate());
    }//from w ww  .  ja  va 2  s . c  o  m
    return coordinates.orElse(new double[] { 0D, 0D });
}

From source file:org.kontalk.system.Database.java

private static void setValue(PreparedStatement stat, int i, Object value) throws SQLException {
    if (value instanceof String) {
        stat.setString(i + 1, (String) value);
    } else if (value instanceof Integer) {
        stat.setInt(i + 1, (int) value);
    } else if (value instanceof Date) {
        stat.setLong(i + 1, ((Date) value).getTime());
    } else if (value instanceof Boolean) {
        stat.setBoolean(i + 1, (boolean) value);
    } else if (value instanceof Enum) {
        stat.setInt(i + 1, ((Enum) value).ordinal());
    } else if (value instanceof EnumSet) {
        stat.setInt(i + 1, EncodingUtils.enumSetToInt(((EnumSet) value)));
    } else if (value instanceof Optional) {
        Optional<?> o = (Optional) value;
        setValue(stat, i, o.orElse(null));
    } else if (value == null) {
        stat.setNull(i + 1, Types.NULL);
    } else {/*from   ww  w  .  j  ava 2  s. c o m*/
        LOGGER.warning("unknown type: " + value);
    }
}

From source file:org.silverpeas.core.contribution.model.ContributionLocalizationBundle.java

/**
 * Gets the {@link ContributionLocalizationBundle} for a {@link Contribution} adapted from a
 * specified language.//w w w  . j av a  2 s .c o  m
 * @param contribution a {@link Contribution} instance.
 * @param language the aimed language for bundles.
 * @return an initialized {@link ContributionLocalizationBundle} instance.
 */
public static ContributionLocalizationBundle getByInstanceAndLanguage(Contribution contribution,
        String language) {
    LocalizationBundle main = ResourceLocator
            .getLocalizationBundle("org.silverpeas.contribution.multilang.contribution", language);
    final String componentName = SilverpeasComponentInstance
            .getComponentName(contribution.getContributionId().getComponentInstanceId());
    final Optional<LocalizationBundle> specific = ResourceLocator.getOptionalLocalizationBundle(
            "org.silverpeas." + componentName.toLowerCase() + ".multilang.contribution", language);
    return new ContributionLocalizationBundle(contribution, main, specific.orElse(null));
}