Skip to content

Fix: Implement Preview Preferences reset and prevent NullPointerException (#14400)#14959

Closed
addix7 wants to merge 0 commit into
JabRef:mainfrom
addix7:main
Closed

Fix: Implement Preview Preferences reset and prevent NullPointerException (#14400)#14959
addix7 wants to merge 0 commit into
JabRef:mainfrom
addix7:main

Conversation

@addix7

@addix7 addix7 commented Jan 30, 2026

Copy link
Copy Markdown

User description

Closes #14400, #14410
Hello Jabref!!,
I am Kalp Pathak, 3rd semester cyberSecurity student. This is my first contribution to the project, and honestly, it was so amazing!

Firstly, since i never used jabref, to understand the problem, i compared it to youtube, I took youtube analogy to understand the problem.

During the initial phases of exploring the codebase, i everytime got a Null pointer exception, and i couldnt understand what wrong i was doing, i tried to implement a new layout, but later realised it was a template,
This is where youtube analogy helped, i realised that , resetting to null was like deleting the profile picture icon, and instead of a default grey picture we all get, i am trying to give nothing, ie null!!
Fix, was to not leave nothing(null), but instead, providing a default icon(again youtube analogy), ie give a Textbased preview layout object, inside which i can sett values to 0 or null.

I had the best time understanding this code,implementing the change, i am determined to learn more, so if you have any suggestions, feedback, please do let me know!,
i need guidance
obsession beats talent :)

Technical Changes:

PreviewPreferences.java: Added a private constructor to return a safe default state and updated setAll() to sync all properties, including the newly merged shouldDownloadCovers setting.

JabRefGuiPreferences.java: Updated the clear() method to utilize the new safe reset logic.

Steps to test
Open JabRef -> Options -> Preferences -> Entry preview.
Click the Reset button at the bottom.
Verification: The app should remain stable, and the layout should revert to default without any console errors or crashes.

Mandatory checks

  • I own the copyright of the code submitted and I license it under the MIT license
  • I manually tested my changes in running JabRef (always required)
  • [/] I added JUnit tests for changes
  • [/] I added screenshots in the PR description
  • I described the change in CHANGELOG.md
  • [/] I checked the [user documentation]

PR Type

Bug fix, Enhancement


Description

  • Implement safe reset for PreviewPreferences to prevent NullPointerException

  • Add private constructor and getDefault() method for safe default state

  • Implement setAll() method to synchronize all preference properties

  • Update JabRefGuiPreferences.clear() to reset preview preferences safely

  • Fix ArrayList initialization in getPreviewLayouts for immutable list handling


Diagram Walkthrough

flowchart LR
  A["Reset Button Clicked"] --> B["JabRefGuiPreferences.clear()"]
  B --> C["getPreviewPreferences().setAll()"]
  C --> D["PreviewPreferences.getDefault()"]
  D --> E["Safe Default State"]
  E --> F["No NullPointerException"]
Loading

File Walkthrough

Relevant files
Bug fix
PreviewPreferences.java
Add safe default state and setAll synchronization               

jabgui/src/main/java/org/jabref/gui/preview/PreviewPreferences.java

  • Added private no-argument constructor to initialize safe default state
  • Added static getDefault() method to return default PreviewPreferences
    instance
  • Implemented setAll() method to synchronize all preference properties
    including shouldDownloadCovers
  • Ensures all properties are properly reset without null values
+30/-0   
JabRefGuiPreferences.java
Integrate preview preferences reset in clear method           

jabgui/src/main/java/org/jabref/gui/preferences/JabRefGuiPreferences.java

  • Added getPreviewPreferences().setAll(PreviewPreferences.getDefault())
    call in clear() method
  • Fixed ArrayList initialization in getPreviewLayouts() to handle
    immutable list from getStringList()
  • Reformatted TextBasedPreviewLayout instantiation for code consistency
  • Ensures preview preferences are properly reset when user clicks Reset
    button
+4/-5     

@github-actions

Copy link
Copy Markdown
Contributor

Hey @addix7! 👋

Thank you for contributing to JabRef!

We have automated checks in place, based on which you will soon get feedback if any of them are failing. We also use Qodo for review assistance. It will update your pull request description with a review help and offer suggestions to improve the pull request.

After all automated checks pass, a maintainer will also review your contribution. Once that happens, you can go through their comments in the "Files changed" tab and act on them, or reply to the conversation if you have further inputs. You can read about the whole pull request process in our contribution guide.

Please ensure that your pull request is in line with our AI Usage Policy and make necessary disclosures.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 30, 2026

Copy link
Copy Markdown
Contributor

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🟡
🎫 #14410
🟢 Enable resetting of PreviewPreferences
Implement a safe reset mechanism for preview preferences
Prevent NullPointerException when resetting preferences
Follow the steps outlined in issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Null parameter handling: The private constructor passes null values for LayoutFormatterPreferences and
JournalAbbreviationRepository to TextBasedPreviewLayout without validation or error
handling.

Referred Code
private PreviewPreferences(){
    this(
            List.of(),
            0,
            new TextBasedPreviewLayout("", null, null),
            "",
            false,
            false,
            List.of(),
            false
    );

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 30, 2026

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent NullPointerException during preference reset

In the PreviewPreferences default constructor, initialize TextBasedPreviewLayout
with valid, non-null dependencies to prevent a NullPointerException during
preference reset.

jabgui/src/main/java/org/jabref/gui/preview/PreviewPreferences.java [50-61]

 private PreviewPreferences(){
     this(
             List.of(),
             0,
-            new TextBasedPreviewLayout("", null, null),
+            new TextBasedPreviewLayout(
+                    "",
+                    org.jabref.preferences.PreferencesService.get().getLayoutFormatterPreferences(),
+                    org.jabref.gui.Injector.instantiateModelOrService(org.jabref.logic.journals.JournalAbbreviationRepository.class)),
             "",
             false,
             false,
             List.of(),
             false
     );
 }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical issue where instantiating TextBasedPreviewLayout with null arguments in the new default constructor will lead to a NullPointerException when a user resets preferences.

High
Learned
best practice
Add null parameter validation

Add null check for the preferences parameter at the beginning of the setAll()
method to prevent NullPointerException when the method is called with null.

jabgui/src/main/java/org/jabref/gui/preview/PreviewPreferences.java [150-160]

 public void setAll(PreviewPreferences preferences){
+    if (preferences == null) {
+        throw new IllegalArgumentException("Preferences must not be null");
+    }
     this.layoutCycle.setAll(preferences.getLayoutCycle());
     this.layoutCyclePosition.set(preferences.getLayoutCyclePosition());
     this.customPreviewLayout.set(preferences.getCustomPreviewLayout());
     this.defaultCustomPreviewLayout.set(preferences.getDefaultCustomPreviewLayout());
     this.showPreviewAsExtraTab.set(preferences.shouldShowPreviewAsExtraTab());
     this.showPreviewEntryTableTooltip.set(preferences.shouldShowPreviewEntryTableTooltip());
     this.bstPreviewLayoutPaths.setAll(preferences.getBstPreviewLayoutPaths());
     this.shouldDownloadCovers.set(preferences.shouldDownloadCovers());
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Add input validation checks to methods that accept external data to ensure parameters are not null before processing, throwing appropriate exceptions when validation fails.

Low
  • Update

@github-actions github-actions Bot added the status: changes-required Pull requests that are not yet complete label Jan 30, 2026
@addix7

addix7 commented Jan 30, 2026

Copy link
Copy Markdown
Author

Hello again !
I have addressed the automated feedback:
Formatting: Reformatted the code using IntelliJ to pass the Checkstyle tests.
Changelog: Added the fix entry to CHANGELOG.md with the proper link format.
Mandatory Checks: Restored the checklist in the PR description.

I'm aware of the 'main branch' warning and will use a dedicated branch for future PRs as suggested. Ready for review!"

@addix7

addix7 commented Jan 30, 2026

Copy link
Copy Markdown
Author

Hello again,
I have completed the reformatting and fixed the compilation issues. The PR is now ready for review. Note: I am aware of the "main" branch warning and will use feature branches for future contributions as suggested by the bot.

@github-actions

github-actions Bot commented Feb 1, 2026

Copy link
Copy Markdown
Contributor

Your pull request conflicts with the target branch.

Please merge with your code. For a step-by-step guide to resolve merge conflicts, see https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/addressing-merge-conflicts/resolving-a-merge-conflict-using-the-command-line.

"\\begin{owncitation}<BR><BR><b>Own citation: </b>\\format[HTMLChars]{\\owncitation} \\end{owncitation}__NEWLINE__" +
"\\begin{comment}<BR><BR><b>Comment: </b>\\format[Markdown,HTMLChars(keepCurlyBraces)]{\\comment}\\end{comment}__NEWLINE__" +
"</font>__NEWLINE__");
defaults.put(PREVIEW_STYLE, "<font face=\"sans-serif\">" + "<b>\\bibtextype</b><a name=\"\\citationkey\">\\begin{citationkey} (\\citationkey)</a>\\end{citationkey}__NEWLINE__" + "\\begin{author}<BR><BR>\\format[Authors(LastFirst, FullName,Sep= / ,LastSep= / ),HTMLChars]{\\author}\\end{author}__NEWLINE__" + "\\begin{editor & !author}<BR><BR>\\format[Authors(LastFirst,FullName,Sep= / ,LastSep= / ),HTMLChars]{\\editor} (\\format[IfPlural(Eds.,Ed.)]{\\editor})\\end{editor & !author}__NEWLINE__" + "\\begin{title}<BR><b>\\format[HTMLChars]{\\title}</b> \\end{title}__NEWLINE__" + "<BR>\\begin{date}\\date\\end{date}\\begin{edition}, \\edition. edition\\end{edition}__NEWLINE__" + "\\begin{editor & author}<BR><BR>\\format[Authors(LastFirst,FullName,Sep= / ,LastSep= / ),HTMLChars]{\\editor} (\\format[IfPlural(Eds.,Ed.)]{\\editor})\\end{editor & author}__NEWLINE__" + "\\begin{booktitle}<BR><i>\\format[HTMLChars]{\\booktitle}</i>\\end{booktitle}__NEWLINE__" + "\\begin{chapter} \\format[HTMLChars]{\\chapter}<BR>\\end{chapter}" + "\\begin{editor & !author}<BR>\\end{editor & !author}\\begin{!editor}<BR>\\end{!editor}\\begin{journal}<BR><i>\\format[HTMLChars]{\\journal}</i> \\end{journal} \\begin{volume}, Vol. \\volume\\end{volume}\\begin{series}<BR>\\format[HTMLChars]{\\series}\\end{series}\\begin{number}, No. \\format[HTMLChars]{\\number}\\end{number}__NEWLINE__" + "\\begin{school} \\format[HTMLChars]{\\school}, \\end{school}__NEWLINE__" + "\\begin{institution} <em>\\format[HTMLChars]{\\institution}, </em>\\end{institution}__NEWLINE__" + "\\begin{publisher}<BR>\\format[HTMLChars]{\\publisher}\\end{publisher}\\begin{location}: \\format[HTMLChars]{\\location} \\end{location}__NEWLINE__" + "\\begin{pages}<BR> p. \\format[FormatPagesForHTML]{\\pages}\\end{pages}__NEWLINE__" + "\\begin{abstract}<BR><BR><b>Abstract: </b>\\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__" + "\\begin{owncitation}<BR><BR><b>Own citation: </b>\\format[HTMLChars]{\\owncitation} \\end{owncitation}__NEWLINE__" + "\\begin{comment}<BR><BR><b>Comment: </b>\\format[Markdown,HTMLChars(keepCurlyBraces)]{\\comment}\\end{comment}__NEWLINE__" + "</font>__NEWLINE__");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Unrelated code change. Strong sign of AI usage. Violating our policy.

@koppor koppor left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please keep the formatting.

@addix7

addix7 commented Feb 2, 2026

Copy link
Copy Markdown
Author

Hello sir, @koppor
I am extremely sorry you felt this way, i admit i used ai but only to understand, this is a new prospect for me and honestly i was overwhelmed, but i assure you, the changes i made, i have knowledge of them, I used ai just to understand the code and the problem,  and i accidentally reformatted the whole code and particularly files- jabguipreferences.java, previewpreferences.java,
My only motive is to understand and help

But I want to assure you that i didnt use ai to reformat code, Instead I used IntelliJ Reformat File and optimise imports , i thought by using this, my code will clear the error
If you could guide, what to do next, I would be extremely grateful

@addix7

addix7 commented Feb 2, 2026

Copy link
Copy Markdown
Author

i have manually undo the reformatting of both the files, but still some problem persists

@koppor

koppor commented Feb 2, 2026

Copy link
Copy Markdown
Member

@addix7 you can just click on "Source Cod Tests / Checkstyle" and read the output

https://github.com/JabRef/jabref/actions/runs/21581094928/job/62178433061?pr=14959

grafik

@github-actions github-actions Bot added status: changes-required Pull requests that are not yet complete and removed status: changes-required Pull requests that are not yet complete labels Feb 2, 2026
@jabref-machine

Copy link
Copy Markdown
Collaborator

You committed your code on the main brach of your fork. This is a bad practice. The right way is to branch out from main, work on your patch/feature in that new branch, and then get that branch merged via the pull request (see GitHub flow).

For this pull request, this is OK. For subsequent pull requests, please start with a different branch with a proper branch name. See CONTRIBUTING.md for more details.

@jabref-machine

Copy link
Copy Markdown
Collaborator

Your code currently does not meet JabRef's code guidelines. IntelliJ auto format covers some cases. There seem to be issues with your code style and autoformat configuration. Please reformat your code (Ctrl+Alt+L) and commit, then push.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement resetting for one preference in JabRefGuiPreferences

3 participants