Search in sources :

Example 1 with FetcherException

use of org.jabref.logic.importer.FetcherException in project jabref by JabRef.

the class ClipBoardManager method extractBibEntriesFromClipboard.

public List<BibEntry> extractBibEntriesFromClipboard() {
    // Get clipboard contents, and see if TransferableBibtexEntry is among the content flavors offered
    Transferable content = CLIPBOARD.getContents(null);
    List<BibEntry> result = new ArrayList<>();
    if (content.isDataFlavorSupported(TransferableBibtexEntry.entryFlavor)) {
        // We have determined that the clipboard data is a set of entries.
        try {
            @SuppressWarnings("unchecked") List<BibEntry> contents = (List<BibEntry>) content.getTransferData(TransferableBibtexEntry.entryFlavor);
            result = contents;
        } catch (UnsupportedFlavorException | ClassCastException ex) {
            LOGGER.warn("Could not paste this type", ex);
        } catch (IOException ex) {
            LOGGER.warn("Could not paste", ex);
        }
    } else if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
            String data = (String) content.getTransferData(DataFlavor.stringFlavor);
            // fetch from doi
            if (DOI.parse(data).isPresent()) {
                LOGGER.info("Found DOI in clipboard");
                Optional<BibEntry> entry = new DoiFetcher(Globals.prefs.getImportFormatPreferences()).performSearchById(new DOI(data).getDOI());
                entry.ifPresent(result::add);
            } else {
                // parse bibtex string
                BibtexParser bp = new BibtexParser(Globals.prefs.getImportFormatPreferences());
                BibDatabase db = bp.parse(new StringReader(data)).getDatabase();
                LOGGER.info("Parsed " + db.getEntryCount() + " entries from clipboard text");
                if (db.hasEntries()) {
                    result = db.getEntries();
                }
            }
        } catch (UnsupportedFlavorException ex) {
            LOGGER.warn("Could not parse this type", ex);
        } catch (IOException ex) {
            LOGGER.warn("Data is no longer available in the requested flavor", ex);
        } catch (FetcherException ex) {
            LOGGER.error("Error while fetching", ex);
        }
    }
    return result;
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) DoiFetcher(org.jabref.logic.importer.fetcher.DoiFetcher) Optional(java.util.Optional) BibtexParser(org.jabref.logic.importer.fileformat.BibtexParser) Transferable(java.awt.datatransfer.Transferable) ArrayList(java.util.ArrayList) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) FetcherException(org.jabref.logic.importer.FetcherException) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) List(java.util.List) BibDatabase(org.jabref.model.database.BibDatabase) DOI(org.jabref.model.entry.identifier.DOI)

Example 2 with FetcherException

use of org.jabref.logic.importer.FetcherException in project jabref by JabRef.

the class LookupIdentifiersWorker method run.

@Override
public void run() {
    BasePanel basePanel = Objects.requireNonNull(frame.getCurrentBasePanel());
    List<BibEntry> bibEntries = basePanel.getSelectedEntries();
    if (!bibEntries.isEmpty()) {
        String totalCount = Integer.toString(bibEntries.size());
        NamedCompound namedCompound = new NamedCompound(Localization.lang("Look up %0", fetcher.getIdentifierName()));
        int count = 0;
        int foundCount = 0;
        for (BibEntry bibEntry : bibEntries) {
            count++;
            frame.output(Localization.lang("Looking up %0... - entry %1 out of %2 - found %3", fetcher.getIdentifierName(), Integer.toString(count), totalCount, Integer.toString(foundCount)));
            Optional<T> identifier = Optional.empty();
            try {
                identifier = fetcher.findIdentifier(bibEntry);
            } catch (FetcherException e) {
                LOGGER.error("Could not fetch " + fetcher.getIdentifierName(), e);
            }
            if (identifier.isPresent() && !bibEntry.hasField(identifier.get().getDefaultField())) {
                Optional<FieldChange> fieldChange = bibEntry.setField(identifier.get().getDefaultField(), identifier.get().getNormalized());
                if (fieldChange.isPresent()) {
                    namedCompound.addEdit(new UndoableFieldChange(fieldChange.get()));
                    foundCount++;
                    frame.output(Localization.lang("Looking up %0... - entry %1 out of %2 - found %3", Integer.toString(count), totalCount, Integer.toString(foundCount)));
                }
            }
        }
        namedCompound.end();
        if (foundCount > 0) {
            basePanel.getUndoManager().addEdit(namedCompound);
            basePanel.markBaseChanged();
        }
        message = Localization.lang("Determined %0 for %1 entries", fetcher.getIdentifierName(), Integer.toString(foundCount));
    }
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) BasePanel(org.jabref.gui.BasePanel) FetcherException(org.jabref.logic.importer.FetcherException) NamedCompound(org.jabref.gui.undo.NamedCompound) FieldChange(org.jabref.model.FieldChange) UndoableFieldChange(org.jabref.gui.undo.UndoableFieldChange) UndoableFieldChange(org.jabref.gui.undo.UndoableFieldChange)

Example 3 with FetcherException

use of org.jabref.logic.importer.FetcherException in project jabref by JabRef.

the class IsbnViaChimboriFetcher method performSearchById.

@Override
public Optional<BibEntry> performSearchById(String identifier) throws FetcherException {
    if (StringUtil.isBlank(identifier)) {
        return Optional.empty();
    }
    this.ensureThatIsbnIsValid(identifier);
    HttpResponse<String> postResponse;
    try {
        postResponse = Unirest.post("https://bibtex.chimbori.com/isbn-bibtex").field("isbn", identifier).asString();
    } catch (UnirestException e) {
        throw new FetcherException("Could not retrieve data from chimbori.com", e);
    }
    if (postResponse.getStatus() != 200) {
        throw new FetcherException("Error while retrieving data from chimbori.com: " + postResponse.getBody());
    }
    List<BibEntry> fetchedEntries;
    try {
        fetchedEntries = getParser().parseEntries(postResponse.getRawBody());
    } catch (ParseException e) {
        throw new FetcherException("An internal parser error occurred", e);
    }
    if (fetchedEntries.isEmpty()) {
        return Optional.empty();
    } else if (fetchedEntries.size() > 1) {
        LOGGER.info("Fetcher " + getName() + "found more than one result for identifier " + identifier + ". We will use the first entry.");
    }
    BibEntry entry = fetchedEntries.get(0);
    // chimbori does not return an ISBN. Thus, we add the one searched for
    entry.setField("isbn", identifier);
    doPostCleanup(entry);
    return Optional.of(entry);
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) FetcherException(org.jabref.logic.importer.FetcherException) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) ParseException(org.jabref.logic.importer.ParseException)

Example 4 with FetcherException

use of org.jabref.logic.importer.FetcherException in project jabref by JabRef.

the class ArXiv method searchForEntries.

private List<ArXivEntry> searchForEntries(BibEntry entry) throws FetcherException {
    // 1. Eprint
    Optional<String> identifier = entry.getField(FieldName.EPRINT);
    if (StringUtil.isNotBlank(identifier)) {
        try {
            // Get pdf of entry with the specified id
            return OptionalUtil.toList(searchForEntryById(identifier.get()));
        } catch (FetcherException e) {
            LOGGER.warn("arXiv eprint API request failed", e);
        }
    }
    // 2. DOI and other fields
    String query;
    Optional<String> doi = entry.getField(FieldName.DOI).flatMap(DOI::parse).map(DOI::getNormalized);
    if (doi.isPresent()) {
        // Search for an entry in the ArXiv which is linked to the doi
        query = "doi:" + doi.get();
    } else {
        Optional<String> authorQuery = entry.getField(FieldName.AUTHOR).map(author -> "au:" + author);
        Optional<String> titleQuery = entry.getField(FieldName.TITLE).map(title -> "ti:" + title);
        query = OptionalUtil.toList(authorQuery, titleQuery).stream().collect(Collectors.joining("+AND+"));
    }
    Optional<ArXivEntry> arxivEntry = searchForEntry(query);
    if (arxivEntry.isPresent()) {
        // Check if entry is a match
        StringSimilarity match = new StringSimilarity();
        String arxivTitle = arxivEntry.get().title.orElse("");
        String entryTitle = entry.getField(FieldName.TITLE).orElse("");
        if (match.isSimilar(arxivTitle, entryTitle)) {
            return OptionalUtil.toList(arxivEntry);
        }
    }
    return Collections.emptyList();
}
Also used : FetcherException(org.jabref.logic.importer.FetcherException) StringSimilarity(org.jabref.logic.util.strings.StringSimilarity) DOI(org.jabref.model.entry.identifier.DOI)

Example 5 with FetcherException

use of org.jabref.logic.importer.FetcherException in project jabref by JabRef.

the class GoogleScholar method downloadEntry.

private BibEntry downloadEntry(String link) throws IOException, FetcherException {
    String downloadedContent = new URLDownload(link).asString();
    BibtexParser parser = new BibtexParser(importFormatPreferences);
    ParserResult result = parser.parse(new StringReader(downloadedContent));
    if ((result == null) || (result.getDatabase() == null)) {
        throw new FetcherException("Parsing entries from Google Scholar bib file failed.");
    } else {
        Collection<BibEntry> entries = result.getDatabase().getEntries();
        if (entries.size() != 1) {
            LOGGER.debug(entries.size() + " entries found! (" + link + ")");
            throw new FetcherException("Parsing entries from Google Scholar bib file failed.");
        } else {
            BibEntry entry = entries.iterator().next();
            return entry;
        }
    }
}
Also used : ParserResult(org.jabref.logic.importer.ParserResult) BibEntry(org.jabref.model.entry.BibEntry) FetcherException(org.jabref.logic.importer.FetcherException) BibtexParser(org.jabref.logic.importer.fileformat.BibtexParser) StringReader(java.io.StringReader) URLDownload(org.jabref.logic.net.URLDownload)

Aggregations

FetcherException (org.jabref.logic.importer.FetcherException)18 IOException (java.io.IOException)12 BibEntry (org.jabref.model.entry.BibEntry)12 URISyntaxException (java.net.URISyntaxException)7 URL (java.net.URL)6 ArrayList (java.util.ArrayList)6 ParserResult (org.jabref.logic.importer.ParserResult)5 DOI (org.jabref.model.entry.identifier.DOI)5 URIBuilder (org.apache.http.client.utils.URIBuilder)4 URLDownload (org.jabref.logic.net.URLDownload)4 StringReader (java.io.StringReader)3 MalformedURLException (java.net.MalformedURLException)3 Optional (java.util.Optional)3 ParseException (org.jabref.logic.importer.ParseException)3 BufferedReader (java.io.BufferedReader)2 HttpURLConnection (java.net.HttpURLConnection)2 URLConnection (java.net.URLConnection)2 List (java.util.List)2 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)2