Search in sources :

Example 6 with ParserResult

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

the class ArgumentProcessor method fetch.

/**
     * Run an entry fetcher from the command line.
     * <p>
     * Note that this only works headlessly if the EntryFetcher does not show any GUI.
     *
     * @param fetchCommand A string containing both the fetcher to use (id of EntryFetcherExtension minus Fetcher) and
     *                     the search query, separated by a :
     * @return A parser result containing the entries fetched or null if an error occurred.
     */
private Optional<ParserResult> fetch(String fetchCommand) {
    if ((fetchCommand == null) || !fetchCommand.contains(":") || (fetchCommand.split(":").length != 2)) {
        System.out.println(Localization.lang("Expected syntax for --fetch='<name of fetcher>:<query>'"));
        System.out.println(Localization.lang("The following fetchers are available:"));
        return Optional.empty();
    }
    String[] split = fetchCommand.split(":");
    String engine = split[0];
    EntryFetchers fetchers = new EntryFetchers(Globals.journalAbbreviationLoader);
    EntryFetcher fetcher = null;
    for (EntryFetcher e : fetchers.getEntryFetchers()) {
        if (engine.equalsIgnoreCase(e.getClass().getSimpleName().replace("Fetcher", ""))) {
            fetcher = e;
        }
    }
    if (fetcher == null) {
        System.out.println(Localization.lang("Could not find fetcher '%0'", engine));
        System.out.println(Localization.lang("The following fetchers are available:"));
        for (EntryFetcher e : fetchers.getEntryFetchers()) {
            System.out.println("  " + e.getClass().getSimpleName().replace("Fetcher", "").toLowerCase(Locale.ENGLISH));
        }
        return Optional.empty();
    }
    String query = split[1];
    System.out.println(Localization.lang("Running query '%0' with fetcher '%1'.", query, engine) + " " + Localization.lang("Please wait..."));
    Collection<BibEntry> result = new ImportInspectionCommandLine().query(query, fetcher);
    if (result.isEmpty()) {
        System.out.println(Localization.lang("Query '%0' with fetcher '%1' did not return any results.", query, engine));
        return Optional.empty();
    }
    return Optional.of(new ParserResult(result));
}
Also used : EntryFetcher(org.jabref.gui.importer.fetcher.EntryFetcher) BibEntry(org.jabref.model.entry.BibEntry) ParserResult(org.jabref.logic.importer.ParserResult) EntryFetchers(org.jabref.gui.importer.fetcher.EntryFetchers)

Example 7 with ParserResult

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

the class ArgumentProcessor method importFile.

private static Optional<ParserResult> importFile(String argument) {
    String[] data = argument.split(",");
    String address = data[0];
    Path file;
    if (address.startsWith("http://") || address.startsWith("https://") || address.startsWith("ftp://")) {
        // Download web resource to temporary file
        try {
            file = new URLDownload(address).toTemporaryFile();
        } catch (IOException e) {
            System.err.println(Localization.lang("Problem downloading from %1", address) + e.getLocalizedMessage());
            return Optional.empty();
        }
    } else {
        if (OS.WINDOWS) {
            file = Paths.get(address);
        } else {
            file = Paths.get(address.replace("~", System.getProperty("user.home")));
        }
    }
    String importFormat;
    if (data.length > 1) {
        importFormat = data[1];
    } else {
        importFormat = "*";
    }
    Optional<ParserResult> importResult = importFile(file, importFormat);
    importResult.ifPresent(result -> {
        OutputPrinter printer = new SystemOutputPrinter();
        if (result.hasWarnings()) {
            printer.showMessage(result.getErrorMessage());
        }
    });
    return importResult;
}
Also used : Path(java.nio.file.Path) ParserResult(org.jabref.logic.importer.ParserResult) IOException(java.io.IOException) URLDownload(org.jabref.logic.net.URLDownload) OutputPrinter(org.jabref.logic.importer.OutputPrinter)

Example 8 with ParserResult

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

the class ArgumentProcessor method automaticallySetFileLinks.

private void automaticallySetFileLinks(List<ParserResult> loaded) {
    for (ParserResult parserResult : loaded) {
        BibDatabase database = parserResult.getDatabase();
        LOGGER.info(Localization.lang("Automatically setting file links"));
        AutoSetLinks.autoSetLinks(database.getEntries(), parserResult.getDatabaseContext());
    }
}
Also used : ParserResult(org.jabref.logic.importer.ParserResult) BibDatabase(org.jabref.model.database.BibDatabase)

Example 9 with ParserResult

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

the class OpenDatabaseAction method openTheFile.

/**
     * @param file the file, may be null or not existing
     */
private void openTheFile(Path file, boolean raisePanel) {
    Objects.requireNonNull(file);
    if (Files.exists(file)) {
        Path fileToLoad = file.toAbsolutePath();
        frame.output(Localization.lang("Opening") + ": '" + file + "'");
        String fileName = file.getFileName().toString();
        Globals.prefs.put(JabRefPreferences.WORKING_DIRECTORY, fileToLoad.getParent().toString());
        if (FileBasedLock.hasLockFile(file)) {
            Optional<FileTime> modificationTime = FileBasedLock.getLockFileTimeStamp(file);
            if ((modificationTime.isPresent()) && ((System.currentTimeMillis() - modificationTime.get().toMillis()) > FileBasedLock.LOCKFILE_CRITICAL_AGE)) {
                // The lock file is fairly old, so we can offer to "steal" the file:
                int answer = JOptionPane.showConfirmDialog(null, "<html>" + Localization.lang("Error opening file") + " '" + fileName + "'. " + Localization.lang("File is locked by another JabRef instance.") + "<p>" + Localization.lang("Do you want to override the file lock?"), Localization.lang("File locked"), JOptionPane.YES_NO_OPTION);
                if (answer == JOptionPane.YES_OPTION) {
                    FileBasedLock.deleteLockFile(file);
                } else {
                    return;
                }
            } else if (!FileBasedLock.waitForFileLock(file)) {
                JOptionPane.showMessageDialog(null, Localization.lang("Error opening file") + " '" + fileName + "'. " + Localization.lang("File is locked by another JabRef instance."), Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        if (BackupManager.checkForBackupFile(fileToLoad)) {
            BackupUIManager.showRestoreBackupDialog(frame, fileToLoad);
        }
        ParserResult result;
        result = OpenDatabase.loadDatabase(fileToLoad.toString(), Globals.prefs.getImportFormatPreferences());
        if (result.getDatabase().isShared()) {
            try {
                new SharedDatabaseUIManager(frame).openSharedDatabaseFromParserResult(result);
            } catch (SQLException | DatabaseNotSupportedException | InvalidDBMSConnectionPropertiesException | NotASharedDatabaseException e) {
                // do not open the original file
                result.getDatabaseContext().clearDatabaseFile();
                result.getDatabase().clearSharedDatabaseID();
                LOGGER.error("Connection error", e);
                JOptionPane.showMessageDialog(frame, e.getMessage() + "\n\n" + Localization.lang("A local copy will be opened."), Localization.lang("Connection error"), JOptionPane.WARNING_MESSAGE);
            }
        }
        BasePanel panel = addNewDatabase(result, file, raisePanel);
        // After adding the database, go through our list and see if
        // any post open actions need to be done. For instance, checking
        // if we found new entry types that can be imported, or checking
        // if the database contents should be modified due to new features
        // in this version of JabRef:
        final ParserResult finalReferenceToResult = result;
        SwingUtilities.invokeLater(() -> OpenDatabaseAction.performPostOpenActions(panel, finalReferenceToResult));
    }
}
Also used : Path(java.nio.file.Path) SharedDatabaseUIManager(org.jabref.gui.shared.SharedDatabaseUIManager) NotASharedDatabaseException(org.jabref.shared.exception.NotASharedDatabaseException) BasePanel(org.jabref.gui.BasePanel) SQLException(java.sql.SQLException) InvalidDBMSConnectionPropertiesException(org.jabref.shared.exception.InvalidDBMSConnectionPropertiesException) FileTime(java.nio.file.attribute.FileTime) ParserResult(org.jabref.logic.importer.ParserResult) DatabaseNotSupportedException(org.jabref.shared.exception.DatabaseNotSupportedException)

Example 10 with ParserResult

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

the class AppendDatabaseAction method openIt.

private void openIt(boolean importEntries, boolean importStrings, boolean importGroups, boolean importSelectorWords) {
    if (filesToOpen.isEmpty()) {
        return;
    }
    for (Path file : filesToOpen) {
        try {
            Globals.prefs.put(JabRefPreferences.WORKING_DIRECTORY, file.getParent().toString());
            // Should this be done _after_ we know it was successfully opened?
            ParserResult parserResult = OpenDatabase.loadDatabase(file.toFile(), Globals.prefs.getImportFormatPreferences());
            AppendDatabaseAction.mergeFromBibtex(panel, parserResult, importEntries, importStrings, importGroups, importSelectorWords);
            panel.output(Localization.lang("Imported from library") + " '" + file + "'");
        } catch (IOException | KeyCollisionException ex) {
            LOGGER.warn("Could not open database", ex);
            JOptionPane.showMessageDialog(panel, ex.getMessage(), Localization.lang("Open library"), JOptionPane.ERROR_MESSAGE);
        }
    }
}
Also used : Path(java.nio.file.Path) KeyCollisionException(org.jabref.model.database.KeyCollisionException) ParserResult(org.jabref.logic.importer.ParserResult) IOException(java.io.IOException)

Aggregations

ParserResult (org.jabref.logic.importer.ParserResult)196 Test (org.junit.Test)145 BibEntry (org.jabref.model.entry.BibEntry)131 StringReader (java.io.StringReader)130 BibtexParser (org.jabref.logic.importer.fileformat.BibtexParser)38 BibtexString (org.jabref.model.entry.BibtexString)30 ArrayList (java.util.ArrayList)23 BibDatabase (org.jabref.model.database.BibDatabase)20 Path (java.nio.file.Path)14 IOException (java.io.IOException)12 StringWriter (java.io.StringWriter)12 File (java.io.File)10 InputStreamReader (java.io.InputStreamReader)10 HashMap (java.util.HashMap)10 BibDatabaseContext (org.jabref.model.database.BibDatabaseContext)9 InputStream (java.io.InputStream)8 Defaults (org.jabref.model.Defaults)8 Charset (java.nio.charset.Charset)6 Scanner (java.util.Scanner)5 BufferedReader (java.io.BufferedReader)4