Skip to content

Commit

Permalink
Replace new instantiation of BuildInfo with calls to Injector
Browse files Browse the repository at this point in the history
  • Loading branch information
calixtus committed Oct 14, 2024
1 parent 7d48050 commit c3e05f7
Show file tree
Hide file tree
Showing 13 changed files with 41 additions and 36 deletions.
2 changes: 1 addition & 1 deletion docs/code-howtos/fetchers.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ In `build.gradle`, these variables are filled:
The `BuildInfo` class reads from that file.

```java
new BuildInfo().springerNatureAPIKey
Injector.instantiateModelOrService(BuildInfo.class).springerNatureAPIKey
```

When executing `./gradlew run`, gradle executes `processResources` and populates `build/build.properties` accordingly. However, when working directly in the IDE, Eclipse keeps reading `build.properties` from `src/main/resources`. In IntelliJ, the task `JabRef Main` is executing `./gradlew processResources` before running JabRef from the IDE to ensure the `build.properties` is properly populated.
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/org/jabref/Launcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.jabref.logic.util.BuildInfo;
import org.jabref.logic.util.Directories;
import org.jabref.logic.util.HeadlessExecutorService;
import org.jabref.logic.util.Version;
import org.jabref.migrations.PreferencesMigrations;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.util.DirectoryMonitor;
Expand Down Expand Up @@ -140,7 +141,8 @@ private static void initLogging(String[] args) {
}

// addLogToDisk
Path directory = Directories.getLogDirectory();
Version version = Injector.instantiateModelOrService(BuildInfo.class).version;
Path directory = Directories.getLogDirectory(version);
try {
Files.createDirectories(directory);
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,18 @@
import org.jabref.logic.util.BuildInfo;
import org.jabref.model.entry.BibEntry;

import com.airhacks.afterburner.injection.Injector;
import com.google.gson.Gson;

public class SemanticScholarFetcher implements CitationFetcher, CustomizableKeyFetcher {
private static final String SEMANTIC_SCHOLAR_API = "https://api.semanticscholar.org/graph/v1/";

private static final String API_KEY = new BuildInfo().semanticScholarApiKey;

private final String apiKey;
private final ImporterPreferences importerPreferences;

public SemanticScholarFetcher(ImporterPreferences importerPreferences) {
this.importerPreferences = importerPreferences;
this.apiKey = Injector.instantiateModelOrService(BuildInfo.class).semanticScholarApiKey;
}

public String getAPIUrl(String entry_point, BibEntry entry) {
Expand Down Expand Up @@ -90,6 +91,6 @@ public String getName() {
}

private String getApiKey() {
return importerPreferences.getApiKey(getName()).orElse(API_KEY);
return importerPreferences.getApiKey(getName()).orElse(apiKey);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import org.jabref.model.paging.Page;
import org.jabref.model.strings.StringUtil;

import com.airhacks.afterburner.injection.Injector;
import kong.unirest.core.json.JSONArray;
import kong.unirest.core.json.JSONException;
import kong.unirest.core.json.JSONObject;
Expand All @@ -52,12 +53,13 @@ public class AstrophysicsDataSystem
private static final String API_SEARCH_URL = "https://api.adsabs.harvard.edu/v1/search/query";
private static final String API_EXPORT_URL = "https://api.adsabs.harvard.edu/v1/export/bibtexabs";

private static final String API_KEY = new BuildInfo().astrophysicsDataSystemAPIKey;
private final String apiKey;
private final ImportFormatPreferences preferences;
private final ImporterPreferences importerPreferences;

public AstrophysicsDataSystem(ImportFormatPreferences preferences, ImporterPreferences importerPreferences) {
this.preferences = Objects.requireNonNull(preferences);
this.apiKey = Injector.instantiateModelOrService(BuildInfo.class).astrophysicsDataSystemAPIKey;
this.importerPreferences = importerPreferences;
}

Expand Down Expand Up @@ -255,7 +257,7 @@ private List<BibEntry> performSearchByIds(Collection<String> identifiers) throws
try {
String postData = buildPostData(ids);
URLDownload download = new URLDownload(urLforExport);
download.addHeader("Authorization", "Bearer " + importerPreferences.getApiKey(getName()).orElse(API_KEY));
download.addHeader("Authorization", "Bearer " + importerPreferences.getApiKey(getName()).orElse(apiKey));
download.addHeader("ContentType", "application/json");
download.setPostData(postData);
String content = download.asString();
Expand Down Expand Up @@ -308,7 +310,7 @@ public Page<BibEntry> performSearchPaged(QueryNode luceneQuery, int pageNumber)
@Override
public URLDownload getUrlDownload(URL url) {
URLDownload urlDownload = new URLDownload(url);
urlDownload.addHeader("Authorization", "Bearer " + importerPreferences.getApiKey(getName()).orElse(API_KEY));
urlDownload.addHeader("Authorization", "Bearer " + importerPreferences.getApiKey(getName()).orElse(apiKey));
return urlDownload;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;

import com.airhacks.afterburner.injection.Injector;
import com.google.common.annotations.VisibleForTesting;
import kong.unirest.core.json.JSONArray;
import kong.unirest.core.json.JSONException;
Expand All @@ -38,16 +39,17 @@
*/
public class BiodiversityLibrary implements SearchBasedParserFetcher, CustomizableKeyFetcher {

private static final String API_KEY = new BuildInfo().biodiversityHeritageApiKey;
private static final String BASE_URL = "https://www.biodiversitylibrary.org/api3";
private static final String RESPONSE_FORMAT = "json";
private static final String TEST_URL_WITHOUT_API_KEY = "https://www.biodiversitylibrary.org/api3?apikey=";

private static final String FETCHER_NAME = "Biodiversity Heritage";

private final String apiKey;
private final ImporterPreferences importerPreferences;

public BiodiversityLibrary(ImporterPreferences importerPreferences) {
this.apiKey = Injector.instantiateModelOrService(BuildInfo.class).biodiversityHeritageApiKey;
this.importerPreferences = importerPreferences;
}

Expand All @@ -63,7 +65,7 @@ public String getTestUrl() {

public URL getBaseURL() throws URISyntaxException, MalformedURLException {
URIBuilder baseURI = new URIBuilder(BASE_URL);
baseURI.addParameter("apikey", importerPreferences.getApiKey(getName()).orElse(API_KEY));
baseURI.addParameter("apikey", importerPreferences.getApiKey(getName()).orElse(apiKey));
baseURI.addParameter("format", RESPONSE_FORMAT);

return baseURI.build().toURL();
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/org/jabref/logic/importer/fetcher/IEEE.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.strings.StringUtil;

import com.airhacks.afterburner.injection.Injector;
import kong.unirest.core.json.JSONArray;
import kong.unirest.core.json.JSONObject;
import org.apache.hc.core5.net.URIBuilder;
Expand Down Expand Up @@ -59,15 +60,16 @@ public class IEEE implements FulltextFetcher, PagedSearchBasedParserFetcher, Cus
private static final Pattern PDF_PATTERN = Pattern.compile("\"(https://ieeexplore.ieee.org/ielx[0-9/]+\\.pdf[^\"]+)\"");
private static final String IEEE_DOI = "10.1109";
private static final String BASE_URL = "https://ieeexplore.ieee.org";
private static final String API_KEY = new BuildInfo().ieeeAPIKey;
private static final String TEST_URL_WITHOUT_API_KEY = "https://ieeexploreapi.ieee.org/api/v1/search/articles?max_records=0&apikey=";

private final String apiKey;
private final ImportFormatPreferences importFormatPreferences;
private final ImporterPreferences importerPreferences;

private IEEEQueryTransformer transformer;

public IEEE(ImportFormatPreferences importFormatPreferences, ImporterPreferences importerPreferences) {
this.apiKey = Injector.instantiateModelOrService(BuildInfo.class).ieeeAPIKey;
this.importFormatPreferences = Objects.requireNonNull(importFormatPreferences);
this.importerPreferences = Objects.requireNonNull(importerPreferences);
}
Expand Down Expand Up @@ -265,7 +267,7 @@ public Optional<HelpFile> getHelpPage() {
}

private String getApiKey() {
return importerPreferences.getApiKey(getName()).orElse(API_KEY);
return importerPreferences.getApiKey(getName()).orElse(apiKey);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.DOI;

import com.airhacks.afterburner.injection.Injector;
import kong.unirest.core.HttpResponse;
import kong.unirest.core.JsonNode;
import kong.unirest.core.Unirest;
Expand All @@ -38,12 +39,13 @@ public class ScienceDirect implements FulltextFetcher, CustomizableKeyFetcher {
private static final Logger LOGGER = LoggerFactory.getLogger(ScienceDirect.class);

private static final String API_URL = "https://api.elsevier.com/content/article/doi/";
private static final String API_KEY = new BuildInfo().scienceDirectApiKey;
private static final String FETCHER_NAME = "ScienceDirect";

private final String apiKey;
private final ImporterPreferences importerPreferences;

public ScienceDirect(ImporterPreferences importerPreferences) {
this.apiKey = Injector.instantiateModelOrService(BuildInfo.class).scienceDirectApiKey;
this.importerPreferences = importerPreferences;
}

Expand Down Expand Up @@ -140,7 +142,7 @@ private String getUrlByDoi(String doi) throws UnirestException {
try {
String request = API_URL + doi;
HttpResponse<JsonNode> jsonResponse = Unirest.get(request)
.header("X-ELS-APIKey", importerPreferences.getApiKey(getName()).orElse(API_KEY))
.header("X-ELS-APIKey", importerPreferences.getApiKey(getName()).orElse(apiKey))
.queryString("httpAccept", "application/json")
.asJson();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;

import com.airhacks.afterburner.injection.Injector;
import com.google.common.base.Strings;
import kong.unirest.core.json.JSONArray;
import kong.unirest.core.json.JSONObject;
Expand All @@ -45,13 +46,14 @@ public class SpringerFetcher implements PagedSearchBasedParserFetcher, Customiza
private static final Logger LOGGER = LoggerFactory.getLogger(SpringerFetcher.class);

private static final String API_URL = "https://api.springernature.com/meta/v1/json";
private static final String API_KEY = new BuildInfo().springerNatureAPIKey;
// Springer query using the parameter 'q=doi:10.1007/s11276-008-0131-4s=1' will respond faster
private static final String TEST_URL_WITHOUT_API_KEY = "https://api.springernature.com/meta/v1/json?q=doi:10.1007/s11276-008-0131-4s=1&p=1&api_key=";

private final String apiKey;
private final ImporterPreferences importerPreferences;

public SpringerFetcher(ImporterPreferences importerPreferences) {
this.apiKey = Injector.instantiateModelOrService(BuildInfo.class).springerNatureAPIKey;
this.importerPreferences = importerPreferences;
}

Expand Down Expand Up @@ -188,7 +190,7 @@ public String getTestUrl() {
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
uriBuilder.addParameter("api_key", importerPreferences.getApiKey(getName()).orElse(apiKey)); // API key
uriBuilder.addParameter("s", String.valueOf(getPageSize() * pageNumber + 1)); // Start entry, starts indexing at 1
uriBuilder.addParameter("p", String.valueOf(getPageSize())); // Page size
return uriBuilder.build().toURL();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.DOI;

import com.airhacks.afterburner.injection.Injector;
import kong.unirest.core.HttpResponse;
import kong.unirest.core.JsonNode;
import kong.unirest.core.Unirest;
Expand All @@ -33,12 +34,13 @@ public class SpringerLink implements FulltextFetcher, CustomizableKeyFetcher {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringerLink.class);

private static final String API_URL = "https://api.springer.com/meta/v1/json";
private static final String API_KEY = new BuildInfo().springerNatureAPIKey;
private static final String CONTENT_HOST = "link.springer.com";

private final String apiKey;
private final ImporterPreferences importerPreferences;

public SpringerLink(ImporterPreferences importerPreferences) {
this.apiKey = Injector.instantiateModelOrService(BuildInfo.class).springerNatureAPIKey;
this.importerPreferences = importerPreferences;
}

Expand All @@ -55,7 +57,7 @@ public Optional<URL> findFullText(BibEntry entry) throws IOException {
// Available in catalog?
try {
HttpResponse<JsonNode> jsonResponse = Unirest.get(API_URL)
.queryString("api_key", importerPreferences.getApiKey(getName()).orElse(API_KEY))
.queryString("api_key", importerPreferences.getApiKey(getName()).orElse(apiKey))
.queryString("q", "doi:%s".formatted(doi.get().getDOI()))
.asJson();
if (jsonResponse.getBody() != null) {
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/org/jabref/logic/util/BuildInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ public final class BuildInfo {
public final Version version;
public final String maintainers;
public final String year;
public final String azureInstrumentationKey;
public final String springerNatureAPIKey;
public final String astrophysicsDataSystemAPIKey;
public final String ieeeAPIKey;
Expand Down Expand Up @@ -50,7 +49,6 @@ public BuildInfo(String path) {
version = Version.parse(properties.getProperty("version"));
year = properties.getProperty("year", "");
maintainers = properties.getProperty("maintainers", "");
azureInstrumentationKey = BuildInfo.getValue(properties, "azureInstrumentationKey", "");
springerNatureAPIKey = BuildInfo.getValue(properties, "springerNatureAPIKey", "118d90a519d0fc2a01ee9715400054d4");
astrophysicsDataSystemAPIKey = BuildInfo.getValue(properties, "astrophysicsDataSystemAPIKey", "tAhPRKADc6cC26mZUnAoBt3MAjCvKbuCZsB4lI3c");
ieeeAPIKey = BuildInfo.getValue(properties, "ieeeAPIKey", "5jv3wyt4tt2bwcwv7jjk7pc3");
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/jabref/logic/util/Directories.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ public static Path getUserDirectory() {
return Path.of(System.getProperty("user.home"));
}

public static Path getLogDirectory() {
public static Path getLogDirectory(Version version) {
return Path.of(AppDirsFactory.getInstance()
.getUserDataDir(
OS.APP_DIR_APP_NAME,
"logs",
OS.APP_DIR_APP_AUTHOR))
.resolve(new BuildInfo().version.toString());
.resolve(version.toString());
}

public static Path getBackupDirectory() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@

@FetcherTest
class BiodiversityLibraryTest {
private final String BASE_URL = "https://www.biodiversitylibrary.org/api3?";
private final String RESPONSE_FORMAT = "&format=json";
private final BuildInfo buildInfo = new BuildInfo();

private String apiKey;
private BiodiversityLibrary fetcher;

@BeforeEach
void setUp() {
apiKey = new BuildInfo().biodiversityHeritageApiKey;
ImporterPreferences importerPreferences = mock(ImporterPreferences.class);
when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet());
fetcher = new BiodiversityLibrary(importerPreferences);
Expand All @@ -49,15 +49,14 @@ void getName() {

@Test
void biodiversityHeritageApiKeyIsNotEmpty() {
BuildInfo buildInfo = new BuildInfo();
assertNotNull(buildInfo.biodiversityHeritageApiKey);
assertNotNull(apiKey);
}

@Test
void baseURLConstruction() throws MalformedURLException, URISyntaxException {
String expected = fetcher
.getTestUrl()
.concat(buildInfo.biodiversityHeritageApiKey)
.concat(apiKey)
.concat(RESPONSE_FORMAT);

assertEquals(expected, fetcher.getBaseURL().toString());
Expand All @@ -68,7 +67,7 @@ void baseURLConstruction() throws MalformedURLException, URISyntaxException {
void getPartMetadaUrl(String id) throws MalformedURLException, URISyntaxException {
String expected = fetcher
.getTestUrl()
.concat(buildInfo.biodiversityHeritageApiKey)
.concat(apiKey)
.concat(RESPONSE_FORMAT)
.concat("&op=GetPartMetadata&pages=f&names=f")
.concat("&id=");
Expand All @@ -81,7 +80,7 @@ void getPartMetadaUrl(String id) throws MalformedURLException, URISyntaxExceptio
void getItemMetadaUrl(String id) throws MalformedURLException, URISyntaxException {
String expected = fetcher
.getTestUrl()
.concat(buildInfo.biodiversityHeritageApiKey)
.concat(apiKey)
.concat(RESPONSE_FORMAT)
.concat("&op=GetItemMetadata&pages=f&ocr=f&ocr=f")
.concat("&id=");
Expand Down
7 changes: 0 additions & 7 deletions src/test/java/org/jabref/logic/util/BuildInfoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

class BuildInfoTest {

Expand All @@ -18,10 +17,4 @@ void fileImport() {
BuildInfo buildInfo = new BuildInfo("/org/jabref/util/build.properties");
assertEquals("42", buildInfo.version.getFullVersion());
}

@Test
void azureInstrumentationKeyIsNotEmpty() {
BuildInfo buildInfo = new BuildInfo();
assertNotNull(buildInfo.azureInstrumentationKey);
}
}

0 comments on commit c3e05f7

Please sign in to comment.