Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

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

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:com.darkstar.beanCartography.utils.NameUtils.java

/**
 * @param o object instanct to check//from   ww  w .j  a va2s  .  c o m
 * @return <code>true</code> if any fields have names associated with them
 */
public static boolean hasFieldBusinessNames(Object o) {
    Preconditions.checkNotNull(o, "Object cannot be null");

    // look for business field annotation...
    Map<String, List<Field>> classFieldMap = getFields(o, true);
    final MutableBoolean hasBusinessName = new MutableBoolean(false);
    classFieldMap.values().stream().forEach(fieldList -> {
        Optional<Field> fieldOpt = fieldList.stream().filter(NameUtils::hasBusinessName).findFirst();
        fieldOpt.ifPresent(field -> hasBusinessName.setValue(field != null));
    });
    return hasBusinessName.booleanValue();
}

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

public static Item create(Optional<URI> href, Iterable<Property> properties, List<Link> links) {
    ObjectNode node = JsonNodeFactory.instance.objectNode();
    href.ifPresent(uri -> node.put("href", uri.toString()));
    if (!Iterables.isEmpty(properties)) {
        node.set("data", StreamSupport.stream(properties.spliterator(), false).map(Extended::asJson)
                .collect(JsonNodeFactory.instance::arrayNode, ArrayNode::add, ArrayNode::addAll));
    }//from  w w w  .j a  va 2s .  c o m
    if (!Iterables.isEmpty(links)) {
        node.set("links", StreamSupport.stream(links.spliterator(), false).map(Extended::asJson)
                .collect(JsonNodeFactory.instance::arrayNode, ArrayNode::add, ArrayNode::addAll));
    }
    return new Item(node);
}

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

private static ObjectNode makeObject(String name, Optional<String> prompt) {
    ObjectNode node = JsonNodeFactory.instance.objectNode();
    node.put("name", name);
    prompt.ifPresent(value -> node.put("prompt", value));
    return node;/*from  w w w .ja va2  s.  c  om*/
}

From source file:com.ikanow.aleph2.logging.utils.LoggingUtils.java

/**
 * Updates a BMBs merge info object w/ an updated count (tracking every log message of this type sent in) and
 * a timestamp of the last time a message was actually logged (i.e. not filtered via rule or log level).
 * @param bmb//w  w  w  . j a  va  2  s.  co  m
 * @param of
 * @return
 */
public static Tuple2<BasicMessageBean, Map<String, Object>> updateInfo(
        final Tuple2<BasicMessageBean, Map<String, Object>> merge_info, final Optional<Long> timestamp) {
    merge_info._2.merge(LOG_COUNT_FIELD, 1L, (n, o) -> (Long) n + (Long) o);
    timestamp.ifPresent(t -> merge_info._2.replace(LAST_LOG_TIMESTAMP_FIELD, t));
    return merge_info;
}

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

/**
 * Generate compaction plan from file-slices
 *
 * @param partitionFileSlicePairs list of partition file-slice pairs
 * @param extraMetadata           Extra Metadata
 * @param metricsCaptureFunction  Metrics Capture function
 *///w  w  w  .ja va  2  s  .  c om
public static HoodieCompactionPlan buildFromFileSlices(List<Pair<String, FileSlice>> partitionFileSlicePairs,
        Optional<Map<String, String>> extraMetadata,
        Optional<Function<Pair<String, FileSlice>, Map<String, Double>>> metricsCaptureFunction) {
    HoodieCompactionPlan.Builder builder = HoodieCompactionPlan.newBuilder();
    extraMetadata.ifPresent(m -> builder.setExtraMetadata(m));
    builder.setOperations(partitionFileSlicePairs.stream()
            .map(pfPair -> buildFromFileSlice(pfPair.getKey(), pfPair.getValue(), metricsCaptureFunction))
            .collect(Collectors.toList()));
    return builder.build();
}

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

public static Query create(Target target, String rel, Optional<String> prompt, Optional<String> name,
        Iterable<Property> data) {
    ObjectNode obj = JsonNodeFactory.instance.objectNode();
    obj.put("href", target.toString());
    if (target.isURITemplate()) {
        obj.put("encoding", "uri-template");
    }//from   w ww  . j  av a 2s  .  com
    obj.put("rel", rel);
    prompt.ifPresent(value -> obj.put("prompt", value));
    name.ifPresent(value -> obj.put("name", value));
    if (!Iterables.isEmpty(data)) {
        obj.set("data", StreamSupport.stream(data.spliterator(), false).map(Extended::asJson)
                .collect(JsonNodeFactory.instance::arrayNode, ArrayNode::add, ArrayNode::addAll));
    }
    return new Query(obj);
}

From source file:net.sf.jabref.gui.desktop.JabRefDesktop.java

public static boolean openExternalFileUnknown(JabRefFrame frame, BibEntry entry,
        BibDatabaseContext databaseContext, String link, UnknownExternalFileType fileType) throws IOException {

    String cancelMessage = Localization.lang("Unable to open file.");
    String[] options = new String[] { Localization.lang("Define '%0'", fileType.getName()),
            Localization.lang("Change file type"), Localization.lang("Cancel") };
    String defOption = options[0];
    int answer = JOptionPane.showOptionDialog(frame,
            Localization.lang(/*  w  w w  . ja v a2s. c o m*/
                    "This external link is of the type '%0', which is undefined. What do you want to do?",
                    fileType.getName()),
            Localization.lang("Undefined file type"), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, defOption);
    if (answer == JOptionPane.CANCEL_OPTION) {
        frame.output(cancelMessage);
        return false;
    } else if (answer == JOptionPane.YES_OPTION) {
        // User wants to define the new file type. Show the dialog:
        ExternalFileType newType = new ExternalFileType(fileType.getName(), "", "", "", "new",
                IconTheme.JabRefIcon.FILE.getSmallIcon());
        ExternalFileTypeEntryEditor editor = new ExternalFileTypeEntryEditor(frame, newType);
        editor.setVisible(true);
        if (editor.okPressed()) {
            // Get the old list of types, add this one, and update the list in prefs:
            List<ExternalFileType> fileTypes = new ArrayList<>(
                    ExternalFileTypes.getInstance().getExternalFileTypeSelection());
            fileTypes.add(newType);
            Collections.sort(fileTypes);
            ExternalFileTypes.getInstance().setExternalFileTypes(fileTypes);
            // Finally, open the file:
            return openExternalFileAnyFormat(databaseContext, link, Optional.of(newType));
        } else {
            // Canceled:
            frame.output(cancelMessage);
            return false;
        }
    } else {
        // User wants to change the type of this link.
        // First get a model of all file links for this entry:
        FileListTableModel tModel = new FileListTableModel();
        Optional<String> oldValue = entry.getFieldOptional(FieldName.FILE);
        oldValue.ifPresent(tModel::setContent);
        FileListEntry flEntry = null;
        // Then find which one we are looking at:
        for (int i = 0; i < tModel.getRowCount(); i++) {
            FileListEntry iEntry = tModel.getEntry(i);
            if (iEntry.link.equals(link)) {
                flEntry = iEntry;
                break;
            }
        }
        if (flEntry == null) {
            // This shouldn't happen, so I'm not sure what to put in here:
            throw new RuntimeException("Could not find the file list entry " + link + " in " + entry);
        }

        FileListEntryEditor editor = new FileListEntryEditor(frame, flEntry, false, true, databaseContext);
        editor.setVisible(true, false);
        if (editor.okPressed()) {
            // Store the changes and add an undo edit:
            String newValue = tModel.getStringRepresentation();
            UndoableFieldChange ce = new UndoableFieldChange(entry, FieldName.FILE, oldValue.orElse(null),
                    newValue);
            entry.setField(FieldName.FILE, newValue);
            frame.getCurrentBasePanel().getUndoManager().addEdit(ce);
            frame.getCurrentBasePanel().markBaseChanged();
            // Finally, open the link:
            return openExternalFileAnyFormat(databaseContext, flEntry.link, flEntry.type);
        } else {
            // Canceled:
            frame.output(cancelMessage);
            return false;
        }
    }
}

From source file:com.spotify.styx.model.WorkflowState.java

@JsonCreator
public static WorkflowState create(@JsonProperty("enabled") Optional<Boolean> enabled,
        @JsonProperty("docker_image") Optional<String> dockerImage,
        @JsonProperty("commit_sha") Optional<String> commitSha,
        @JsonProperty("next_natural_trigger") Optional<Instant> nextNaturalTrigger,
        @JsonProperty("next_natural_offset_trigger") Optional<Instant> nextNaturalOffsetTrigger) {
    Builder builder = builder();//from  ww w.  j  a  v a 2s . c o  m
    enabled.ifPresent(builder::enabled);
    dockerImage.ifPresent(builder::dockerImage);
    commitSha.ifPresent(builder::commitSha);
    nextNaturalTrigger.ifPresent(builder::nextNaturalTrigger);
    nextNaturalOffsetTrigger.ifPresent(builder::nextNaturalOffsetTrigger);
    return builder.build();
}

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

public static Collection create(Optional<URI> href, List<Link> links, List<Item> items, List<Query> queries,
        Optional<Template> template, Optional<Error> error) {
    ObjectNode obj = JsonNodeFactory.instance.objectNode();
    obj.put("version", Version.ONE.getIdentifier());
    href.ifPresent(value -> obj.put("href", value.toString()));
    if (!links.isEmpty()) {
        obj.set("links", links.stream().map(Extended::asJson).collect(JsonNodeFactory.instance::arrayNode,
                ArrayNode::add, ArrayNode::addAll));
    }//from   www  . j av a 2 s  .  com
    if (!items.isEmpty()) {
        obj.set("items", items.stream().map(Extended::asJson).collect(JsonNodeFactory.instance::arrayNode,
                ArrayNode::add, ArrayNode::addAll));
    }
    if (!queries.isEmpty()) {
        obj.set("queries", queries.stream().map(Extended::asJson).collect(JsonNodeFactory.instance::arrayNode,
                ArrayNode::add, ArrayNode::addAll));
    }
    template.ifPresent(value -> obj.set("template", value.asJson()));
    error.ifPresent(value -> obj.set("error", value.asJson()));
    Collection coll = new Collection(obj);
    coll.validate();
    return coll;
}

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

public static Link create(URI href, String rel, Optional<String> prompt, Optional<String> name,
        Optional<Render> render) {
    ObjectNode node = JsonNodeFactory.instance.objectNode();
    node.put("href", Optional.ofNullable(href)
            .orElseThrow(() -> new IllegalArgumentException("Href may not be null")).toString());
    node.put("rel", Optional.ofNullable(rel)
            .orElseThrow(() -> new IllegalArgumentException("Relation may not be null")));
    prompt.ifPresent(value -> node.put("prompt", value));
    render.ifPresent(value -> node.put("render", value.getName()));
    name.ifPresent(value -> node.put("name", value));
    return new Link(node);
}