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:com.ikanow.aleph2.example.flume_harvester.utils.FlumeUtils.java

/** Returns the config name 
 *  Generated by taking 1-3 directories from the path and then appening the end of a UUID
 * @param path// ww w  .  j  a  va  2s.  c  o  m
 * @return
 */
public static String getConfigName(final String path, final Optional<String> agent_name) {

    String[] components = Optional.of(path).map(p -> p.startsWith("/") ? p.substring(1) : p).get().split("[/]");

    if (1 == components.length) {
        return tidyUpIndexName(safeTruncate(components[0], MAX_CFG_COMP_LEN)
                + addOptionalAgentName(agent_name, MAX_CFG_COMP_LEN)) + "_"
                + generateUuidSuffix(path + agent_name.orElse(""));
    } else if (2 == components.length) {
        return tidyUpIndexName(safeTruncate(components[0], MAX_CFG_COMP_LEN) + "_"
                + safeTruncate(components[1], MAX_CFG_COMP_LEN)
                + addOptionalAgentName(agent_name, MAX_CFG_COMP_LEN)) + "_"
                + generateUuidSuffix(path + agent_name.orElse(""));
    } else { // take the first and the last 2
        final int n = components.length;
        return tidyUpIndexName(safeTruncate(components[0], MAX_CFG_COMP_LEN) + "_"
                + safeTruncate(components[n - 2], MAX_CFG_COMP_LEN) + "_"
                + safeTruncate(components[n - 1], MAX_CFG_COMP_LEN)
                + addOptionalAgentName(agent_name, MAX_CFG_COMP_LEN)) + "_"
                + generateUuidSuffix(path + agent_name.orElse(""));
    }
}

From source file:fr.landel.utils.io.InternalFileSystemUtils.java

/**
 * List the files in a directory/*from w w w  . j a va  2s .  c  o  m*/
 * 
 * @param output
 *            the output list (optional)
 * @param src
 *            the directory to analyze
 * @param fileFilter
 *            the file filter (optional)
 * @param filenameFilter
 *            the filename filter (optional)
 * @param actionOnEachFile
 *            the action applied on each file (optional)
 * @return the list of files
 * @throws IOException
 *             on IO errors
 */
protected static List<File> listFiles(final Optional<List<File>> output, final File src,
        final FileFilter fileFilter, final FilenameFilter filenameFilter, Consumer<File> actionOnEachFile)
        throws IOException {

    final List<File> list = output.orElse(new ArrayList<>());

    if (src.isDirectory()) {
        // creation du repertoire si necessaire
        // creation de la liste des fichiers et repertoires
        File[] files = listFiles(src, fileFilter, filenameFilter);

        if (files != null) {
            list.addAll(Arrays.asList(files));

            for (File entry : files) {
                if (actionOnEachFile != null) {
                    actionOnEachFile.accept(entry);
                }

                if (entry.isDirectory()) {
                    InternalFileSystemUtils.listFiles(Optional.of(list), entry, fileFilter, filenameFilter,
                            actionOnEachFile);
                }
            }
        }
    } else if (matchFilter(src, fileFilter, filenameFilter)) {
        list.add(src);
        if (actionOnEachFile != null) {
            actionOnEachFile.accept(src);
        }
    }
    return list;
}

From source file:org.eclipse.che.api.project.server.impl.FileItemUtils.java

static FileItemParsed parseFile(Iterator<FileItem> iterator) throws ServerException {
    List<FileItem> fileItems = new LinkedList<>();
    iterator.forEachRemaining(fileItems::add);

    List<FileItem> fileContents = fileItems.stream().filter(it -> !it.isFormField())
            .collect(Collectors.toList());

    if (fileContents.size() > 1) {
        throw new ServerException("Expected no more than one file to upload");
    }/*from w w  w.ja  va  2s.  c  o m*/

    if (fileContents.size() < 1) {
        throw new ServerException("Can't find file for upload");
    }

    FileItem content = fileContents.iterator().next();

    InputStream inputStream;
    try {
        inputStream = content.getInputStream();
    } catch (IOException e) {
        throw new ServerException(e);
    }

    Optional<String> name = fileItems.stream().filter(FileItem::isFormField)
            .filter(it -> "name".equals(it.getFieldName())).map(FileItem::getString).map(String::trim)
            .filter(Objects::nonNull).filter(it -> !it.isEmpty()).findAny();

    Optional<Boolean> overwrite = fileItems.stream().filter(FileItem::isFormField)
            .filter(it -> "overwrite".equals(it.getFieldName())).map(FileItem::getString).map(String::trim)
            .map(Boolean::parseBoolean).findAny();

    return new FileItemParsed() {
        @Override
        public String getName() {
            return name.orElse(content.getName());
        }

        @Override
        public InputStream getContent() {
            return inputStream;
        }

        @Override
        public boolean getOverwrite() {
            return overwrite.orElse(false);
        }
    };
}

From source file:io.leishvl.core.prov.ProvFactory.java

public static void addEditProv(final Document graph, final User editor, final String lvlId) {
    final String lvlId2 = parseParam(lvlId);
    checkArgument(editor != null, "Uninitialized editor");
    checkArgument(isNotBlank(editor.getUserid()), "Uninitialized user Id");
    checkArgument(isNotBlank(editor.getProvider()), "Uninitialized identity provider");

    final Bundle bundle = getBundle(graph);
    final Agent system = getSystem(bundle);

    // imported draft is open to future editions
    final QualifiedName editActQn = PROVENANCE.qn("edit");
    final QualifiedName revisedDraftQn = PROVENANCE.qn(LVL_PREFIX, "RevisedDraft");
    final Optional<Statement> revisedDraftOpt = ofNullable(bundle.getStatement().stream()
            .filter(stmt -> stmt instanceof Entity && revisedDraftQn.equals(((Entity) stmt).getId()))
            .findFirst().orElse(null));//  ww w  .  j  a  v a 2  s  .co  m
    final Entity revisedDraft = (Entity) revisedDraftOpt.orElse(PROVENANCE.entity(LVL_PREFIX, "RevisedDraft"));
    if (!revisedDraftOpt.isPresent()) {
        final Activity editAct = PROVENANCE.factory().newActivity(editActQn);
        final QualifiedName objQn = PROVENANCE.qn(LVL_PREFIX, lvlId2);
        bundle.getStatement()
                .addAll(asList(editAct, revisedDraft,
                        PROVENANCE.factory().newUsed(null, editAct.getId(), objQn),
                        PROVENANCE.factory().newWasDerivedFrom(null, revisedDraft.getId(), objQn),
                        PROVENANCE.factory().newWasGeneratedBy(null, revisedDraft.getId(), editAct.getId())));
    }

    // add editor
    final QualifiedName editorQn = PROVENANCE.qn(LVL_PREFIX, editor.getUserid());
    final Optional<Statement> editorAgentOpt = ofNullable(bundle.getStatement().stream()
            .filter(stmt -> stmt instanceof Agent && editorQn.equals(((Agent) stmt).getId())).findFirst()
            .orElse(null));
    final Agent editorAgent = (Agent) editorAgentOpt.orElse(PROVENANCE.personAgent(editor));
    if (!editorAgentOpt.isPresent()) {
        bundle.getStatement()
                .addAll(asList(editorAgent,
                        PROVENANCE.factory().newActedOnBehalfOf(null, editorAgent.getId(), system.getId()),
                        PROVENANCE.factory().newWasAssociatedWith(null, editActQn, editorAgent.getId())));
    }
}

From source file:com.uber.hoodie.common.model.HoodieTestUtils.java

public static final String createNewLogFile(FileSystem fs, String basePath, String partitionPath,
        String commitTime, String fileID, Optional<Integer> version) throws IOException {
    String folderPath = basePath + "/" + partitionPath + "/";
    boolean makeDir = fs.mkdirs(new Path(folderPath));
    if (!makeDir) {
        throw new IOException("cannot create directory for path " + folderPath);
    }/*w ww.  jav a 2 s . c  o m*/
    boolean createFile = fs.createNewFile(new Path(folderPath
            + FSUtils.makeLogFileName(fileID, ".log", commitTime, version.orElse(DEFAULT_TASK_PARTITIONID))));
    if (!createFile) {
        throw new IOException(
                StringUtils.format("cannot create data file for commit %s and fileId %s", commitTime, fileID));
    }
    return fileID;
}

From source file:nu.yona.server.subscriptions.rest.UserController.java

private static Link getConfirmMobileLink(UUID userId, Optional<UUID> requestingDeviceId) {
    ControllerLinkBuilder linkBuilder = linkTo(methodOn(UserController.class)
            .confirmMobileNumber(Optional.empty(), userId, requestingDeviceId.orElse(null), null));
    return linkBuilder.withRel("confirmMobileNumber");
}

From source file:com.ikanow.aleph2.core.shared.services.ReadOnlyMultiCrudService.java

/** Returns a multi bucket crud wrapper 
 *  DOESN'T CURRENTLY SUPPORT LIMITS OR SORTBY PROPERLY
 * @param buckets - a list of bucket paths
 * @param maybe_extra_query_builder - for each bucket lets the user specify an additional query to be applied to all queries
 * @return//from   w w w .  ja va2s.  c om
 */
public static <O> Optional<ReadOnlyMultiCrudService<O>> from(final Class<O> clazz, final List<String> buckets,
        final Optional<String> owner_id, final IGenericDataService data_service,
        final IManagementCrudService<DataBucketBean> bucket_store, final IServiceContext service_context,
        final Optional<Function<DataBucketBean, Optional<QueryComponent<O>>>> maybe_extra_query_builder) {

    final DataBucketBean dummy_bucket = BeanTemplateUtils.build(DataBucketBean.class)
            .with(DataBucketBean::owner_id, owner_id.orElse(null))
            .with(DataBucketBean::multi_bucket_children, buckets).done().get();

    final List<ICrudService<O>> services = MultiBucketUtils
            .expandMultiBuckets(Arrays.asList(dummy_bucket), bucket_store, service_context).values().stream()
            .map(b -> Tuples._2T(b,
                    data_service.getReadableCrudService(clazz, Arrays.asList(b), Optional.empty())
                            .<ICrudService<O>>flatMap(ds -> ds.getCrudService())))
            .filter(bucket_crud -> bucket_crud._2().isPresent())
            .map(bucket_crud -> Tuples._2T(bucket_crud._1(), bucket_crud._2().get())) // because of above filter)
            .map(bucket_crud -> maybe_extra_query_builder.flatMap(qb -> qb.apply(bucket_crud._1()))
                    .map(extra_query -> CrudServiceUtils.intercept(clazz, bucket_crud._2(),
                            Optional.of(extra_query), Optional.empty(), Collections.emptyMap(),
                            Optional.empty()))
                    .orElse(bucket_crud._2()))
            .collect(Collectors.toList());

    return services.isEmpty() ? Optional.empty() : Optional.of(new ReadOnlyMultiCrudService<O>(services));
}

From source file:com.facebook.presto.accumulo.AccumuloClient.java

/**
 * Gets the row ID based on a table properties or the first column name.
 *
 * @param meta ConnectorTableMetadata//from w  w w.  j a  v  a2  s .co m
 * @return Lowercase Presto column name mapped to the Accumulo row ID
 */
private static String getRowIdColumn(ConnectorTableMetadata meta) {
    Optional<String> rowIdColumn = AccumuloTableProperties.getRowId(meta.getProperties());
    return rowIdColumn.orElse(meta.getColumns().get(0).getName()).toLowerCase(Locale.ENGLISH);
}

From source file:com.facebook.presto.accumulo.AccumuloClient.java

/**
 * Auto-generates the mapping of Presto column name to Accumulo family/qualifier, respecting the locality groups (if any).
 *
 * @param columns Presto columns for the table
 * @param groups Mapping of locality groups to a set of Presto columns, or null if none
 * @return Column mappings//from  ww w .  j ava2  s .  c  o m
 */
private static Map<String, Pair<String, String>> autoGenerateMapping(List<ColumnMetadata> columns,
        Optional<Map<String, Set<String>>> groups) {
    Map<String, Pair<String, String>> mapping = new HashMap<>();
    for (ColumnMetadata column : columns) {
        Optional<String> family = getColumnLocalityGroup(column.getName(), groups);
        mapping.put(column.getName(), Pair.of(family.orElse(column.getName()), column.getName()));
    }
    return mapping;
}

From source file:org.cloudfoundry.client.v2.ApplicationsTest.java

private static Mono<ApplicationInstanceInfo> waitForInstanceRestart(CloudFoundryClient cloudFoundryClient,
        String applicationId, String instanceName, Optional<Double> optionalSince) {
    return getInstanceInfo(cloudFoundryClient, applicationId, instanceName)
            .filter(info -> !isIdentical(info.getSince(), optionalSince.orElse(null)))
            .repeatWhenEmpty(DelayUtils.exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15),
                    Duration.ofMinutes(5)));
}