Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

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

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

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();
    }/*from  ww  w .  j ava2  s  .  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;
}

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

/**
 * Return latest record in the history table.
 *
 * @param historyTable  history table//from   w  ww.  ja  v  a  2  s. c o  m
 * @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:co.runrightfast.vertx.orientdb.impl.embedded.EmbeddedOrientDBServiceTest.java

private static void initDatabase() {
    final OServerAdmin admin = service.getServerAdmin();
    try {/*from w ww.  jav  a 2  s.co  m*/
        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:cz.lbenda.rcp.DialogHelper.java

/** Open dialog with chooser when user can choose single option
 * @param question question which is show to user
 * @param items list of items which user can choose
 * @param <T> type of item/* w  w  w .j  av a 2s.c o  m*/
 * @return null if user click on cancel or don't choose anything, elsewhere choosed item */
@SuppressWarnings("unchecked")
public static <T> T chooseSingOption(String question, T... items) {
    if (items.length == 0) {
        return null;
    }
    Dialog<T> dialog = new Dialog<>();
    dialog.setResizable(false);
    dialog.setTitle(chooseSingleOption_title);
    dialog.setHeaderText(question);

    ComboBox<T> comboBox = new ComboBox<>();
    comboBox.getItems().addAll(items);
    dialog.getDialogPane().setContent(comboBox);

    ButtonType btCancel = ButtonType.CANCEL;
    ButtonType btOk = ButtonType.OK;
    dialog.getDialogPane().getButtonTypes().addAll(btCancel, btOk);

    Optional<T> result = dialog.showAndWait();
    if (result.isPresent()) {
        if (btCancel == result.get()) {
            return null;
        }
        if (btOk == result.get()) {
            return comboBox.getSelectionModel().getSelectedItem();
        }
    } else {
        return null;
    }
    return result.get();
}

From source file:com.facebook.buck.testutil.integration.TarInspector.java

private static TarArchiveInputStream getArchiveInputStream(Optional<String> compressorType, Path tar)
        throws IOException, CompressorException {
    BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(tar));
    if (compressorType.isPresent()) {
        return new TarArchiveInputStream(
                new CompressorStreamFactory().createCompressorInputStream(compressorType.get(), inputStream));
    }/*from  ww  w.  j a  v  a  2  s .c  o  m*/
    return new TarArchiveInputStream(inputStream);
}

From source file:gov.ca.cwds.cals.util.PlacementHomeUtil.java

private static StringBuilder composeSecondPartOfFacilityName(Optional<ApplicantDTO> firstApplicant,
        ApplicantDTO secondApplicant) {//w  w w. ja v  a2 s  .  c o m
    StringBuilder sbForSecondApplicant = new StringBuilder();
    Optional<String> secondLastName = Optional.ofNullable(secondApplicant.getLastName());
    Optional<String> secondFirstName = Optional.ofNullable(secondApplicant.getFirstName());
    if (firstApplicant.isPresent() && secondLastName.isPresent()
            && !secondLastName.get().equals(firstApplicant.get().getLastName())) {
        sbForSecondApplicant.append(secondLastName.get());
        if (secondFirstName.isPresent()) {
            sbForSecondApplicant.append(", ");
        }
    }
    secondFirstName.ifPresent(sbForSecondApplicant::append);
    return sbForSecondApplicant;
}

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

/**
 * Write the resource data into a file as JSON
 * @param directory the directory//w  ww .  jav  a2  s  . c  om
 * @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: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();/*from  ww  w . j  a va  2 s. c o  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.hops.hopsworks.util.CertificateHelper.java

public static Optional<Triplet<KeyStore, KeyStore, String>> loadKeystoreFromDB(String masterPswd,
        String clusterName, ClusterCertificateFacade certFacade,
        CertificatesMgmService certificatesMgmService) {
    try {/*from ww  w.  j  a  v  a 2s . c  o m*/
        Optional<ClusterCertificate> cert = certFacade.getClusterCert(clusterName);
        if (!cert.isPresent()) {
            return Optional.empty();
        }
        String certPswd = HopsUtils.decrypt(masterPswd, cert.get().getCertificatePassword(),
                certificatesMgmService.getMasterEncryptionPassword());
        KeyStore keystore, truststore;
        try (ByteArrayInputStream keystoreIS = new ByteArrayInputStream(cert.get().getClusterKey());
                ByteArrayInputStream truststoreIS = new ByteArrayInputStream(cert.get().getClusterCert())) {
            keystore = keystore(keystoreIS, certPswd);
            truststore = keystore(truststoreIS, certPswd);
        }
        return Optional.of(Triplet.with(keystore, truststore, certPswd));
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "keystore ex. {0}", ex.getMessage());
        return Optional.empty();
    }
}

From source file:io.github.lxgaming.teleportbow.managers.CommandManager.java

public static boolean registerCommand(Class<? extends AbstractCommand> commandClass) {
    if (getCommandClasses().contains(commandClass)) {
        TeleportBow.getInstance().getLogger().warn("{} has already been registered",
                commandClass.getSimpleName());
        return false;
    }//from  w w  w . j  av a  2s  .  c  o  m

    getCommandClasses().add(commandClass);
    Optional<AbstractCommand> command = Toolbox.newInstance(commandClass);
    if (!command.isPresent()) {
        TeleportBow.getInstance().getLogger().error("{} failed to initialize", commandClass.getSimpleName());
        return false;
    }

    getCommands().add(command.get());
    Sponge.getCommandManager().register(TeleportBow.getInstance().getPluginContainer(), command.get(),
            command.get().getAliases().toArray(new String[0]));
    TeleportBow.getInstance().getLogger().debug("{} registered", commandClass.getSimpleName());
    return true;
}