diff --git a/.github/workflows/sbom-pr.yml b/.github/workflows/sbom-pr.yml index 25484d23e84..8b13a5cbd38 100644 --- a/.github/workflows/sbom-pr.yml +++ b/.github/workflows/sbom-pr.yml @@ -58,7 +58,7 @@ jobs: Generated via Gradle task `cyclonedxBom` using the org.cyclonedx.bom plugin configured in the build. branch: chore/update-sbom delete-branch: true - labels: "dev: dependencies"" + labels: "dev: dependencies" add-paths: | bom.json bom.xml diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e06e5fd586..e3404275b0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -133,6 +133,8 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv - We removed unnecessary spacing and margin in the AutomaticFieldEditor. [#13792](https://github.com/JabRef/jabref/pull/13792) - We fixed an issue where global search auto-completion only worked after switching tabs. [#11428](https://github.com/JabRef/jabref/issues/11428) - We fixed an issue where hierarchical keywords would only show the parent keyword in the entry editor. [#11390](https://github.com/JabRef/jabref/issues/11390) +- We fixed an issue where some file choosers regarding LaTeX-aux files did not open in the directory of the last selected file. [#13861](https://github.com/JabRef/jabref/pull/13861) +- We fixed an issue where the LaTeX file directory was not stored correctly in combination with the usage of groups from aux files. [#8344](https://github.com/JabRef/jabref/issues/8344) ### Removed diff --git a/jabgui/src/main/java/org/jabref/gui/auximport/FromAuxDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/auximport/FromAuxDialogViewModel.java index 27bf4831bcf..412161608b1 100644 --- a/jabgui/src/main/java/org/jabref/gui/auximport/FromAuxDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/auximport/FromAuxDialogViewModel.java @@ -82,7 +82,7 @@ public void browse() { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(StandardFileType.AUX) .withDefaultExtension(StandardFileType.AUX) - .withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory()).build(); + .withInitialDirectory(auxFileProperty.get() == null ? preferences.getFilePreferences().getWorkingDirectory().toString() : auxFileProperty.get()).build(); dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(file -> auxFileProperty.setValue(file.toAbsolutePath().toString())); } diff --git a/jabgui/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java b/jabgui/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java index b750e3da8d9..04226effec1 100644 --- a/jabgui/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java @@ -132,7 +132,7 @@ public void setLatexDirectory() { .withInitialDirectory(directory.get()).build(); dialogService.showDirectorySelectionDialog(directoryDialogConfiguration).ifPresent(selectedDirectory -> - currentDatabaseContext.getMetaData().setLatexFileDirectory(preferences.getFilePreferences().getUserAndHost(), selectedDirectory.toAbsolutePath())); + currentDatabaseContext.getMetaData().setLatexFileDirectory(preferences.getFilePreferences().getUserAndHost(), selectedDirectory.toAbsolutePath().toString())); checkAndUpdateDirectory(); } diff --git a/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java b/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java index 282de43bb15..72a5a0ea91c 100644 --- a/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java @@ -231,8 +231,8 @@ private void setupValidation() { return false; } return FileUtil.getFileExtension(input) - .map("aux"::equalsIgnoreCase) - .orElse(false); + .map("aux"::equalsIgnoreCase) + .orElse(false); } }, ValidationMessage.error(Localization.lang("Please provide a valid aux file."))); @@ -373,7 +373,9 @@ public AbstractGroup resultConverter(ButtonType button) { Path.of(texGroupFilePathProperty.getValue().trim()), new DefaultAuxParser(new BibDatabase()), fileUpdateMonitor, - currentDatabase.getMetaData()); + currentDatabase.getMetaData(), + preferences.getFilePreferences().getUserAndHost() + ); } if (resultingGroup != null) { @@ -485,9 +487,10 @@ public void texGroupBrowse() { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(StandardFileType.AUX) .withDefaultExtension(StandardFileType.AUX) - .withInitialDirectory(currentDatabase.getMetaData() - .getLatexFileDirectory(preferences.getFilePreferences().getUserAndHost()) - .orElse(FileUtil.getInitialDirectory(currentDatabase, preferences.getFilePreferences().getWorkingDirectory()))).build(); + .withInitialDirectory(texGroupFilePathProperty.getValue().isBlank() ? + currentDatabase.getMetaData() + .getLatexFileDirectory(preferences.getFilePreferences().getUserAndHost()) + .orElse(FileUtil.getInitialDirectory(currentDatabase, preferences.getFilePreferences().getWorkingDirectory())).toString() : texGroupFilePathProperty.get()).build(); dialogService.showFileOpenDialog(fileDialogConfiguration) .ifPresent(file -> texGroupFilePathProperty.setValue( FileUtil.relativize(file.toAbsolutePath(), getFileDirectoriesAsPaths()).toString() diff --git a/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java b/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java index 6df51a1f897..b87b56c4f86 100644 --- a/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java +++ b/jabgui/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java @@ -113,7 +113,7 @@ public void storeSettings() { if (latexFileDirectory.isEmpty()) { newMetaData.clearLatexFileDirectory(preferences.getFilePreferences().getUserAndHost()); } else if (laTexFileDirectoryStatus().isValid()) { - newMetaData.setLatexFileDirectory(preferences.getFilePreferences().getUserAndHost(), Path.of(latexFileDirectory)); + newMetaData.setLatexFileDirectory(preferences.getFilePreferences().getUserAndHost(), latexFileDirectory); } databaseContext.setMetaData(newMetaData); @@ -271,7 +271,8 @@ public void togglePath(StringProperty fileDirectory) { if (!currPath.isAbsolute()) { newPath = parentPath.resolve(fileDirectory.get()).toAbsolutePath().toString(); } else if (currPath.isAbsolute()) { - newPath = parentPath.relativize(currPath).toString(); + Path rel = parentPath.relativize(currPath); + newPath = rel.toString().isEmpty() ? "." : rel.toString(); } else { // case: convert to relative path and currPath is relative return; diff --git a/jabgui/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java b/jabgui/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java index 8a8c0aa504c..2fff4432e8e 100644 --- a/jabgui/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java +++ b/jabgui/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java @@ -221,7 +221,8 @@ private BibDatabaseContext getBibDatabaseContextForSharedDatabase() { preferences.getBibEntryPreferences().getKeywordSeparator(), preferences.getFieldPreferences(), preferences.getCitationKeyPatternPreferences().getKeyPatterns(), - fileUpdateMonitor); + fileUpdateMonitor, + preferences.getFilePreferences().getUserAndHost()); bibDatabaseContext.convertToSharedDatabase(synchronizer); return bibDatabaseContext; } diff --git a/jablib/src/main/java/org/jabref/logic/exporter/MetaDataSerializer.java b/jablib/src/main/java/org/jabref/logic/exporter/MetaDataSerializer.java index 8e38375a986..9b1e1fa99b0 100644 --- a/jablib/src/main/java/org/jabref/logic/exporter/MetaDataSerializer.java +++ b/jablib/src/main/java/org/jabref/logic/exporter/MetaDataSerializer.java @@ -57,7 +57,7 @@ public static Map getSerializedStringMap(MetaData metaData, metaData.getUserFileDirectories().forEach((user, path) -> stringyMetaData .put(MetaData.FILE_DIRECTORY + '-' + user, List.of(path.trim()))); metaData.getLatexFileDirectories().forEach((user, path) -> stringyMetaData - .put(MetaData.FILE_DIRECTORY_LATEX + '-' + user, List.of(path.toString().trim()))); + .put(MetaData.FILE_DIRECTORY_LATEX + '-' + user, List.of(path.trim()))); metaData.getVersionDBStructure().ifPresent( versionDBStructure -> stringyMetaData.put(MetaData.VERSION_DB_STRUCT, List.of(versionDBStructure.trim()))); metaData.getBlgFilePaths().forEach((user, path) -> stringyMetaData.put(MetaData.BLG_FILE_PATH + "-" + user, List.of(path.toString().trim()))); diff --git a/jablib/src/main/java/org/jabref/logic/importer/ImportFormatPreferences.java b/jablib/src/main/java/org/jabref/logic/importer/ImportFormatPreferences.java index 7ffa747719e..cb5d65e3149 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/ImportFormatPreferences.java +++ b/jablib/src/main/java/org/jabref/logic/importer/ImportFormatPreferences.java @@ -1,5 +1,6 @@ package org.jabref.logic.importer; +import org.jabref.logic.FilePreferences; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.importer.util.GrobidPreferences; @@ -13,5 +14,6 @@ public record ImportFormatPreferences( FieldPreferences fieldPreferences, XmpPreferences xmpPreferences, DOIPreferences doiPreferences, - GrobidPreferences grobidPreferences) { + GrobidPreferences grobidPreferences, + FilePreferences filePreferences) { } diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibtexParser.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibtexParser.java index ea6c1423f89..ebea6f7737e 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibtexParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/BibtexParser.java @@ -273,7 +273,8 @@ private ParserResult parseFileContent() throws IOException { try { MetaData metaData = metaDataParser.parse( meta, - importFormatPreferences.bibEntryPreferences().getKeywordSeparator()); + importFormatPreferences.bibEntryPreferences().getKeywordSeparator(), + importFormatPreferences.filePreferences().getUserAndHost()); if (bibDeskGroupTreeNode != null) { metaData.getGroups().ifPresentOrElse(existingGroupTree -> { String existingGroups = meta.get(MetaData.GROUPSTREE); diff --git a/jablib/src/main/java/org/jabref/logic/importer/util/GroupsParser.java b/jablib/src/main/java/org/jabref/logic/importer/util/GroupsParser.java index f7e77cd11ce..1cd522b2393 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/util/GroupsParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/util/GroupsParser.java @@ -45,13 +45,13 @@ public class GroupsParser { private GroupsParser() { } - public static GroupTreeNode importGroups(List orderedData, Character keywordSeparator, FileUpdateMonitor fileMonitor, MetaData metaData) + public static GroupTreeNode importGroups(List orderedData, Character keywordSeparator, FileUpdateMonitor fileMonitor, MetaData metaData, String userAndHost) throws ParseException { try { GroupTreeNode cursor = null; GroupTreeNode root = null; for (String string : orderedData) { - // This allows to read databases that have been modified by, e.g., BibDesk + // This allows reading databases that have been modified by, e.g., BibDesk string = string.trim(); if (string.isEmpty()) { continue; @@ -62,7 +62,7 @@ public static GroupTreeNode importGroups(List orderedData, Character key throw new ParseException("Expected \"" + string + "\" to contain whitespace"); } int level = Integer.parseInt(string.substring(0, spaceIndex)); - AbstractGroup group = GroupsParser.fromString(string.substring(spaceIndex + 1), keywordSeparator, fileMonitor, metaData); + AbstractGroup group = GroupsParser.fromString(string.substring(spaceIndex + 1), keywordSeparator, fileMonitor, metaData, userAndHost); GroupTreeNode newNode = GroupTreeNode.fromGroup(group); if (cursor == null) { // create new root @@ -92,7 +92,7 @@ public static GroupTreeNode importGroups(List orderedData, Character key * @return New instance of the encoded group. * @throws ParseException If an error occurred and a group could not be created, e.g. due to a malformed regular expression. */ - public static AbstractGroup fromString(String s, Character keywordSeparator, FileUpdateMonitor fileMonitor, MetaData metaData) + public static AbstractGroup fromString(String s, Character keywordSeparator, FileUpdateMonitor fileMonitor, MetaData metaData, String userAndHost) throws ParseException { if (s.startsWith(MetadataSerializationConfiguration.KEYWORD_GROUP_ID)) { return keywordGroupFromString(s, keywordSeparator); @@ -119,13 +119,13 @@ public static AbstractGroup fromString(String s, Character keywordSeparator, Fil return automaticKeywordGroupFromString(s); } if (s.startsWith(MetadataSerializationConfiguration.TEX_GROUP_ID)) { - return texGroupFromString(s, fileMonitor, metaData); + return texGroupFromString(s, fileMonitor, metaData, userAndHost); } throw new ParseException("Unknown group: " + s); } - private static AbstractGroup texGroupFromString(String string, FileUpdateMonitor fileMonitor, MetaData metaData) throws ParseException { + private static AbstractGroup texGroupFromString(String string, FileUpdateMonitor fileMonitor, MetaData metaData, String userAndHost) throws ParseException { QuotedStringTokenizer tok = new QuotedStringTokenizer(string.substring(MetadataSerializationConfiguration.TEX_GROUP_ID .length()), MetadataSerializationConfiguration.GROUP_UNIT_SEPARATOR, MetadataSerializationConfiguration.GROUP_QUOTE_CHAR); @@ -134,14 +134,14 @@ private static AbstractGroup texGroupFromString(String string, FileUpdateMonitor try { Path path = Path.of(tok.nextToken()); try { - TexGroup newGroup = TexGroup.create(name, context, path, new DefaultAuxParser(new BibDatabase()), fileMonitor, metaData); + TexGroup newGroup = TexGroup.create(name, context, path, new DefaultAuxParser(new BibDatabase()), fileMonitor, metaData, userAndHost); addGroupDetails(tok, newGroup); return newGroup; } catch (IOException ex) { // Problem accessing file -> create without file monitoring LOGGER.warn("Could not access file {}. The group {} will not reflect changes to the aux file.", path, name, ex); - TexGroup newGroup = TexGroup.create(name, context, path, new DefaultAuxParser(new BibDatabase()), metaData); + TexGroup newGroup = TexGroup.create(name, context, path, new DefaultAuxParser(new BibDatabase()), metaData, userAndHost); addGroupDetails(tok, newGroup); return newGroup; } @@ -187,7 +187,7 @@ private static AbstractGroup automaticKeywordGroupFromString(String string) { * * @param s The String representation obtained from KeywordGroup.toString() */ - private static KeywordGroup keywordGroupFromString(String s, Character keywordSeparator) throws ParseException { + private static KeywordGroup keywordGroupFromString(String s, Character keywordSeparator) { if (!s.startsWith(MetadataSerializationConfiguration.KEYWORD_GROUP_ID)) { throw new IllegalArgumentException("KeywordGroup cannot be created from \"" + s + "\"."); } @@ -267,7 +267,7 @@ private static ExplicitGroup legacyExplicitGroupFromString(String input, Charact /** * Called only when created fromString. * JabRef used to store the entries of an explicit group in the serialization, e.g. - * ExplicitGroup:GroupName\;0\;Key1\;Key2\;; + * ExplicitGroup:GroupName\;0\;Key1\;Key2\;; * This method exists for backwards compatibility. */ private static void addLegacyEntryKeys(QuotedStringTokenizer tok, ExplicitGroup group) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/util/MetaDataParser.java b/jablib/src/main/java/org/jabref/logic/importer/util/MetaDataParser.java index 7a1862495fb..59c9309b138 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/util/MetaDataParser.java +++ b/jablib/src/main/java/org/jabref/logic/importer/util/MetaDataParser.java @@ -32,7 +32,6 @@ import org.jabref.model.metadata.ContentSelectors; import org.jabref.model.metadata.MetaData; import org.jabref.model.metadata.SaveOrder; -import org.jabref.model.metadata.UserHostInfo; import org.jabref.model.strings.StringUtil; import org.jabref.model.util.FileUpdateMonitor; @@ -94,8 +93,8 @@ public static Optional parseCustomEntryType(String comment) { /** * Parses the given data map and returns a new resulting {@link MetaData} instance. */ - public MetaData parse(Map data, Character keywordSeparator) throws ParseException { - return parse(new MetaData(), data, keywordSeparator); + public MetaData parse(Map data, Character keywordSeparator, String userAndHost) throws ParseException { + return parse(new MetaData(), data, keywordSeparator, userAndHost); } /** @@ -103,7 +102,7 @@ public MetaData parse(Map data, Character keywordSeparator) thro * * @return the given metaData instance (which is modified, too) */ - public MetaData parse(MetaData metaData, Map data, Character keywordSeparator) throws ParseException { + public MetaData parse(MetaData metaData, Map data, Character keywordSeparator, String userAndHost) throws ParseException { CitationKeyPattern defaultCiteKeyPattern = CitationKeyPattern.NULL_CITATION_KEY_PATTERN; Map nonDefaultCiteKeyPatterns = new HashMap<>(); @@ -131,20 +130,7 @@ public MetaData parse(MetaData metaData, Map data, Character key } else if (entry.getKey().startsWith(MetaData.FILE_DIRECTORY_LATEX)) { // The user-host string starts directly after FILE_DIRECTORY_LATEX + '-' String userHostString = entry.getKey().substring(MetaData.FILE_DIRECTORY_LATEX.length() + 1); - Path path = Path.of(parseDirectory(entry.getValue())).normalize(); - - UserHostInfo userHostInfo = UserHostInfo.parse(userHostString); - String currentHost = org.jabref.logic.os.OS.getHostName(); - - if (!userHostInfo.host().isEmpty() && !userHostInfo.host().equals(currentHost)) { - // If the host doesn't match the current host, we need to use the current user-host - // This w that the LaTeX file directory is set for the current user on the current host - LOGGER.warn("Host mismatch for LaTeX file directory: {} vs current host {}", userHostInfo.host(), currentHost); - // We don't have access to the current user-host here, so we'll just store the path - // The correct user-host will be used when the path is retrieved via the GUI - } - - metaData.setLatexFileDirectory(userHostString, path); + metaData.setLatexFileDirectory(userHostString, parseDirectory(entry.getValue())); } else if (MetaData.SAVE_ACTIONS.equals(entry.getKey())) { metaData.setSaveActions(fieldFormatterCleanupsParse(values)); } else if (MetaData.DATABASE_TYPE.equals(entry.getKey())) { @@ -160,7 +146,7 @@ public MetaData parse(MetaData metaData, Map data, Character key } else if (MetaData.SAVE_ORDER_CONFIG.equals(entry.getKey())) { metaData.setSaveOrder(SaveOrder.parse(values)); } else if (MetaData.GROUPSTREE.equals(entry.getKey()) || MetaData.GROUPSTREE_LEGACY.equals(entry.getKey())) { - metaData.setGroups(GroupsParser.importGroups(values, keywordSeparator, fileMonitor, metaData)); + metaData.setGroups(GroupsParser.importGroups(values, keywordSeparator, fileMonitor, metaData, userAndHost)); } else if (MetaData.GROUPS_SEARCH_SYNTAX_VERSION.equals(entry.getKey())) { Version version = Version.parse(getSingleItem(values)); metaData.setGroupSearchSyntaxVersion(version); diff --git a/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java b/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java index 2df96e6b608..3d071a3aa65 100644 --- a/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java +++ b/jablib/src/main/java/org/jabref/logic/preferences/JabRefCliPreferences.java @@ -2411,7 +2411,8 @@ public ImportFormatPreferences getImportFormatPreferences() { getFieldPreferences(), getXmpPreferences(), getDOIPreferences(), - getGrobidPreferences()); + getGrobidPreferences(), + getFilePreferences()); } // endregion diff --git a/jablib/src/main/java/org/jabref/logic/shared/DBMSSynchronizer.java b/jablib/src/main/java/org/jabref/logic/shared/DBMSSynchronizer.java index d388de0b884..32bfdee3e26 100644 --- a/jablib/src/main/java/org/jabref/logic/shared/DBMSSynchronizer.java +++ b/jablib/src/main/java/org/jabref/logic/shared/DBMSSynchronizer.java @@ -57,10 +57,11 @@ public class DBMSSynchronizer implements DatabaseSynchronizer { private final FieldPreferences fieldPreferences; private final FileUpdateMonitor fileMonitor; private Optional lastEntryChanged; + private final String userAndHost; public DBMSSynchronizer(BibDatabaseContext bibDatabaseContext, Character keywordSeparator, FieldPreferences fieldPreferences, - GlobalCitationKeyPatterns globalCiteKeyPattern, FileUpdateMonitor fileMonitor) { + GlobalCitationKeyPatterns globalCiteKeyPattern, FileUpdateMonitor fileMonitor, String userAndHost) { this.bibDatabaseContext = Objects.requireNonNull(bibDatabaseContext); this.bibDatabase = bibDatabaseContext.getDatabase(); this.metaData = bibDatabaseContext.getMetaData(); @@ -70,6 +71,7 @@ public DBMSSynchronizer(BibDatabaseContext bibDatabaseContext, Character keyword this.keywordSeparator = keywordSeparator; this.globalCiteKeyPattern = Objects.requireNonNull(globalCiteKeyPattern); this.lastEntryChanged = Optional.empty(); + this.userAndHost = userAndHost; } /** @@ -267,7 +269,7 @@ public void synchronizeLocalMetaData() { try { metaData.setEventPropagation(false); MetaDataParser parser = new MetaDataParser(fileMonitor); - parser.parse(metaData, dbmsProcessor.getSharedMetaData(), keywordSeparator); + parser.parse(metaData, dbmsProcessor.getSharedMetaData(), keywordSeparator, userAndHost); metaData.setEventPropagation(true); } catch (ParseException e) { LOGGER.error("Parse error", e); diff --git a/jablib/src/main/java/org/jabref/logic/util/io/FileUtil.java b/jablib/src/main/java/org/jabref/logic/util/io/FileUtil.java index 878e6746432..a2f181ce408 100644 --- a/jablib/src/main/java/org/jabref/logic/util/io/FileUtil.java +++ b/jablib/src/main/java/org/jabref/logic/util/io/FileUtil.java @@ -146,9 +146,9 @@ public static Path addExtension(Path path, String extension) { } /// Looks for the shortest unique path of the parent directory in the list of paths + /// /// @param paths List of paths as Strings /// @param comparePath The to be tested path - /// /// @return Optional.empty() if the paths are disjoint public static Optional getUniquePathDirectory(List paths, Path comparePath) { // Difference to getUniquePathFragment: We want the parent directory, so we cut off the last path fragment @@ -161,7 +161,6 @@ public static Optional getUniquePathDirectory(List paths, Path c /// /// @param paths List of paths as Strings /// @param comparePath The to be shortened path - /// /// @return Shortest unique path fragment (if exists) - Optional.empty() if the paths are disjoint public static Optional getUniquePathFragment(List paths, Path comparePath) { return uniquePathSubstrings(paths).stream() @@ -644,7 +643,8 @@ public static Path convertCygwinPathToWindows(String filePath) { } /// Builds a Windows-style path from a Cygwin-style path using a known prefix index. - /// @param path the input file path + /// + /// @param path the input file path /// @param letterIndex the index driver letter, zero-based indexing /// @return a windows-style path private static Path buildWindowsPathWithDriveLetterIndex(String path, int letterIndex) { diff --git a/jablib/src/main/java/org/jabref/model/groups/TexGroup.java b/jablib/src/main/java/org/jabref/model/groups/TexGroup.java index 503bcc2d269..12d04a55323 100644 --- a/jablib/src/main/java/org/jabref/model/groups/TexGroup.java +++ b/jablib/src/main/java/org/jabref/model/groups/TexGroup.java @@ -1,7 +1,6 @@ package org.jabref.model.groups; import java.io.IOException; -import java.net.InetAddress; import java.nio.file.Path; import java.util.List; import java.util.Objects; @@ -41,19 +40,15 @@ public class TexGroup extends AbstractGroup implements FileUpdateListener { this.fileMonitor = fileMonitor; } - TexGroup(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, FileUpdateMonitor fileMonitor, MetaData metaData) throws IOException { - this(name, context, filePath, auxParser, fileMonitor, metaData, System.getProperty("user.name") + '-' + InetAddress.getLocalHost().getHostName()); - } - - public static TexGroup create(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, FileUpdateMonitor fileMonitor, MetaData metaData) throws IOException { - TexGroup group = new TexGroup(name, context, filePath, auxParser, fileMonitor, metaData); + public static TexGroup create(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, FileUpdateMonitor fileMonitor, MetaData metaData, String userAndHost) throws IOException { + TexGroup group = new TexGroup(name, context, filePath, auxParser, fileMonitor, metaData, userAndHost); fileMonitor.addListenerForFile(group.getFilePathResolved(), group); return group; } // without FileUpdateMonitor - public static TexGroup create(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, MetaData metaData) throws IOException { - return new TexGroup(name, context, filePath, auxParser, new DummyFileUpdateMonitor(), metaData); + public static TexGroup create(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, MetaData metaData, String userAndHost) throws IOException { + return new TexGroup(name, context, filePath, auxParser, new DummyFileUpdateMonitor(), metaData, userAndHost); } public Path getFilePathResolved() { @@ -77,13 +72,7 @@ public boolean isDynamic() { @Override public AbstractGroup deepCopy() { - try { - return new TexGroup(name.getValue(), context, filePath, auxParser, fileMonitor, metaData); - } catch (IOException ex) { - // This should never happen because we were able to monitor the file just fine until now - LOGGER.error("Problem creating copy of group", ex); - return null; - } + return new TexGroup(name.getValue(), context, filePath, auxParser, fileMonitor, metaData, user); } @Override @@ -127,6 +116,13 @@ public void fileUpdated() { metaData.groupsBinding().invalidate(); } + /** + * Relativizes the given path to the file directories. + * The getLatexFileDirectory must be absolute to correctly relativize because we do not have a bibdatabasecontext + * + * @param path The path to relativize + * @return A relative path or the original one if it could not be made relative + */ private Path relativize(Path path) { List fileDirectories = getFileDirectoriesAsPaths(); return FileUtil.relativize(path, fileDirectories); diff --git a/jablib/src/main/java/org/jabref/model/metadata/MetaData.java b/jablib/src/main/java/org/jabref/model/metadata/MetaData.java index 7214bf5c10d..28e494100c1 100644 --- a/jablib/src/main/java/org/jabref/model/metadata/MetaData.java +++ b/jablib/src/main/java/org/jabref/model/metadata/MetaData.java @@ -63,7 +63,7 @@ public class MetaData { private final EventBus eventBus = new EventBus(); private final Map citeKeyPatterns = new HashMap<>(); // private final Map userFileDirectory = new HashMap<>(); // - private final Map latexFileDirectory = new HashMap<>(); // + private final Map latexFileDirectory = new HashMap<>(); // private final ObjectProperty groupsRoot = new SimpleObjectProperty<>(null); private final OptionalBinding groupsRootBinding = new OptionalWrapper<>(groupsRoot); @@ -261,29 +261,10 @@ public void clearUserFileDirectory(String user) { } public Optional getLatexFileDirectory(String userHostString) { - // First try to get the LaTeX file directory for the exact user-host - Path path = latexFileDirectory.get(userHostString); - if (path != null) { - return Optional.of(path); - } - - // If not found, try to find a LaTeX file directory for the same host - // This handles the case where a file is moved between hosts with different users - UserHostInfo requestedUserHost = UserHostInfo.parse(userHostString); - if (!requestedUserHost.host().isEmpty()) { - for (Map.Entry entry : latexFileDirectory.entrySet()) { - UserHostInfo entryUserHost = UserHostInfo.parse(entry.getKey()); - if (entryUserHost.hasSameHost(requestedUserHost)) { - // Found a LaTeX file directory for the same host, return it - return Optional.of(entry.getValue()); - } - } - } - - return Optional.empty(); + return Optional.ofNullable(latexFileDirectory.get(userHostString)).map(Path::of); } - public void setLatexFileDirectory(@NonNull String userHostString, @NonNull Path path) { + public void setLatexFileDirectory(@NonNull String userHostString, @NonNull String path) { latexFileDirectory.put(userHostString, path); postChange(); } @@ -380,7 +361,7 @@ public Map getUserFileDirectories() { return Collections.unmodifiableMap(userFileDirectory); } - public Map getLatexFileDirectories() { + public Map getLatexFileDirectories() { return Collections.unmodifiableMap(latexFileDirectory); } diff --git a/jablib/src/test/java/org/jabref/logic/exporter/BibDatabaseWriterTest.java b/jablib/src/test/java/org/jabref/logic/exporter/BibDatabaseWriterTest.java index f6186a1d689..236f0a1dcd9 100644 --- a/jablib/src/test/java/org/jabref/logic/exporter/BibDatabaseWriterTest.java +++ b/jablib/src/test/java/org/jabref/logic/exporter/BibDatabaseWriterTest.java @@ -810,7 +810,7 @@ void writeProtectedFlag() throws IOException { void writeFileDirectories() throws IOException { metaData.setLibrarySpecificFileDirectory("\\Literature\\"); metaData.setUserFileDirectory("defaultOwner-user", "D:\\Documents"); - metaData.setLatexFileDirectory("defaultOwner-user", Path.of("D:\\Latex")); + metaData.setLatexFileDirectory("defaultOwner-user", "D:\\Latex"); databaseWriter.savePartOfDatabase(bibtexContext, List.of()); diff --git a/jablib/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java b/jablib/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java index 035dab28012..54a4ff17135 100644 --- a/jablib/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java +++ b/jablib/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java @@ -34,7 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; /** - * Loading of groups is tested at {@link org.jabref.logic.importer.util.GroupsParserTest}. + * Loading of groups is tested in the GroupsParserTest class. */ class GroupSerializerTest { @@ -129,7 +129,7 @@ void serializeSingleAutomaticPersonGroup() { @Test void serializeSingleTexGroup() throws IOException { - TexGroup group = TexGroup.create("myTexGroup", GroupHierarchyType.INDEPENDENT, Path.of("path", "To", "File"), new DefaultAuxParser(new BibDatabase()), new MetaData()); + TexGroup group = TexGroup.create("myTexGroup", GroupHierarchyType.INDEPENDENT, Path.of("path", "To", "File"), new DefaultAuxParser(new BibDatabase()), new MetaData(), ""); List serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(List.of("0 TexGroup:myTexGroup;0;path/To/File;1;;;;"), serialization); } diff --git a/jablib/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java b/jablib/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java index 3f981952758..9bde0c834a9 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java @@ -2,7 +2,6 @@ import java.io.IOException; import java.io.Reader; -import java.net.InetAddress; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; @@ -58,6 +57,7 @@ import org.jabref.model.groups.TexGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.SaveOrder; +import org.jabref.model.metadata.UserHostInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -1708,6 +1708,7 @@ void integrationTestBibDeskMultipleGroup() throws IOException { */ @Test void integrationTestTexGroup() throws IOException { + String userHostInfo = new UserHostInfo(System.getProperty("user.name"), OS.getHostName()).getUserHostString(); ParserResult result = parser.parse(Reader.of( "@comment{jabref-meta: grouping:" + OS.NEWLINE + "0 AllEntriesGroup:;" + OS.NEWLINE @@ -1716,19 +1717,16 @@ void integrationTestTexGroup() throws IOException { + "@Comment{jabref-meta: databaseType:biblatex;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory:src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory-" - + System.getProperty("user.name") + "-" - + InetAddress.getLocalHost().getHostName() + + userHostInfo + ":src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectoryLatex-" - + System.getProperty("user.name") + "-" - + InetAddress.getLocalHost().getHostName() + + userHostInfo + ":src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE )); GroupTreeNode root = result.getMetaData().getGroups().get(); - assertEquals(((TexGroup) root.getChildren().getFirst().getGroup()).getFilePath(), - Path.of("src/test/resources/org/jabref/model/groups/paper.aux")); + assertEquals(Path.of("paper.aux"), ((TexGroup) root.getChildren().getFirst().getGroup()).getFilePath()); } @Test diff --git a/jablib/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java b/jablib/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java index 0b9a6460396..5fdb42a5473 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java @@ -42,11 +42,11 @@ void setUp() { metaData = new MetaData(); } - @Test // For https://github.com/JabRef/jabref/issues/1681 + @Test void fromStringParsesExplicitGroupWithEscapedCharacterInName() throws ParseException { ExplicitGroup expected = new ExplicitGroup("B{\\\"{o}}hmer", GroupHierarchyType.INDEPENDENT, ','); - AbstractGroup parsed = GroupsParser.fromString("ExplicitGroup:B{\\\\\"{o}}hmer;0;", ',', fileMonitor, metaData); + AbstractGroup parsed = GroupsParser.fromString("ExplicitGroup:B{\\\\\"{o}}hmer;0;", ',', fileMonitor, metaData, "userAndHost"); assertEquals(expected, parsed); } @@ -54,20 +54,20 @@ void fromStringParsesExplicitGroupWithEscapedCharacterInName() throws ParseExcep @Test void keywordDelimiterThatNeedsToBeEscaped() throws ParseException { AutomaticGroup expected = new AutomaticKeywordGroup("group1", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, ';', '>'); - AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:group1;0;keywords;\\;;>;1;;;;;", ';', fileMonitor, metaData); + AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:group1;0;keywords;\\;;>;1;;;;;", ';', fileMonitor, metaData, "userAndHost"); assertEquals(expected, parsed); } @Test void hierarchicalDelimiterThatNeedsToBeEscaped() throws ParseException { AutomaticGroup expected = new AutomaticKeywordGroup("group1", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, ',', ';'); - AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:group1;0;keywords;,;\\;;1;;;;;", ';', fileMonitor, metaData); + AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:group1;0;keywords;,;\\;;1;;;;;", ';', fileMonitor, metaData, "userAndHost"); assertEquals(expected, parsed); } @Test void fromStringThrowsParseExceptionForNotEscapedGroupName() { - assertThrows(ParseException.class, () -> GroupsParser.fromString("ExplicitGroup:slit\\\\;0\\;mertsch_slit2_2007\\;;", ',', fileMonitor, metaData)); + assertThrows(ParseException.class, () -> GroupsParser.fromString("ExplicitGroup:slit\\\\;0\\;mertsch_slit2_2007\\;;", ',', fileMonitor, metaData, "userAndHost")); } @Test @@ -93,7 +93,7 @@ void importSubGroups() throws ParseException { AbstractGroup thirdSubGrpLvl1 = new ExplicitGroup("3", GroupHierarchyType.INDEPENDENT, ','); rootNode.addSubgroup(thirdSubGrpLvl1); - GroupTreeNode parsedNode = GroupsParser.importGroups(orderedData, ',', fileMonitor, metaData); + GroupTreeNode parsedNode = GroupsParser.importGroups(orderedData, ',', fileMonitor, metaData, "userAndHost"); assertEquals(rootNode.getChildren(), parsedNode.getChildren()); } @@ -104,7 +104,7 @@ void fromStringParsesExplicitGroupWithIconAndDescription() throws ParseException expected.setExpanded(true); expected.setColor(Color.ALICEBLUE); expected.setDescription("test description"); - AbstractGroup parsed = GroupsParser.fromString("StaticGroup:myExplicitGroup;0;1;0xf0f8ffff;test icon;test description;", ',', fileMonitor, metaData); + AbstractGroup parsed = GroupsParser.fromString("StaticGroup:myExplicitGroup;0;1;0xf0f8ffff;test icon;test description;", ',', fileMonitor, metaData, "userAndHost"); assertEquals(expected, parsed); } @@ -112,33 +112,33 @@ void fromStringParsesExplicitGroupWithIconAndDescription() throws ParseException @Test void fromStringParsesAutomaticKeywordGroup() throws ParseException { AutomaticGroup expected = new AutomaticKeywordGroup("myAutomaticGroup", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, ',', '>'); - AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:myAutomaticGroup;0;keywords;,;>;1;;;;", ',', fileMonitor, metaData); + AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:myAutomaticGroup;0;keywords;,;>;1;;;;", ',', fileMonitor, metaData, "userAndHost"); assertEquals(expected, parsed); } @Test void fromStringParsesAutomaticPersonGroup() throws ParseException { AutomaticPersonsGroup expected = new AutomaticPersonsGroup("myAutomaticGroup", GroupHierarchyType.INDEPENDENT, StandardField.AUTHOR); - AbstractGroup parsed = GroupsParser.fromString("AutomaticPersonsGroup:myAutomaticGroup;0;author;1;;;;", ',', fileMonitor, metaData); + AbstractGroup parsed = GroupsParser.fromString("AutomaticPersonsGroup:myAutomaticGroup;0;author;1;;;;", ',', fileMonitor, metaData, "userAndHost"); assertEquals(expected, parsed); } @Test void fromStringParsesTexGroup() throws ParseException, IOException { - TexGroup expected = TexGroup.create("myTexGroup", GroupHierarchyType.INDEPENDENT, Path.of("path", "To", "File"), new DefaultAuxParser(new BibDatabase()), metaData); - AbstractGroup parsed = GroupsParser.fromString("TexGroup:myTexGroup;0;path/To/File;1;;;;", ',', fileMonitor, metaData); + TexGroup expected = TexGroup.create("myTexGroup", GroupHierarchyType.INDEPENDENT, Path.of("path", "To", "File"), new DefaultAuxParser(new BibDatabase()), metaData, "userAndHost"); + AbstractGroup parsed = GroupsParser.fromString("TexGroup:myTexGroup;0;path/To/File;1;;;;", ',', fileMonitor, metaData, "userAndHost"); assertEquals(expected, parsed); } @Test void fromStringUnknownGroupThrowsException() { - assertThrows(ParseException.class, () -> GroupsParser.fromString("0 UnknownGroup:myUnknownGroup;0;;1;;;;", ',', fileMonitor, metaData)); + assertThrows(ParseException.class, () -> GroupsParser.fromString("0 UnknownGroup:myUnknownGroup;0;;1;;;;", ',', fileMonitor, metaData, "userAndHost")); } @Test void fromStringParsesSearchGroup() throws ParseException { SearchGroup expected = new SearchGroup("Data", GroupHierarchyType.INCLUDING, "project=data|number|quant*", EnumSet.of(SearchFlags.REGULAR_EXPRESSION)); - AbstractGroup parsed = GroupsParser.fromString("SearchGroup:Data;2;project=data|number|quant*;0;1;1;;;;;", ',', fileMonitor, metaData); + AbstractGroup parsed = GroupsParser.fromString("SearchGroup:Data;2;project=data|number|quant*;0;1;1;;;;;", ',', fileMonitor, metaData, "userAndHost"); assertEquals(expected, parsed); } } diff --git a/jablib/src/test/java/org/jabref/logic/importer/util/MetaDataParserTest.java b/jablib/src/test/java/org/jabref/logic/importer/util/MetaDataParserTest.java index 230075fa8cd..6ac9657a2df 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/util/MetaDataParserTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/util/MetaDataParserTest.java @@ -72,7 +72,7 @@ void parseCustomizedEntryType(BibEntryTypeBuilder expected, String source) { void saveActions() throws ParseException { Map data = Map.of("saveActions", "enabled;title[lower_case]"); MetaDataParser metaDataParser = new MetaDataParser(new DummyFileUpdateMonitor()); - MetaData parsed = metaDataParser.parse(new MetaData(), data, ','); + MetaData parsed = metaDataParser.parse(new MetaData(), data, ',', "userAndHost"); MetaData expected = new MetaData(); FieldFormatterCleanups fieldFormatterCleanups = new FieldFormatterCleanups(true, List.of(new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter()))); @@ -87,11 +87,11 @@ void parsesUserSpecificBlgPathSuccessfully() throws ParseException { String rawValue = "/home/user/test.blg;"; MetaDataParser parser = new MetaDataParser(new DummyFileUpdateMonitor()); - MetaData parsed = parser.parse(Map.of(rawKey, rawValue), ','); + MetaData parsed = parser.parse(Map.of(rawKey, rawValue), ',', "userAndHost"); assertEquals(Optional.of(Path.of("/home/user/test.blg")), parsed.getBlgFilePath(user)); } - + @Test void parsesLatexFileDirectoryForUserHostSuccessfully() throws ParseException { String user = "testUser"; @@ -101,43 +101,28 @@ void parsesLatexFileDirectoryForUserHostSuccessfully() throws ParseException { String rawValue = "/home/user/latex;"; MetaDataParser parser = new MetaDataParser(new DummyFileUpdateMonitor()); - MetaData parsed = parser.parse(Map.of(rawKey, rawValue), ','); + MetaData parsed = parser.parse(Map.of(rawKey, rawValue), ',', "userAndHost"); assertEquals(Optional.of(Path.of("/home/user/latex")), parsed.getLatexFileDirectory(userHost)); } - + @Test void parsesMultipleLatexFileDirectoriesSuccessfully() throws ParseException { String userHost1 = "user1-host1"; String userHost2 = "user2-host2"; - + Map data = Map.of( "fileDirectoryLatex-" + userHost1, "/path/for/host1;", "fileDirectoryLatex-" + userHost2, "/path/for/host2;" ); MetaDataParser parser = new MetaDataParser(new DummyFileUpdateMonitor()); - MetaData parsed = parser.parse(data, ','); + MetaData parsed = parser.parse(data, ',', "userAndHost"); assertEquals(Optional.of(Path.of("/path/for/host1")), parsed.getLatexFileDirectory(userHost1)); assertEquals(Optional.of(Path.of("/path/for/host2")), parsed.getLatexFileDirectory(userHost2)); } - - @Test - void retrievesLatexFileDirectoryForDifferentUserOnSameHost() throws ParseException { - String originalUserHost = "user1-host"; - String newUserHost = "user2-host"; - - Map data = Map.of( - "fileDirectoryLatex-" + originalUserHost, "/path/to/latex;" - ); - - MetaDataParser parser = new MetaDataParser(new DummyFileUpdateMonitor()); - MetaData parsed = parser.parse(data, ','); - assertEquals(Optional.of(Path.of("/path/to/latex")), parsed.getLatexFileDirectory(newUserHost)); - } - @Test void parsesWindowsPathsInLatexFileDirectoryCorrectly() throws ParseException { String userHost = "user-host"; @@ -145,7 +130,7 @@ void parsesWindowsPathsInLatexFileDirectoryCorrectly() throws ParseException { String rawValue = "C:\\\\Path\\\\To\\\\Latex;"; MetaDataParser parser = new MetaDataParser(new DummyFileUpdateMonitor()); - MetaData parsed = parser.parse(Map.of(rawKey, rawValue), ','); + MetaData parsed = parser.parse(Map.of(rawKey, rawValue), ',', "userAndHost"); assertEquals(Optional.of(Path.of("C:\\Path\\To\\Latex")), parsed.getLatexFileDirectory(userHost)); } diff --git a/jablib/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java b/jablib/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java index a63dc0305bb..41eebb1ef3d 100644 --- a/jablib/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java +++ b/jablib/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java @@ -45,9 +45,7 @@ class DBMSSynchronizerTest { private DBMSSynchronizer dbmsSynchronizer; private BibDatabase bibDatabase; private final GlobalCitationKeyPatterns pattern = GlobalCitationKeyPatterns.fromPattern("[auth][year]"); - private DBMSConnection dbmsConnection; private DBMSProcessor dbmsProcessor; - private DBMSType dbmsType; private BibEntry createExampleBibEntry(int index) { BibEntry bibEntry = new BibEntry(StandardEntryType.Book) @@ -59,10 +57,10 @@ private BibEntry createExampleBibEntry(int index) { @BeforeEach void setup() throws SQLException, InvalidDBMSConnectionPropertiesException, DatabaseNotSupportedException { - this.dbmsType = TestManager.getDBMSTypeTestParameter(); - this.dbmsConnection = ConnectorTest.getTestDBMSConnection(dbmsType); - this.dbmsProcessor = DBMSProcessor.getProcessorInstance(this.dbmsConnection); - TestManager.clearTables(this.dbmsConnection); + DBMSType dbmsType = TestManager.getDBMSTypeTestParameter(); + DBMSConnection dbmsConnection = ConnectorTest.getTestDBMSConnection(dbmsType); + this.dbmsProcessor = DBMSProcessor.getProcessorInstance(dbmsConnection); + TestManager.clearTables(dbmsConnection); this.dbmsProcessor.setupSharedDatabase(); bibDatabase = new BibDatabase(); @@ -71,7 +69,7 @@ void setup() throws SQLException, InvalidDBMSConnectionPropertiesException, Data FieldPreferences fieldPreferences = mock(FieldPreferences.class); when(fieldPreferences.getNonWrappableFields()).thenReturn(FXCollections.observableArrayList()); - dbmsSynchronizer = new DBMSSynchronizer(context, ',', fieldPreferences, pattern, new DummyFileUpdateMonitor()); + dbmsSynchronizer = new DBMSSynchronizer(context, ',', fieldPreferences, pattern, new DummyFileUpdateMonitor(), "UserAndHost"); bibDatabase.registerListener(dbmsSynchronizer); dbmsSynchronizer.openSharedDatabase(dbmsConnection); diff --git a/jablib/src/test/java/org/jabref/logic/shared/SynchronizationSimulatorTest.java b/jablib/src/test/java/org/jabref/logic/shared/SynchronizationSimulatorTest.java index e14072821e4..fcd378dadc9 100644 --- a/jablib/src/test/java/org/jabref/logic/shared/SynchronizationSimulatorTest.java +++ b/jablib/src/test/java/org/jabref/logic/shared/SynchronizationSimulatorTest.java @@ -57,12 +57,12 @@ void setup() throws SQLException, InvalidDBMSConnectionPropertiesException, Data when(fieldPreferences.getNonWrappableFields()).thenReturn(FXCollections.observableArrayList()); clientContextA = new BibDatabaseContext(); - DBMSSynchronizer synchronizerA = new DBMSSynchronizer(clientContextA, ',', fieldPreferences, pattern, new DummyFileUpdateMonitor()); + DBMSSynchronizer synchronizerA = new DBMSSynchronizer(clientContextA, ',', fieldPreferences, pattern, new DummyFileUpdateMonitor(), "UserAndHost"); clientContextA.convertToSharedDatabase(synchronizerA); clientContextA.getDBMSSynchronizer().openSharedDatabase(dbmsConnection); clientContextB = new BibDatabaseContext(); - DBMSSynchronizer synchronizerB = new DBMSSynchronizer(clientContextB, ',', fieldPreferences, pattern, new DummyFileUpdateMonitor()); + DBMSSynchronizer synchronizerB = new DBMSSynchronizer(clientContextB, ',', fieldPreferences, pattern, new DummyFileUpdateMonitor(), "UserAndHost"); clientContextB.convertToSharedDatabase(synchronizerB); // use a second connection, because this is another client (typically on another machine) clientContextB.getDBMSSynchronizer().openSharedDatabase(ConnectorTest.getTestDBMSConnection(TestManager.getDBMSTypeTestParameter())); diff --git a/jablib/src/test/java/org/jabref/model/groups/TexGroupTest.java b/jablib/src/test/java/org/jabref/model/groups/TexGroupTest.java index a18915432a9..8bd21f060c5 100644 --- a/jablib/src/test/java/org/jabref/model/groups/TexGroupTest.java +++ b/jablib/src/test/java/org/jabref/model/groups/TexGroupTest.java @@ -1,6 +1,5 @@ package org.jabref.model.groups; -import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; @@ -29,9 +28,9 @@ void setUp() { } @Test - void containsReturnsTrueForEntryInAux() throws IOException, URISyntaxException { + void containsReturnsTrueForEntryInAux() throws URISyntaxException { Path auxFile = Path.of(TexGroupTest.class.getResource("paper.aux").toURI()); - TexGroup group = new TexGroup("paper", GroupHierarchyType.INDEPENDENT, auxFile, new DefaultAuxParser(new BibDatabase()), new DummyFileUpdateMonitor(), metaData); + TexGroup group = new TexGroup("paper", GroupHierarchyType.INDEPENDENT, auxFile, new DefaultAuxParser(new BibDatabase()), new DummyFileUpdateMonitor(), metaData, "userandHost"); BibEntry inAux = new BibEntry(); inAux.setCitationKey("Darwin1888"); @@ -39,9 +38,9 @@ void containsReturnsTrueForEntryInAux() throws IOException, URISyntaxException { } @Test - void containsReturnsTrueForEntryNotInAux() throws IOException, URISyntaxException { + void containsReturnsTrueForEntryNotInAux() throws URISyntaxException { Path auxFile = Path.of(TexGroupTest.class.getResource("paper.aux").toURI()); - TexGroup group = new TexGroup("paper", GroupHierarchyType.INDEPENDENT, auxFile, new DefaultAuxParser(new BibDatabase()), new DummyFileUpdateMonitor(), metaData); + TexGroup group = new TexGroup("paper", GroupHierarchyType.INDEPENDENT, auxFile, new DefaultAuxParser(new BibDatabase()), new DummyFileUpdateMonitor(), metaData, "userandHost"); BibEntry notInAux = new BibEntry(); notInAux.setCitationKey("NotInAux2017"); @@ -52,7 +51,7 @@ void containsReturnsTrueForEntryNotInAux() throws IOException, URISyntaxExceptio void getFilePathReturnsRelativePath() throws URISyntaxException { Path auxFile = Path.of(TexGroupTest.class.getResource("paper.aux").toURI()); String user = "Darwin"; - metaData.setLatexFileDirectory(user, auxFile.getParent()); + metaData.setLatexFileDirectory(user, auxFile.getParent().toString()); TexGroup group = new TexGroup("paper", GroupHierarchyType.INDEPENDENT, auxFile, new DefaultAuxParser(new BibDatabase()), new DummyFileUpdateMonitor(), metaData, user); assertEquals("paper.aux", group.getFilePath().toString()); diff --git a/jablib/src/test/java/org/jabref/model/metadata/MetaDataTest.java b/jablib/src/test/java/org/jabref/model/metadata/MetaDataTest.java index 3306bbecdc3..891860c65a7 100644 --- a/jablib/src/test/java/org/jabref/model/metadata/MetaDataTest.java +++ b/jablib/src/test/java/org/jabref/model/metadata/MetaDataTest.java @@ -1,13 +1,11 @@ package org.jabref.model.metadata; -import java.nio.file.Path; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; class MetaDataTest { @@ -22,70 +20,9 @@ void setUp() { void emptyGroupsIfNotSet() { assertEquals(Optional.empty(), metaData.getGroups()); } - + @Test void getLatexFileDirectoryReturnsEmptyWhenNotSet() { assertEquals(Optional.empty(), metaData.getLatexFileDirectory("user-host")); } - - @Test - void getLatexFileDirectoryReturnsPathForExactUserHostMatch() { - String userHost = "user-host"; - Path expectedPath = Path.of("/path/to/latex"); - metaData.setLatexFileDirectory(userHost, expectedPath); - - Optional result = metaData.getLatexFileDirectory(userHost); - - assertTrue(result.isPresent()); - assertEquals(expectedPath, result.get()); - } - - @Test - void getLatexFileDirectoryReturnsPathForSameHostButDifferentUser() { - String originalUserHost = "user1-host"; - String newUserHost = "user2-host"; - Path expectedPath = Path.of("/path/to/latex"); - metaData.setLatexFileDirectory(originalUserHost, expectedPath); - - Optional result = metaData.getLatexFileDirectory(newUserHost); - - assertTrue(result.isPresent()); - assertEquals(expectedPath, result.get()); - } - - @Test - void getLatexFileDirectoryReturnsEmptyForDifferentHost() { - String userHost1 = "user-host1"; - Path path1 = Path.of("/path/for/host1"); - metaData.setLatexFileDirectory(userHost1, path1); - - Optional result = metaData.getLatexFileDirectory("user-host2"); - - assertEquals(Optional.empty(), result); - } - - @Test - void getLatexFileDirectoryHandlesMultipleEntriesCorrectly() { - String userHost1 = "user1-host1"; - String userHost2 = "user2-host2"; - String userHost3 = "user3-host1"; - - Path path1 = Path.of("/path/for/host1/user1"); - Path path2 = Path.of("/path/for/host2"); - Path path3 = Path.of("/path/for/host1/user3"); - - metaData.setLatexFileDirectory(userHost1, path1); - metaData.setLatexFileDirectory(userHost2, path2); - metaData.setLatexFileDirectory(userHost3, path3); - - assertEquals(path1, metaData.getLatexFileDirectory(userHost1).get()); - assertEquals(path2, metaData.getLatexFileDirectory(userHost2).get()); - assertEquals(path3, metaData.getLatexFileDirectory(userHost3).get()); - - String newUserOnHost1 = "newuser-host1"; - Optional resultForNewUser = metaData.getLatexFileDirectory(newUserOnHost1); - assertTrue(resultForNewUser.isPresent()); - - assertEquals(Optional.empty(), metaData.getLatexFileDirectory("user-differenthost")); - } } diff --git a/jabsrv/src/test/java/org/jabref/http/server/ServerTest.java b/jabsrv/src/test/java/org/jabref/http/server/ServerTest.java index c434babc077..d58cc7581bc 100644 --- a/jabsrv/src/test/java/org/jabref/http/server/ServerTest.java +++ b/jabsrv/src/test/java/org/jabref/http/server/ServerTest.java @@ -11,11 +11,13 @@ import org.jabref.http.dto.GsonFactory; import org.jabref.http.server.cayw.format.FormatterService; import org.jabref.http.server.services.FilesToServe; +import org.jabref.logic.FilePreferences; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.preferences.CliPreferences; import org.jabref.logic.preferences.LastFilesOpenedPreferences; import org.jabref.model.entry.BibEntryPreferences; +import org.jabref.model.metadata.UserHostInfo; import com.google.gson.Gson; import org.glassfish.hk2.utilities.binding.AbstractBinder; @@ -128,6 +130,11 @@ private static void initializePreferencesService() { LastFilesOpenedPreferences lastFilesOpenedPreferences = mock(LastFilesOpenedPreferences.class); when(preferences.getLastFilesOpenedPreferences()).thenReturn(lastFilesOpenedPreferences); when(lastFilesOpenedPreferences.getLastFilesOpened()).thenReturn(FXCollections.emptyObservableList()); + + FilePreferences filePreferences = mock(FilePreferences.class); + when(preferences.getFilePreferences()).thenReturn(filePreferences); + when(filePreferences.getUserAndHost()).thenReturn(new UserHostInfo("user", "host").getUserHostString()); + when(importFormatPreferences.filePreferences()).thenReturn(filePreferences); } protected void addGlobalExceptionMapperToResourceConfig(ResourceConfig resourceConfig) {