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:jparser.JParser.java

/**
 * @param args the command line arguments
 */// w w  w  .ja  v a2 s . c  o  m
public static void main(String[] args) {

    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(
            Option.builder().longOpt("to").desc("Indica el tipo de archivo al que debera convertir: JSON / XML")
                    .hasArg().argName("tipo").build());

    options.addOption(Option.builder().longOpt("path")
            .desc("Indica la ruta donde se encuentra el archivo origen").hasArg().argName("origen").build());

    options.addOption(
            Option.builder().longOpt("target").desc("Indica la ruta donde se guardara el archivo resultante")
                    .hasArg().argName("destino").build());

    options.addOption("h", "help", false, "Muestra la guia de como usar la aplicacion");

    try {
        CommandLine command = parser.parse(options, args);
        Path source = null;
        Path target = null;
        FactoryFileParse.TypeParce type = FactoryFileParse.TypeParce.NULL;
        Optional<Customer> customer = Optional.empty();

        if (command.hasOption("h")) {
            HelpFormatter helper = new HelpFormatter();
            helper.printHelp("JParser", options);

            System.exit(0);
        }

        if (command.hasOption("to"))
            type = FactoryFileParse.TypeParce.fromValue(command.getOptionValue("to", ""));

        if (command.hasOption("path"))
            source = Paths.get(command.getOptionValue("path", ""));

        if (command.hasOption("target"))
            target = Paths.get(command.getOptionValue("target", ""));

        switch (type) {
        case JSON:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.XML).read(source);

            break;

        case XML:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.JSON).read(source);

            break;
        }

        if (customer.isPresent()) {
            Customer c = customer.get();

            boolean success = FactoryFileParse.createNewInstance(type).write(c, target);

            System.out.println(String.format("Operatation was: %s", success ? "success" : "fails"));
        }

    } catch (ParseException ex) {
        Logger.getLogger(JParser.class.getSimpleName()).log(Level.SEVERE, ex.getMessage(), ex);

        System.exit(-1);
    }
}

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  w  w  w . j  ava2s  . c om
 * <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 w w .  jav a 2  s .  com
    return Stream.empty();
}

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();
    }/* www .j a v  a  2  s. c  om*/
    return null;
}

From source file:io.github.medinam.jcheesum.util.VersionChecker.java

public static void showDownloadLatestAlert() {
    Alert alert = new Alert(Alert.AlertType.INFORMATION);

    ResourceBundle resources = ResourceBundle.getBundle("i18n/Bundle", Locale.getDefault());

    alert.setTitle(resources.getString("newVersion"));
    alert.setHeaderText(resources.getString("newVersionLooksLike"));
    alert.setContentText(resources.getString("youHave") + App.class.getPackage().getImplementationVersion()
            + " " + resources.getString("latestVersionIs") + getLatestStable() + "\n\n"
            + resources.getString("wannaDownload"));

    ButtonType yesBtn = new ButtonType(resources.getString("yes"));
    ButtonType noBtn = new ButtonType(resources.getString("no"), ButtonBar.ButtonData.CANCEL_CLOSE);

    alert.getButtonTypes().setAll(yesBtn, noBtn);

    Optional<ButtonType> o = alert.showAndWait();

    if (o.get() == yesBtn) {
        General.openLink(getLatestStableDownloadURL());
    } else if (o.get() == noBtn) {
        alert.close();/*from  ww w  .j  a v a 2 s . c o  m*/
    }
}

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: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:org.rapidpm.microservice.optionals.service.ServiceWrapper.java

private static String getAdminRestPath(Optional<Annotation> pathAnnotation) {
    Path annotation = (Path) pathAnnotation.get();
    return annotation.value();
}

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());
        }//from  w  w w  . j  ava 2 s .  com
    }

    return treeSet;
}

From source file:io.github.retz.web.AppRequestHandler.java

static String listApp(Request req, Response res) throws JsonProcessingException {
    Optional<AuthHeader> authHeaderValue = getAuthInfo(req);
    LOG.info("Listing all apps owned by {}", authHeaderValue.get().key());
    ListAppResponse response = new ListAppResponse(Applications.getAll(authHeaderValue.get().key()));
    response.ok();/*ww w.  j a  v  a2s .  com*/
    return MAPPER.writeValueAsString(response);
}