Search in sources :

Example 91 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class XMPUtil method readXMP.

/**
     * Try to read the given BibTexEntry from the XMP-stream of the given
     * inputstream containing a PDF-file.
     *
     * @param inputStream The inputstream to read from.
     * @return list of BibEntries retrieved from the stream. May be empty, but never null
     * @throws IOException Throws an IOException if the file cannot be read, so the user than remove a lock or cancel
     *                     the operation.
     */
public static List<BibEntry> readXMP(InputStream inputStream, XMPPreferences xmpPreferences) throws IOException {
    List<BibEntry> result = new LinkedList<>();
    try (PDDocument document = loadWithAutomaticDecryption(inputStream)) {
        Optional<XMPMetadata> meta = XMPUtil.getXMPMetadata(document);
        if (meta.isPresent()) {
            List<XMPSchema> schemas = meta.get().getSchemasByNamespaceURI(XMPSchemaBibtex.NAMESPACE);
            for (XMPSchema schema : schemas) {
                XMPSchemaBibtex bib = (XMPSchemaBibtex) schema;
                BibEntry entry = bib.getBibtexEntry();
                if (entry.getType() == null) {
                    entry.setType(BibEntry.DEFAULT_TYPE);
                }
                result.add(entry);
            }
            // If we did not find anything have a look if a Dublin Core exists
            if (result.isEmpty()) {
                schemas = meta.get().getSchemasByNamespaceURI(XMPSchemaDublinCore.NAMESPACE);
                for (XMPSchema schema : schemas) {
                    XMPSchemaDublinCore dc = (XMPSchemaDublinCore) schema;
                    Optional<BibEntry> entry = XMPUtil.getBibtexEntryFromDublinCore(dc, xmpPreferences);
                    if (entry.isPresent()) {
                        if (entry.get().getType() == null) {
                            entry.get().setType(BibEntry.DEFAULT_TYPE);
                        }
                        result.add(entry.get());
                    }
                }
            }
        }
        if (result.isEmpty()) {
            // If we did not find any XMP metadata, search for non XMP metadata
            PDDocumentInformation documentInformation = document.getDocumentInformation();
            Optional<BibEntry> entry = XMPUtil.getBibtexEntryFromDocumentInformation(documentInformation);
            entry.ifPresent(result::add);
        }
    }
    // return empty list, if no metadata was found
    if (result.isEmpty()) {
        return Collections.emptyList();
    }
    return result;
}
Also used : XMPSchemaDublinCore(org.apache.jempbox.xmp.XMPSchemaDublinCore) BibEntry(org.jabref.model.entry.BibEntry) TypedBibEntry(org.jabref.logic.TypedBibEntry) XMPSchema(org.apache.jempbox.xmp.XMPSchema) LinkedList(java.util.LinkedList) XMPMetadata(org.apache.jempbox.xmp.XMPMetadata) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) PDDocumentInformation(org.apache.pdfbox.pdmodel.PDDocumentInformation)

Example 92 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class XMPSchemaBibtex method getBibtexEntry.

public BibEntry getBibtexEntry() {
    String type = getTextProperty(BibEntry.TYPE_HEADER);
    BibEntry e = new BibEntry(type);
    // Get Text Properties
    Map<String, String> text = XMPSchemaBibtex.getAllProperties(this, "bibtex");
    text.remove(BibEntry.TYPE_HEADER);
    e.setField(text);
    return e;
}
Also used : BibEntry(org.jabref.model.entry.BibEntry)

Example 93 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class CiteKeyBasedFileFinder method findAssociatedFiles.

@Override
public Map<BibEntry, List<Path>> findAssociatedFiles(List<BibEntry> entries, List<Path> directories, List<String> extensions) {
    Objects.requireNonNull(directories);
    Objects.requireNonNull(entries);
    Map<BibEntry, List<Path>> result = new HashMap<>();
    // First scan directories
    Set<Path> filesWithExtension = findFilesByExtension(directories, extensions);
    // Initialize Result-Set
    for (BibEntry entry : entries) {
        result.put(entry, new ArrayList<>());
    }
    // Now look for keys
    nextFile: for (Path file : filesWithExtension) {
        String name = file.getFileName().toString();
        int dot = name.lastIndexOf('.');
        // First, look for exact matches:
        for (BibEntry entry : entries) {
            Optional<String> citeKey = entry.getCiteKeyOptional();
            if ((citeKey.isPresent()) && !citeKey.get().isEmpty() && (dot > 0) && name.substring(0, dot).equals(citeKey.get())) {
                result.get(entry).add(file);
                continue nextFile;
            }
        }
        // matches are allowed, try to find one:
        if (!exactKeyOnly) {
            for (BibEntry entry : entries) {
                Optional<String> citeKey = entry.getCiteKeyOptional();
                if ((citeKey.isPresent()) && !citeKey.get().isEmpty() && name.startsWith(citeKey.get())) {
                    result.get(entry).add(file);
                    continue nextFile;
                }
            }
        }
    }
    return result;
}
Also used : Path(java.nio.file.Path) BibEntry(org.jabref.model.entry.BibEntry) Optional(java.util.Optional) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List)

Example 94 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class RegExpBasedFileFinder method findFile.

/**
     * The actual work-horse. Will find absolute filepaths starting from the
     * given directory using the given regular expression string for search.
     */
private List<Path> findFile(BibEntry entry, Path directory, String file, String extensionRegExp) {
    List<Path> res = new ArrayList<>();
    String fileName = file;
    Path actualDirectory;
    if (fileName.startsWith("/")) {
        actualDirectory = Paths.get(".");
        fileName = fileName.substring(1);
    } else {
        actualDirectory = directory;
    }
    // Escape handling...
    Matcher m = ESCAPE_PATTERN.matcher(fileName);
    StringBuffer s = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(s, m.group(1) + '/' + m.group(2));
    }
    m.appendTail(s);
    fileName = s.toString();
    String[] fileParts = fileName.split("/");
    if (fileParts.length == 0) {
        return res;
    }
    for (int i = 0; i < (fileParts.length - 1); i++) {
        String dirToProcess = fileParts[i];
        dirToProcess = expandBrackets(dirToProcess, entry, null, keywordDelimiter);
        if (dirToProcess.matches("^.:$")) {
            // Windows Drive Letter
            actualDirectory = Paths.get(dirToProcess + '/');
            continue;
        }
        if (".".equals(dirToProcess)) {
            // Stay in current directory
            continue;
        }
        if ("..".equals(dirToProcess)) {
            actualDirectory = actualDirectory.getParent();
            continue;
        }
        if ("*".equals(dirToProcess)) {
            // Do for all direct subdirs
            File[] subDirs = actualDirectory.toFile().listFiles();
            if (subDirs != null) {
                String restOfFileString = StringUtil.join(fileParts, "/", i + 1, fileParts.length);
                for (File subDir : subDirs) {
                    if (subDir.isDirectory()) {
                        res.addAll(findFile(entry, subDir.toPath(), restOfFileString, extensionRegExp));
                    }
                }
            }
        }
        // Do for all direct and indirect subdirs
        if ("**".equals(dirToProcess)) {
            String restOfFileString = StringUtil.join(fileParts, "/", i + 1, fileParts.length);
            try {
                Path finalActualDirectory = actualDirectory;
                Files.walk(actualDirectory).forEach(subElement -> {
                    if (!finalActualDirectory.equals(subElement) && Files.isDirectory(subElement)) {
                        res.addAll(findFile(entry, subElement, restOfFileString, extensionRegExp));
                    }
                });
            } catch (IOException e) {
                LOGGER.debug(e);
            }
        }
    // End process directory information
    }
    // Last step: check if the given file can be found in this directory
    String filePart = fileParts[fileParts.length - 1].replace("[extension]", EXT_MARKER);
    String filenameToLookFor = expandBrackets(filePart, entry, null, keywordDelimiter).replaceAll(EXT_MARKER, extensionRegExp);
    final Pattern toMatch = Pattern.compile('^' + filenameToLookFor.replaceAll("\\\\\\\\", "\\\\") + '$', Pattern.CASE_INSENSITIVE);
    try {
        List<Path> matches = Files.find(actualDirectory, Integer.MAX_VALUE, (path, attributes) -> toMatch.matcher(path.getFileName().toString()).matches()).collect(Collectors.toList());
        res.addAll(matches);
    } catch (IOException e) {
        LOGGER.debug(e);
    }
    return res;
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) Files(java.nio.file.Files) StringUtil(org.jabref.model.strings.StringUtil) BibDatabase(org.jabref.model.database.BibDatabase) BibEntry(org.jabref.model.entry.BibEntry) IOException(java.io.IOException) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) File(java.io.File) ArrayList(java.util.ArrayList) List(java.util.List) Matcher(java.util.regex.Matcher) BibtexKeyPatternUtil(org.jabref.logic.bibtexkeypattern.BibtexKeyPatternUtil) Paths(java.nio.file.Paths) Map(java.util.Map) Log(org.apache.commons.logging.Log) Pattern(java.util.regex.Pattern) LogFactory(org.apache.commons.logging.LogFactory) Path(java.nio.file.Path) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) IOException(java.io.IOException) File(java.io.File)

Example 95 with BibEntry

use of org.jabref.model.entry.BibEntry in project jabref by JabRef.

the class PdfImporter method createNewEntry.

private Optional<BibEntry> createNewEntry() {
    // Find out what type is desired
    EntryTypeDialog etd = new EntryTypeDialog(frame);
    // We want to center the dialog, to make it look nicer.
    etd.setLocationRelativeTo(frame);
    etd.setVisible(true);
    EntryType type = etd.getChoice();
    if (type != null) {
        // Only if the dialog was not canceled.
        final BibEntry bibEntry = new BibEntry(type.getName());
        try {
            panel.getDatabase().insertEntry(bibEntry);
            // Set owner/timestamp if options are enabled:
            List<BibEntry> list = new ArrayList<>();
            list.add(bibEntry);
            UpdateField.setAutomaticFields(list, true, true, Globals.prefs.getUpdateFieldPreferences());
            // Create an UndoableInsertEntry object.
            panel.getUndoManager().addEdit(new UndoableInsertEntry(panel.getDatabase(), bibEntry, panel));
            panel.output(Localization.lang("Added new") + " '" + type.getName().toLowerCase(Locale.ROOT) + "' " + Localization.lang("entry") + ".");
            // and adjustment of the splitter.
            if (panel.getMode() != BasePanelMode.SHOWING_EDITOR) {
                panel.setMode(BasePanelMode.WILL_SHOW_EDITOR);
            }
            SwingUtilities.invokeLater(() -> panel.showEntry(bibEntry));
            // The database just changed.
            panel.markBaseChanged();
            return Optional.of(bibEntry);
        } catch (KeyCollisionException ex) {
            LOGGER.info("Key collision occurred", ex);
        }
    }
    return Optional.empty();
}
Also used : KeyCollisionException(org.jabref.model.database.KeyCollisionException) BibEntry(org.jabref.model.entry.BibEntry) EntryType(org.jabref.model.entry.EntryType) EntryTypeDialog(org.jabref.gui.EntryTypeDialog) ArrayList(java.util.ArrayList) UndoableInsertEntry(org.jabref.gui.undo.UndoableInsertEntry)

Aggregations

BibEntry (org.jabref.model.entry.BibEntry)716 Test (org.junit.Test)466 ParserResult (org.jabref.logic.importer.ParserResult)131 StringReader (java.io.StringReader)107 ArrayList (java.util.ArrayList)75 BibDatabase (org.jabref.model.database.BibDatabase)63 Path (java.nio.file.Path)52 IOException (java.io.IOException)43 HashMap (java.util.HashMap)37 Before (org.junit.Before)36 NamedCompound (org.jabref.gui.undo.NamedCompound)30 BibtexParser (org.jabref.logic.importer.fileformat.BibtexParser)28 BibtexString (org.jabref.model.entry.BibtexString)28 List (java.util.List)23 File (java.io.File)21 StringWriter (java.io.StringWriter)19 Optional (java.util.Optional)19 BasePanel (org.jabref.gui.BasePanel)19 FieldChange (org.jabref.model.FieldChange)18 InputStream (java.io.InputStream)16