Example usage for java.util Optional equals

List of usage examples for java.util Optional equals

Introduction

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

Prototype

@Override
public boolean equals(Object obj) 

Source Link

Document

Indicates whether some other object is "equal to" this Optional .

Usage

From source file:net.sf.jabref.model.DuplicateCheck.java

public static double compareEntriesStrictly(BibEntry one, BibEntry two) {
    Set<String> allFields = new HashSet<>();
    allFields.addAll(one.getFieldNames());
    allFields.addAll(two.getFieldNames());

    int score = 0;
    for (String field : allFields) {
        Optional<String> stringOne = one.getFieldOptional(field);
        Optional<String> stringTwo = two.getFieldOptional(field);
        if (stringOne.equals(stringTwo)) {
            score++;/*from w w  w . j  a v  a2 s  .  com*/
        }
    }
    if (score == allFields.size()) {
        return 1.01; // Just to make sure we can
        // use score>1 without
        // trouble.
    }
    return (double) score / allFields.size();
}

From source file:nu.yona.server.messaging.entities.MessageDestination.java

public List<Message> getMessagesFromUser(UUID sentByUserAnonymizedId) {
    Optional<UUID> sentByUserAnonymizedIdInOptional = Optional.of(sentByUserAnonymizedId);
    return messages.stream()
            .filter(message -> sentByUserAnonymizedIdInOptional.equals(message.getRelatedUserAnonymizedId()))
            .collect(Collectors.toList());
}

From source file:io.syndesis.controllers.integration.IntegrationController.java

private void checkIntegrationStatus(Integration integration) {
    if (integration == null) {
        return;/*from   www. j av  a2 s  .c om*/
    }
    Optional<Integration.Status> desired = integration.getDesiredStatus();
    Optional<Integration.Status> current = integration.getCurrentStatus();
    if (!current.equals(desired)) {
        desired.ifPresent(desiredStatus -> integration.getId().ifPresent(integrationId -> {
            StatusChangeHandlerProvider.StatusChangeHandler statusChangeHandler = handlers.get(desiredStatus);
            if (statusChangeHandler != null) {
                LOG.info(
                        "Integration {} : Desired status \"{}\" != current status \"{}\" --> calling status change handler",
                        integrationId, desiredStatus.toString(), current.map(Enum::toString).orElse("[none]"));
                callStatusChangeHandler(statusChangeHandler, integrationId);
            }
        }));
    } else {
        // When the desired state is reached remove the marker so that a next change trigger a check again
        // Doesn't harm when no such key exists
        desired.ifPresent(d -> scheduledChecks.remove(getIntegrationMarkerKey(integration)));
    }
}

From source file:io.syndesis.controllers.integration.IntegrationController.java

private boolean stale(StatusChangeHandlerProvider.StatusChangeHandler handler, Integration integration) {
    if (integration == null || handler == null) {
        return true;
    }//  ww w  .j  a  v a  2 s .c om

    Optional<Integration.Status> desiredStatus = integration.getDesiredStatus();
    return !desiredStatus.isPresent() || desiredStatus.equals(integration.getCurrentStatus())
            || !handler.getTriggerStatuses().contains(desiredStatus.get());
}

From source file:nu.yona.server.device.service.DeviceService.java

@Transactional
public UserDeviceDto updateDevice(UUID userId, UUID deviceId, DeviceUpdateRequestDto changeRequest) {
    userService.updateUser(userId, userEntity -> {
        UserDevice deviceEntity = getDeviceEntity(deviceId);

        String oldName = deviceEntity.getName();
        if (!oldName.equals(changeRequest.name)) {
            assertAcceptableDeviceName(userEntity, changeRequest.name);
            deviceEntity.setName(changeRequest.name);
            userDeviceRepository.save(deviceEntity);
            sendDeviceChangeMessageToBuddies(DeviceChange.RENAME, userEntity, Optional.of(oldName),
                    Optional.of(changeRequest.name), deviceEntity.getDeviceAnonymized().getId());
        }//from   ww  w .j  a  va2  s.  c  o  m

        DeviceAnonymized deviceAnonymized = deviceEntity.getDeviceAnonymized();
        Optional<String> oldFirebaseInstanceId = deviceAnonymized.getFirebaseInstanceId();
        if (changeRequest.firebaseInstanceId.isPresent()
                && !oldFirebaseInstanceId.equals(changeRequest.firebaseInstanceId)) {
            deviceAnonymized.setFirebaseInstanceId(changeRequest.firebaseInstanceId.get());
            deviceAnonymizedRepository.save(deviceAnonymized);
        }
    });
    return getDevice(deviceId);
}

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

/**
 * @param builder a measure builder of type T
 * @param listNode the JSON node representing an individual datapoint, which contains the start and end time
 * properties, from within the response array
 *//* w w w  . ja  v  a2s .  c  o  m*/
public void setEffectiveTimeFrameIfPresent(T.Builder builder, JsonNode listNode) {

    Optional<String> startTimeNanosString = asOptionalString(listNode, "startTimeNanos");
    Optional<String> endTimeNanosString = asOptionalString(listNode, "endTimeNanos");

    // When the start and end times are identical, such as for a single body weight measure, then we only need to
    // create an effective time frame with a single date time value
    if (startTimeNanosString.isPresent() && endTimeNanosString.isPresent()) {
        if (startTimeNanosString.equals(endTimeNanosString)) {
            builder.setEffectiveTimeFrame(convertGoogleNanosToOffsetDateTime(startTimeNanosString.get()));

        } else {
            builder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndEndDateTime(
                    convertGoogleNanosToOffsetDateTime(startTimeNanosString.get()),
                    convertGoogleNanosToOffsetDateTime(endTimeNanosString.get())));
        }

    }
}

From source file:net.sf.jabref.gui.mergeentries.MergeEntries.java

/**
 * Main function for building the merge entry JPanel
 *//*w  w w . jav  a2 s  . c om*/
private void initialize() {
    doneBuilding = false;
    setupFields();

    // Fill diff mode combo box
    for (String diffText : DIFF_MODES) {
        diffMode.addItem(diffText);
    }
    diffMode.setSelectedIndex(Math.min(Globals.prefs.getInt(JabRefPreferences.MERGE_ENTRIES_DIFF_MODE),
            diffMode.getItemCount() - 1));
    diffMode.addActionListener(e -> {
        updateTextPanes(differentFields);
        storePreference();
    });

    // Create main layout
    String colSpecMain = "left:pref, 5px, center:3cm:grow, 5px, center:pref, 3px, center:pref, 3px, center:pref, 5px, center:3cm:grow";
    String colSpecMerge = "left:pref, 5px, fill:3cm:grow, 5px, center:pref, 3px, center:pref, 3px, center:pref, 5px, fill:3cm:grow";
    String rowSpec = "pref, pref, 10px, fill:5cm:grow, 10px, pref, 10px, fill:3cm:grow";
    StringBuilder rowBuilder = new StringBuilder("");
    for (int i = 0; i < allFields.size(); i++) {
        rowBuilder.append("pref, 2dlu, ");
    }
    rowBuilder.append("pref");

    JPanel mergePanel = new JPanel();
    FormLayout mainLayout = new FormLayout(colSpecMain, rowSpec);
    FormLayout mergeLayout = new FormLayout(colSpecMerge, rowBuilder.toString());
    mainPanel.setLayout(mainLayout);
    mergePanel.setLayout(mergeLayout);

    CellConstraints cc = new CellConstraints();

    mainPanel.add(boldFontLabel(Localization.lang("Use")), cc.xyw(4, 1, 7, "center, bottom"));
    mainPanel.add(diffMode, cc.xy(11, 1, "right, bottom"));

    // Set headings
    JLabel[] headingLabels = new JLabel[6];
    for (int i = 0; i < 6; i++) {
        headingLabels[i] = boldFontLabel(COLUMN_HEADINGS[i]);
        mainPanel.add(headingLabels[i], cc.xy(1 + (i * 2), 2));

    }

    mainPanel.add(new JSeparator(), cc.xyw(1, 3, 11));

    // Start with entry type
    mergePanel.add(boldFontLabel(Localization.lang("Entry type")), cc.xy(1, 1));

    JTextPane leftTypeDisplay = getStyledTextPane();
    leftTypeDisplay.setText(HTML_START + leftEntry.getType() + HTML_END);
    mergePanel.add(leftTypeDisplay, cc.xy(3, 1));
    if (leftEntry.getType().equals(rightEntry.getType())) {
        identicalTypes = true;
    } else {
        identicalTypes = false;
        ButtonGroup group = new ButtonGroup();
        typeRadioButtons = new ArrayList<>(2);
        for (int k = 0; k < 3; k += 2) {
            JRadioButton button = new JRadioButton();
            typeRadioButtons.add(button);
            group.add(button);
            mergePanel.add(button, cc.xy(5 + (k * 2), 1));
            button.addChangeListener(e -> updateAll());
        }
        typeRadioButtons.get(0).setSelected(true);
    }
    JTextPane rightTypeDisplay = getStyledTextPane();
    rightTypeDisplay.setText(HTML_START + rightEntry.getType() + HTML_END);
    mergePanel.add(rightTypeDisplay, cc.xy(11, 1));

    // For all fields in joint add a row and possibly radio buttons
    int row = 2;
    int maxLabelWidth = -1;
    for (String field : allFields) {
        JLabel label = boldFontLabel(new SentenceCaseFormatter().format(field));
        mergePanel.add(label, cc.xy(1, (2 * row) - 1, "left, top"));
        Optional<String> leftString = leftEntry.getFieldOptional(field);
        Optional<String> rightString = rightEntry.getFieldOptional(field);
        if (leftString.equals(rightString)) {
            identicalFields.add(field);
        } else {
            differentFields.add(field);
        }

        maxLabelWidth = Math.max(maxLabelWidth, label.getPreferredSize().width);

        // Left text pane
        if (leftString.isPresent()) {
            JTextPane tf = getStyledTextPane();
            mergePanel.add(tf, cc.xy(3, (2 * row) - 1, "f, f"));
            leftTextPanes.put(field, tf);
        }

        // Add radio buttons if the two entries do not have identical fields
        if (identicalFields.contains(field)) {
            mergedEntry.setField(field, leftString.get()); // Will only happen if both entries have the field and the content is identical
        } else {
            ButtonGroup group = new ButtonGroup();
            List<JRadioButton> list = new ArrayList<>(3);
            for (int k = 0; k < 3; k++) {
                JRadioButton button = new JRadioButton();
                group.add(button);
                mergePanel.add(button, cc.xy(5 + (k * 2), (2 * row) - 1));
                button.addChangeListener(e -> updateAll());
                list.add(button);
            }
            radioButtons.put(field, list);
            if (leftString.isPresent()) {
                list.get(0).setSelected(true);
                if (!rightString.isPresent()) {
                    list.get(2).setEnabled(false);
                }
            } else {
                list.get(0).setEnabled(false);
                list.get(2).setSelected(true);
            }
        }

        // Right text pane
        if (rightString.isPresent()) {
            JTextPane tf = getStyledTextPane();
            mergePanel.add(tf, cc.xy(11, (2 * row) - 1, "f, f"));
            rightTextPanes.put(field, tf);
        }
        row++;
    }

    scrollPane = new JScrollPane(mergePanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    updateTextPanes(allFields);
    mainPanel.add(scrollPane, cc.xyw(1, 4, 11));
    mainPanel.add(new JSeparator(), cc.xyw(1, 5, 11));

    // Synchronize column widths
    String[] rbAlign = { "right", "center", "left" };
    mainLayout.setColumnSpec(1, ColumnSpec.decode(Integer.toString(maxLabelWidth) + "px"));
    Integer maxRBWidth = -1;
    for (int k = 2; k < 5; k++) {
        maxRBWidth = Math.max(maxRBWidth, headingLabels[k].getPreferredSize().width);
    }
    for (int k = 0; k < 3; k++) {
        mergeLayout.setColumnSpec(5 + (k * 2), ColumnSpec.decode(rbAlign[k] + ":" + maxRBWidth + "px"));
    }

    // Setup a PreviewPanel and a Bibtex source box for the merged entry
    mainPanel.add(boldFontLabel(Localization.lang("Merged entry")), cc.xyw(1, 6, 6));

    entryPreview = new PreviewPanel(null, mergedEntry, null, Globals.prefs.get(JabRefPreferences.PREVIEW_0));
    mainPanel.add(entryPreview, cc.xyw(1, 8, 6));

    mainPanel.add(boldFontLabel(Localization.lang("Merged BibTeX source code")), cc.xyw(8, 6, 4));

    sourceView = new JTextArea();
    sourceView.setLineWrap(true);
    sourceView.setFont(new Font("Monospaced", Font.PLAIN, Globals.prefs.getInt(JabRefPreferences.FONT_SIZE)));
    mainPanel.add(new JScrollPane(sourceView), cc.xyw(8, 8, 4));
    sourceView.setEditable(false);

    // Add some margin around the layout
    mainLayout.appendRow(RowSpec.decode(MARGIN));
    mainLayout.appendColumn(ColumnSpec.decode(MARGIN));
    mainLayout.insertRow(1, RowSpec.decode(MARGIN));
    mainLayout.insertColumn(1, ColumnSpec.decode(MARGIN));

    // Everything done, allow any action to actually update the merged entry
    doneBuilding = true;

    updateAll();

    // Show what we've got
    mainPanel.setVisible(true);
    javax.swing.SwingUtilities.invokeLater(() -> scrollPane.getVerticalScrollBar().setValue(0));
}

From source file:com.spotify.heroic.suggest.elasticsearch.SuggestBackendKV.java

@Override
public AsyncFuture<TagSuggest> tagSuggest(TagSuggest.Request request) {
    return connection.doto((final Connection c) -> {
        final BoolQueryBuilder bool = boolQuery();

        final Optional<String> key = request.getKey();
        final Optional<String> value = request.getValue();

        // special case: key and value are equal, which indicates that _any_ match should be
        // in effect.
        // XXX: Enhance API to allow for this to be intentional instead of this by
        // introducing an 'any' field.
        if (key.isPresent() && value.isPresent() && key.equals(value)) {
            bool.should(matchTermKey(key.get()));
            bool.should(matchTermValue(value.get()));
        } else {//ww w  .  j a v a 2 s .  co m
            key.ifPresent(k -> {
                if (!k.isEmpty()) {
                    bool.must(matchTermKey(k).boost(2.0f));
                }
            });

            value.ifPresent(v -> {
                if (!v.isEmpty()) {
                    bool.must(matchTermValue(v));
                }
            });
        }

        QueryBuilder query = bool.hasClauses() ? bool : matchAllQuery();

        if (!(request.getFilter() instanceof TrueFilter)) {
            query = new BoolQueryBuilder().must(query).filter(filter(request.getFilter()));
        }

        final SearchRequestBuilder builder = c.search(TAG_TYPE).setSize(0).setQuery(query).setTimeout(TIMEOUT);

        // aggregation
        {
            final TopHitsAggregationBuilder hits = AggregationBuilders.topHits("hits").size(1)
                    .fetchSource(TAG_SUGGEST_SOURCES, new String[0]);

            final TermsAggregationBuilder terms = AggregationBuilders.terms("terms").field(TAG_KV)
                    .subAggregation(hits);

            request.getLimit().asInteger().ifPresent(terms::size);

            builder.addAggregation(terms);
        }

        return bind(builder.execute()).directTransform((SearchResponse response) -> {
            final ImmutableList.Builder<Suggestion> suggestions = ImmutableList.builder();

            final Aggregations aggregations = response.getAggregations();

            if (aggregations == null) {
                return TagSuggest.of();
            }

            final StringTerms terms = aggregations.get("terms");

            for (final Terms.Bucket bucket : terms.getBuckets()) {
                final TopHits topHits = bucket.getAggregations().get("hits");
                final SearchHits hits = topHits.getHits();
                final SearchHit hit = hits.getAt(0);
                final Map<String, Object> doc = hit.getSource();

                final String k = (String) doc.get(TAG_SKEY);
                final String v = (String) doc.get(TAG_SVAL);

                suggestions.add(new Suggestion(hits.getMaxScore(), k, v));
            }

            return TagSuggest.of(suggestions.build());
        });
    });
}