Search in sources :

Example 1 with FileFinder

use of org.jabref.logic.util.io.FileFinder in project jabref by JabRef.

the class LinkedFilesEditorViewModel method findAssociatedNotLinkedFiles.

/**
     * Find files that are probably associated  to the given entry but not yet linked.
     */
private List<LinkedFileViewModel> findAssociatedNotLinkedFiles(BibEntry entry) {
    final List<Path> dirs = databaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences());
    final List<String> extensions = ExternalFileTypes.getInstance().getExternalFileTypeSelection().stream().map(ExternalFileType::getExtension).collect(Collectors.toList());
    // Run the search operation:
    FileFinder fileFinder = FileFinders.constructFromConfiguration(Globals.prefs.getAutoLinkPreferences());
    List<Path> newFiles = fileFinder.findAssociatedFiles(entry, dirs, extensions);
    List<LinkedFileViewModel> result = new ArrayList<>();
    for (Path newFile : newFiles) {
        boolean alreadyLinked = files.get().stream().map(file -> file.findIn(dirs)).anyMatch(file -> file.isPresent() && file.get().equals(newFile));
        if (!alreadyLinked) {
            LinkedFileViewModel newLinkedFile = new LinkedFileViewModel(fromFile(newFile, dirs));
            newLinkedFile.markAsAutomaticallyFound();
            result.add(newLinkedFile);
        }
    }
    return result;
}
Also used : Path(java.nio.file.Path) URL(java.net.URL) BindingsHelper(org.jabref.gui.util.BindingsHelper) FXCollections(javafx.collections.FXCollections) DialogService(org.jabref.gui.DialogService) SimpleListProperty(javafx.beans.property.SimpleListProperty) JabRefPreferences(org.jabref.preferences.JabRefPreferences) FileDownloadTask(org.jabref.gui.externalfiles.FileDownloadTask) LinkedFile(org.jabref.model.entry.LinkedFile) ArrayList(java.util.ArrayList) URLDownload(org.jabref.logic.net.URLDownload) FulltextFetchers(org.jabref.logic.importer.FulltextFetchers) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) Localization(org.jabref.logic.l10n.Localization) FileFieldWriter(org.jabref.model.entry.FileFieldWriter) ListProperty(javafx.beans.property.ListProperty) BibDatabaseContext(org.jabref.model.database.BibDatabaseContext) Path(java.nio.file.Path) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) FileFinders(org.jabref.logic.util.io.FileFinders) FileUtil(org.jabref.logic.util.io.FileUtil) FileDialogConfiguration(org.jabref.gui.util.FileDialogConfiguration) MalformedURLException(java.net.MalformedURLException) BibEntry(org.jabref.model.entry.BibEntry) DownloadExternalFile(org.jabref.gui.externalfiles.DownloadExternalFile) BackgroundTask(org.jabref.gui.util.BackgroundTask) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Globals(org.jabref.Globals) FileFinder(org.jabref.logic.util.io.FileFinder) FileHelper(org.jabref.model.util.FileHelper) TaskExecutor(org.jabref.gui.util.TaskExecutor) FileFieldParser(org.jabref.model.entry.FileFieldParser) List(java.util.List) BooleanProperty(javafx.beans.property.BooleanProperty) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) Paths(java.nio.file.Paths) OS(org.jabref.logic.util.OS) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) ObservableList(javafx.collections.ObservableList) ExternalFileTypes(org.jabref.gui.externalfiletype.ExternalFileTypes) LogFactory(org.apache.commons.logging.LogFactory) ArrayList(java.util.ArrayList) FileFinder(org.jabref.logic.util.io.FileFinder)

Example 2 with FileFinder

use of org.jabref.logic.util.io.FileFinder in project jabref by JabRef.

the class AutoSetLinks method autoSetLinks.

/**
     * Automatically add links for this set of entries, based on the globally stored list of external file types. The
     * entries are modified, and corresponding UndoEdit elements added to the NamedCompound given as argument.
     * Furthermore, all entries which are modified are added to the Set of entries given as an argument.
     * <p>
     * The entries' bibtex keys must have been set - entries lacking key are ignored. The operation is done in a new
     * thread, which is returned for the caller to wait for if needed.
     *
     * @param entries          A collection of BibEntry objects to find links for.
     * @param ce               A NamedCompound to add UndoEdit elements to.
     * @param changedEntries   MODIFIED, optional. A Set of BibEntry objects to which all modified entries is added.
     *                         This is used for status output and debugging
     * @param singleTableModel UGLY HACK. The table model to insert links into. Already existing links are not
     *                         duplicated or removed. This parameter has to be null if entries.count() != 1. The hack has been
     *                         introduced as a bibtexentry does not (yet) support the function getListTableModel() and the
     *                         FileListEntryEditor editor holds an instance of that table model and does not reconstruct it after the
     *                         search has succeeded.
     * @param databaseContext  The database providing the relevant file directory, if any.
     * @param callback         An ActionListener that is notified (on the event dispatch thread) when the search is finished.
     *                         The ActionEvent has id=0 if no new links were added, and id=1 if one or more links were added. This
     *                         parameter can be null, which means that no callback will be notified.
     * @param diag             An instantiated modal JDialog which will be used to display the progress of the automatically setting. This
     *                         parameter can be null, which means that no progress update will be shown.
     * @return the thread performing the automatically setting
     */
public static Runnable autoSetLinks(final List<BibEntry> entries, final NamedCompound ce, final Set<BibEntry> changedEntries, final FileListTableModel singleTableModel, final BibDatabaseContext databaseContext, final ActionListener callback, final JDialog diag) {
    final Collection<ExternalFileType> types = ExternalFileTypes.getInstance().getExternalFileTypeSelection();
    if (diag != null) {
        final JProgressBar prog = new JProgressBar(SwingConstants.HORIZONTAL, 0, types.size() - 1);
        final JLabel label = new JLabel(Localization.lang("Searching for files"));
        prog.setIndeterminate(true);
        prog.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        diag.setTitle(Localization.lang("Automatically setting file links"));
        diag.getContentPane().add(prog, BorderLayout.CENTER);
        diag.getContentPane().add(label, BorderLayout.SOUTH);
        diag.pack();
        diag.setLocationRelativeTo(diag.getParent());
    }
    Runnable r = new Runnable() {

        @Override
        public void run() {
            // determine directories to search in
            final List<Path> dirs = databaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences());
            // determine extensions
            final List<String> extensions = types.stream().map(ExternalFileType::getExtension).collect(Collectors.toList());
            // Run the search operation:
            FileFinder fileFinder = FileFinders.constructFromConfiguration(Globals.prefs.getAutoLinkPreferences());
            Map<BibEntry, List<Path>> result = fileFinder.findAssociatedFiles(entries, dirs, extensions);
            boolean foundAny = false;
            // Iterate over the entries:
            for (Entry<BibEntry, List<Path>> entryFilePair : result.entrySet()) {
                FileListTableModel tableModel;
                Optional<String> oldVal = entryFilePair.getKey().getField(FieldName.FILE);
                if (singleTableModel == null) {
                    tableModel = new FileListTableModel();
                    oldVal.ifPresent(tableModel::setContent);
                } else {
                    assert entries.size() == 1;
                    tableModel = singleTableModel;
                }
                List<Path> files = entryFilePair.getValue();
                for (Path f : files) {
                    f = FileUtil.shortenFileName(f, dirs);
                    boolean alreadyHas = false;
                    //System.out.println("File: "+f.getPath());
                    for (int j = 0; j < tableModel.getRowCount(); j++) {
                        FileListEntry existingEntry = tableModel.getEntry(j);
                        //System.out.println("Comp: "+existingEntry.getLink());
                        if (Paths.get(existingEntry.getLink()).equals(f)) {
                            alreadyHas = true;
                            foundAny = true;
                            break;
                        }
                    }
                    if (!alreadyHas) {
                        foundAny = true;
                        Optional<ExternalFileType> type;
                        Optional<String> extension = FileHelper.getFileExtension(f);
                        if (extension.isPresent()) {
                            type = ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension.get());
                        } else {
                            type = Optional.of(new UnknownExternalFileType(""));
                        }
                        FileListEntry flEntry = new FileListEntry(f.getFileName().toString(), f.toString(), type);
                        tableModel.addEntry(tableModel.getRowCount(), flEntry);
                        String newVal = tableModel.getStringRepresentation();
                        if (newVal.isEmpty()) {
                            newVal = null;
                        }
                        if (ce != null) {
                            // store undo information
                            UndoableFieldChange change = new UndoableFieldChange(entryFilePair.getKey(), FieldName.FILE, oldVal.orElse(null), newVal);
                            ce.addEdit(change);
                        }
                        // hack: if table model is given, do NOT modify entry
                        if (singleTableModel == null) {
                            entryFilePair.getKey().setField(FieldName.FILE, newVal);
                        }
                        if (changedEntries != null) {
                            changedEntries.add(entryFilePair.getKey());
                        }
                    }
                }
            }
            // handle callbacks and dialog
            // FIXME: The ID signals if action was successful :/
            final int id = foundAny ? 1 : 0;
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    if (diag != null) {
                        diag.dispose();
                    }
                    if (callback != null) {
                        callback.actionPerformed(new ActionEvent(this, id, ""));
                    }
                }
            });
        }
    };
    SwingUtilities.invokeLater(() -> {
        // show dialog which will be hidden when the task is done
        if (diag != null) {
            diag.setVisible(true);
        }
    });
    return r;
}
Also used : ActionEvent(java.awt.event.ActionEvent) JProgressBar(javax.swing.JProgressBar) FileListEntry(org.jabref.gui.filelist.FileListEntry) FileFinder(org.jabref.logic.util.io.FileFinder) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) UndoableFieldChange(org.jabref.gui.undo.UndoableFieldChange) List(java.util.List) Path(java.nio.file.Path) BibEntry(org.jabref.model.entry.BibEntry) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) JLabel(javax.swing.JLabel)

Aggregations

Path (java.nio.file.Path)2 List (java.util.List)2 ExternalFileType (org.jabref.gui.externalfiletype.ExternalFileType)2 UnknownExternalFileType (org.jabref.gui.externalfiletype.UnknownExternalFileType)2 FileFinder (org.jabref.logic.util.io.FileFinder)2 BibEntry (org.jabref.model.entry.BibEntry)2 ActionEvent (java.awt.event.ActionEvent)1 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Paths (java.nio.file.Paths)1 ArrayList (java.util.ArrayList)1 Optional (java.util.Optional)1 Collectors (java.util.stream.Collectors)1 BooleanProperty (javafx.beans.property.BooleanProperty)1 ListProperty (javafx.beans.property.ListProperty)1 SimpleBooleanProperty (javafx.beans.property.SimpleBooleanProperty)1 SimpleListProperty (javafx.beans.property.SimpleListProperty)1 FXCollections (javafx.collections.FXCollections)1 ObservableList (javafx.collections.ObservableList)1