Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

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

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

From source file:cz.lbenda.dataman.db.frm.DbConfigFrmController.java

public static DbConfig openDialog(final DbConfig sc) {
    Dialog<DbConfig> dialog = DialogHelper.createDialog();
    dialog.setResizable(false);//w  w w .jav a 2s. co m
    final Tuple2<Parent, DbConfigFrmController> tuple = createNewInstance();
    if (sc != null) {
        tuple.get2().loadDataFromSessionConfiguration(sc);
    }
    dialog.setTitle(msgDialogTitle);
    dialog.setHeaderText(msgDialogHeader);

    dialog.getDialogPane().setContent(tuple.get1());
    ButtonType buttonTypeOk = ButtonType.OK;
    ButtonType buttonTypeCancel = ButtonType.CANCEL;
    dialog.getDialogPane().getButtonTypes().add(buttonTypeCancel);
    dialog.getDialogPane().getButtonTypes().add(buttonTypeOk);
    dialog.getDialogPane().setPadding(new Insets(0, 0, 0, 0));

    dialog.setResultConverter(b -> {
        if (b == buttonTypeOk) {
            DbConfig sc1 = sc;
            if (sc1 == null) {
                sc1 = new DbConfig();
                tuple.get2().storeDataToSessionConfiguration(sc1);
                DbConfigFactory.getConfigurations().add(sc1);
            } else {
                tuple.get2().storeDataToSessionConfiguration(sc1);
                if (DbConfigFactory.getConfigurations().contains(sc1)) { // The copied session isn't in list yet
                    int idx = DbConfigFactory.getConfigurations().indexOf(sc1);
                    DbConfigFactory.getConfigurations().remove(sc1);
                    DbConfigFactory.getConfigurations().add(idx, sc1);
                } else {
                    DbConfigFactory.getConfigurations().add(sc1);
                }
            }
            DbConfigFactory.saveConfiguration();
            return sc1;
        }
        return null;
    });

    Optional<DbConfig> result = dialog.showAndWait();
    if (result.isPresent()) {
        return result.get();
    }
    return null;
}

From source file:org.trellisldp.rosid.file.CachedResource.java

/**
 * Write the resource data into a file as JSON
 * @param directory the directory//from w  w w.j av a 2  s .  co m
 * @param identifier the resource identifier
 * @param time the time
 * @return true if the write operation succeeds
 */
public static Boolean write(final File directory, final IRI identifier, final Instant time) {

    if (isNull(directory)) {
        return false;
    }

    // Write the JSON file
    LOGGER.debug("Writing JSON cache for {}", identifier.getIRIString());
    final Optional<ResourceData> data = VersionedResource.read(directory, identifier, time);
    try {
        if (data.isPresent()) {
            MAPPER.writeValue(new File(directory, RESOURCE_CACHE), data.get());
        } else {
            LOGGER.error("No resource data to cache for {}", identifier.getIRIString());
            return false;
        }
    } catch (final IOException ex) {
        LOGGER.error("Error writing resource metadata cache for {}: {}", identifier.getIRIString(),
                ex.getMessage());
        return false;
    }

    // Write the quads
    LOGGER.debug("Writing NQuads cache for {}", identifier.getIRIString());
    try (final BufferedWriter writer = newBufferedWriter(new File(directory, RESOURCE_QUADS).toPath(), UTF_8,
            CREATE, WRITE, TRUNCATE_EXISTING)) {
        final File file = new File(directory, RESOURCE_JOURNAL);
        final Iterator<String> lineIter = RDFPatch.asStream(rdf, file, identifier, time)
                .map(RDFPatch.quadToString).iterator();
        while (lineIter.hasNext()) {
            writer.write(lineIter.next() + lineSeparator());
        }
    } catch (final IOException ex) {
        LOGGER.error("Error writing resource cache for {}: {}", identifier.getIRIString(), ex.getMessage());
        return false;
    }

    return true;
}

From source file:co.runrightfast.vertx.orientdb.impl.embedded.EmbeddedOrientDBServiceTest.java

private static void initDatabase() {
    final OServerAdmin admin = service.getServerAdmin();
    try {//from www .  ja  va 2s. com
        OrientDBUtils.createDatabase(admin, CLASS_NAME);
    } finally {
        admin.close();
    }

    final Optional<ODatabaseDocumentTxSupplier> dbSupplier = service.getODatabaseDocumentTxSupplier(CLASS_NAME);
    assertThat(dbSupplier.isPresent(), is(true));

    try (final ODatabase db = dbSupplier.get().get()) {
        final OClass timestampedClass = db.getMetadata().getSchema()
                .createAbstractClass(Timestamped.class.getSimpleName());
        timestampedClass.createProperty(Timestamped.Field.created_on.name(), OType.DATETIME);
        timestampedClass.createProperty(Timestamped.Field.updated_on.name(), OType.DATETIME);

        final OClass logRecordClass = db.getMetadata().getSchema()
                .createClass(EventLogRecord.class.getSimpleName())
                .setSuperClasses(ImmutableList.of(timestampedClass));
        logRecordClass.createProperty(EventLogRecord.Field.event.name(), OType.STRING);
    }
}

From source file:org.openmhealth.shim.ihealth.mapper.IHealthDataPointMapper.java

/**
 * Get an effective time frame based on the measurement date/time information in the list entry node. The effective
 * time frame is set as a single point in time using an OffsetDateTime. This method does not get effective time
 * frame as a time interval./*from   w  ww  . ja v  a  2 s .  c  om*/
 *
 * @param listEntryNode A single node from the response result array.
 */
protected static Optional<TimeFrame> getEffectiveTimeFrameAsDateTime(JsonNode listEntryNode) {

    Optional<Long> weirdSeconds = asOptionalLong(listEntryNode, "MDate");

    if (!weirdSeconds.isPresent()) {
        return Optional.empty();
    }

    ZoneOffset zoneOffset = null;

    // if the time zone is a JSON string
    if (asOptionalString(listEntryNode, "TimeZone").isPresent()
            && !asOptionalString(listEntryNode, "TimeZone").get().isEmpty()) {

        zoneOffset = ZoneOffset.of(asOptionalString(listEntryNode, "TimeZone").get());
    }
    // if the time zone is an JSON integer
    else if (asOptionalLong(listEntryNode, "TimeZone").isPresent()) {

        Long timeZoneOffsetValue = asOptionalLong(listEntryNode, "TimeZone").get();

        String timeZoneString = timeZoneOffsetValue.toString();

        // Zone offset cannot parse a positive string offset that's missing a '+' sign (i.e., "0200" vs "+0200")
        if (timeZoneOffsetValue >= 0) {

            timeZoneString = "+" + timeZoneString;
        }

        zoneOffset = ZoneOffset.of(timeZoneString);
    }

    if (zoneOffset == null) {

        return Optional.empty();
    }

    return Optional.of(new TimeFrame(getDateTimeWithCorrectOffset(weirdSeconds.get(), zoneOffset)));
}

From source file:com.formkiq.core.form.FormFinder.java

/**
 * Find {@link FormJSONField} by field id.
 * @param form {@link FormJSON}/*from  w  ww  . j  a v a  2s  . c  o m*/
 * @param id int
 * @return {@link Optional} of {@link FormJSONField}
 */
public static Optional<FormJSONField> findField(final FormJSON form, final int id) {
    Optional<Pair<FormJSONSection, FormJSONField>> op = findSectionAndField(form, id);
    return op.isPresent() ? Optional.of(op.get().getRight()) : Optional.empty();
}

From source file:io.github.jeddict.relation.mapper.initializer.ColumnUtil.java

/**
 * Exception Description: The @JoinColumns on the annotated element [method
 * get] from the entity class [class Employee] is incomplete.
 *
 * When the source entity class uses a composite primary key, a @JoinColumn
 * must be specified for each join column using the @JoinColumns. Both the
 * name and the referencedColumnName elements must be specified in each such
 * '@JoinColumn'./*ww  w. j a v  a2s. c  o  m*/
 */
public static void syncronizeCompositeKeyJoincolumn(TableWidget<DBTable> sourceTableWidget,
        final TableWidget<DBTable> targetTableWidget) {
    if (sourceTableWidget.getPrimaryKeyWidgets().size() > 1) {
        for (IPrimaryKeyWidget<DBColumn<Id>> primaryKeyWidget : sourceTableWidget.getPrimaryKeyWidgets()) {
            Optional<ReferenceFlowWidget> optionalReferenceFlowWidget = primaryKeyWidget
                    .getReferenceFlowWidget().stream()
                    .filter(r -> r.getForeignKeyWidget().getTableWidget() == targetTableWidget).findFirst();
            if (optionalReferenceFlowWidget.isPresent()) {
                ForeignKeyWidget foreignKeyWidget = optionalReferenceFlowWidget.get().getForeignKeyWidget();
                IJoinColumn joinColumn;
                if (foreignKeyWidget instanceof ParentAssociationColumnWidget) {
                    joinColumn = ((DBParentAssociationColumn) foreignKeyWidget.getBaseElementSpec())
                            .getJoinColumnOverride();
                } else {
                    joinColumn = ((DBForeignKey) foreignKeyWidget.getBaseElementSpec()).getJoinColumn();
                }
                if (StringUtils.isEmpty(joinColumn.getReferencedColumnName())) {
                    joinColumn.setReferencedColumnName(primaryKeyWidget.getName());
                }
                if (StringUtils.isEmpty(joinColumn.getName())) {
                    joinColumn.setName(foreignKeyWidget.getName());
                }
            }
        }
    }
}

From source file:info.archinnov.achilles.internals.runtime.BeanValueExtractor.java

public static <T> BoundValuesWrapper extractPartitionKeysAndStaticValues(T instance,
        AbstractEntityProperty<T> entityProperty, Options options) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Extract partition key values and static columns from entity %s of type %",
                instance, entityProperty.entityClass.getCanonicalName()));
    }//from  w w w .j a va2 s.c o  m

    final List<BoundValueInfo> boundValues = new ArrayList<>();
    final List<BoundValueInfo> partitionKeys = entityProperty.partitionKeys.stream().map(x -> {
        final AbstractProperty x1 = (AbstractProperty) x;
        final BiConsumer<Object, SettableData> lambda = x1::encodeToSettable;
        return BoundValueInfo.of(lambda, x.getFieldValue(instance), x.encodeField(instance));
    }).collect(toList());

    boundValues.addAll(partitionKeys);

    boundValues.addAll(entityProperty.staticColumns.stream().map(x -> {
        final AbstractProperty x1 = (AbstractProperty) x;
        return BoundValueInfo.of(x1::encodeToSettable, x.getFieldValue(instance), x.encodeField(instance));
    }).collect(toList()));

    final Optional<Integer> ttl = OverridingOptional.from(options.getTimeToLive())
            .andThen(entityProperty.staticTTL).getOptional();

    boundValues.add(ttl.isPresent()
            ? BoundValueInfo.of(
                    (Object value, SettableData settableData) -> settableData.setInt("ttl", ttl.get()),
                    ttl.get(), ttl.get())
            : BoundValueInfo.of((Object value, SettableData settableData) -> settableData.setInt("ttl", 0), 0,
                    0));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Extracted encoded bound values : %s", boundValues));
    }
    return new BoundValuesWrapper(entityProperty, boundValues);

}

From source file:nc.noumea.mairie.appock.util.StockSpreadsheetImporter.java

private static void updateStock(Service service, String reference, int stockReel, StockService stockService,
        int ligne) throws ImportExcelException {
    Stock stock = stockService.findOne(service.getStock().getId());
    Optional<ArticleStock> articleStockOptional = stock.getListeArticleStock().stream() //
            .filter(articleStock -> articleStock.getReferenceArticleStock().equals(reference)) //
            .findFirst();/*w  w w.j a  va2 s .co m*/
    if (articleStockOptional.isPresent()) {
        int diffQuantite = stockReel - articleStockOptional.get().getQuantiteStock();
        if (diffQuantite == 0) {
            return;
        }
        TypeMouvementStock typeMouvementStock = diffQuantite < 0 ? TypeMouvementStock.SORTIE
                : TypeMouvementStock.ENTREE;
        stockService.creeEntreeSortieEtMouvement(articleStockOptional.get(), Math.abs(diffQuantite),
                typeMouvementStock, "Import inventaire");
        return;
    } else {
        throw new ImportExcelException(ligne + 1, reference,
                "Aucun article n'a t trouv dans le stock pour cette rfrence");
    }
}

From source file:io.pravega.controller.store.stream.tables.HistoryRecord.java

/**
 * Return latest record in the history table.
 *
 * @param historyTable  history table//  w w w  .  jav  a  2 s  .c  om
 * @param ignorePartial If latest entry is partial entry, if ignore is set then read the previous
 * @return returns the history record if it is found.
 */
public static Optional<HistoryRecord> readLatestRecord(final byte[] historyTable, boolean ignorePartial) {
    if (historyTable.length < PARTIAL_FIELDS_FIXED_LENGTH) {
        return Optional.empty();
    }

    final int backToTop = BitConverter.readInt(historyTable, historyTable.length - (Integer.BYTES));

    // ignore partial means if latest record is partial, read the previous record
    Optional<HistoryRecord> record = readRecord(historyTable, historyTable.length - backToTop, false);
    assert record.isPresent();

    if (ignorePartial && record.get().isPartial()) {
        return fetchPrevious(record.get(), historyTable);
    } else {
        return record;
    }
}

From source file:com.plotsquared.iserver.util.FileUtils.java

public static String getDocument(final File file, int buffer, boolean create) {
    final Optional<String> cacheEntry = Server.getInstance().getCacheManager().getCachedFile(file.toString());
    if (cacheEntry.isPresent()) {
        return cacheEntry.get();
    }/*  w w  w .  ja  v a  2s . c o  m*/

    StringBuilder document = new StringBuilder();
    try {
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (create) {
                file.createNewFile();
                return "";
            }
        }

        BufferedReader reader = new BufferedReader(new FileReader(file), buffer);
        String line;
        while ((line = reader.readLine()) != null) {
            document.append(line).append("\n");
        }
        reader.close();
    } catch (final Exception e) {
        e.printStackTrace();
    }

    final String content = document.toString();
    Server.getInstance().getCacheManager().setCachedFile(file.toString(), content);
    return content;
}