Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement mass addition of bib information (Closes #372) #12025

Draft
wants to merge 46 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 40 commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
887dd35
feat: enhance right-click context menu with new actions (extract refe…
KUMOAWAI Oct 19, 2024
656facf
fix: Restore MERGE_WITH_FETCHED_ENTRY and add BATCH_MERGE_WITH_FETCHE…
KUMOAWAI Oct 19, 2024
0409856
Refactor and optimize FetchAndMergeEntry class
KUMOAWAI Oct 19, 2024
489b512
Merge branch 'JabRef:main' into fix-for-issue-#372
KUMOAWAI Oct 19, 2024
dc138ce
Updated CHANGELOG.md
KUMOAWAI Oct 19, 2024
0532df4
Added a period at the end of the description in CHANGELOG.md.
KUMOAWAI Oct 19, 2024
012dd9a
Updated JabRef_en.properties
KUMOAWAI Oct 19, 2024
f8267ac
Move and rename "Mass Getting bibliographic data" action
KUMOAWAI Oct 20, 2024
74f2473
Refactor FetchAndMergeEntry class for improved functionality and read…
KUMOAWAI Oct 20, 2024
29759a6
Merge branch 'main' into fix-for-issue-#372
koppor Oct 20, 2024
37cfeae
Refactor entry fetching and merging process
KUMOAWAI Oct 20, 2024
77e0d51
Updated CHANGELOG.md
KUMOAWAI Oct 20, 2024
e6f0ad2
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Oct 20, 2024
c5b7b4c
refactor: Separate UI and core logic in entry merging system
KUMOAWAI Oct 25, 2024
5b829b1
Merge remote-tracking branch 'upstream/fix-for-issue-#372' into fix-f…
KUMOAWAI Oct 25, 2024
350502e
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Oct 25, 2024
fe46c0c
Refactored updateFieldIfNecessaryWithUndo method in MergeEntriesHelpe…
KUMOAWAI Oct 25, 2024
8eac6a9
Merge remote-tracking branch 'upstream/fix-for-issue-#372' into fix-f…
KUMOAWAI Oct 25, 2024
5d54083
refactor: Replace String.format with string concatenation in MergingI…
KUMOAWAI Oct 25, 2024
93072cf
refactor: Fixed incorrect placeholder in updateProgress Method
KUMOAWAI Oct 25, 2024
262d25d
Updated JabRef_en.properties to fix the failing LocalizationConsisten…
KUMOAWAI Oct 25, 2024
4667124
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Oct 26, 2024
ae4df14
refactor: optimize BibEntry merging and fetching logic:
KUMOAWAI Oct 26, 2024
5ed3d70
Roll Back: FetchAndMergeEntry.java and MergeWithFetchedEntryAction.java.
KUMOAWAI Oct 27, 2024
74a6285
Merge branch 'main' into fix-for-issue-#372
koppor Oct 27, 2024
8d9bdce
Refactor: improve MergingIdBasedFetcher, BatchEntryMergeWithFetchedD…
KUMOAWAI Oct 27, 2024
95e9ae8
Fixed the minor import format issue.
KUMOAWAI Oct 27, 2024
9fdbbb4
Merge remote-tracking branch 'upstream/fix-for-issue-#372' into fix-f…
KUMOAWAI Oct 27, 2024
ce1ea3e
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Oct 27, 2024
7305f3c
Apply suggestions from code review
KUMOAWAI Oct 27, 2024
9dce81a
Refactor: Reorder parameters to (fetcher, library) in merge operations
KUMOAWAI Oct 27, 2024
5f24815
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Oct 27, 2024
d17fd88
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Oct 30, 2024
61f5a8f
Refactor: Deleted the empty line before package
KUMOAWAI Oct 31, 2024
86051ac
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Oct 31, 2024
198f2d0
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Oct 31, 2024
ace1975
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Nov 13, 2024
74681e1
Refactor: Deleted the empty line before package
KUMOAWAI Nov 16, 2024
3197ef4
refactor: Extract background processing into BatchEntryMergeTask, opt…
KUMOAWAI Nov 16, 2024
c04a2fa
Updated JabRef_en.properties
KUMOAWAI Nov 16, 2024
d2566db
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Nov 17, 2024
4d1b88d
Apply suggestions from code review
KUMOAWAI Nov 17, 2024
e8645a2
Modify log messages correspondingly.
KUMOAWAI Nov 17, 2024
ac8c59d
Refactor: Move string normalization from StringNormalizer to StringUtil
KUMOAWAI Nov 17, 2024
5172bc2
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Nov 18, 2024
05b3c42
Merge branch 'main' into fix-for-issue-#372
KUMOAWAI Dec 5, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv
- We added support to automatically open a `.bib` file in the current/parent folder if no other library is opened. [koppor#377](https://github.com/koppor/jabref/issues/377)
- We added a search bar for filtering keyboard shortcuts. [#11686](https://github.com/JabRef/jabref/issues/11686)
- By double clicking on a local citation in the Citation Relations Tab you can now jump the linked entry. [#11955](https://github.com/JabRef/jabref/pull/11955)
- Added batch fetching of bibliographic data for multiple entries in the "Lookup" menu. [koppor#372](https://github.com/koppor/jabref/issues/372)
- We use the menu icon for background tasks as a progress indicator to visualise an import's progress when dragging and dropping several PDF files into the main table. [#12072](https://github.com/JabRef/jabref/pull/12072)

### Changed
Expand Down
1 change: 1 addition & 0 deletions src/main/java/org/jabref/gui/actions/StandardActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public enum StandardActions implements Action {
OPEN_URL(Localization.lang("Open URL or DOI"), IconTheme.JabRefIcons.WWW, KeyBinding.OPEN_URL_OR_DOI),
SEARCH_SHORTSCIENCE(Localization.lang("Search ShortScience")),
MERGE_WITH_FETCHED_ENTRY(Localization.lang("Get bibliographic data from %0", "DOI/ISBN/...")),
BATCH_MERGE_WITH_FETCHED_ENTRY(Localization.lang("Get bibliographic data from %0 (fully automated)", "DOI/ISBN/...")),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure, what I written in the last review, but I think, it was about consistency?

Haven't I written MULTI_ be used as prefix?

image

ATTACH_FILE(Localization.lang("Attach file"), IconTheme.JabRefIcons.ATTACH_FILE),
ATTACH_FILE_FROM_URL(Localization.lang("Attach file from URL"), IconTheme.JabRefIcons.DOWNLOAD_FILE),
PRIORITY(Localization.lang("Priority"), IconTheme.JabRefIcons.PRIORITY),
Expand Down
16 changes: 15 additions & 1 deletion src/main/java/org/jabref/gui/frame/MainMenu.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
import org.jabref.gui.linkedfile.RedownloadMissingFilesAction;
import org.jabref.gui.maintable.NewLibraryFromPdfActionOffline;
import org.jabref.gui.maintable.NewLibraryFromPdfActionOnline;
import org.jabref.gui.mergeentries.BatchEntryMergeWithFetchedDataAction;
import org.jabref.gui.mergeentries.MergeEntriesAction;
import org.jabref.gui.mergeentries.MergeWithFetchedEntryAction;
import org.jabref.gui.plaincitationparser.PlainCitationParserAction;
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.gui.preferences.ShowPreferencesAction;
Expand Down Expand Up @@ -273,7 +275,19 @@ private void createMenu() {

new SeparatorMenuItem(),

factory.createMenuItem(StandardActions.FIND_UNLINKED_FILES, new FindUnlinkedFilesAction(dialogService, stateManager))
factory.createMenuItem(StandardActions.FIND_UNLINKED_FILES, new FindUnlinkedFilesAction(dialogService, stateManager)),

new SeparatorMenuItem(),

factory.createMenuItem(
StandardActions.MERGE_WITH_FETCHED_ENTRY,
new MergeWithFetchedEntryAction(dialogService, stateManager, taskExecutor, preferences, undoManager)),

new SeparatorMenuItem(),

factory.createMenuItem(
StandardActions.BATCH_MERGE_WITH_FETCHED_ENTRY,
new BatchEntryMergeWithFetchedDataAction(stateManager, undoManager, preferences, dialogService, taskExecutor))
);

final MenuItem pushToApplicationMenuItem = factory.createMenuItem(pushToApplicationCommand.getAction(), pushToApplicationCommand);
Expand Down
9 changes: 1 addition & 8 deletions src/main/java/org/jabref/gui/maintable/RightClickMenu.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.linkedfile.AttachFileAction;
import org.jabref.gui.linkedfile.AttachFileFromURLAction;
import org.jabref.gui.menus.ChangeEntryTypeMenu;
import org.jabref.gui.mergeentries.MergeEntriesAction;
import org.jabref.gui.mergeentries.MergeWithFetchedEntryAction;
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.gui.preview.CopyCitationAction;
import org.jabref.gui.preview.PreviewPreferences;
Expand Down Expand Up @@ -87,12 +85,7 @@ public static ContextMenu create(BibEntryTableViewModel entry,
extractFileReferencesOffline,

factory.createMenuItem(StandardActions.OPEN_URL, new OpenUrlAction(dialogService, stateManager, preferences)),
factory.createMenuItem(StandardActions.SEARCH_SHORTSCIENCE, new SearchShortScienceAction(dialogService, stateManager, preferences)),

new SeparatorMenuItem(),

new ChangeEntryTypeMenu(libraryTab.getSelectedEntries(), libraryTab.getBibDatabaseContext(), undoManager, entryTypesManager).asSubMenu(),
factory.createMenuItem(StandardActions.MERGE_WITH_FETCHED_ENTRY, new MergeWithFetchedEntryAction(dialogService, stateManager, taskExecutor, preferences, undoManager))
factory.createMenuItem(StandardActions.SEARCH_SHORTSCIENCE, new SearchShortScienceAction(dialogService, stateManager, preferences))
);

EasyBind.subscribe(preferences.getGrobidPreferences().grobidEnabledProperty(), enabled -> {
Expand Down
153 changes: 153 additions & 0 deletions src/main/java/org/jabref/gui/mergeentries/BatchEntryMergeTask.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package org.jabref.gui.mergeentries;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import javax.swing.undo.UndoManager;

import org.jabref.gui.undo.NamedCompound;
import org.jabref.logic.importer.fetcher.MergingIdBasedFetcher;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.BackgroundTask;
import org.jabref.logic.util.NotificationService;
import org.jabref.model.entry.BibEntry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* A background task that handles fetching and merging of bibliography entries.
* This implementation provides improved concurrency handling, better Optional usage,
* and more robust error handling.
*/
public class BatchEntryMergeTask extends BackgroundTask<List<String>> {

private static final Logger LOGGER = LoggerFactory.getLogger(BatchEntryMergeTask.class);
private final MergeContext context;
private final NamedCompound compoundEdit;
private final AtomicInteger processedEntries;
private final AtomicInteger successfulUpdates;

public BatchEntryMergeTask(MergeContext context) {
this.context = context;
this.compoundEdit = new NamedCompound(Localization.lang("Merge entries"));
this.processedEntries = new AtomicInteger(0);
this.successfulUpdates = new AtomicInteger(0);

configureTask();
}

private void configureTask() {
setTitle(Localization.lang("Fetching and merging entries"));
withInitialMessage(Localization.lang("Starting merge operation..."));
showToUser(true);
}

@Override
public List<String> call() throws Exception {
try {
List<String> updatedEntries = processMergeEntries();
finalizeOperation(updatedEntries);
LOGGER.debug("Merge operation completed. Processed: {}, Successfully updated: {}",
processedEntries.get(), successfulUpdates.get());
notifySuccess(successfulUpdates.get());
return updatedEntries;
} catch (Exception e) {
LOGGER.error("Critical error during merge operation", e);
notifyError(e);
throw e;
}
}

private List<String> processMergeEntries() {
return context.entries().stream()
.takeWhile(_ -> !isCancelled())
.map(this::processSingleEntryWithProgress)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}

private Optional<String> processSingleEntryWithProgress(BibEntry entry) {
updateProgress(processedEntries.incrementAndGet(), context.entries().size());
updateMessage(Localization.lang("Processing entry %0 of %1",
processedEntries.get(),
context.entries().size()));
return processSingleEntry(entry);
}

private Optional<String> processSingleEntry(BibEntry entry) {
try {
LOGGER.debug("Processing entry: {}", entry);
return context.fetcher().fetchEntry(entry)
.filter(MergingIdBasedFetcher.FetcherResult::hasChanges)
.flatMap(result -> {
boolean changesApplied = applyMerge(entry, result);
if (changesApplied) {
successfulUpdates.incrementAndGet();
return entry.getCitationKey();
}
return Optional.empty();
});
} catch (Exception e) {
handleEntryProcessingError(entry, e);
return Optional.empty();
}
}

private boolean applyMerge(BibEntry entry, MergingIdBasedFetcher.FetcherResult result) {
synchronized (compoundEdit) {
try {
return MergeEntriesHelper.mergeEntries(result.mergedEntry(), entry, compoundEdit);
} catch (Exception e) {
LOGGER.error("Error during merge operation for entry: {}", entry, e);
return false;
}
}
}

private void handleEntryProcessingError(BibEntry entry, Exception e) {
String citationKey = entry.getCitationKey().orElse("unknown");
String message = Localization.lang("Error processing entry", citationKey, e.getMessage());
LOGGER.error(message, e);
context.notificationService().notify(message);
}

private void finalizeOperation(List<String> updatedEntries) {
if (!updatedEntries.isEmpty()) {
synchronized (compoundEdit) {
compoundEdit.end();
context.undoManager.addEdit(compoundEdit);
}
}
}

private void notifySuccess(int updateCount) {
String message = updateCount == 0
? Localization.lang("No updates found.")
: Localization.lang("Batch update successful. %0 entries updated.", updateCount);
context.notificationService().notify(message);
}

private void notifyError(Exception e) {
context.notificationService().notify(
Localization.lang("Merge operation failed: %0", e.getMessage()));
}

/**
* Record containing all the context needed for the merge operation.
* Implements defensive copying to ensure immutability.
*/
public record MergeContext(
List<BibEntry> entries,
MergingIdBasedFetcher fetcher,
UndoManager undoManager,
NotificationService notificationService
) {
public MergeContext {
entries = List.copyOf(entries); // Defensive copy
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package org.jabref.gui.mergeentries;

import java.util.List;

import javax.swing.undo.UndoManager;

import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.logic.importer.fetcher.MergingIdBasedFetcher;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.NotificationService;
import org.jabref.logic.util.TaskExecutor;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;

/**
* Handles batch merging of bibliography entries with fetched data.
*/
public class BatchEntryMergeWithFetchedDataAction extends SimpleCommand {

private final StateManager stateManager;
private final UndoManager undoManager;
private final GuiPreferences preferences;
private final NotificationService notificationService;
private final TaskExecutor taskExecutor;

public BatchEntryMergeWithFetchedDataAction(StateManager stateManager,
UndoManager undoManager,
GuiPreferences preferences,
NotificationService notificationService,
TaskExecutor taskExecutor) {
this.stateManager = stateManager;
this.undoManager = undoManager;
this.preferences = preferences;
this.notificationService = notificationService;
this.taskExecutor = taskExecutor;

this.executable.bind(ActionHelper.needsDatabase(stateManager));
}

@Override
public void execute() {
if (stateManager.getActiveDatabase().isEmpty()) {
return;
}

List<BibEntry> entries = stateManager.getActiveDatabase()
.map(BibDatabaseContext::getEntries)
.orElse(List.of());

if (entries.isEmpty()) {
notificationService.notify(Localization.lang("No entries available for merging"));
return;
}

MergingIdBasedFetcher fetcher = new MergingIdBasedFetcher(preferences.getImportFormatPreferences());
BatchEntryMergeTask mergeTask = new BatchEntryMergeTask(
new BatchEntryMergeTask.MergeContext(entries,
fetcher,
undoManager,
notificationService));

mergeTask.executeWith(taskExecutor);
}
}
Loading
Loading