Skip to content

Commit

Permalink
Enable Slf4jBestPractices (#11714)
Browse files Browse the repository at this point in the history
* Enable Slf4jBestPractices

* Remove unused imports
  • Loading branch information
koppor authored Sep 7, 2024
1 parent 4e5715c commit e801f41
Show file tree
Hide file tree
Showing 46 changed files with 59 additions and 69 deletions.
3 changes: 3 additions & 0 deletions rewrite.yml
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,6 @@ recipeList:
- org.openrewrite.java.testing.junit5.RemoveTryCatchFailBlocks
- org.openrewrite.java.testing.junit5.LifecycleNonPrivate
- org.openrewrite.java.testing.junit5.StaticImports

# Logging
- org.openrewrite.java.logging.slf4j.Slf4jBestPractices
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/ClipBoardManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public static String getContentsPrimary() {
try {
return (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException e) {
LOGGER.warn(e.getMessage());
LOGGER.warn("", e);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/FallbackExceptionHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static void installExceptionHandler() {

@Override
public void uncaughtException(Thread thread, Throwable exception) {
LOGGER.error("Uncaught exception occurred in " + thread, exception);
LOGGER.error("Uncaught exception occurred in {}", thread, exception);
UiTaskExecutor.runInJavaFXThread(() -> {
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
dialogService.showErrorDialogAndWait("Uncaught exception occurred in " + thread, exception);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/copyfiles/CopyFilesTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

public class CopyFilesTask extends Task<List<CopyFilesResultItemViewModel>> {

private static final Logger LOGGER = LoggerFactory.getLogger(CopyFilesAction.class);
private static final Logger LOGGER = LoggerFactory.getLogger(CopyFilesTask.class);
private static final String LOGFILE_PREFIX = "copyFileslog_";
private static final String LOGFILE_EXT = ".log";
private final BibDatabaseContext databaseContext;
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/desktop/os/NativeDesktop.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public String getHostName() {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
LoggerFactory.getLogger(OS.class).info("Hostname not found. Using \"localhost\" as fallback.", e);
LoggerFactory.getLogger(NativeDesktop.class).info("Hostname not found. Using \"localhost\" as fallback.", e);
hostName = "localhost";
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ private ScrollPane getRelatedArticleInfo(List<BibEntry> list, MrDLibFetcher fetc
try {
JabRefDesktop.openBrowser(entry.getField(StandardField.URL).get(), preferencesService.getFilePreferences());
} catch (IOException e) {
LOGGER.error("Error opening the browser to: " + entry.getField(StandardField.URL).get(), e);
LOGGER.error("Error opening the browser to: {}", entry.getField(StandardField.URL).get(), e);
dialogService.showErrorDialogAndWait(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public void notifyNewSelectedFile(Path newFile) {
try {
fileMonitor.addListenerForFile(currentFile, fileListener);
} catch (IOException e) {
LOGGER.error("Problem while watching file for changes " + currentFile, e);
LOGGER.error("Problem while watching file for changes {}", currentFile, e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ protected Void call() throws Exception {
String.valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors)));

if (!failedWrittenFiles.isEmpty()) {
LOGGER.error("Failed to write XMP data to PDFs:\n" + failedWrittenFiles);
LOGGER.error("Failed to write XMP data to PDFs:\n{}", failedWrittenFiles);
}

return null;
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/org/jabref/gui/icon/IconTheme.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,7 @@ private static Image getImageFX(String name) {
public static URL getIconUrl(String name) {
String key = Objects.requireNonNull(name, "icon name");
if (!KEY_TO_ICON.containsKey(key)) {
LOGGER.warn("Could not find icon url by name " + name + ", so falling back on default icon "
+ DEFAULT_ICON_PATH);
LOGGER.warn("Could not find icon url by name {}, so falling back on default icon {}", name, DEFAULT_ICON_PATH);
}
String path = KEY_TO_ICON.getOrDefault(key, DEFAULT_ICON_PATH);
return Objects.requireNonNull(IconTheme.class.getResource(path), "Path must not be null for key " + key);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private String lookupIdentifiers(List<BibEntry> bibEntries) {
try {
identifier = fetcher.findIdentifier(bibEntry);
} catch (FetcherException e) {
LOGGER.error("Could not fetch " + fetcher.getIdentifierName(), e);
LOGGER.error("Could not fetch {}", fetcher.getIdentifierName(), e);
}
if (identifier.isPresent() && !bibEntry.hasField(identifier.get().getDefaultField())) {
Optional<FieldChange> fieldChange = bibEntry.setField(identifier.get().getDefaultField(), identifier.get().getNormalized());
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/jabref/gui/journals/AbbreviateAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public AbbreviateAction(StandardActions action,
case ABBREVIATE_DEFAULT -> abbreviationType = AbbreviationType.DEFAULT;
case ABBREVIATE_DOTLESS -> abbreviationType = AbbreviationType.DOTLESS;
case ABBREVIATE_SHORTEST_UNIQUE -> abbreviationType = AbbreviationType.SHORTEST_UNIQUE;
default -> LOGGER.debug("Unknown action: " + action.name());
default -> LOGGER.debug("Unknown action: {}", action.name());
}

this.executable.bind(ActionHelper.needsEntriesSelected(stateManager));
Expand All @@ -92,7 +92,7 @@ public void execute() {
.onSuccess(dialogService::notify)
.executeWith(taskExecutor));
} else {
LOGGER.debug("Unknown action: " + action.name());
LOGGER.debug("Unknown action: {}", action.name());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import javafx.beans.property.SimpleDoubleProperty;

import org.jabref.gui.DialogService;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
Expand Down Expand Up @@ -48,7 +47,7 @@

public class DownloadLinkedFileAction extends SimpleCommand {

private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class);
private static final Logger LOGGER = LoggerFactory.getLogger(DownloadLinkedFileAction.class);

private final DialogService dialogService;
private final BibEntry entry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import java.util.Optional;

import org.jabref.gui.DialogService;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.TaskExecutor;
Expand All @@ -21,7 +20,7 @@

public class RedownloadMissingFilesAction extends SimpleCommand {

private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class);
private static final Logger LOGGER = LoggerFactory.getLogger(RedownloadMissingFilesAction.class);

private final StateManager stateManager;
private final DialogService dialogService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
* </ul>
*/
public abstract class NewLibraryFromPdfAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(NewLibraryFromPdfAction .class);
private static final Logger LOGGER = LoggerFactory.getLogger(NewLibraryFromPdfAction.class);

protected final PreferencesService preferencesService;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import javafx.collections.ObservableList;

import org.jabref.gui.DialogService;
import org.jabref.gui.exporter.CreateModifyExporterDialogViewModel;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.preferences.PreferenceTabViewModel;
Expand All @@ -20,7 +19,7 @@

public class ExternalFileTypesTabViewModel implements PreferenceTabViewModel {

private static final Logger LOGGER = LoggerFactory.getLogger(CreateModifyExporterDialogViewModel.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ExternalFileTypesTabViewModel.class);
private final ObservableList<ExternalFileTypeItemViewModel> fileTypes = FXCollections.observableArrayList();

private final FilePreferences filePreferences;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private void setClipBoardContent(List<String> citations) {
case HTML -> content = processHtml(citations);
case TEXT -> content = processText(citations);
default -> {
LOGGER.warn("unknown output format: '" + outputFormat + "', processing it via the default.");
LOGGER.warn("unknown output format: '{}', processing it via the default.", outputFormat);
content = processText(citations);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ private FileNodeViewModel searchDirectory(Path directory) throws IOException {
try (Stream<Path> filesStream = Files.list(directory)) {
fileListPartition = filesStream.collect(Collectors.partitioningBy(path -> path.toFile().isDirectory()));
} catch (IOException e) {
LOGGER.error("%s while searching files: %s".formatted(e.getClass().getName(), e.getMessage()));
LOGGER.error("%s while searching files: %s".formatted(e.getClass().getName(), e.getMessage()), e);
return parent;
}

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/jabref/gui/theme/StyleSheet.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ static Optional<StyleSheet> create(String name) {
try {
styleSheetUrl = Optional.of(Path.of(name).toUri().toURL());
} catch (InvalidPathException e) {
LOGGER.warn("Cannot load additional css {} because it is an invalid path: {}", name, e.getLocalizedMessage());
LOGGER.warn("Cannot load additional css {} because it is an invalid path: {}", name, e.getLocalizedMessage(), e);
} catch (MalformedURLException e) {
LOGGER.warn("Cannot load additional css url {} because it is a malformed url: {}", name, e.getLocalizedMessage());
LOGGER.warn("Cannot load additional css url {} because it is a malformed url: {}", name, e.getLocalizedMessage(), e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
* And it also will store the embeddings.
*/
public class GenerateEmbeddingsForSeveralTask extends BackgroundTask<Void> {
private static final Logger LOGGER = LoggerFactory.getLogger(GenerateEmbeddingsTask.class);
private static final Logger LOGGER = LoggerFactory.getLogger(GenerateEmbeddingsForSeveralTask.class);

private final StringProperty name;
private final List<ProcessingInfo<LinkedFile, Void>> linkedFiles;
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/jabref/logic/bst/BstVMVisitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -273,8 +273,8 @@ public Integer visitStackitem(BstParser.StackitemContext ctx) {
}
} catch (BstVMException e) {
bstVMContext.path().ifPresentOrElse(
path -> LOGGER.error("{} ({})", e.getMessage(), path),
() -> LOGGER.error(e.getMessage()));
path -> LOGGER.error("{} ({})", e.getMessage(), path, e),
() -> LOGGER.error("", e));
throw e;
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/org/jabref/logic/bst/util/BstCaseChanger.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ private String doChangeCase(String s, FormatMode format) {
sb.append(c[i]);
i++;
if (braceLevel == 0) {
LOGGER.warn("Too many closing braces in string: " + s);
LOGGER.warn("Too many closing braces in string: {}", s);
} else {
braceLevel--;
}
Expand All @@ -125,7 +125,7 @@ private String doChangeCase(String s, FormatMode format) {
i++;
}
if (braceLevel > 0) {
LOGGER.warn("No enough closing braces in string: " + s);
LOGGER.warn("No enough closing braces in string: {}", s);
}
return sb.toString();
}
Expand Down Expand Up @@ -204,7 +204,7 @@ private int convertAccented(char[] c, int start, String s, StringBuilder sb, For
}
break;
default:
LOGGER.info("convertAccented - Unknown format: " + format);
LOGGER.info("convertAccented - Unknown format: {}", format);
break;
}
return pos;
Expand All @@ -222,7 +222,7 @@ private int convertNonControl(char[] c, int start, StringBuilder sb, FormatMode
pos++;
}
default ->
LOGGER.info("convertNonControl - Unknown format: " + format);
LOGGER.info("convertNonControl - Unknown format: {}", format);
}
return pos;
}
Expand All @@ -247,7 +247,7 @@ private int convertCharIfBraceLevelIsZero(char[] c, int start, StringBuilder sb,
case ALL_UPPERS ->
sb.append(Character.toUpperCase(c[i]));
default ->
LOGGER.info("convertCharIfBraceLevelIsZero - Unknown format: " + format);
LOGGER.info("convertCharIfBraceLevelIsZero - Unknown format: {}", format);
}
i++;
return i;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,14 +227,14 @@ public static int width(String toMeasure) {
if (braceLevel > 0) {
braceLevel--;
} else {
LOGGER.warn("Too many closing braces in string: " + toMeasure);
LOGGER.warn("Too many closing braces in string: {}", toMeasure);
}
}
result += BstWidthCalculator.getCharWidth(c[i]);
i++;
}
if (braceLevel > 0) {
LOGGER.warn("No enough closing braces in string: " + toMeasure);
LOGGER.warn("No enough closing braces in string: {}", toMeasure);
}
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ static Optional<StyleInfo> parseStyleInfo(String filename, String content) {
return Optional.empty();
}
} catch (XMLStreamException e) {
LOGGER.error("Error parsing XML for file {}: {}", filename, e.getMessage());
LOGGER.error("Error parsing XML for file {}: {}", filename, e.getMessage(), e);
return Optional.empty();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public String format(String text) {
// Find non-covered special characters with alphabetic codes
m = ESCAPED_PATTERN4.matcher(result);
while (m.find()) {
LOGGER.warn("HTML escaped char not converted: " + m.group(1));
LOGGER.warn("HTML escaped char not converted: {}", m.group(1));
}

return result.trim();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public String format(String text) {
for (int i = 0; i <= (result.length() - 1); i++) {
int cp = result.codePointAt(i);
if (cp >= 129) {
LOGGER.warn("Unicode character not converted: " + cp);
LOGGER.warn("Unicode character not converted: {}", cp);
}
}
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ public String getIdentifierName() {
*/
protected class ArXiv implements FulltextFetcher, PagedSearchBasedFetcher, IdBasedFetcher, IdFetcher<ArXivIdentifier> {

private static final Logger LOGGER = LoggerFactory.getLogger(ArXivFetcher.ArXiv.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ArXiv.class);

private static final String API_URL = "https://export.arxiv.org/api/query";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ private Optional<URL> search(String url) throws IOException {
if (!target.isEmpty() && new URLDownload(target).isPdf()) {
// TODO: check title inside pdf + length?
// TODO: report error function needed?! query -> result
LOGGER.info("Fulltext PDF found @ Google: " + target);
LOGGER.info("Fulltext PDF found @ Google: {}", target);
pdfLink = Optional.of(new URL(target));
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,7 @@ public List<BibEntry> performSearch(QueryNode luceneQuery) throws FetcherExcepti
return Collections.emptyList();
}
if (numberOfResultsFound > NUMBER_TO_FETCH) {
LOGGER.info(
numberOfResultsFound + " results found. Only 50 relevant results will be fetched by default.");
LOGGER.info("{} results found. Only 50 relevant results will be fetched by default.", numberOfResultsFound);
}

// pass the list of ids to fetchMedline to download them. like a id fetcher for mutliple ids
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* API is documented at http://unpaywall.org/api/v2
*/
public class OpenAccessDoi implements FulltextFetcher {
private static final Logger LOGGER = LoggerFactory.getLogger(FulltextFetcher.class);
private static final Logger LOGGER = LoggerFactory.getLogger(OpenAccessDoi.class);

private static final String API_URL = "https://api.oadoi.org/v2/";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ private BibEntry parseEntry(Element element) {
List<Element> datafields = getChildren("datafield", element);
for (Element datafield : datafields) {
String tag = datafield.getAttribute("tag");
LOGGER.debug("tag: " + tag);
LOGGER.debug("tag: {}", tag);

if ("020".equals(tag)) {
putIsbn(bibEntry, datafield);
Expand Down Expand Up @@ -146,7 +146,7 @@ private void putIsbn(BibEntry bibEntry, Element datafield) {

int length = isbn.length();
if (length != 10 && length != 13) {
LOGGER.debug("Malformed ISBN recieved, length: " + length);
LOGGER.debug("Malformed ISBN recieved, length: {}", length);
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private String convertToString(BufferedReader input) {
stringBuilder.append(line);
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
LOGGER.error("", e);
}
return stringBuilder.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private BibEntry parseEntry(Element e) {
List<Element> datafields = getChildren("datafield", e);
for (Element datafield : datafields) {
String tag = datafield.getAttribute("tag");
LOGGER.debug("tag: " + tag);
LOGGER.debug("tag: {}", tag);

// genre/type of the entry https://swbtools.bsz-bw.de/cgi-bin/k10plushelp.pl?cmd=kat&val=0500&katalog=Standard
if ("002@".equals(tag)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
*/
public class LatexIntegrityChecker implements EntryChecker {

private static final Logger LOGGER = LoggerFactory.getLogger(SnuggleSession.class);
private static final Logger LOGGER = LoggerFactory.getLogger(LatexIntegrityChecker.class);
private static final SnuggleEngine ENGINE = new SnuggleEngine();
private static final SnuggleSession SESSION;
private static final ResourceBundle ERROR_MESSAGES = ENGINE.getPackages().getFirst().getErrorMessageBundle();
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/logic/l10n/Localization.java
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public static void setLanguage(Language language) {
createResourceBundles(locale);
} catch (MissingResourceException ex) {
// should not happen as we have scripts to enforce this
LoggerFactory.getLogger(Localization.class).warn("Could not find bundles for language " + locale + ", switching to full english language", ex);
LoggerFactory.getLogger(Localization.class).warn("Could not find bundles for language {}, switching to full english language", locale, ex);
setLanguage(Language.ENGLISH);
}
}
Expand Down
Loading

0 comments on commit e801f41

Please sign in to comment.