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:net.sf.jabref.logic.xmp.XMPUtil.java

/**
 * Command-line tool for working with XMP-data.
 *
 * Read or write XMP-metadata from or to pdf file.
 *
 * Usage:/*from www  . jav a2  s .c o m*/
 * <dl>
 * <dd>Read from PDF and print as bibtex:</dd>
 * <dt>xmpUtil PDF</dt>
 * <dd>Read from PDF and print raw XMP:</dd>
 * <dt>xmpUtil -x PDF</dt>
 * <dd>Write the entry in BIB given by KEY to the PDF:</dd>
 * <dt>xmpUtil KEY BIB PDF</dt>
 * <dd>Write all entries in BIB to the PDF:</dd>
 * <dt>xmpUtil BIB PDF</dt>
 * </dl>
 *
 * @param args
 *            Command line strings passed to utility.
 * @throws IOException
 *             If any of the given files could not be read or written.
 * @throws TransformerException
 *             If the given BibEntry is malformed.
 */
public static void main(String[] args) throws IOException, TransformerException {

    // Don't forget to initialize the preferences
    if (Globals.prefs == null) {
        Globals.prefs = JabRefPreferences.getInstance();
    }

    switch (args.length) {
    case 0:
        XMPUtil.usage();
        break;
    case 1:

        if (args[0].endsWith(".pdf")) {
            // Read from pdf and write as BibTex
            List<BibEntry> l = XMPUtil.readXMP(new File(args[0]), Globals.prefs);

            BibEntryWriter bibtexEntryWriter = new BibEntryWriter(
                    new LatexFieldFormatter(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs)),
                    false);

            for (BibEntry entry : l) {
                StringWriter sw = new StringWriter();
                bibtexEntryWriter.write(entry, sw, BibDatabaseMode.BIBTEX);
                System.out.println(sw.getBuffer());
            }

        } else if (args[0].endsWith(".bib")) {
            // Read from bib and write as XMP
            try (FileReader fr = new FileReader(args[0])) {
                ParserResult result = BibtexParser.parse(fr);
                Collection<BibEntry> entries = result.getDatabase().getEntries();

                if (entries.isEmpty()) {
                    System.err.println("Could not find BibEntry in " + args[0]);
                } else {
                    System.out.println(XMPUtil.toXMP(entries, result.getDatabase()));
                }
            }
        } else {
            XMPUtil.usage();
        }
        break;
    case 2:
        if ("-x".equals(args[0]) && args[1].endsWith(".pdf")) {
            // Read from pdf and write as BibTex
            Optional<XMPMetadata> meta = XMPUtil.readRawXMP(new File(args[1]));

            if (meta.isPresent()) {
                XMLUtil.save(meta.get().getXMPDocument(), System.out, StandardCharsets.UTF_8.name());
            } else {
                System.err.println("The given pdf does not contain any XMP-metadata.");
            }
            break;
        }

        if (args[0].endsWith(".bib") && args[1].endsWith(".pdf")) {
            ParserResult result = BibtexParser.parse(new FileReader(args[0]));

            Collection<BibEntry> entries = result.getDatabase().getEntries();

            if (entries.isEmpty()) {
                System.err.println("Could not find BibEntry in " + args[0]);
            } else {
                XMPUtil.writeXMP(new File(args[1]), entries, result.getDatabase(), false);
                System.out.println("XMP written.");
            }
            break;
        }

        XMPUtil.usage();
        break;
    case 3:
        if (!args[1].endsWith(".bib") && !args[2].endsWith(".pdf")) {
            XMPUtil.usage();
            break;
        }

        ParserResult result = BibtexParser.parse(new FileReader(args[1]));

        Optional<BibEntry> bibEntry = result.getDatabase().getEntryByKey(args[0]);

        if (bibEntry.isPresent()) {
            XMPUtil.writeXMP(new File(args[2]), bibEntry.get(), result.getDatabase());

            System.out.println("XMP written.");
        } else {
            System.err.println("Could not find BibEntry " + args[0] + " in " + args[0]);
        }
        break;

    default:
        XMPUtil.usage();
    }
}

From source file:Main.java

public static <T> Stream<T> toStream(Optional<T> optional) {
    if (optional.isPresent()) {
        return Stream.of(optional.get());
    }/*w  ww.ja v a  2 s. co m*/
    return Stream.empty();
}

From source file:Main.java

public static <T> List<T> subListOn(List<T> list, Predicate<T> predicate) {
    Optional<T> first = list.stream().filter(predicate).findFirst();
    if (!first.isPresent())
        return list;
    return list.subList(0, list.indexOf(first.get()));
}

From source file:me.ferrybig.javacoding.webmapper.test.session.DefaultDataStorageTest.java

private static <T> T extr(Optional<T> in) {
    if (in.isPresent()) {
        return in.get();
    }/*from   w ww. j a  v  a  2  s . com*/
    return null;
}

From source file:Main.java

public static Optional<String> getTextOfElement(List<XMLEvent> events, String elementName) {
    Optional<Characters> characters = getCharacterEventOfElement(events, elementName);

    if (characters.isPresent())
        return Optional.of(characters.get().getData());

    return Optional.empty();
}

From source file:com.thoughtworks.go.apiv4.agents.representers.UpdateRequestRepresenter.java

static List<String> extractToList(Optional<JsonArray> arrayOptional) {
    final List<String> treeSet = new ArrayList<>();
    if (arrayOptional.isPresent()) {
        for (JsonElement jsonElement : arrayOptional.get()) {
            treeSet.add(jsonElement.getAsString());
        }// w w w .j  a  va 2s  . c om
    }

    return treeSet;
}

From source file:com.schnobosoft.semeval.cortical.PrintCorrelations.java

private static double getPearson(List<Optional> gold, List<Optional> scores) {
    assert gold.size() == scores.size();

    List<Double> gsList = new ArrayList<>(gold.size());
    List<Double> sList = new ArrayList<>(scores.size());

    for (int i = 0; i < gold.size(); i++) {
        Optional goldOpt = gold.get(i);
        Optional scoreOpt = scores.get(i);
        if (goldOpt.isPresent() && scoreOpt.isPresent()) {
            gsList.add((Double) goldOpt.get());
            sList.add((Double) scoreOpt.get());
        } else {/*  ww  w .j  a v a  2 s  .  c o m*/
            LOG.warn("No score found in line " + i + ".");
        }
    }
    return new PearsonsCorrelation().correlation(listToArray(gsList), listToArray(sList));
}

From source file:org.trustedanalytics.hadoop.admin.tools.HadoopClientParamsImporter.java

static void performAction(CLIParameters params) throws IOException, XPathExpressionException {
    Optional<InputStream> inputStreamOptional = getSourceInputStream(params);
    if (inputStreamOptional.isPresent()) {
        try (InputStream sourceStream = inputStreamOptional.get()) {
            LOGGER.info(returnJSON(scanConfigZipArchive(sourceStream).get()));
        }//from  w w w .  j  a v a  2  s. c o m
    }
}

From source file:com.github.horrorho.inflatabledonkey.cloud.clients.BackupAccountClient.java

public static Optional<BackupAccount> backupAccount(HttpClient httpClient, CloudKitty kitty,
        ProtectionZone zone) throws IOException {

    List<CloudKit.RecordRetrieveResponse> responses = kitty.recordRetrieveRequest(httpClient, "mbksync",
            "BackupAccount");
    logger.debug("-- backupAccount() - responses: {}", responses);

    if (responses.size() != 1) {
        logger.warn("-- backupAccount() - bad response list size: {}", responses);
        return Optional.empty();
    }/*w  ww.j  ava  2  s. co m*/

    CloudKit.ProtectionInfo protectionInfo = responses.get(0).getRecord().getProtectionInfo();

    Optional<ProtectionZone> optionalNewZone = zone.newProtectionZone(protectionInfo);
    if (!optionalNewZone.isPresent()) {
        logger.warn("-- backupAccount() - failed to retrieve protection info");
        return Optional.empty();
    }
    ProtectionZone newZone = optionalNewZone.get();

    BackupAccount backupAccount = BackupAccountFactory.from(responses.get(0).getRecord(),
            (bs, id) -> newZone.decrypt(bs, id).get()); // TODO rework BackupAccount
    logger.debug("-- backupAccount() - backup account: {}", backupAccount);

    return Optional.of(backupAccount);
}

From source file:com.ejisto.core.classloading.javassist.ObjectEditor.java

private static boolean hasAlreadyBeenProcessed(FieldAccess f, String fieldName) {
    Optional<String> fieldMarker = getFieldMarker(fieldName);
    return !fieldMarker.isPresent() || Arrays.stream(f.getEnclosingClass().getDeclaredFields())
            .anyMatch(field -> field.getName().equals(fieldMarker.get()));
}