getURLByDoi(DOI doi) throws IOException, NullPointerException {
return Optional.of(link);
}
+ private Document getPage(URL url) throws IOException {
+ return Jsoup.connect(url.toString())
+ .userAgent(URLDownload.USER_AGENT)
+ .referrer("www.google.com")
+ .ignoreHttpErrors(true)
+ .get();
+ }
+
/**
* Constructs a URL based on the query, size and page number.
- *
* Extract the numerical internal ID and add it to the URL to receive a link to a {@link BibEntry}
+ *
*
* @param luceneQuery the search query.
* @return A URL that lets us download a .bib file
- * @throws URISyntaxException from {@link URIBuilder}'s build() method
- * @throws IOException from {@link Connection}'s get() method
*/
- private Document getPage(QueryNode luceneQuery) throws URISyntaxException, IOException {
+ private static URL getUrlForQuery(QueryNode luceneQuery) throws URISyntaxException, MalformedURLException {
String query = new DefaultQueryTransformer().transformLuceneQuery(luceneQuery).orElse("");
URIBuilder source = new URIBuilder(SEARCH);
source.addParameter("type", "publication");
source.addParameter("query", query);
- return Jsoup.connect(source.build().toString())
- .userAgent(URLDownload.USER_AGENT)
- .referrer("www.google.com")
- .ignoreHttpErrors(true)
- .get();
+ return source.build().toURL();
}
@Override
@@ -206,14 +209,22 @@ public TrustLevel getTrustLevel() {
@Override
public List performSearch(QueryNode luceneQuery) throws FetcherException {
Document html;
+
+ URL url;
try {
- html = getPage(luceneQuery);
+ url = getUrlForQuery(luceneQuery);
+ } catch (URISyntaxException | MalformedURLException e) {
+ throw new FetcherException("Invalid URL", e);
+ }
+
+ try {
+ html = getPage(url);
// ResearchGate's server blocks when too many request are made
if (!html.getElementsByClass("nova-legacy-v-publication-item__title").hasText()) {
- throw new FetcherException("ResearchGate server unavailable");
+ throw new FetcherException(url, "Required HTML element not found", null);
}
- } catch (URISyntaxException | IOException e) {
- throw new FetcherException("URL is not correct", e);
+ } catch (IOException e) {
+ throw new FetcherException(url, e);
}
Elements sol = html.getElementsByClass("nova-legacy-v-publication-item__title");
@@ -234,7 +245,7 @@ public List performSearch(QueryNode luceneQuery) throws FetcherExcepti
entry = parser.parseSingleEntry(bib);
entry.ifPresent(list::add);
} catch (ParseException e) {
- LOGGER.debug("Entry is not convertible to Bibtex", e);
+ LOGGER.debug("Entry is not convertible to BibTeX", e);
}
}
return list;
@@ -245,7 +256,7 @@ private BufferedReader getInputStream(String urlString) {
URL url = new URL(urlString);
return new BufferedReader(new InputStreamReader(url.openStream()));
} catch (IOException e) {
- LOGGER.debug("Wrong URL:", e);
+ LOGGER.debug("Wrong URL", e);
}
return null;
}
diff --git a/src/main/java/org/jabref/logic/importer/fetcher/RfcFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/RfcFetcher.java
index db1df209765..43849ff3319 100644
--- a/src/main/java/org/jabref/logic/importer/fetcher/RfcFetcher.java
+++ b/src/main/java/org/jabref/logic/importer/fetcher/RfcFetcher.java
@@ -7,7 +7,6 @@
import java.util.Optional;
import org.jabref.logic.help.HelpFile;
-import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.IdBasedParserFetcher;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.Parser;
@@ -46,7 +45,7 @@ public Optional getHelpPage() {
* @return the URL of the RFC resource
*/
@Override
- public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException, FetcherException {
+ public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException {
String prefixedIdentifier = identifier.toLowerCase(Locale.ENGLISH);
// if not a "draft" version
if ((!prefixedIdentifier.startsWith(DRAFT_PREFIX)) && (!prefixedIdentifier.startsWith("rfc"))) {
diff --git a/src/main/java/org/jabref/logic/importer/fetcher/ScholarArchiveFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/ScholarArchiveFetcher.java
index 27a5273f45b..3c1521e1861 100644
--- a/src/main/java/org/jabref/logic/importer/fetcher/ScholarArchiveFetcher.java
+++ b/src/main/java/org/jabref/logic/importer/fetcher/ScholarArchiveFetcher.java
@@ -8,7 +8,6 @@
import java.util.Optional;
import java.util.stream.IntStream;
-import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.PagedSearchBasedParserFetcher;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.Parser;
@@ -46,7 +45,7 @@ public class ScholarArchiveFetcher implements PagedSearchBasedParserFetcher {
* @return URL
*/
@Override
- public URL getURLForQuery(QueryNode luceneQuery, int pageNumber) throws URISyntaxException, MalformedURLException, FetcherException {
+ public URL getURLForQuery(QueryNode luceneQuery, int pageNumber) throws URISyntaxException, MalformedURLException {
URIBuilder uriBuilder = new URIBuilder(API_URL);
uriBuilder.addParameter("q", new ScholarArchiveQueryTransformer().transformLuceneQuery(luceneQuery).orElse(""));
uriBuilder.addParameter("from", String.valueOf(getPageSize() * pageNumber));
diff --git a/src/main/java/org/jabref/logic/importer/fetcher/SemanticScholar.java b/src/main/java/org/jabref/logic/importer/fetcher/SemanticScholar.java
index ab993deeeb1..09f8534e6a3 100644
--- a/src/main/java/org/jabref/logic/importer/fetcher/SemanticScholar.java
+++ b/src/main/java/org/jabref/logic/importer/fetcher/SemanticScholar.java
@@ -133,15 +133,16 @@ String getURLBySource(String source) throws IOException, FetcherException {
}
@Override
- public URL getURLForQuery(QueryNode luceneQuery, int pageNumber) throws URISyntaxException, MalformedURLException, FetcherException {
+ public URL getURLForQuery(QueryNode luceneQuery, int pageNumber) throws URISyntaxException, MalformedURLException {
URIBuilder uriBuilder = new URIBuilder(SOURCE_WEB_SEARCH);
uriBuilder.addParameter("query", new DefaultQueryTransformer().transformLuceneQuery(luceneQuery).orElse(""));
uriBuilder.addParameter("offset", String.valueOf(pageNumber * getPageSize()));
uriBuilder.addParameter("limit", String.valueOf(Math.min(getPageSize(), 10000 - pageNumber * getPageSize())));
// All fields need to be specified
uriBuilder.addParameter("fields", "paperId,externalIds,url,title,abstract,venue,year,authors");
- LOGGER.debug("URL for query: {}", uriBuilder.build().toURL());
- return uriBuilder.build().toURL();
+ URL result = uriBuilder.build().toURL();
+ LOGGER.debug("URL for query: {}", result);
+ return result;
}
/**
diff --git a/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java
index b271b113c39..33be2ee890e 100644
--- a/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java
+++ b/src/main/java/org/jabref/logic/importer/fetcher/SpringerFetcher.java
@@ -11,7 +11,6 @@
import java.util.stream.Collectors;
import org.jabref.logic.help.HelpFile;
-import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ImporterPreferences;
import org.jabref.logic.importer.PagedSearchBasedParserFetcher;
import org.jabref.logic.importer.Parser;
@@ -185,8 +184,7 @@ public String getTestUrl() {
* @return URL
*/
@Override
- public URL getURLForQuery(QueryNode luceneQuery, int pageNumber) throws URISyntaxException, MalformedURLException, FetcherException {
-
+ public URL getURLForQuery(QueryNode luceneQuery, int pageNumber) throws URISyntaxException, MalformedURLException {
URIBuilder uriBuilder = new URIBuilder(API_URL);
uriBuilder.addParameter("q", new SpringerQueryTransformer().transformLuceneQuery(luceneQuery).orElse("")); // Search query
uriBuilder.addParameter("api_key", importerPreferences.getApiKey(getName()).orElse(API_KEY)); // API key
diff --git a/src/main/java/org/jabref/logic/importer/fetcher/ZbMATH.java b/src/main/java/org/jabref/logic/importer/fetcher/ZbMATH.java
index 8f88bdf0675..b02c19d9025 100644
--- a/src/main/java/org/jabref/logic/importer/fetcher/ZbMATH.java
+++ b/src/main/java/org/jabref/logic/importer/fetcher/ZbMATH.java
@@ -104,7 +104,7 @@ public URL getURLForEntry(BibEntry entry) throws URISyntaxException, MalformedUR
}
@Override
- public URL getURLForQuery(QueryNode luceneQuery) throws URISyntaxException, MalformedURLException, FetcherException {
+ public URL getURLForQuery(QueryNode luceneQuery) throws URISyntaxException, MalformedURLException {
URIBuilder uriBuilder = new URIBuilder("https://zbmath.org/bibtexoutput/");
uriBuilder.addParameter("q", new ZbMathQueryTransformer().transformLuceneQuery(luceneQuery).orElse("")); // search all fields
uriBuilder.addParameter("start", "0"); // start index
@@ -113,7 +113,7 @@ public URL getURLForQuery(QueryNode luceneQuery) throws URISyntaxException, Malf
}
@Override
- public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException, FetcherException {
+ public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException {
URIBuilder uriBuilder = new URIBuilder("https://zbmath.org/bibtexoutput/");
String query = "an:".concat(identifier); // use an: to search for a zbMATH identifier
uriBuilder.addParameter("q", query);
diff --git a/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/DoiToBibtexConverterComIsbnFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/DoiToBibtexConverterComIsbnFetcher.java
index 1ebc813c7bc..66bd0235ee6 100644
--- a/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/DoiToBibtexConverterComIsbnFetcher.java
+++ b/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/DoiToBibtexConverterComIsbnFetcher.java
@@ -8,7 +8,6 @@
import java.util.stream.IntStream;
import java.util.stream.Stream;
-import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.Parser;
@@ -40,7 +39,7 @@ public String getName() {
}
@Override
- public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException, FetcherException {
+ public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException {
this.ensureThatIsbnIsValid(identifier);
return new URIBuilder(BASE_URL)
.setPathSegments("getInfo.php")
diff --git a/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/EbookDeIsbnFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/EbookDeIsbnFetcher.java
index 42effb2bf05..f55ba6eaa76 100644
--- a/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/EbookDeIsbnFetcher.java
+++ b/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/EbookDeIsbnFetcher.java
@@ -7,7 +7,6 @@
import org.jabref.logic.cleanup.FieldFormatterCleanup;
import org.jabref.logic.formatter.bibtexfields.NormalizeNamesFormatter;
import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter;
-import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.fetcher.AbstractIsbnFetcher;
import org.jabref.model.entry.BibEntry;
@@ -31,7 +30,7 @@ public String getName() {
}
@Override
- public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException, FetcherException {
+ public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException {
this.ensureThatIsbnIsValid(identifier);
return new URIBuilder(BASE_URL)
.addParameter("isbn", identifier)
diff --git a/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcher.java b/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcher.java
index 3283a169cf8..cb8e7267d77 100644
--- a/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcher.java
+++ b/src/main/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcher.java
@@ -11,7 +11,6 @@
import java.util.stream.Stream;
import org.jabref.logic.importer.AuthorListParser;
-import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.Parser;
@@ -53,7 +52,7 @@ public String getName() {
}
@Override
- public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException, FetcherException {
+ public URL getUrlForIdentifier(String identifier) throws URISyntaxException, MalformedURLException {
this.ensureThatIsbnIsValid(identifier);
return new URIBuilder(BASE_URL)
.setPathSegments("isbn", identifier + ".json")
diff --git a/src/main/java/org/jabref/logic/importer/fileformat/ACMPortalParser.java b/src/main/java/org/jabref/logic/importer/fileformat/ACMPortalParser.java
index fb60e4a92f4..e1eef008b2c 100644
--- a/src/main/java/org/jabref/logic/importer/fileformat/ACMPortalParser.java
+++ b/src/main/java/org/jabref/logic/importer/fileformat/ACMPortalParser.java
@@ -83,16 +83,16 @@ public List parseDoiSearchPage(InputStream stream) throws ParseException
return doiList;
}
- /**
- * Obtain BibEntry according to DOI
- *
- * @param doiList DOI List
- * @return BibEntry List
- */
public List getBibEntriesFromDoiList(List doiList) throws FetcherException {
List bibEntries = new ArrayList<>();
CookieHandler.setDefault(new CookieManager());
- try (InputStream stream = new URLDownload(getUrlFromDoiList(doiList)).asInputStream()) {
+ URL urlFromDoiList;
+ try {
+ urlFromDoiList = getUrlFromDoiList(doiList);
+ } catch (URISyntaxException | MalformedURLException e) {
+ throw new FetcherException("Wrong URL", e);
+ }
+ try (InputStream stream = new URLDownload(urlFromDoiList).asInputStream()) {
String jsonString = new String((stream.readAllBytes()), StandardCharsets.UTF_8);
JsonElement jsonElement = JsonParser.parseString(jsonString);
@@ -104,8 +104,8 @@ public List getBibEntriesFromDoiList(List doiList) throws Fetc
}
}
}
- } catch (IOException | URISyntaxException e) {
- throw new FetcherException("A network error occurred while fetching from ", e);
+ } catch (IOException e) {
+ throw new FetcherException(urlFromDoiList, e);
}
return bibEntries;
diff --git a/src/main/java/org/jabref/logic/importer/util/ShortDOIService.java b/src/main/java/org/jabref/logic/importer/util/ShortDOIService.java
index f10996f9b4f..e9c6446fc19 100644
--- a/src/main/java/org/jabref/logic/importer/util/ShortDOIService.java
+++ b/src/main/java/org/jabref/logic/importer/util/ShortDOIService.java
@@ -1,11 +1,11 @@
package org.jabref.logic.importer.util;
-import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
+import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.net.URLDownload;
import org.jabref.model.entry.identifier.DOI;
@@ -36,8 +36,8 @@ public DOI getShortDOI(DOI doi) throws ShortDOIServiceException {
private JSONObject makeRequest(DOI doi) throws ShortDOIServiceException {
- URIBuilder uriBuilder = null;
- URL url = null;
+ URIBuilder uriBuilder;
+ URL url;
try {
uriBuilder = new URIBuilder(BASIC_URL);
@@ -58,7 +58,7 @@ private JSONObject makeRequest(DOI doi) throws ShortDOIServiceException {
throw new ShortDOIServiceException("Cannot get short DOI");
}
return resultAsJSON;
- } catch (ParseException | IOException | JSONException e) {
+ } catch (ParseException | JSONException | FetcherException e) {
throw new ShortDOIServiceException("Cannot get short DOI", e);
}
}
diff --git a/src/main/java/org/jabref/logic/net/URLDownload.java b/src/main/java/org/jabref/logic/net/URLDownload.java
index 19d4d2e4bc1..db9e3b4d9f7 100644
--- a/src/main/java/org/jabref/logic/net/URLDownload.java
+++ b/src/main/java/org/jabref/logic/net/URLDownload.java
@@ -2,7 +2,6 @@
import java.io.BufferedInputStream;
import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -40,7 +39,9 @@
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
+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.util.io.FileUtil;
@@ -240,7 +241,7 @@ public void setPostData(String postData) {
*
* @return the downloaded string
*/
- public String asString() throws IOException {
+ public String asString() throws FetcherException {
return asString(StandardCharsets.UTF_8, this.openConnection());
}
@@ -250,7 +251,7 @@ public String asString() throws IOException {
* @param encoding the desired String encoding
* @return the downloaded string
*/
- public String asString(Charset encoding) throws IOException {
+ public String asString(Charset encoding) throws FetcherException {
return asString(encoding, this.openConnection());
}
@@ -260,7 +261,7 @@ public String asString(Charset encoding) throws IOException {
* @param existingConnection an existing connection
* @return the downloaded string
*/
- public static String asString(URLConnection existingConnection) throws IOException {
+ public static String asString(URLConnection existingConnection) throws FetcherException {
return asString(StandardCharsets.UTF_8, existingConnection);
}
@@ -271,16 +272,17 @@ public static String asString(URLConnection existingConnection) throws IOExcepti
* @param connection an existing connection
* @return the downloaded string
*/
- public static String asString(Charset encoding, URLConnection connection) throws IOException {
-
+ public static String asString(Charset encoding, URLConnection connection) throws FetcherException {
try (InputStream input = new BufferedInputStream(connection.getInputStream());
Writer output = new StringWriter()) {
copy(input, output, encoding);
return output.toString();
+ } catch (IOException e) {
+ throw new FetcherException("Error downloading", e);
}
}
- public List getCookieFromUrl() throws IOException {
+ public List getCookieFromUrl() throws FetcherException {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
@@ -301,27 +303,41 @@ public List getCookieFromUrl() throws IOException {
*
* @param destination the destination file path.
*/
- public void toFile(Path destination) throws IOException {
+ public void toFile(Path destination) throws FetcherException {
try (InputStream input = new BufferedInputStream(this.openConnection().getInputStream())) {
Files.copy(input, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOGGER.warn("Could not copy input", e);
- throw e;
+ throw new FetcherException("Could not copy input", e);
}
}
/**
* Takes the web resource as the source for a monitored input stream.
*/
- public ProgressInputStream asInputStream() throws IOException {
+ public ProgressInputStream asInputStream() throws FetcherException {
HttpURLConnection urlConnection = (HttpURLConnection) this.openConnection();
- if ((urlConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) || (urlConnection.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST)) {
- LOGGER.error("Response message {} returned for url {}", urlConnection.getResponseMessage(), urlConnection.getURL());
- return new ProgressInputStream(new ByteArrayInputStream(new byte[0]), 0);
+ int responseCode;
+ try {
+ responseCode = urlConnection.getResponseCode();
+ } catch (IOException e) {
+ throw new FetcherException("Error getting response code", e);
+ }
+ LOGGER.debug("Response code: {}", responseCode); // We could check for != 200, != 204
+ if (responseCode >= 300) {
+ SimpleHttpResponse simpleHttpResponse = new SimpleHttpResponse(urlConnection);
+ LOGGER.error("Failed to read from url: {}", simpleHttpResponse);
+ throw FetcherException.of(this.source, simpleHttpResponse);
}
long fileSize = urlConnection.getContentLengthLong();
- return new ProgressInputStream(new BufferedInputStream(urlConnection.getInputStream()), fileSize);
+ InputStream inputStream;
+ try {
+ inputStream = urlConnection.getInputStream();
+ } catch (IOException e) {
+ throw new FetcherException("Error getting input stream", e);
+ }
+ return new ProgressInputStream(new BufferedInputStream(inputStream), fileSize);
}
/**
@@ -329,7 +345,7 @@ public ProgressInputStream asInputStream() throws IOException {
*
* @return the path of the temporary file.
*/
- public Path toTemporaryFile() throws IOException {
+ public Path toTemporaryFile() throws FetcherException {
// Determine file name and extension from source url
String sourcePath = source.getPath();
@@ -339,7 +355,12 @@ public Path toTemporaryFile() throws IOException {
String extension = "." + FileUtil.getFileExtension(fileNameWithExtension).orElse("tmp");
// Create temporary file and download to it
- Path file = Files.createTempFile(fileName, extension);
+ Path file = null;
+ try {
+ file = Files.createTempFile(fileName, extension);
+ } catch (IOException e) {
+ throw new FetcherException("Could not create temporary file", e);
+ }
file.toFile().deleteOnExit();
toFile(file);
@@ -363,44 +384,65 @@ private static void copy(InputStream in, Writer out, Charset encoding) throws IO
}
/**
- * Open a connection to this object's URL (with specified settings). If accessing an HTTP URL, don't forget
- * to close the resulting connection after usage.
+ * Open a connection to this object's URL (with specified settings).
+ *
+ * If accessing an HTTP URL, remeber to close the resulting connection after usage.
*
* @return an open connection
*/
- public URLConnection openConnection() throws IOException {
- URLConnection connection = this.source.openConnection();
- connection.setConnectTimeout((int) connectTimeout.toMillis());
- for (Entry entry : this.parameters.entrySet()) {
- connection.setRequestProperty(entry.getKey(), entry.getValue());
- }
- if (!this.postData.isEmpty()) {
- connection.setDoOutput(true);
- try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
- wr.writeBytes(this.postData);
- }
+ public URLConnection openConnection() throws FetcherException {
+ URLConnection connection;
+ try {
+ connection = getUrlConnection();
+ } catch (IOException e) {
+ throw new FetcherException("Error opening connection", e);
}
- if (connection instanceof HttpURLConnection lConnection) {
- // this does network i/o: GET + read returned headers
- int status = lConnection.getResponseCode();
+ if (connection instanceof HttpURLConnection httpURLConnection) {
+ int status;
+ try {
+ // this does network i/o: GET + read returned headers
+ status = httpURLConnection.getResponseCode();
+ } catch (IOException e) {
+ LOGGER.error("Error getting response code", e);
+ throw new FetcherException("Error getting response code", e);
+ }
- // normally, 3xx is redirect
if ((status == HttpURLConnection.HTTP_MOVED_TEMP)
|| (status == HttpURLConnection.HTTP_MOVED_PERM)
|| (status == HttpURLConnection.HTTP_SEE_OTHER)) {
// get redirect url from "location" header field
String newUrl = connection.getHeaderField("location");
// open the new connection again
- connection = new URLDownload(newUrl).openConnection();
+ try {
+ connection = new URLDownload(newUrl).openConnection();
+ } catch (MalformedURLException e) {
+ throw new FetcherException("Could not open URL Download", e);
+ }
+ } else if (status >= 400) {
+ // in case of an error, propagate the error message
+ SimpleHttpResponse httpResponse = new SimpleHttpResponse(httpURLConnection);
+ LOGGER.info("{}", httpResponse);
+ if ((status >= 400) && (status < 500)) {
+ throw new FetcherClientException(this.source, httpResponse);
+ } else if (status >= 500) {
+ throw new FetcherServerException(this.source, httpResponse);
+ }
}
- if ((status >= 400) && (status < 500)) {
- LOGGER.info("HTTP {}, details: {}, {}", status, lConnection.getResponseMessage(), lConnection.getContentLength() > 0 ? lConnection.getContent() : "");
- throw new IOException(new FetcherClientException("Encountered HTTP %s %s".formatted(status, lConnection.getResponseMessage())));
- }
- if (status >= 500) {
- LOGGER.info("HTTP {}, details: {}, {}", status, lConnection.getResponseMessage(), lConnection.getContentLength() > 0 ? lConnection.getContent() : "");
- throw new IOException(new FetcherServerException("Encountered HTTP %s %s".formatted(status, lConnection.getResponseMessage())));
+ }
+ return connection;
+ }
+
+ private URLConnection getUrlConnection() throws IOException {
+ URLConnection connection = this.source.openConnection();
+ connection.setConnectTimeout((int) connectTimeout.toMillis());
+ for (Entry entry : this.parameters.entrySet()) {
+ connection.setRequestProperty(entry.getKey(), entry.getValue());
+ }
+ if (!this.postData.isEmpty()) {
+ connection.setDoOutput(true);
+ try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
+ wr.writeBytes(this.postData);
}
}
return connection;
diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties
index f32e815d31c..9f1c5fa38ef 100644
--- a/src/main/resources/l10n/JabRef_en.properties
+++ b/src/main/resources/l10n/JabRef_en.properties
@@ -329,8 +329,14 @@ Extract\ references\ from\ file\ (offline)=Extract references from file (offline
Extract\ references\ from\ file\ (online)=Extract references from file (online)
Extract\ References\ (offline)=Extract References (offline)
Extract\ References\ (online)=Extract References (online)
+
+Processing...=Processing...
+Processing\ "%0"...=Processing "%0"...
+Processing\ Citation\ Style\ "%0"...=Processing Citation Style "%0"...
Processing\ PDF(s)=Processing PDF(s)
+Processing\ file\ %0=Processing file %0
Processing\ a\ large\ number\ of\ files=Processing a large number of files
+
You\ are\ about\ to\ process\ %0\ files.\ Continue?=You are about to process %0 files. Continue?
Will\ write\ metadata\ to\ the\ PDFs\ linked\ from\ selected\ entries.=Will write metadata to the PDFs linked from selected entries.
@@ -691,7 +697,6 @@ Preferences=Preferences
Preferences\ recorded.=Preferences recorded.
Preview=Preview
-Citation\ Style=Citation Style
Current\ Preview=Current Preview
Add\ BST\ file=Add BST file
@@ -707,7 +712,6 @@ Selected\ Layouts\ can\ not\ be\ empty=Selected Layouts can not be empty
Reset\ default\ preview\ style=Reset default preview style
Previous\ entry=Previous entry
Problem\ with\ parsing\ entry=Problem with parsing entry
-Processing\ %0=Processing %0
Pull\ changes\ from\ shared\ database=Pull changes from shared database
Pushed\ citations\ to\ %0=Pushed citations to %0
@@ -1841,7 +1845,6 @@ Fetcher\ '%0'\ did\ not\ find\ an\ entry\ for\ id\ '%1'.=Fetcher '%0' did not fi
Select\ first\ entry=Select first entry
Select\ last\ entry=Select last entry
-Invalid\ ISBN\:\ '%0'.=Invalid ISBN: '%0'.
should\ be\ an\ integer\ or\ normalized=should be an integer or normalized
should\ be\ normalized=should be normalized
@@ -1917,7 +1920,6 @@ Removes\ all\ line\ breaks\ in\ the\ field\ content.=Removes all line breaks in
Remove\ hyphenated\ line\ breaks=Remove hyphenated line breaks
Removes\ all\ hyphenated\ line\ breaks\ in\ the\ field\ content.=Removes all hyphenated line breaks in the field content.
-Could\ not\ retrieve\ entry\ data\ from\ '%0'.=Could not retrieve entry data from '%0'.
Entry\ from\ %0\ could\ not\ be\ parsed.=Entry from %0 could not be parsed.
Invalid\ identifier\:\ '%0'.=Invalid identifier: '%0'.
empty\ citation\ key=empty citation key
@@ -2383,7 +2385,6 @@ Error\ reading\ PDF\ content\:\ %0=Error reading PDF content\: %0
Bib\ entry\ was\ successfully\ imported=Bib entry was successfully imported
File\ was\ successfully\ imported\ as\ a\ new\ entry=File was successfully imported as a new entry
No\ BibTeX\ data\ was\ found.\ An\ empty\ entry\ was\ created\ with\ file\ link.=No BibTeX data was found. An empty entry was created with file link.
-Processing\ file\ %0=Processing file %0
Export\ selected=Export selected
Separate\ merged\ citations=Separate merged citations
@@ -2709,16 +2710,16 @@ File\ "%0"\ cannot\ be\ added\!=File "%0" cannot be added!
Illegal\ characters\ in\ the\ file\ name\ detected.\nFile\ will\ be\ renamed\ to\ "%0"\ and\ added.=Illegal characters in the file name detected.\nFile will be renamed to "%0" and added.
Rename\ and\ add=Rename and add
-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=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
-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=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
-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=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
-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.=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.
-Error\ message\:\ %0\ \nURL\:\ %1\ \nPlease\ check\ the\ URL\ and\ try\ again.=Error message: %0 \nURL: %1 \nPlease check the URL and try again.
Failed\ to\ download\ from\ URL=Failed to download from URL
+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.=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.
+Access\ denied.\ You\ do\ not\ have\ permission\ to\ access\ this\ resource.\ Please\ contact\ the\ administrator\ for\ assistance\ or\ try\ a\ different\ action.=Access denied. You do not have permission to access this resource. Please contact the administrator for assistance or try a different action.
+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.=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.
+Something\ is\ wrong\ on\ JabRef\ side.\ Please\ check\ the\ URL\ and\ try\ again.=Something is wrong on JabRef side. Please check the URL and try again.
+Error\ downloading\ from\ URL.\ Cause\ is\ likely\ the\ server\ side.\nPlease\ try\ again\ later\ or\ contact\ the\ server\ administrator.=Error downloading from URL. Cause is likely the server side.\nPlease try again later or contact the server administrator.
+Please\ check\ the\ URL\ and\ try\ again.\nURL\:\ %0\nDetails\:\ %1=Please check the URL and try again.\nURL: %0\nDetails: %1
Finished=Finished
Finished\ writing\ metadata\ for\ library\ %0\ (%1\ succeeded,\ %2\ skipped,\ %3\ errors).=Finished writing metadata for library %0 (%1 succeeded, %2 skipped, %3 errors).
-Processing...=Processing...
Writing\ metadata\ to\ %0=Writing metadata to %0
Get\ more\ themes...=Get more themes...
diff --git a/src/test/java/org/jabref/logic/importer/fetcher/GoogleScholarTest.java b/src/test/java/org/jabref/logic/importer/fetcher/GoogleScholarTest.java
index 4432e20a19b..a3a96315a11 100644
--- a/src/test/java/org/jabref/logic/importer/fetcher/GoogleScholarTest.java
+++ b/src/test/java/org/jabref/logic/importer/fetcher/GoogleScholarTest.java
@@ -38,7 +38,7 @@ void setUp() {
}
@Test
- void linkFound() throws IOException, FetcherException {
+ void linkFound() throws Exception {
entry.setField(StandardField.TITLE, "Towards Application Portability in Platform as a Service");
assertEquals(
diff --git a/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java b/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java
index 5fdccc287c6..8ccc6f6f1af 100644
--- a/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java
+++ b/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java
@@ -56,7 +56,7 @@ void fullTextNotFoundByDOI() throws IOException, FetcherException {
}
@Test
- void getDocumentByTitle() throws IOException, NullPointerException {
+ void getDocumentByTitle() throws Exception {
Optional source = fetcher.getURLByString(entry.getTitle().get());
assertTrue(source.isPresent() && source.get().startsWith(URL_PAGE));
}
diff --git a/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java b/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java
index fc1672af602..d9f641ab855 100644
--- a/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java
+++ b/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java
@@ -1,6 +1,5 @@
package org.jabref.logic.importer.fileformat;
-import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.MalformedURLException;
@@ -11,7 +10,6 @@
import java.util.Optional;
import org.jabref.logic.importer.FetcherException;
-import org.jabref.logic.importer.ParseException;
import org.jabref.logic.net.URLDownload;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
@@ -69,7 +67,7 @@ void setUp() throws URISyntaxException, MalformedURLException {
}
@Test
- void parseEntries() throws IOException, ParseException {
+ void parseEntries() throws Exception {
CookieHandler.setDefault(new CookieManager());
List bibEntries = parser.parseEntries(new URLDownload(searchUrl).asInputStream());
for (BibEntry bibEntry : bibEntries) {
@@ -79,7 +77,7 @@ void parseEntries() throws IOException, ParseException {
}
@Test
- void parseDoiSearchPage() throws ParseException, IOException {
+ void parseDoiSearchPage() throws Exception {
String testDoi = "10.1145/3129790.3129810";
CookieHandler.setDefault(new CookieManager());
List doiList = parser.parseDoiSearchPage(new URLDownload(searchUrl).asInputStream());
@@ -139,7 +137,7 @@ void parseBibEntryWithFamilyAuthorOnly() {
}
@Test
- void noEntryFound() throws URISyntaxException, IOException, ParseException {
+ void noEntryFound() throws Exception {
CookieHandler.setDefault(new CookieManager());
URL url = new URIBuilder("https://dl.acm.org/action/doSearch?AllField=10.1145/3129790.31298").build().toURL();
List bibEntries = parser.parseEntries(new URLDownload(url).asInputStream());
diff --git a/src/test/java/org/jabref/logic/net/URLDownloadTest.java b/src/test/java/org/jabref/logic/net/URLDownloadTest.java
index 926d5c67c38..38b0846d8a5 100644
--- a/src/test/java/org/jabref/logic/net/URLDownloadTest.java
+++ b/src/test/java/org/jabref/logic/net/URLDownloadTest.java
@@ -1,7 +1,6 @@
package org.jabref.logic.net;
import java.io.File;
-import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@@ -17,7 +16,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -28,21 +26,21 @@ public class URLDownloadTest {
private static final Logger LOGGER = LoggerFactory.getLogger(URLDownloadTest.class);
@Test
- public void stringDownloadWithSetEncoding() throws IOException {
+ public void stringDownloadWithSetEncoding() throws Exception {
URLDownload dl = new URLDownload(new URL("http://www.google.com"));
assertTrue(dl.asString().contains("Google"), "google.com should contain google");
}
@Test
- public void stringDownload() throws IOException {
+ public void stringDownload() throws Exception {
URLDownload dl = new URLDownload(new URL("http://www.google.com"));
assertTrue(dl.asString(StandardCharsets.UTF_8).contains("Google"), "google.com should contain google");
}
@Test
- public void fileDownload() throws IOException {
+ public void fileDownload() throws Exception {
File destination = File.createTempFile("jabref-test", ".html");
try {
URLDownload dl = new URLDownload(new URL("http://www.google.com"));
@@ -57,14 +55,14 @@ public void fileDownload() throws IOException {
}
@Test
- public void determineMimeType() throws IOException {
+ public void determineMimeType() throws Exception {
URLDownload dl = new URLDownload(new URL("http://www.google.com"));
assertTrue(dl.getMimeType().startsWith("text/html"));
}
@Test
- public void downloadToTemporaryFilePathWithoutFileSavesAsTmpFile() throws IOException {
+ public void downloadToTemporaryFilePathWithoutFileSavesAsTmpFile() throws Exception {
URLDownload google = new URLDownload(new URL("http://www.google.com"));
String path = google.toTemporaryFile().toString();
@@ -72,7 +70,7 @@ public void downloadToTemporaryFilePathWithoutFileSavesAsTmpFile() throws IOExce
}
@Test
- public void downloadToTemporaryFileKeepsName() throws IOException {
+ public void downloadToTemporaryFileKeepsName() throws Exception {
URLDownload google = new URLDownload(new URL("https://github.com/JabRef/jabref/blob/main/LICENSE"));
String path = google.toTemporaryFile().toString();
@@ -81,7 +79,7 @@ public void downloadToTemporaryFileKeepsName() throws IOException {
@Test
@DisabledOnCIServer("CI Server is apparently blocked")
- public void downloadOfFTPSucceeds() throws IOException {
+ public void downloadOfFTPSucceeds() throws Exception {
URLDownload ftp = new URLDownload(new URL("ftp://ftp.informatik.uni-stuttgart.de/pub/library/ncstrl.ustuttgart_fi/INPROC-2016-15/INPROC-2016-15.pdf"));
Path path = ftp.toTemporaryFile();
@@ -89,7 +87,7 @@ public void downloadOfFTPSucceeds() throws IOException {
}
@Test
- public void downloadOfHttpSucceeds() throws IOException {
+ public void downloadOfHttpSucceeds() throws Exception {
URLDownload ftp = new URLDownload(new URL("http://www.jabref.org"));
Path path = ftp.toTemporaryFile();
@@ -97,7 +95,7 @@ public void downloadOfHttpSucceeds() throws IOException {
}
@Test
- public void downloadOfHttpsSucceeds() throws IOException {
+ public void downloadOfHttpsSucceeds() throws Exception {
URLDownload ftp = new URLDownload(new URL("https://www.jabref.org"));
Path path = ftp.toTemporaryFile();
@@ -128,18 +126,14 @@ public void connectTimeoutIsNeverNull() throws MalformedURLException {
}
@Test
- public void test503ErrorThrowsNestedIOExceptionWithFetcherServerException() throws Exception {
+ public void test503ErrorThrowsFetcherServerException() throws Exception {
URLDownload urlDownload = new URLDownload(new URL("http://httpstat.us/503"));
-
- Exception exception = assertThrows(IOException.class, urlDownload::asString);
- assertInstanceOf(FetcherServerException.class, exception.getCause());
+ assertThrows(FetcherServerException.class, urlDownload::asString);
}
@Test
- public void test429ErrorThrowsNestedIOExceptionWithFetcherServerException() throws Exception {
+ public void test429ErrorThrowsFetcherClientException() throws Exception {
URLDownload urlDownload = new URLDownload(new URL("http://httpstat.us/429"));
-
- Exception exception = assertThrows(IOException.class, urlDownload::asString);
- assertInstanceOf(FetcherClientException.class, exception.getCause());
+ Exception exception = assertThrows(FetcherClientException.class, urlDownload::asString);
}
}