Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/ai-pr-1' into ai-pr-1
Browse files Browse the repository at this point in the history
  • Loading branch information
InAnYan committed Aug 13, 2024
2 parents 85382a1 + d6f9c3d commit bb46869
Show file tree
Hide file tree
Showing 66 changed files with 918 additions and 578 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv

### Changed

- When a communication error with an [online service](https://docs.jabref.org/collect/import-using-online-bibliographic-database) occurs, JabRef displays the HTTP error. [#11223](https://github.com/JabRef/jabref/issues/11223)
- The Pubmed/Medline Plain importer now imports the PMID field as well [#11488](https://github.com/JabRef/jabref/issues/11488)
- The 'Check for updates' menu bar button is now always enabled. [#11485](https://github.com/JabRef/jabref/pull/11485)
- JabRef respects the [configuration for storing files relative to the .bib file](https://docs.jabref.org/finding-sorting-and-cleaning-entries/filelinks#directories-for-files) in more cases. [#11492](https://github.com/JabRef/jabref/pull/11492)
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/org/jabref/cli/ArgumentProcessor.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.jabref.cli;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Expand Down Expand Up @@ -133,7 +134,7 @@ private Optional<ParserResult> importFile(String argument) {
// Download web resource to temporary file
try {
file = new URLDownload(address).toTemporaryFile();
} catch (IOException e) {
} catch (FetcherException | MalformedURLException e) {
System.err.println(Localization.lang("Problem downloading from %1", address) + e.getLocalizedMessage());
return Optional.empty();
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/org/jabref/gui/DialogService.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.importer.FetcherException;

import org.controlsfx.control.textfield.CustomPasswordField;
import org.controlsfx.dialog.ProgressDialog;
Expand Down Expand Up @@ -97,9 +97,9 @@ default <T> Optional<T> showEditableChoiceDialogAndWait(String title, String con
*
* @param exception the exception causing the error
*/
default void showErrorDialogAndWait(Exception exception) {
showErrorDialogAndWait(Localization.lang("Unhandled exception occurred."), exception);
}
void showErrorDialogAndWait(Exception exception);

void showErrorDialogAndWait(FetcherException fetcherException);

/**
* Create and display error dialog displaying the given exception.
Expand Down
41 changes: 41 additions & 0 deletions src/main/java/org/jabref/gui/JabRefDialogService.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.gui.util.UiTaskExecutor;
import org.jabref.gui.util.ZipFileChooser;
import org.jabref.http.dto.SimpleHttpResponse;
import org.jabref.logic.importer.FetcherClientException;
import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.FetcherServerException;
import org.jabref.logic.l10n.Localization;

import com.tobiasdiez.easybind.EasyBind;
Expand Down Expand Up @@ -87,6 +91,7 @@ private FXDialog createDialog(AlertType type, String title, String content) {
alert.setResizable(true);

TextArea area = new TextArea(content);
area.setWrapText(true);

alert.getDialogPane().setContent(area);
alert.initOwner(mainWindow);
Expand Down Expand Up @@ -204,6 +209,42 @@ public void showErrorDialogAndWait(String message, Throwable exception) {
exceptionDialog.showAndWait();
}

@Override
public void showErrorDialogAndWait(Exception exception) {
if (exception instanceof FetcherException fetcherException) {
// Somehow, Java does not route correctly to the other method
showErrorDialogAndWait(fetcherException);
} else {
showErrorDialogAndWait(Localization.lang("Unhandled exception occurred."), exception);
}
}

@Override
public void showErrorDialogAndWait(FetcherException fetcherException) {
String failedTitle = Localization.lang("Failed to download from URL");
String localizedMessage = fetcherException.getLocalizedMessage();
Optional<SimpleHttpResponse> httpResponse = fetcherException.getHttpResponse();
if (httpResponse.isPresent()) {
int statusCode = httpResponse.get().statusCode();
if (statusCode == 401) {
this.showInformationDialogAndWait(failedTitle, Localization.lang("Access denied. You are not authorized to access this resource. Please check your credentials and try again. If you believe you should have access, please contact the administrator for assistance.") + "\n\n" + localizedMessage);
} else if (statusCode == 403) {
this.showInformationDialogAndWait(failedTitle, Localization.lang("Access denied. You do not have permission to access this resource. Please contact the administrator for assistance or try a different action.") + "\n\n" + localizedMessage);
} else if (statusCode == 404) {
this.showInformationDialogAndWait(failedTitle, Localization.lang("The requested resource could not be found. It seems that the file you are trying to download is not available or has been moved. Please verify the URL and try again. If you believe this is an error, please contact the administrator for further assistance.") + "\n\n" + localizedMessage);
} else {
this.showErrorDialogAndWait(failedTitle, Localization.lang("Something is wrong on JabRef side. Please check the URL and try again.") + "\n\n" + localizedMessage);
}
} else if (fetcherException instanceof FetcherClientException) {
this.showErrorDialogAndWait(failedTitle, Localization.lang("Something is wrong on JabRef side. Please check the URL and try again.") + "\n\n" + localizedMessage);
} else if (fetcherException instanceof FetcherServerException) {
this.showInformationDialogAndWait(failedTitle,
Localization.lang("Error downloading from URL. Cause is likely the server side.\nPlease try again later or contact the server administrator.") + "\n\n" + localizedMessage);
} else {
this.showErrorDialogAndWait(failedTitle, localizedMessage);
}
}

@Override
public void showErrorDialogAndWait(String title, String content, Throwable exception) {
ExceptionDialog exceptionDialog = new ExceptionDialog(exception);
Expand Down
30 changes: 14 additions & 16 deletions src/main/java/org/jabref/gui/entryeditor/SciteTabViewModel.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.jabref.gui.entryeditor;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
Expand Down Expand Up @@ -96,25 +95,24 @@ private void cancelSearch() {
}

public SciteTallyModel fetchTallies(DOI doi) throws FetcherException {
URL url;
try {
URL url = new URI(BASE_URL + "tallies/" + doi.getDOI()).toURL();
LOGGER.debug("Fetching tallies from {}", url);
URLDownload download = new URLDownload(url);
String response = download.asString();
LOGGER.debug("Response {}", response);
JSONObject tallies = new JSONObject(response);
if (tallies.has("detail")) {
String message = tallies.getString("detail");
throw new FetcherException(message);
} else if (!tallies.has("total")) {
throw new FetcherException("Unexpected result data.");
}
return SciteTallyModel.fromJSONObject(tallies);
url = new URI(BASE_URL + "tallies/" + doi.getDOI()).toURL();
} catch (MalformedURLException | URISyntaxException ex) {
throw new FetcherException("Malformed URL for DOI", ex);
} catch (IOException ioex) {
throw new FetcherException("Failed to retrieve tallies for DOI - I/O Exception", ioex);
}
LOGGER.debug("Fetching tallies from {}", url);
URLDownload download = new URLDownload(url);
String response = download.asString();
LOGGER.debug("Response {}", response);
JSONObject tallies = new JSONObject(response);
if (tallies.has("detail")) {
String message = tallies.getString("detail");
throw new FetcherException(message);
} else if (!tallies.has("total")) {
throw new FetcherException("Unexpected result data.");
}
return SciteTallyModel.fromJSONObject(tallies);
}

public ObjectProperty<SciteStatus> statusProperty() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package org.jabref.gui.entryeditor.citationrelationtab.semanticscholar;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.List;
Expand Down Expand Up @@ -33,50 +33,55 @@ public String getAPIUrl(String entry_point, BibEntry entry) {

@Override
public List<BibEntry> searchCitedBy(BibEntry entry) throws FetcherException {
if (entry.getDOI().isPresent()) {
try {
URL citationsUrl = URI.create(getAPIUrl("citations", entry)).toURL();
URLDownload urlDownload = new URLDownload(citationsUrl);

String apiKey = getApiKey();
if (!apiKey.isEmpty()) {
urlDownload.addHeader("x-api-key", apiKey);
}
CitationsResponse citationsResponse = new Gson()
.fromJson(urlDownload.asString(), CitationsResponse.class);

return citationsResponse.getData()
.stream().filter(citationDataItem -> citationDataItem.getCitingPaper() != null)
.map(citationDataItem -> citationDataItem.getCitingPaper().toBibEntry()).toList();
} catch (IOException e) {
throw new FetcherException("Could not fetch", e);
}
if (!entry.getDOI().isPresent()) {
return List.of();
}
return List.of();

URL citationsUrl;
try {
citationsUrl = URI.create(getAPIUrl("citations", entry)).toURL();
} catch (MalformedURLException e) {
throw new FetcherException("Malformed URL", e);
}
URLDownload urlDownload = new URLDownload(citationsUrl);

String apiKey = getApiKey();
if (!apiKey.isEmpty()) {
urlDownload.addHeader("x-api-key", apiKey);
}
CitationsResponse citationsResponse = new Gson()
.fromJson(urlDownload.asString(), CitationsResponse.class);

return citationsResponse.getData()
.stream().filter(citationDataItem -> citationDataItem.getCitingPaper() != null)
.map(citationDataItem -> citationDataItem.getCitingPaper().toBibEntry()).toList();
}

@Override
public List<BibEntry> searchCiting(BibEntry entry) throws FetcherException {
if (entry.getDOI().isPresent()) {
try {
URL referencesUrl = URI.create(getAPIUrl("references", entry)).toURL();
URLDownload urlDownload = new URLDownload(referencesUrl);
String apiKey = getApiKey();
if (!apiKey.isEmpty()) {
urlDownload.addHeader("x-api-key", apiKey);
}
ReferencesResponse referencesResponse = new Gson()
.fromJson(urlDownload.asString(), ReferencesResponse.class);

return referencesResponse.getData()
.stream()
.filter(citationDataItem -> citationDataItem.getCitedPaper() != null)
.map(referenceDataItem -> referenceDataItem.getCitedPaper().toBibEntry()).toList();
} catch (IOException e) {
throw new FetcherException("Could not fetch", e);
}
if (!entry.getDOI().isPresent()) {
return List.of();
}
return List.of();

URL referencesUrl;
try {
referencesUrl = URI.create(getAPIUrl("references", entry)).toURL();
} catch (MalformedURLException e) {
throw new FetcherException("Malformed URL", e);
}

URLDownload urlDownload = new URLDownload(referencesUrl);
String apiKey = getApiKey();
if (!apiKey.isEmpty()) {
urlDownload.addHeader("x-api-key", apiKey);
}
ReferencesResponse referencesResponse = new Gson()
.fromJson(urlDownload.asString(), ReferencesResponse.class);

return referencesResponse.getData()
.stream()
.filter(citationDataItem -> citationDataItem.getCitedPaper() != null)
.map(referenceDataItem -> referenceDataItem.getCitedPaper().toBibEntry()).toList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,17 +144,22 @@ public void search() {
}

SearchBasedFetcher activeFetcher = getSelectedFetcher();
Callable<ParserResult> parserResultCallable = () -> new ParserResult(activeFetcher.performSearch(query));

Callable<ParserResult> parserResultCallable;

String fetcherName = activeFetcher.getName();

if (CompositeIdFetcher.containsValidId(query)) {
CompositeIdFetcher compositeIdFetcher = new CompositeIdFetcher(preferencesService.getImportFormatPreferences());
parserResultCallable = () -> new ParserResult(OptionalUtil.toList(compositeIdFetcher.performSearchById(query)));
fetcherName = Localization.lang("Identifier-based Web Search");
} else {
// Exceptions are handled below at "task.onFailure(dialogService::showErrorDialogAndWait)"
parserResultCallable = () -> new ParserResult(activeFetcher.performSearch(query));
}

BackgroundTask<ParserResult> task = BackgroundTask.wrap(parserResultCallable)
.withInitialMessage(Localization.lang("Processing %0", query));
.withInitialMessage(Localization.lang("Processing \"%0\"...", query));
task.onFailure(dialogService::showErrorDialogAndWait);

ImportEntriesDialog dialog = new ImportEntriesDialog(stateManager.getActiveDatabase().get(), task);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.externalfiles.LinkedFileHandler;
import org.jabref.logic.importer.FetcherClientException;
import org.jabref.logic.importer.FetcherServerException;
import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.ProgressInputStream;
import org.jabref.logic.net.URLDownload;
Expand Down Expand Up @@ -199,24 +198,12 @@ private void onSuccess(Path targetDirectory, Path downloadedFile) {

private void onFailure(URLDownload urlDownload, Exception ex) {
LOGGER.error("Error downloading from URL: {}", urlDownload, ex);
String fetcherExceptionMessage = ex.getMessage();
String failedTitle = Localization.lang("Failed to download from URL");
int statusCode;
if (ex instanceof FetcherClientException clientException) {
statusCode = clientException.getStatusCode();
if (statusCode == 401) {
dialogService.showInformationDialogAndWait(failedTitle, Localization.lang("401 Unauthorized: Access Denied. You are not authorized to access this resource. Please check your credentials and try again. If you believe you should have access, please contact the administrator for assistance.\nURL: %0 \n %1", urlDownload.getSource(), fetcherExceptionMessage));
} else if (statusCode == 403) {
dialogService.showInformationDialogAndWait(failedTitle, Localization.lang("403 Forbidden: Access Denied. You do not have permission to access this resource. Please contact the administrator for assistance or try a different action.\nURL: %0 \n %1", urlDownload.getSource(), fetcherExceptionMessage));
} else if (statusCode == 404) {
dialogService.showInformationDialogAndWait(failedTitle, Localization.lang("404 Not Found Error: The requested resource could not be found. It seems that the file you are trying to download is not available or has been moved. Please verify the URL and try again. If you believe this is an error, please contact the administrator for further assistance.\nURL: %0 \n %1", urlDownload.getSource(), fetcherExceptionMessage));
}
} else if (ex instanceof FetcherServerException serverException) {
statusCode = serverException.getStatusCode();
dialogService.showInformationDialogAndWait(failedTitle,
Localization.lang("Error downloading from URL. Cause is likely the server side. HTTP Error %0 \n %1 \nURL: %2 \nPlease try again later or contact the server administrator.", statusCode, fetcherExceptionMessage, urlDownload.getSource()));
if (ex instanceof FetcherException fetcherException) {
dialogService.showErrorDialogAndWait(fetcherException);
} else {
dialogService.showErrorDialogAndWait(failedTitle, Localization.lang("Error message: %0 \nURL: %1 \nPlease check the URL and try again.", fetcherExceptionMessage, urlDownload.getSource()));
String fetcherExceptionMessage = ex.getLocalizedMessage();
String failedTitle = Localization.lang("Failed to download from URL");
dialogService.showErrorDialogAndWait(failedTitle, Localization.lang("Please check the URL and try again.\nURL: %0\nDetails: %1", urlDownload.getSource(), fetcherExceptionMessage));
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/preview/PreviewViewer.java
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ private void update() {
final BibEntry theEntry = entry.get();
BackgroundTask
.wrap(() -> layout.generatePreview(theEntry, database))
.onRunning(() -> setPreviewText("<i>" + Localization.lang("Processing %0", Localization.lang("Citation Style")) + ": " + layout.getDisplayName() + " ..." + "</i>"))
.onRunning(() -> setPreviewText("<i>" + Localization.lang("Processing Citation Style \"%0\"...", layout.getDisplayName()) + "</i>"))
.onSuccess(this::setPreviewText)
.onFailure(exception -> {
LOGGER.error("Error while generating citation style", exception);
Expand Down
Loading

0 comments on commit bb46869

Please sign in to comment.