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

Use environment variables for hostname detection #9910

Merged
merged 7 commits into from
Jun 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -45,6 +45,7 @@ Note that this project **does not** adhere to [Semantic Versioning](http://semve
- `log.txt` now contains an entry if a BibTeX entry could not be parsed.
- `log.txt` now contains debug messages. Debugging needs to be enabled explicitly. [#9678](https://github.com/JabRef/jabref/pull/9678)
- `log.txt` does not contain entries for non-found files during PDF indexing. [#9678](https://github.com/JabRef/jabref/pull/9678)
- The hostname is now determined using environment variables (`COMPUTERNAME`/`HOSTNAME`) first. [#9910](https://github.com/JabRef/jabref/pull/9910)
- We improved the Medline importer to correctly import ISO dates for `revised`. [#9536](https://github.com/JabRef/jabref/issues/9536)
- To avoid cluttering of the directory, We always delete the `.sav` file upon successful write. [#9675](https://github.com/JabRef/jabref/pull/9675)
- We improved the unlinking/deletion of multiple linked files of an entry using the <kbd>Delete</kbd> key. [#9473](https://github.com/JabRef/jabref/issues/9473)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* https://tinylog.org/v2/configuration/
**/
@AllowedToUseAwt("Requires AWT to open a file")
public class DefaultDesktop implements NativeDesktop {
public class DefaultDesktop extends NativeDesktop {

@Override
public void openFile(String filePath, String fileType) throws IOException {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/desktop/os/Linux.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
* https://tinylog.org/v2/configuration/
**/
@AllowedToUseAwt("Requires AWT to open a file with the native method")
public class Linux implements NativeDesktop {
public class Linux extends NativeDesktop {

private static final String ETC_ALTERNATIVES_X_TERMINAL_EMULATOR = "/etc/alternatives/x-terminal-emulator";

Expand Down
64 changes: 49 additions & 15 deletions src/main/java/org/jabref/gui/desktop/os/NativeDesktop.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,62 @@

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.jabref.cli.Launcher;
import org.jabref.gui.DialogService;
import org.jabref.logic.util.BuildInfo;
import org.jabref.logic.util.OS;
import org.jabref.model.pdf.search.SearchFieldConstants;
import org.jabref.model.strings.StringUtil;

import net.harawata.appdirs.AppDirsFactory;

public interface NativeDesktop {

void openFile(String filePath, String fileType) throws IOException;
import org.slf4j.LoggerFactory;

/**
* This class contains bundles OS specific implementations for file directories and file/application open handling methods.
* In case the default does not work, subclasses provide the correct behavior.
*
* <p>
* We cannot use a static logger instance here in this class as the Logger first needs to be configured in the {@link Launcher#addLogToDisk}
* The configuration of tinylog will become immutable as soon as the first log entry is issued.
* https://tinylog.org/v2/configuration/
* </p>
*/
public abstract class NativeDesktop {

public abstract void openFile(String filePath, String fileType) throws IOException;

/**
* Opens a file on an Operating System, using the given application.
*
* @param filePath The filename.
* @param application Link to the app that opens the file.
*/
void openFileWithApplication(String filePath, String application) throws IOException;
public abstract void openFileWithApplication(String filePath, String application) throws IOException;

void openFolderAndSelectFile(Path file) throws IOException;
public abstract void openFolderAndSelectFile(Path file) throws IOException;

void openConsole(String absolutePath, DialogService dialogService) throws IOException;
public abstract void openConsole(String absolutePath, DialogService dialogService) throws IOException;

String detectProgramPath(String programName, String directoryName);
public abstract String detectProgramPath(String programName, String directoryName);

/**
* Returns the path to the system's applications folder.
*
* @return the path to the applications folder.
*/
Path getApplicationDirectory();
public abstract Path getApplicationDirectory();

/**
* Get the user's default file chooser directory
*
* @return The path to the directory
*/
default Path getDefaultFileChooserDirectory() {
public Path getDefaultFileChooserDirectory() {
Path userDirectory = getUserDirectory();
Path documents = userDirectory.resolve("Documents");
if (!Files.exists(documents)) {
Expand All @@ -56,11 +71,11 @@ default Path getDefaultFileChooserDirectory() {
*
* @return the path to the user directory.
*/
default Path getUserDirectory() {
public Path getUserDirectory() {
return Path.of(System.getProperty("user.home"));
}

default Path getLogDirectory() {
public Path getLogDirectory() {
return Path.of(AppDirsFactory.getInstance()
.getUserDataDir(
OS.APP_DIR_APP_NAME,
Expand All @@ -69,25 +84,44 @@ default Path getLogDirectory() {
.resolve(new BuildInfo().version.toString());
}

default Path getBackupDirectory() {
public Path getBackupDirectory() {
return Path.of(AppDirsFactory.getInstance()
.getUserDataDir(
OS.APP_DIR_APP_NAME,
"backups",
OS.APP_DIR_APP_AUTHOR));
}

default Path getFulltextIndexBaseDirectory() {
public Path getFulltextIndexBaseDirectory() {
return Path.of(AppDirsFactory.getInstance()
.getUserDataDir(OS.APP_DIR_APP_NAME,
"lucene" + File.separator + SearchFieldConstants.VERSION,
OS.APP_DIR_APP_AUTHOR));
}

default Path getSslDirectory() {
public Path getSslDirectory() {
return Path.of(AppDirsFactory.getInstance()
.getUserDataDir(OS.APP_DIR_APP_NAME,
"ssl",
OS.APP_DIR_APP_AUTHOR));
}

public String getHostName() {
String hostName;
// Following code inspired by https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/SystemUtils.html#getHostName--
// See also https://stackoverflow.com/a/20793241/873282
hostName = System.getenv("HOSTNAME");
if (StringUtil.isBlank(hostName)) {
hostName = System.getenv("COMPUTERNAME");
}
if (StringUtil.isBlank(hostName)) {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
LoggerFactory.getLogger(OS.class).info("Hostname not found. Using \"localhost\" as fallback.", e);
hostName = "localhost";
}
}
return hostName;
}
}
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/desktop/os/OSX.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* https://tinylog.org/v2/configuration/
**/
@AllowedToUseAwt("Requires AWT to open a file")
public class OSX implements NativeDesktop {
public class OSX extends NativeDesktop {

@Override
public void openFile(String filePath, String fileType) throws IOException {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/desktop/os/Windows.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* The configuration of tinylog will become immutable as soon as the first log entry is issued.
* https://tinylog.org/v2/configuration/
**/
public class Windows implements NativeDesktop {
public class Windows extends NativeDesktop {

private static final String DEFAULT_EXECUTABLE_EXTENSION = ".exe";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public LatexCitationsTabViewModel(BibDatabaseContext databaseContext,
this.preferencesService = preferencesService;
this.taskExecutor = taskExecutor;
this.dialogService = dialogService;
this.directory = new SimpleObjectProperty<>(databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUser())
this.directory = new SimpleObjectProperty<>(databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost())
.orElse(FileUtil.getInitialDirectory(databaseContext, preferencesService.getFilePreferences().getWorkingDirectory())));
this.citationList = FXCollections.observableArrayList();
this.status = new SimpleObjectProperty<>(Status.IN_PROGRESS);
Expand Down Expand Up @@ -130,7 +130,7 @@ private void cancelSearch() {

private Collection<Citation> searchAndParse(String citeKey) throws IOException {
// we need to check whether the user meanwhile set the LaTeX file directory or the database changed locations
Path newDirectory = databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUser())
Path newDirectory = databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost())
.orElse(FileUtil.getInitialDirectory(databaseContext, preferencesService.getFilePreferences().getWorkingDirectory()));

if (latexParserResult == null || !newDirectory.equals(directory.get())) {
Expand Down Expand Up @@ -172,7 +172,7 @@ public void setLatexDirectory() {
.withInitialDirectory(directory.get()).build();

dialogService.showDirectorySelectionDialog(directoryDialogConfiguration).ifPresent(selectedDirectory ->
databaseContext.getMetaData().setLatexFileDirectory(preferencesService.getFilePreferences().getUser(), selectedDirectory.toAbsolutePath()));
databaseContext.getMetaData().setLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost(), selectedDirectory.toAbsolutePath()));

init(currentEntry);
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ private void setupValidation() {
* @return an absolute path if LatexFileDirectory exists; otherwise, returns input
*/
private Path getAbsoluteTexGroupPath(String input) {
Optional<Path> latexFileDirectory = currentDatabase.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUser());
Optional<Path> latexFileDirectory = currentDatabase.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost());
return latexFileDirectory.map(path -> path.resolve(input)).orElse(Path.of(input));
}

Expand Down Expand Up @@ -444,7 +444,7 @@ public void texGroupBrowse() {
.addExtensionFilter(StandardFileType.AUX)
.withDefaultExtension(StandardFileType.AUX)
.withInitialDirectory(currentDatabase.getMetaData()
.getLatexFileDirectory(preferencesService.getFilePreferences().getUser())
.getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost())
.orElse(FileUtil.getInitialDirectory(currentDatabase, preferencesService.getFilePreferences().getWorkingDirectory()))).build();
dialogService.showFileOpenDialog(fileDialogConfiguration)
.ifPresent(file -> texGroupFilePathProperty.setValue(
Expand All @@ -459,7 +459,7 @@ public void openHelpPage() {
private List<Path> getFileDirectoriesAsPaths() {
List<Path> fileDirs = new ArrayList<>();
MetaData metaData = currentDatabase.getMetaData();
metaData.getLatexFileDirectory(preferencesService.getFilePreferences().getUser()).ifPresent(fileDirs::add);
metaData.getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost()).ifPresent(fileDirs::add);

return fileDirs;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public void setValues() {
selectedEncodingProperty.setValue(metaData.getEncoding().orElse(StandardCharsets.UTF_8));
selectedDatabaseModeProperty.setValue(metaData.getMode().orElse(BibDatabaseMode.BIBLATEX));
generalFileDirectoryProperty.setValue(metaData.getDefaultFileDirectory().orElse("").trim());
userSpecificFileDirectoryProperty.setValue(metaData.getUserFileDirectory(preferencesService.getFilePreferences().getUser()).orElse("").trim());
laTexFileDirectoryProperty.setValue(metaData.getLatexFileDirectory(preferencesService.getFilePreferences().getUser()).map(Path::toString).orElse(""));
userSpecificFileDirectoryProperty.setValue(metaData.getUserFileDirectory(preferencesService.getFilePreferences().getUserAndHost()).orElse("").trim());
laTexFileDirectoryProperty.setValue(metaData.getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost()).map(Path::toString).orElse(""));
}

@Override
Expand All @@ -80,16 +80,16 @@ public void storeSettings() {

String userSpecificFileDirectory = userSpecificFileDirectoryProperty.getValue();
if (userSpecificFileDirectory.isEmpty()) {
newMetaData.clearUserFileDirectory(preferencesService.getFilePreferences().getUser());
newMetaData.clearUserFileDirectory(preferencesService.getFilePreferences().getUserAndHost());
} else {
newMetaData.setUserFileDirectory(preferencesService.getFilePreferences().getUser(), userSpecificFileDirectory);
newMetaData.setUserFileDirectory(preferencesService.getFilePreferences().getUserAndHost(), userSpecificFileDirectory);
}

String latexFileDirectory = laTexFileDirectoryProperty.getValue();
if (latexFileDirectory.isEmpty()) {
newMetaData.clearLatexFileDirectory(preferencesService.getFilePreferences().getUser());
newMetaData.clearLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost());
} else {
newMetaData.setLatexFileDirectory(preferencesService.getFilePreferences().getUser(), Path.of(latexFileDirectory));
newMetaData.setLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost(), Path.of(latexFileDirectory));
}

databaseContext.setMetaData(newMetaData);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public ParseLatexDialogViewModel(BibDatabaseContext databaseContext,
this.taskExecutor = taskExecutor;
this.preferencesService = preferencesService;
this.fileMonitor = fileMonitor;
this.latexFileDirectory = new SimpleStringProperty(databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUser())
this.latexFileDirectory = new SimpleStringProperty(databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost())
.orElse(FileUtil.getInitialDirectory(databaseContext, preferencesService.getFilePreferences().getWorkingDirectory()))
.toAbsolutePath().toString());
this.root = new SimpleObjectProperty<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public List<Path> getFileDirectories(FilePreferences preferences) {
List<Path> fileDirs = new ArrayList<>();

// 1. Metadata user-specific directory
metaData.getUserFileDirectory(preferences.getUser())
metaData.getUserFileDirectory(preferences.getUserAndHost())
.ifPresent(userFileDirectory -> fileDirs.add(getFileDirectoryPath(userFileDirectory)));

// 2. Metadata general directory
Expand Down
20 changes: 10 additions & 10 deletions src/main/java/org/jabref/preferences/FilePreferences.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class FilePreferences {

public static final String[] DEFAULT_FILENAME_PATTERNS = new String[] {"[bibtexkey]", "[bibtexkey] - [title]"};

private final StringProperty user = new SimpleStringProperty();
private final StringProperty userAndHost = new SimpleStringProperty();
private final SimpleStringProperty mainFileDirectory = new SimpleStringProperty();
private final BooleanProperty storeFilesRelativeToBibFile = new SimpleBooleanProperty();
private final StringProperty fileNamePattern = new SimpleStringProperty();
Expand All @@ -35,9 +35,9 @@ public class FilePreferences {
private final ObjectProperty<Path> workingDirectory = new SimpleObjectProperty<>();
private final ObservableSet<ExternalFileType> externalFileTypes = FXCollections.observableSet(new TreeSet<>(Comparator.comparing(ExternalFileType::getName)));
private final BooleanProperty createBackup = new SimpleBooleanProperty();
private final ObjectProperty<Path> backupDiretory = new SimpleObjectProperty<>();
private final ObjectProperty<Path> backupDirectory = new SimpleObjectProperty<>();

public FilePreferences(String user,
public FilePreferences(String userAndHost,
Copy link
Member

Choose a reason for hiding this comment

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

Single responsibility? Please use separate variables instead and differentiate between the vars in FilePreferences and InternalPreferences if you want to use it for different purposes.

Copy link
Member Author

Choose a reason for hiding this comment

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

I renamed the variables to match the existing (!!!) content. Separatiin can be done in a follow up PR.

Copy link
Member

@calixtus calixtus May 17, 2023

Choose a reason for hiding this comment

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

In other words, calixtus can do the separation in a follow up pr? 😅

Copy link
Member Author

Choose a reason for hiding this comment

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

The renaming is now in 7025d45 (#9910). I think, the combination is OK, because it is "only" needed for the directory and the stitching together should be done as early as possible.

Nevertheless, some changes will be necessary to prevent restart of JabRef when the owner name is changed. I made a small beginning at cc40eaf (#9910).

Copy link
Member Author

Choose a reason for hiding this comment

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

I think, you are right. Was nevertheless too much work for me now ^^

String mainFileDirectory,
boolean storeFilesRelativeToBibFile,
String fileNamePattern,
Expand All @@ -48,7 +48,7 @@ public FilePreferences(String user,
Set<ExternalFileType> externalFileTypes,
boolean createBackup,
Path backupDirectory) {
this.user.setValue(user);
this.userAndHost.setValue(userAndHost);
this.mainFileDirectory.setValue(mainFileDirectory);
this.storeFilesRelativeToBibFile.setValue(storeFilesRelativeToBibFile);
this.fileNamePattern.setValue(fileNamePattern);
Expand All @@ -58,11 +58,11 @@ public FilePreferences(String user,
this.workingDirectory.setValue(workingDirectory);
this.externalFileTypes.addAll(externalFileTypes);
this.createBackup.setValue(createBackup);
this.backupDiretory.setValue(backupDirectory);
this.backupDirectory.setValue(backupDirectory);
}

public String getUser() {
return user.getValue();
public String getUserAndHost() {
return userAndHost.getValue();
}

public Optional<Path> getMainFileDirectory() {
Expand Down Expand Up @@ -170,14 +170,14 @@ public BooleanProperty createBackupProperty() {
}

public ObjectProperty<Path> backupDirectoryProperty() {
return this.backupDiretory;
return this.backupDirectory;
}

public void setBackupDirectory(Path backupPath) {
this.backupDiretory.set(backupPath);
this.backupDirectory.set(backupPath);
}

public Path getBackupDirectory() {
return this.backupDiretory.getValue();
return this.backupDirectory.getValue();
}
}
10 changes: 5 additions & 5 deletions src/main/java/org/jabref/preferences/InternalPreferences.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,16 @@ public class InternalPreferences {

private final ObjectProperty<Version> ignoredVersion;
private final ObjectProperty<Path> lastPreferencesExportPath;
private final StringProperty user;
private final StringProperty userAndHost;
private final BooleanProperty memoryStickMode;

public InternalPreferences(Version ignoredVersion,
Path exportPath,
String user,
String userAndHost,
boolean memoryStickMode) {
this.ignoredVersion = new SimpleObjectProperty<>(ignoredVersion);
this.lastPreferencesExportPath = new SimpleObjectProperty<>(exportPath);
this.user = new SimpleStringProperty(user);
this.userAndHost = new SimpleStringProperty(userAndHost);
this.memoryStickMode = new SimpleBooleanProperty(memoryStickMode);
}

Expand Down Expand Up @@ -52,8 +52,8 @@ public void setLastPreferencesExportPath(Path lastPreferencesExportPath) {
this.lastPreferencesExportPath.set(lastPreferencesExportPath);
}

public String getUser() {
return user.get();
public String getUserAndHost() {
return userAndHost.get();
}

public boolean isMemoryStickMode() {
Expand Down
Loading