From 39d17e7e98ea6eea09cd1b06476a5436b30d2c5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20T=C3=A1rraga=20Gim=C3=A9nez?= Date: Wed, 23 Aug 2023 09:52:47 +0200 Subject: [PATCH] core: rename token to apiKey, #TASK-4791, #TASK-4641 --- .../app/cli/admin/AdminCliOptionsParser.java | 38 ++++---- .../cellbase/app/cli/admin/AdminMain.java | 4 +- ...ecutor.java => ApiKeyCommandExecutor.java} | 62 ++++++------- .../executors/ExportCommandExecutor.java | 6 +- .../executors/ValidationCommandExecutor.java | 2 +- .../cellbase/client/rest/CellBaseClient.java | 30 +++--- .../client/rest/ClinicalVariantClient.java | 4 +- .../cellbase/client/rest/FeatureClient.java | 4 +- .../cellbase/client/rest/GeneClient.java | 4 +- .../cellbase/client/rest/GenericClient.java | 11 +-- .../client/rest/GenomicRegionClient.java | 4 +- .../cellbase/client/rest/MetaClient.java | 4 +- .../client/rest/ParentRestClient.java | 22 ++--- .../cellbase/client/rest/ProteinClient.java | 4 +- .../client/rest/TranscriptClient.java | 4 +- .../cellbase/client/rest/VariantClient.java | 8 +- .../cellbase/client/rest/VariationClient.java | 4 +- .../opencb/cellbase/core/ParamConstants.java | 2 +- .../key/ApiKeyJwtPayload.java} | 18 ++-- .../key/ApiKeyManager.java} | 70 +++++++------- .../key/ApiKeyQuota.java} | 10 +- .../key/ApiKeyStats.java} | 34 +++---- .../core/api/query/AbstractQuery.java | 23 ++++- .../core/result/CellBaseDataResponse.java | 16 ++-- .../lib/impl/core/MetaMongoDBAdaptor.java | 31 +++---- .../lib/managers/AbstractManager.java | 18 +++- .../lib/managers/ClinicalManager.java | 13 +-- .../cellbase/lib/managers/MetaManager.java | 21 ++--- ...anagerTest.java => ApiKeyManagerTest.java} | 93 +++++++++---------- .../server/rest/GenericRestWSServer.java | 73 +++++++-------- .../cellbase/server/rest/MetaWSServer.java | 76 ++++++++------- .../server/rest/OntologyWSServer.java | 5 +- .../server/rest/PublicationWSServer.java | 4 +- .../cellbase/server/rest/SpeciesWSServer.java | 3 +- .../rest/clinical/ClinicalWSServer.java | 3 +- .../clinical/PharmacogenomicsWSServer.java | 12 ++- .../server/rest/feature/GeneWSServer.java | 5 +- .../server/rest/feature/IdWSServer.java | 8 +- .../server/rest/feature/ProteinWSServer.java | 5 +- .../rest/feature/TranscriptWSServer.java | 5 +- .../rest/genomic/ChromosomeWSServer.java | 3 +- .../server/rest/genomic/RegionWSServer.java | 3 +- .../server/rest/genomic/VariantWSServer.java | 7 +- .../rest/regulatory/RegulatoryWSServer.java | 3 +- .../server/rest/regulatory/TfWSServer.java | 5 +- 45 files changed, 416 insertions(+), 368 deletions(-) rename cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/{DataTokenCommandExecutor.java => ApiKeyCommandExecutor.java} (58%) rename cellbase-core/src/main/java/org/opencb/cellbase/core/{token/TokenJwtPayload.java => api/key/ApiKeyJwtPayload.java} (84%) rename cellbase-core/src/main/java/org/opencb/cellbase/core/{token/DataAccessTokenManager.java => api/key/ApiKeyManager.java} (69%) rename cellbase-core/src/main/java/org/opencb/cellbase/core/{token/TokenQuota.java => api/key/ApiKeyQuota.java} (85%) rename cellbase-core/src/main/java/org/opencb/cellbase/core/{token/TokenStats.java => api/key/ApiKeyStats.java} (71%) rename cellbase-lib/src/test/java/org/opencb/cellbase/lib/managers/{DataAccessTokenManagerTest.java => ApiKeyManagerTest.java} (55%) diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/AdminCliOptionsParser.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/AdminCliOptionsParser.java index 8854d89c8..6de98bf82 100644 --- a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/AdminCliOptionsParser.java +++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/AdminCliOptionsParser.java @@ -18,7 +18,7 @@ import com.beust.jcommander.*; import org.opencb.cellbase.app.cli.CliOptionsParser; -import org.opencb.cellbase.core.token.TokenQuota; +import org.opencb.cellbase.core.api.key.ApiKeyQuota; import java.util.HashMap; import java.util.List; @@ -35,7 +35,7 @@ public class AdminCliOptionsParser extends CliOptionsParser { private DownloadCommandOptions downloadCommandOptions; private BuildCommandOptions buildCommandOptions; private DataReleaseCommandOptions dataReleaseCommandOptions; - private DataTokenCommandOptions dataTokenCommandOptions; + private ApiKeyCommandOptions apiKeyCommandOptions; private LoadCommandOptions loadCommandOptions; private ExportCommandOptions exportCommandOptions; private CustomiseCommandOptions customiseCommandOptions; @@ -52,7 +52,7 @@ public AdminCliOptionsParser() { downloadCommandOptions = new DownloadCommandOptions(); buildCommandOptions = new BuildCommandOptions(); dataReleaseCommandOptions = new DataReleaseCommandOptions(); - dataTokenCommandOptions = new DataTokenCommandOptions(); + apiKeyCommandOptions = new ApiKeyCommandOptions(); loadCommandOptions = new LoadCommandOptions(); exportCommandOptions = new ExportCommandOptions(); customiseCommandOptions = new CustomiseCommandOptions(); @@ -64,7 +64,7 @@ public AdminCliOptionsParser() { jCommander.addCommand("download", downloadCommandOptions); jCommander.addCommand("build", buildCommandOptions); jCommander.addCommand("data-release", dataReleaseCommandOptions); - jCommander.addCommand("data-token", dataTokenCommandOptions); + jCommander.addCommand("api-key", apiKeyCommandOptions); jCommander.addCommand("load", loadCommandOptions); jCommander.addCommand("export", exportCommandOptions); jCommander.addCommand("customise", customiseCommandOptions); @@ -153,31 +153,31 @@ public class DataReleaseCommandOptions { public String versions; } - @Parameters(commandNames = {"data-token"}, commandDescription = "Manage data access tokens in order to access to restricted/licensed data sources") - public class DataTokenCommandOptions { + @Parameters(commandNames = {"api-key"}, commandDescription = "Manage API keys in order to access to restricted/licensed data sources and set quota") + public class ApiKeyCommandOptions { @ParametersDelegate public CommonCommandOptions commonOptions = commonCommandOptions; - @Parameter(names = {"--create-token"}, description = "Create a data access token with the data sources indicated separated by" + @Parameter(names = {"--create-api-key"}, description = "Create an API key with the licensed data sources indicated separated by" + " commas and optionally the expiration date: source[:dd/mm/yyyy]. e.g.: cosmic:31/01/2025,hgmd. In addition the" + " 'organization' has to be specified", arity = 1) public String createWithDataSources; - @Parameter(names = {"--expiration"}, description = "Use this parameter in conjunction with --create-token to specify the" + @Parameter(names = {"--expiration"}, description = "Use this parameter in conjunction with --create-api-key to specify the" + " expiration date in format dd/mm/yyyy, e.g.: 03/09/2030", arity = 1) public String expiration; - @Parameter(names = {"--organization"}, description = "Use this parameter in conjunction with --create-token to specify the" + @Parameter(names = {"--organization"}, description = "Use this parameter in conjunction with --create-api-key to specify the" + " organization", arity = 1) public String organization; - @Parameter(names = {"--max-num-queries"}, description = "Use this parameter in conjunction with --create-token to specify the" + @Parameter(names = {"--max-num-queries"}, description = "Use this parameter in conjunction with --create-api-key to specify the" + " maximum number of queries per month", arity = 1) - public long maxNumQueries = TokenQuota.DEFAULT_MAX_NUM_QUERIES; + public long maxNumQueries = ApiKeyQuota.DEFAULT_MAX_NUM_QUERIES; - @Parameter(names = {"--view-token"}, description = "Token to view", arity = 1) - public String tokenToView; + @Parameter(names = {"--view-api-key"}, description = "API key to view", arity = 1) + public String apiKeyToView; } @Parameters(commandNames = {"load"}, commandDescription = "Load the built data models into the database") @@ -245,8 +245,8 @@ public class ExportCommandOptions { @Parameter(names = {"--data-release"}, description = "Data release for exporting data.", required = true, arity = 1) public int dataRelease; - @Parameter(names = {"--token"}, description = "Data token to export licensed data.", arity = 1) - public String token; + @Parameter(names = {"--api-key"}, description = "API key to export licensed data.", arity = 1) + public String apiKey; @Parameter(names = {"--gene"}, description = "List of genes (separated by commas). Exported data will be related to these genes" + " (gene coordinates will be taken into account).", required = true, arity = 1) @@ -353,8 +353,8 @@ public class ValidationCommandOptions { @Parameter(names = {"--data-release"}, description = "Data release. To use the default data release, please, set this parameter to 0", required = false, arity = 1) public int dataRelease = 0; - @Parameter(names = {"--token"}, description = "Data token to get access to licensed/restricted data sources such as COSMIC or HGMD", required = false, arity = 1) - public String token; + @Parameter(names = {"--api-key"}, description = "API key to get access to licensed/restricted data sources such as COSMIC or HGMD", required = false, arity = 1) + public String apiKey; @Parameter(names = {"-i", "--input-file"}, description = "Full path to VCF", required = true, arity = 1) public String inputFile; @@ -405,9 +405,7 @@ public DataReleaseCommandOptions getDataReleaseCommandOptions() { return dataReleaseCommandOptions; } - public DataTokenCommandOptions getDataTokenCommandOptions() { - return dataTokenCommandOptions; - } + public ApiKeyCommandOptions getApiKeyCommandOptions() {return apiKeyCommandOptions; } public LoadCommandOptions getLoadCommandOptions() { return loadCommandOptions; } diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/AdminMain.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/AdminMain.java index cfe4652c8..10c43d637 100644 --- a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/AdminMain.java +++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/AdminMain.java @@ -66,8 +66,8 @@ public static void main(String[] args) { case "data-release": commandExecutor = new DataReleaseCommandExecutor(cliOptionsParser.getDataReleaseCommandOptions()); break; - case "data-token": - commandExecutor = new DataTokenCommandExecutor(cliOptionsParser.getDataTokenCommandOptions()); + case "api-key": + commandExecutor = new ApiKeyCommandExecutor(cliOptionsParser.getApiKeyCommandOptions()); break; case "load": commandExecutor = new LoadCommandExecutor(cliOptionsParser.getLoadCommandOptions()); diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/DataTokenCommandExecutor.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ApiKeyCommandExecutor.java similarity index 58% rename from cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/DataTokenCommandExecutor.java rename to cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ApiKeyCommandExecutor.java index 0cdf78844..b1dade5f6 100644 --- a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/DataTokenCommandExecutor.java +++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ApiKeyCommandExecutor.java @@ -20,9 +20,9 @@ import org.apache.commons.lang3.StringUtils; import org.opencb.cellbase.app.cli.CommandExecutor; import org.opencb.cellbase.app.cli.admin.AdminCliOptionsParser; -import org.opencb.cellbase.core.token.DataAccessTokenManager; -import org.opencb.cellbase.core.token.TokenJwtPayload; -import org.opencb.cellbase.core.token.TokenQuota; +import org.opencb.cellbase.core.api.key.ApiKeyJwtPayload; +import org.opencb.cellbase.core.api.key.ApiKeyManager; +import org.opencb.cellbase.core.api.key.ApiKeyQuota; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; @@ -35,17 +35,17 @@ import java.util.HashMap; import java.util.Map; -public class DataTokenCommandExecutor extends CommandExecutor { +public class ApiKeyCommandExecutor extends CommandExecutor { - private AdminCliOptionsParser.DataTokenCommandOptions dataTokenCommandOptions; + private AdminCliOptionsParser.ApiKeyCommandOptions apiKeyCommandOptions; private DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy"); - public DataTokenCommandExecutor(AdminCliOptionsParser.DataTokenCommandOptions dataTokenCommandOptions) { - super(dataTokenCommandOptions.commonOptions.logLevel, dataTokenCommandOptions.commonOptions.conf); + public ApiKeyCommandExecutor(AdminCliOptionsParser.ApiKeyCommandOptions apiKeyCommandOptions) { + super(apiKeyCommandOptions.commonOptions.logLevel, apiKeyCommandOptions.commonOptions.conf); - this.dataTokenCommandOptions = dataTokenCommandOptions; + this.apiKeyCommandOptions = apiKeyCommandOptions; } @@ -57,27 +57,27 @@ public void execute() { Key key = new SecretKeySpec(Base64.getEncoder().encode(configuration.getSecretKey().getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS256.getJcaName()); - DataAccessTokenManager datManager = new DataAccessTokenManager(SignatureAlgorithm.HS256.getValue(), key); + ApiKeyManager apiKeyManager = new ApiKeyManager(SignatureAlgorithm.HS256.getValue(), key); try { - if (StringUtils.isNotEmpty(dataTokenCommandOptions.createWithDataSources)) { - // Create the token payload - TokenJwtPayload payload = new TokenJwtPayload(); - payload.setSubject(dataTokenCommandOptions.organization); - payload.setVersion(TokenJwtPayload.CURRENT_VERSION); + if (StringUtils.isNotEmpty(apiKeyCommandOptions.createWithDataSources)) { + // Create the API key JWT payload + ApiKeyJwtPayload payload = new ApiKeyJwtPayload(); + payload.setSubject(apiKeyCommandOptions.organization); + payload.setVersion(ApiKeyJwtPayload.CURRENT_VERSION); payload.setIssuedAt(new Date()); - if (dataTokenCommandOptions.expiration != null) { - payload.setExpiration(parseDate(dataTokenCommandOptions.expiration)); + if (apiKeyCommandOptions.expiration != null) { + payload.setExpiration(parseDate(apiKeyCommandOptions.expiration)); } - payload.setSources(parseSources(dataTokenCommandOptions.createWithDataSources)); - payload.setQuota(new TokenQuota(dataTokenCommandOptions.maxNumQueries)); - - // Create token - String token = datManager.encode(payload); - System.out.println("Data access token generated:\n" + token); - } else if (StringUtils.isNotEmpty(dataTokenCommandOptions.tokenToView)) { - // View data token - datManager.display(dataTokenCommandOptions.tokenToView); + payload.setSources(parseSources(apiKeyCommandOptions.createWithDataSources)); + payload.setQuota(new ApiKeyQuota(apiKeyCommandOptions.maxNumQueries)); + + // Create API key + String apiKey = apiKeyManager.encode(payload); + System.out.println("API key generated:\n" + apiKey); + } else if (StringUtils.isNotEmpty(apiKeyCommandOptions.apiKeyToView)) { + // View API key + apiKeyManager.display(apiKeyCommandOptions.apiKeyToView); } } catch (ParseException e) { e.printStackTrace(); @@ -86,18 +86,18 @@ public void execute() { } private void checkParameters() { - if (StringUtils.isNotEmpty(dataTokenCommandOptions.createWithDataSources) - && StringUtils.isNotEmpty(dataTokenCommandOptions.tokenToView)) { + if (StringUtils.isNotEmpty(apiKeyCommandOptions.createWithDataSources) + && StringUtils.isNotEmpty(apiKeyCommandOptions.apiKeyToView)) { throw new IllegalArgumentException("Please, select only one of these input parameters: create or view"); } - if (StringUtils.isEmpty(dataTokenCommandOptions.createWithDataSources) - && StringUtils.isEmpty(dataTokenCommandOptions.tokenToView)) { + if (StringUtils.isEmpty(apiKeyCommandOptions.createWithDataSources) + && StringUtils.isEmpty(apiKeyCommandOptions.apiKeyToView)) { throw new IllegalArgumentException("Please, it is mandatory to select one of these input parameters: create or view"); } // Check create parameters - if (StringUtils.isNotEmpty(dataTokenCommandOptions.createWithDataSources)) { - if (StringUtils.isEmpty(dataTokenCommandOptions.organization)) { + if (StringUtils.isNotEmpty(apiKeyCommandOptions.createWithDataSources)) { + if (StringUtils.isEmpty(apiKeyCommandOptions.organization)) { throw new IllegalArgumentException("Missing organization"); } } diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ExportCommandExecutor.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ExportCommandExecutor.java index 19aff216c..4b40db467 100644 --- a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ExportCommandExecutor.java +++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ExportCommandExecutor.java @@ -58,7 +58,7 @@ public class ExportCommandExecutor extends CommandExecutor { private Path output; private String[] dataToExport; private int dataRelease; - private String token; + private String apiKey; private String database; private CellBaseManagerFactory managerFactory; @@ -71,7 +71,7 @@ public ExportCommandExecutor(AdminCliOptionsParser.ExportCommandOptions exportCo this.exportCommandOptions = exportCommandOptions; this.dataRelease = exportCommandOptions.dataRelease; - this.token = exportCommandOptions.token; + this.apiKey = exportCommandOptions.apiKey; this.output = Paths.get(exportCommandOptions.output); @@ -324,7 +324,7 @@ private int exportClinicalVariantData(List regions) throws CellBaseExcep ClinicalManager clinicalManager = managerFactory.getClinicalManager(species, assembly); ClinicalVariantQuery query = new ClinicalVariantQuery(); query.setDataRelease(dataRelease); - query.setToken(token); + query.setApiKey(apiKey); int counter = 0; for (Region region : regions) { query.setRegions(Collections.singletonList(region)); diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ValidationCommandExecutor.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ValidationCommandExecutor.java index 2d7f19b1d..81a2809bd 100644 --- a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ValidationCommandExecutor.java +++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/admin/executors/ValidationCommandExecutor.java @@ -72,7 +72,7 @@ public void execute() { VariantAnnotationCalculator variantAnnotationCalculator = null; try { variantAnnotationCalculator = new VariantAnnotationCalculator(validationCommandOptions.species, - validationCommandOptions.assembly, validationCommandOptions.dataRelease, validationCommandOptions.token, + validationCommandOptions.assembly, validationCommandOptions.dataRelease, validationCommandOptions.apiKey, cellBaseManagerFactory); } catch (CellBaseException e) { e.printStackTrace(); diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/CellBaseClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/CellBaseClient.java index 9816a199e..f7450b374 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/CellBaseClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/CellBaseClient.java @@ -31,6 +31,8 @@ public class CellBaseClient { private final String species; private final String assembly; private final String dataRelease; + private final String apiKey; + @Deprecated private final String token; private ClientConfiguration clientConfiguration; @@ -53,14 +55,15 @@ public CellBaseClient(String species, String assembly, String dataRelease, Clien this(species, assembly, dataRelease, null, clientConfiguration); } - public CellBaseClient(String species, String assembly, String dataRelease, String token, ClientConfiguration clientConfiguration) { + public CellBaseClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration clientConfiguration) { if (StringUtils.isBlank(species)) { throw new IllegalArgumentException("Species parameter cannot be empty when building a CellBaseClient"); } this.species = species; this.assembly = StringUtils.isEmpty(assembly) ? null : assembly; this.dataRelease = StringUtils.isEmpty(dataRelease) ? null : dataRelease; - this.token = token; + this.token = apiKey; + this.apiKey = apiKey; if (clientConfiguration != null && clientConfiguration.getRest() != null && clientConfiguration.getRest().getHosts() != null && !clientConfiguration.getRest().getHosts().isEmpty() @@ -75,11 +78,11 @@ public CellBaseClient(String species, String assembly, String dataRelease, Strin } public GeneClient getGeneClient() { - return getClient("GENE", () -> new GeneClient(species, assembly, dataRelease, token, clientConfiguration)); + return getClient("GENE", () -> new GeneClient(species, assembly, dataRelease, apiKey, clientConfiguration)); } public TranscriptClient getTranscriptClient() { - return getClient("TRANSCRIPT", () -> new TranscriptClient(species, assembly, dataRelease, token, clientConfiguration)); + return getClient("TRANSCRIPT", () -> new TranscriptClient(species, assembly, dataRelease, apiKey, clientConfiguration)); } // public VariationClient getVariationClient() { @@ -87,27 +90,27 @@ public TranscriptClient getTranscriptClient() { // } public VariantClient getVariantClient() { - return getClient("VARIANT", () -> new VariantClient(species, assembly, dataRelease, token, clientConfiguration)); + return getClient("VARIANT", () -> new VariantClient(species, assembly, dataRelease, apiKey, clientConfiguration)); } public ProteinClient getProteinClient() { - return getClient("PROTEIN", () -> new ProteinClient(species, assembly, dataRelease, token, clientConfiguration)); + return getClient("PROTEIN", () -> new ProteinClient(species, assembly, dataRelease, apiKey, clientConfiguration)); } public GenomicRegionClient getGenomicRegionClient() { - return getClient("GENOME_REGION", () -> new GenomicRegionClient(species, assembly, dataRelease, token, clientConfiguration)); + return getClient("GENOME_REGION", () -> new GenomicRegionClient(species, assembly, dataRelease, apiKey, clientConfiguration)); } public MetaClient getMetaClient() { - return getClient("META", () -> new MetaClient(species, assembly, dataRelease, token, clientConfiguration)); + return getClient("META", () -> new MetaClient(species, assembly, dataRelease, apiKey, clientConfiguration)); } public ClinicalVariantClient getClinicalClient() { - return getClient("CLINICAL", () -> new ClinicalVariantClient(species, assembly, dataRelease, token, clientConfiguration)); + return getClient("CLINICAL", () -> new ClinicalVariantClient(species, assembly, dataRelease, apiKey, clientConfiguration)); } public GenericClient getGenericClient() { - return getClient("GENERIC", () -> new GenericClient(species, assembly, dataRelease, token, clientConfiguration)); + return getClient("GENERIC", () -> new GenericClient(species, assembly, dataRelease, apiKey, clientConfiguration)); } @SuppressWarnings("unchecked") @@ -144,8 +147,13 @@ public String getDataRelease() { return dataRelease; } + public String getApiKey() { + return apiKey; + } + + @Deprecated public String getToken() { - return token; + return apiKey; } public ClientConfiguration getClientConfiguration() { diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ClinicalVariantClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ClinicalVariantClient.java index 9a66ce464..8d531fde9 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ClinicalVariantClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ClinicalVariantClient.java @@ -30,8 +30,8 @@ */ public class ClinicalVariantClient extends ParentRestClient { - ClinicalVariantClient(String species, String assembly, String dataRelease, String token, ClientConfiguration configuration) { - super(species, assembly, dataRelease, token, configuration); + ClinicalVariantClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration configuration) { + super(species, assembly, dataRelease, apiKey, configuration); this.clazz = Variant.class; diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/FeatureClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/FeatureClient.java index 6a16a612e..046e9b614 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/FeatureClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/FeatureClient.java @@ -30,8 +30,8 @@ */ public class FeatureClient extends ParentRestClient { - FeatureClient(String species, String assembly, String dataRelease, String token, ClientConfiguration configuration) { - super(species, assembly, dataRelease, token, configuration); + FeatureClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration configuration) { + super(species, assembly, dataRelease, apiKey, configuration); } diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GeneClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GeneClient.java index 1d187ac22..d30ea7aeb 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GeneClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GeneClient.java @@ -34,8 +34,8 @@ */ public class GeneClient extends FeatureClient { - GeneClient(String species, String assembly, String dataRelease, String token, ClientConfiguration clientConfiguration) { - super(species, assembly, dataRelease, token, clientConfiguration); + GeneClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration clientConfiguration) { + super(species, assembly, dataRelease, apiKey, clientConfiguration); this.clazz = Gene.class; diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GenericClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GenericClient.java index 25833ceba..1fbaf2370 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GenericClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GenericClient.java @@ -32,17 +32,16 @@ */ public class GenericClient extends ParentRestClient { - GenericClient(String species, String assembly, String dataRelease, String token, ClientConfiguration clientConfiguration) { - super(species, assembly, dataRelease, token, clientConfiguration); + GenericClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration clientConfiguration) { + super(species, assembly, dataRelease, apiKey, clientConfiguration); } - public CellBaseDataResponse get(String category, String resource, QueryOptions queryOptions, - Class clazz) throws IOException { + public CellBaseDataResponse get(String category, String resource, QueryOptions queryOptions, Class clazz) throws IOException { return this.get(category, null, EMPTY_STRING, resource, queryOptions, clazz); } - public CellBaseDataResponse get(String category, String subcategory, String ids, String resource, - QueryOptions queryOptions, Class clazz) throws IOException { + public CellBaseDataResponse get(String category, String subcategory, String ids, String resource, QueryOptions queryOptions, + Class clazz) throws IOException { this.category = category; this.subcategory = subcategory; return execute(ids, resource, queryOptions, clazz); diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GenomicRegionClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GenomicRegionClient.java index 4b656fea0..00f69ec37 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GenomicRegionClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/GenomicRegionClient.java @@ -32,8 +32,8 @@ */ public class GenomicRegionClient extends ParentRestClient { - GenomicRegionClient(String species, String assembly, String dataRelease, String token, ClientConfiguration clientConfiguration) { - super(species, assembly, dataRelease, token, clientConfiguration); + GenomicRegionClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration clientConfiguration) { + super(species, assembly, dataRelease, apiKey, clientConfiguration); this.clazz = GenomeSequenceFeature.class; diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/MetaClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/MetaClient.java index 913332b19..19685ca97 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/MetaClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/MetaClient.java @@ -34,8 +34,8 @@ */ public class MetaClient extends ParentRestClient { - MetaClient(String species, String assembly, String dataRelease, String token, ClientConfiguration clientConfiguration) { - super(species, assembly, dataRelease, token, clientConfiguration); + MetaClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration clientConfiguration) { + super(species, assembly, dataRelease, apiKey, clientConfiguration); this.clazz = ObjectMap.class; diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ParentRestClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ParentRestClient.java index 12cf3f74a..2ab955eac 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ParentRestClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ParentRestClient.java @@ -61,7 +61,7 @@ public class ParentRestClient { protected final String species; protected final String assembly; protected final String dataRelease; - protected final String token; + protected final String apiKey; protected final Client client; // TODO: Should this be final? @@ -95,11 +95,11 @@ public class ParentRestClient { this(species, assembly, null, null, configuration); } - ParentRestClient(String species, String assembly, String dataRelease, String token, ClientConfiguration configuration) { + ParentRestClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration configuration) { this.species = species; this.assembly = assembly; this.dataRelease = dataRelease; - this.token = token; + this.apiKey = apiKey; this.configuration = configuration; logger = LoggerFactory.getLogger(this.getClass().toString()); @@ -122,8 +122,8 @@ public String getDataRelease() { return dataRelease; } - public String getToken() { - return token; + public String getApiKey() { + return apiKey; } static { @@ -408,11 +408,11 @@ private CellBaseDataResponse robustRestCall(List idList, String r logger.warn("CellBase REST warning. Skipping id. {}", idList.get(0)); Event event = new Event(Event.Type.ERROR, "CellBase REST error. Skipping id " + idList.get(0)); CellBaseDataResult result = new CellBaseDataResult(idList.get(0), 0, Collections.emptyList(), 0, null, 0); - return new CellBaseDataResponse(configuration.getVersion(), 0, getToken(), 0, Collections.singletonList(event), + return new CellBaseDataResponse(configuration.getVersion(), 0, getApiKey(), 0, Collections.singletonList(event), new ObjectMap(queryOptions), Collections.singletonList(result)); } List> cellBaseDataResultList = new LinkedList<>(); - queryResponse = new CellBaseDataResponse(configuration.getVersion(), 0, getToken(), -1, null, queryOptions, + queryResponse = new CellBaseDataResponse(configuration.getVersion(), 0, getApiKey(), -1, null, queryOptions, cellBaseDataResultList); logger.info("Re-attempting to solve the query - trying to identify any problematic id to skip it"); List idList1 = idList.subList(0, idList.size() / 2); @@ -450,8 +450,8 @@ private CellBaseDataResponse restCall(List hosts, String version, if (dataRelease != null && StringUtils.isEmpty(queryOptions.getString(AbstractQuery.DATA_RELEASE))) { callUrl = callUrl.queryParam(AbstractQuery.DATA_RELEASE, dataRelease); } - if (token != null && StringUtils.isEmpty(queryOptions.getString(AbstractQuery.DATA_ACCESS_TOKEN))) { - callUrl = callUrl.queryParam(AbstractQuery.DATA_ACCESS_TOKEN, token); + if (apiKey != null && StringUtils.isEmpty(queryOptions.getString(AbstractQuery.API_KEY_PARAM))) { + callUrl = callUrl.queryParam(AbstractQuery.API_KEY_PARAM, apiKey); } } else { if (assembly != null) { @@ -460,8 +460,8 @@ private CellBaseDataResponse restCall(List hosts, String version, if (dataRelease != null) { callUrl = callUrl.queryParam(AbstractQuery.DATA_RELEASE, dataRelease); } - if (token != null) { - callUrl = callUrl.queryParam(AbstractQuery.DATA_ACCESS_TOKEN, token); + if (apiKey != null) { + callUrl = callUrl.queryParam(AbstractQuery.API_KEY_PARAM, apiKey); } } diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ProteinClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ProteinClient.java index 1cbf46f62..1dc16c7d8 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ProteinClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/ProteinClient.java @@ -30,8 +30,8 @@ */ public class ProteinClient extends FeatureClient { - ProteinClient(String species, String assembly, String dataRelease, String token, ClientConfiguration configuration) { - super(species, assembly, dataRelease, token, configuration); + ProteinClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration configuration) { + super(species, assembly, dataRelease, apiKey, configuration); this.clazz = Entry.class; diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/TranscriptClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/TranscriptClient.java index 86449c25d..c1e966e52 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/TranscriptClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/TranscriptClient.java @@ -33,8 +33,8 @@ */ public class TranscriptClient extends ParentRestClient { - TranscriptClient(String species, String assembly, String dataRelease, String token, ClientConfiguration configuration) { - super(species, assembly, dataRelease, token, configuration); + TranscriptClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration configuration) { + super(species, assembly, dataRelease, apiKey, configuration); this.clazz = Transcript.class; this.category = "feature"; diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/VariantClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/VariantClient.java index be784dabc..e9479ad18 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/VariantClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/VariantClient.java @@ -44,8 +44,8 @@ public final class VariantClient extends FeatureClient { private static final char ABSENT_ALLELE = '0'; private static final String REFERENCE_HOMOZYGOUS_GENOTYPE = "0|0"; - VariantClient(String species, String assembly, String dataRelease, String token, ClientConfiguration configuration) { - super(species, assembly, dataRelease, token, configuration); + VariantClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration configuration) { + super(species, assembly, dataRelease, apiKey, configuration); this.clazz = Variant.class; this.category = "genomic"; @@ -90,8 +90,8 @@ public CellBaseDataResponse annotate(List variants, QueryOptio Collections.singletonList(variants.get(i)), 1)); } - return new CellBaseDataResponse<>(configuration.getVersion(), 0, getToken(), annotations.getTime(), null, - new ObjectMap(options), annotatedVariants); + return new CellBaseDataResponse<>(configuration.getVersion(), Integer.parseInt(getDataRelease()), getApiKey(), + annotations.getTime(), null, new ObjectMap(options), annotatedVariants); } public CellBaseDataResponse getAnnotation(List variants, QueryOptions options) throws IOException { diff --git a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/VariationClient.java b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/VariationClient.java index 99b63cda8..0dbe09d97 100644 --- a/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/VariationClient.java +++ b/cellbase-client/src/main/java/org/opencb/cellbase/client/rest/VariationClient.java @@ -32,8 +32,8 @@ @Deprecated public class VariationClient extends FeatureClient { - VariationClient(String species, String assembly, String dataRelease, String token, ClientConfiguration configuration) { - super(species, assembly, dataRelease, token, configuration); + VariationClient(String species, String assembly, String dataRelease, String apiKey, ClientConfiguration configuration) { + super(species, assembly, dataRelease, apiKey, configuration); this.clazz = Variant.class; this.category = "feature"; diff --git a/cellbase-core/src/main/java/org/opencb/cellbase/core/ParamConstants.java b/cellbase-core/src/main/java/org/opencb/cellbase/core/ParamConstants.java index a07f6daa6..8c0c93274 100644 --- a/cellbase-core/src/main/java/org/opencb/cellbase/core/ParamConstants.java +++ b/cellbase-core/src/main/java/org/opencb/cellbase/core/ParamConstants.java @@ -113,7 +113,7 @@ public Type type() { public static final String VERSION_DESCRIPTION = "API version, e.g.: " + DEFAULT_VERSION; public static final String DATA_RELEASE_DESCRIPTION = "Data release. To use the default data release, set this to 0. To get the list" + " of available data release, please call the endpoint 'meta/dataReleases'"; - public static final String DATA_ACCESS_TOKEN_DESCRIPTION = "Data token to allow access to licensed/restricted data sources such as" + public static final String API_KEY_DESCRIPTION = "Data token to allow access to licensed/restricted data sources such as" + " Cosmic or HGMD"; public static final String DEFAULT_ASSEMBLY = "grch38"; public static final String ASSEMBLY_DESCRIPTION = "Set the reference genome assembly, e.g. grch38. For a full list of " diff --git a/cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenJwtPayload.java b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyJwtPayload.java similarity index 84% rename from cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenJwtPayload.java rename to cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyJwtPayload.java index ba9273856..031182198 100644 --- a/cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenJwtPayload.java +++ b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyJwtPayload.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.opencb.cellbase.core.token; +package org.opencb.cellbase.core.api.key; import io.jsonwebtoken.Claims; import io.jsonwebtoken.impl.DefaultClaims; @@ -26,9 +26,9 @@ import java.util.LinkedHashMap; import java.util.Map; -public class TokenJwtPayload extends DefaultClaims { +public class ApiKeyJwtPayload extends DefaultClaims { - // CellBase token claim names + // CellBase API key claim names private static final String VERSION = "version"; private static final String SOURCES = "sources"; private static final String QUOTA = "quota"; @@ -36,14 +36,14 @@ public class TokenJwtPayload extends DefaultClaims { public static final String CURRENT_VERSION = "1.0"; public static final DateFormat DATE_FORMATTER = new SimpleDateFormat("dd/MM/yyyy"); - public TokenJwtPayload() { + public ApiKeyJwtPayload() { super(); } - public TokenJwtPayload(Claims claims) { + public ApiKeyJwtPayload(Claims claims) { super(claims); } - // Getters and setters for the new fields + public String getVersion() { return get(VERSION, String.class); } @@ -67,16 +67,16 @@ public void setSources(Map sources) { put(SOURCES, sources); } - public TokenQuota getQuota() { + public ApiKeyQuota getQuota() { LinkedHashMap input = get(QUOTA, LinkedHashMap.class); - TokenQuota output = new TokenQuota(); + ApiKeyQuota output = new ApiKeyQuota(); if (input != null) { output.setMaxNumQueries(((Integer) input.get("maxNumQueries")).longValue()); } return output; } - public void setQuota(TokenQuota quota) { + public void setQuota(ApiKeyQuota quota) { put(QUOTA, quota); } } diff --git a/cellbase-core/src/main/java/org/opencb/cellbase/core/token/DataAccessTokenManager.java b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyManager.java similarity index 69% rename from cellbase-core/src/main/java/org/opencb/cellbase/core/token/DataAccessTokenManager.java rename to cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyManager.java index 884e21e9f..ba8b0b913 100644 --- a/cellbase-core/src/main/java/org/opencb/cellbase/core/token/DataAccessTokenManager.java +++ b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyManager.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.opencb.cellbase.core.token; +package org.opencb.cellbase.core.api.key; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.JwtParser; @@ -31,40 +31,40 @@ import java.security.Key; import java.util.*; -import static org.opencb.cellbase.core.token.TokenJwtPayload.DATE_FORMATTER; +import static org.opencb.cellbase.core.api.key.ApiKeyJwtPayload.DATE_FORMATTER; -public class DataAccessTokenManager { +public class ApiKeyManager { private SignatureAlgorithm algorithm; private Key privateKey; private Key publicKey; private JwtParser jwtParser; - private String defaultToken; + private String defaultApiKey; - private final Logger logger = LoggerFactory.getLogger(DataAccessTokenManager.class); + private final Logger logger = LoggerFactory.getLogger(ApiKeyManager.class); public static final int SECRET_KEY_MIN_LENGTH = 50; - public DataAccessTokenManager(String key) { + public ApiKeyManager(String key) { this(SignatureAlgorithm.HS256.getValue(), new SecretKeySpec(Base64.getEncoder().encode(key.getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS256.getJcaName())); } - public DataAccessTokenManager(String algorithm, Key secretKey) { + public ApiKeyManager(String algorithm, Key secretKey) { this.algorithm = SignatureAlgorithm.forName(algorithm); this.privateKey = secretKey; this.publicKey = secretKey; jwtParser = Jwts.parserBuilder().setSigningKey(publicKey).build(); - // Create the default token - TokenJwtPayload payload = new TokenJwtPayload(); + // Create the default API key + ApiKeyJwtPayload payload = new ApiKeyJwtPayload(); payload.setSubject("ANONYMOUS"); - payload.setVersion(TokenJwtPayload.CURRENT_VERSION); - payload.setQuota(new TokenQuota(TokenQuota.MAX_NUM_ANOYMOUS_QUERIES)); - defaultToken = encode(payload); + payload.setVersion(ApiKeyJwtPayload.CURRENT_VERSION); + payload.setQuota(new ApiKeyQuota(ApiKeyQuota.MAX_NUM_ANOYMOUS_QUERIES)); + defaultApiKey = encode(payload); } - public String encode(TokenJwtPayload payload) { + public String encode(ApiKeyJwtPayload payload) { JwtBuilder jwtBuilder = Jwts.builder(); return jwtBuilder.setClaims(payload) @@ -72,19 +72,19 @@ public String encode(TokenJwtPayload payload) { .compact(); } - public TokenJwtPayload decode(String token) { + public ApiKeyJwtPayload decode(String apiKey) { if (publicKey == null) { // Remove signature to parse JWT - token = token.substring(0, token.lastIndexOf(".") + 1); - return new TokenJwtPayload(jwtParser.parseClaimsJwt(token).getBody()); + apiKey = apiKey.substring(0, apiKey.lastIndexOf(".") + 1); + return new ApiKeyJwtPayload(jwtParser.parseClaimsJwt(apiKey).getBody()); } else { // Parse signed JWT (aka a 'JWS') - return new TokenJwtPayload(jwtParser.parseClaimsJws(token).getBody()); + return new ApiKeyJwtPayload(jwtParser.parseClaimsJws(apiKey).getBody()); } } - public String recode(String token) { - TokenJwtPayload payload = decode(token); + public String recode(String apiKey) { + ApiKeyJwtPayload payload = decode(apiKey); if (MapUtils.isNotEmpty(payload.getSources())) { Map sources = new HashMap<>(); for (Map.Entry entry : payload.getSources().entrySet()) { @@ -98,36 +98,36 @@ public String recode(String token) { return encode(payload); } - public void validate(String token) { - decode(token); + public void validate(String apiKey) { + decode(apiKey); } - public boolean hasExpiredSource(String source, String token) throws IllegalArgumentException { - TokenJwtPayload payload = decode(token); + public boolean hasExpiredSource(String source, String apiKey) throws IllegalArgumentException { + ApiKeyJwtPayload payload = decode(apiKey); if (MapUtils.isNotEmpty(payload.getSources()) && payload.getSources().containsKey(source)) { return (new Date().getTime() > payload.getSources().get(source).getTime()); } - throw new IllegalArgumentException("Data source '" + source + "' is not enabled for token '" + token + "'"); + throw new IllegalArgumentException("Data source '" + source + "' is not enabled for API key '" + apiKey + "'"); } - public Set getValidSources(String token) throws IllegalArgumentException { - return getValidSources(token, new HashSet<>()); + public Set getValidSources(String apiKey) throws IllegalArgumentException { + return getValidSources(apiKey, new HashSet<>()); } - public Set getValidSources(String token, Set init) throws IllegalArgumentException { + public Set getValidSources(String apiKey, Set init) throws IllegalArgumentException { Set validSources = new HashSet<>(); if (CollectionUtils.isNotEmpty(init)) { validSources.addAll(init); } - if (StringUtils.isNotEmpty(token)) { - TokenJwtPayload payload = decode(token); + if (StringUtils.isNotEmpty(apiKey)) { + ApiKeyJwtPayload payload = decode(apiKey); if (MapUtils.isNotEmpty(payload.getSources())) { for (Map.Entry entry : payload.getSources().entrySet()) { if (new Date().getTime() <= entry.getValue().getTime()) { validSources.add(entry.getKey()); } else { - String msg = "CellBase token expired at " + DATE_FORMATTER.format(entry.getValue()) + String msg = "CellBase API key expired at " + DATE_FORMATTER.format(entry.getValue()) + " for data source '" + entry.getKey() + "'"; logger.error(msg); throw new IllegalArgumentException(msg); @@ -138,15 +138,15 @@ public Set getValidSources(String token, Set init) throws Illega return validSources; } - public String getDefaultToken() { - return defaultToken; + public String getDefaultApiKey() { + return defaultApiKey; } - public void display(String token) { - TokenJwtPayload payload = decode(token); + public void display(String apiKey) { + ApiKeyJwtPayload payload = decode(apiKey); final StringBuilder sb = new StringBuilder(); - sb.append("Token: ").append(token).append("\n"); + sb.append("API key: ").append(apiKey).append("\n"); sb.append("Organization: ").append(payload.getSubject()).append("\n"); if (payload.getIssuedAt() != null) { sb.append("Issued at: ").append(DATE_FORMATTER.format(payload.getIssuedAt())).append("\n"); diff --git a/cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenQuota.java b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyQuota.java similarity index 85% rename from cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenQuota.java rename to cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyQuota.java index 6ce69994d..682b50b77 100644 --- a/cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenQuota.java +++ b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyQuota.java @@ -14,20 +14,20 @@ * limitations under the License. */ -package org.opencb.cellbase.core.token; +package org.opencb.cellbase.core.api.key; -public class TokenQuota { +public class ApiKeyQuota { private long maxNumQueries; public static final Long MAX_NUM_ANOYMOUS_QUERIES = 1000000L; public static final Long DEFAULT_MAX_NUM_QUERIES = 10000000L; - public TokenQuota() { + public ApiKeyQuota() { this(DEFAULT_MAX_NUM_QUERIES); } - public TokenQuota(long maxNumQueries) { + public ApiKeyQuota(long maxNumQueries) { this.maxNumQueries = maxNumQueries; } @@ -43,7 +43,7 @@ public long getMaxNumQueries() { return maxNumQueries; } - public TokenQuota setMaxNumQueries(long maxNumQueries) { + public ApiKeyQuota setMaxNumQueries(long maxNumQueries) { this.maxNumQueries = maxNumQueries; return this; } diff --git a/cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenStats.java b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyStats.java similarity index 71% rename from cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenStats.java rename to cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyStats.java index 7f4dd0efb..600b1c335 100644 --- a/cellbase-core/src/main/java/org/opencb/cellbase/core/token/TokenStats.java +++ b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/key/ApiKeyStats.java @@ -14,24 +14,24 @@ * limitations under the License. */ -package org.opencb.cellbase.core.token; +package org.opencb.cellbase.core.api.key; -public class TokenStats { - private String token; +public class ApiKeyStats { + private String apiKey; private String date; // date consists of year + month, e.g.: 202304 private long numQueries; private long duration; private long bytes; - public TokenStats() { + public ApiKeyStats() { } - public TokenStats(String token, String date) { - this(token, date, 0, 0, 0); + public ApiKeyStats(String apiKey, String date) { + this(apiKey, date, 0, 0, 0); } - public TokenStats(String token, String date, long numQueries, long duration, long bytes) { - this.token = token; + public ApiKeyStats(String apiKey, String date, long numQueries, long duration, long bytes) { + this.apiKey = apiKey; this.date = date; this.numQueries = numQueries; this.duration = duration; @@ -41,7 +41,7 @@ public TokenStats(String token, String date, long numQueries, long duration, lon @Override public String toString() { final StringBuilder sb = new StringBuilder("TokenStats{"); - sb.append("token='").append(token).append('\''); + sb.append("apiKey='").append(apiKey).append('\''); sb.append(", date='").append(date).append('\''); sb.append(", numQueries=").append(numQueries); sb.append(", duration=").append(duration); @@ -50,12 +50,12 @@ public String toString() { return sb.toString(); } - public String getToken() { - return token; + public String getApiKey() { + return apiKey; } - public TokenStats setToken(String token) { - this.token = token; + public ApiKeyStats setApiKey(String apiKey) { + this.apiKey = apiKey; return this; } @@ -63,7 +63,7 @@ public String getDate() { return date; } - public TokenStats setDate(String date) { + public ApiKeyStats setDate(String date) { this.date = date; return this; } @@ -72,7 +72,7 @@ public long getNumQueries() { return numQueries; } - public TokenStats setNumQueries(long numQueries) { + public ApiKeyStats setNumQueries(long numQueries) { this.numQueries = numQueries; return this; } @@ -81,7 +81,7 @@ public long getDuration() { return duration; } - public TokenStats setDuration(long duration) { + public ApiKeyStats setDuration(long duration) { this.duration = duration; return this; } @@ -90,7 +90,7 @@ public long getBytes() { return bytes; } - public TokenStats setBytes(long bytes) { + public ApiKeyStats setBytes(long bytes) { this.bytes = bytes; return this; } diff --git a/cellbase-core/src/main/java/org/opencb/cellbase/core/api/query/AbstractQuery.java b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/query/AbstractQuery.java index c3d2b4e6a..6fa4cf7b9 100644 --- a/cellbase-core/src/main/java/org/opencb/cellbase/core/api/query/AbstractQuery.java +++ b/cellbase-core/src/main/java/org/opencb/cellbase/core/api/query/AbstractQuery.java @@ -46,7 +46,9 @@ public abstract class AbstractQuery extends CellBaseQueryOptions { public static final int DEFAULT_SKIP = 0; public static final String DATA_RELEASE = "dataRelease"; - public static final String DATA_ACCESS_TOKEN = "token"; + public static final String API_KEY_PARAM = "apiKey"; + @Deprecated + public static final String TOKEN_PARAM = "token"; // list of fields in this class private Map classFields; @@ -60,8 +62,8 @@ public abstract class AbstractQuery extends CellBaseQueryOptions { @QueryParameter(id = DATA_RELEASE) private Integer dataRelease; - @QueryParameter(id = DATA_ACCESS_TOKEN) - private String token; + @QueryParameter(id = API_KEY_PARAM) + private String apiKey; public AbstractQuery() { init(); @@ -459,12 +461,23 @@ public AbstractQuery setDataRelease(Integer dataRelease) { return this; } + public String getApiKey() { + return apiKey; + } + + public AbstractQuery setApiKey(String apiKey) { + this.apiKey = apiKey; + return this; + } + + @Deprecated public String getToken() { - return token; + return apiKey; } + @Deprecated public AbstractQuery setToken(String token) { - this.token = token; + this.apiKey = token; return this; } } diff --git a/cellbase-core/src/main/java/org/opencb/cellbase/core/result/CellBaseDataResponse.java b/cellbase-core/src/main/java/org/opencb/cellbase/core/result/CellBaseDataResponse.java index afc0945b2..3682f714e 100644 --- a/cellbase-core/src/main/java/org/opencb/cellbase/core/result/CellBaseDataResponse.java +++ b/cellbase-core/src/main/java/org/opencb/cellbase/core/result/CellBaseDataResponse.java @@ -27,7 +27,7 @@ public class CellBaseDataResponse { private String apiVersion; private int dataRelease; - private String token; + private String apiKey; private int time; private List events; private ObjectMap params; @@ -40,11 +40,11 @@ public CellBaseDataResponse(ObjectMap params, List> respon this("", 0, "", -1, Collections.emptyList(), params, responses); } - public CellBaseDataResponse(String apiVersion, int dataRelease, String token, int time, List events, ObjectMap params, + public CellBaseDataResponse(String apiVersion, int dataRelease, String apiKey, int time, List events, ObjectMap params, List> responses) { this.apiVersion = apiVersion; this.dataRelease = dataRelease; - this.token = token; + this.apiKey = apiKey; this.time = time; this.events = events; this.params = params; @@ -152,7 +152,7 @@ public String toString() { final StringBuilder sb = new StringBuilder("CellBaseDataResponse{"); sb.append("apiVersion='").append(apiVersion).append('\''); sb.append(", dataRelease=").append(dataRelease); - sb.append(", token=").append(token); + sb.append(", apiKey=").append(apiKey); sb.append(", time=").append(time); sb.append(", events=").append(events); sb.append(", params=").append(params); @@ -179,12 +179,12 @@ public CellBaseDataResponse setDataRelease(int dataRelease) { return this; } - public String getToken() { - return token; + public String getApiKey() { + return apiKey; } - public CellBaseDataResponse setToken(String token) { - this.token = token; + public CellBaseDataResponse setApiKey(String apiKey) { + this.apiKey = apiKey; return this; } diff --git a/cellbase-lib/src/main/java/org/opencb/cellbase/lib/impl/core/MetaMongoDBAdaptor.java b/cellbase-lib/src/main/java/org/opencb/cellbase/lib/impl/core/MetaMongoDBAdaptor.java index 0e1172f46..9361f48d0 100644 --- a/cellbase-lib/src/main/java/org/opencb/cellbase/lib/impl/core/MetaMongoDBAdaptor.java +++ b/cellbase-lib/src/main/java/org/opencb/cellbase/lib/impl/core/MetaMongoDBAdaptor.java @@ -26,7 +26,7 @@ import org.opencb.cellbase.core.api.query.ProjectionQueryOptions; import org.opencb.cellbase.core.exception.CellBaseException; import org.opencb.cellbase.core.result.CellBaseDataResult; -import org.opencb.cellbase.core.token.TokenStats; +import org.opencb.cellbase.core.api.key.ApiKeyStats; import org.opencb.cellbase.lib.iterator.CellBaseIterator; import org.opencb.commons.datastore.core.FacetField; import org.opencb.commons.datastore.core.QueryOptions; @@ -40,11 +40,10 @@ /** * Created by fjlopez on 07/06/16. */ -@Deprecated public class MetaMongoDBAdaptor extends MongoDBAdaptor implements CellBaseCoreDBAdaptor { private MongoDBCollection mongoDBCollection; - private MongoDBCollection tokenStatsMongoDBCollection; + private MongoDBCollection apiKeyStatsMongoDBCollection; public MetaMongoDBAdaptor(MongoDataStore mongoDataStore) { super(mongoDataStore); @@ -56,7 +55,7 @@ public MetaMongoDBAdaptor(MongoDataStore mongoDataStore) { private void init() { logger.debug("MetaMongoDBAdaptor: in 'constructor'"); mongoDBCollection = mongoDataStore.getCollection("metadata"); - tokenStatsMongoDBCollection = mongoDataStore.getCollection("token_stats"); + apiKeyStatsMongoDBCollection = mongoDataStore.getCollection("apikey_stats"); } public CellBaseDataResult getAll() { @@ -90,7 +89,7 @@ public CellBaseDataResult distinct(AbstractQuery query) { } @Override - public List info(List ids, ProjectionQueryOptions queryOptions, int dataRelease, String token) { + public List info(List ids, ProjectionQueryOptions queryOptions, int dataRelease, String apiKey) { return null; } @@ -104,28 +103,28 @@ public CellBaseDataResult groupBy(AbstractQuery query) { return null; } - public CellBaseDataResult getQuota(String token, String date) { + public CellBaseDataResult getQuota(String apiKey, String date) { List andBsonList = new ArrayList<>(); - andBsonList.add(Filters.eq("token", token)); + andBsonList.add(Filters.eq("apiKey", apiKey)); andBsonList.add(Filters.eq("date", date)); Bson query = Filters.and(andBsonList); - return new CellBaseDataResult<>(tokenStatsMongoDBCollection.find(query, null, TokenStats.class, QueryOptions.empty())); + return new CellBaseDataResult<>(apiKeyStatsMongoDBCollection.find(query, null, ApiKeyStats.class, QueryOptions.empty())); } - public CellBaseDataResult initTokenStats(String token, String date) throws CellBaseException { + public CellBaseDataResult initApiKeyStats(String apiKey, String date) throws CellBaseException { try { - TokenStats tokenStats = new TokenStats(token, date); - Document document = Document.parse(new ObjectMapper().writeValueAsString(tokenStats)); - return new CellBaseDataResult<>(tokenStatsMongoDBCollection.insert(document, QueryOptions.empty())); + ApiKeyStats apiKeyStats = new ApiKeyStats(apiKey, date); + Document document = Document.parse(new ObjectMapper().writeValueAsString(apiKeyStats)); + return new CellBaseDataResult<>(apiKeyStatsMongoDBCollection.insert(document, QueryOptions.empty())); } catch (IOException e) { - throw new CellBaseException("Error initializing quota for token '" + token.substring(0, 10) + "...': " + e.getMessage()); + throw new CellBaseException("Error initializing quota for API key '" + apiKey.substring(0, 10) + "...': " + e.getMessage()); } } - public CellBaseDataResult incTokenStats(String token, String date, long incNumQueries, long incDuration, long incBytes) { + public CellBaseDataResult incApiKeyStats(String apiKey, String date, long incNumQueries, long incDuration, long incBytes) { List andBsonList = new ArrayList<>(); - andBsonList.add(Filters.eq("token", token)); + andBsonList.add(Filters.eq("apiKey", apiKey)); andBsonList.add(Filters.eq("date", date)); Bson query = Filters.and(andBsonList); @@ -139,7 +138,7 @@ public CellBaseDataResult incTokenStats(String token, String date, long incNumQu QueryOptions queryOptions = new QueryOptions("replace", true); - return new CellBaseDataResult<>(tokenStatsMongoDBCollection.findAndUpdate(query, projection, null, update, TokenStats.class, + return new CellBaseDataResult<>(apiKeyStatsMongoDBCollection.findAndUpdate(query, projection, null, update, ApiKeyStats.class, queryOptions)); } } diff --git a/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/AbstractManager.java b/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/AbstractManager.java index fd230d5bc..9e5b0744a 100644 --- a/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/AbstractManager.java +++ b/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/AbstractManager.java @@ -17,13 +17,14 @@ package org.opencb.cellbase.lib.managers; import org.apache.commons.lang3.StringUtils; +import org.opencb.cellbase.core.api.key.ApiKeyManager; import org.opencb.cellbase.core.config.CellBaseConfiguration; import org.opencb.cellbase.core.exception.CellBaseException; import org.opencb.cellbase.core.utils.SpeciesUtils; import org.opencb.cellbase.lib.db.MongoDBManager; import org.opencb.cellbase.lib.impl.core.MongoDBAdaptorFactory; -import org.opencb.cellbase.core.token.DataAccessTokenManager; import org.opencb.commons.datastore.core.Query; +import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.mongodb.MongoDataStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,6 +32,9 @@ import java.util.ArrayList; import java.util.List; +import static org.opencb.cellbase.core.api.query.AbstractQuery.API_KEY_PARAM; +import static org.opencb.cellbase.core.api.query.AbstractQuery.TOKEN_PARAM; + public class AbstractManager implements AutoCloseable { protected String species; @@ -41,7 +45,7 @@ public class AbstractManager implements AutoCloseable { protected MongoDataStore mongoDatastore; protected MongoDBAdaptorFactory dbAdaptorFactory; - protected DataAccessTokenManager tokenManager; + protected ApiKeyManager tokenManager; protected Logger logger; @@ -55,7 +59,7 @@ public AbstractManager(String databaseName, CellBaseConfiguration configuration) mongoDatastore = mongoDBManager.createMongoDBDatastore(databaseName); dbAdaptorFactory = new MongoDBAdaptorFactory(mongoDatastore); - tokenManager = new DataAccessTokenManager(configuration.getSecretKey()); + tokenManager = new ApiKeyManager(configuration.getSecretKey()); } public AbstractManager(String species, String assembly, CellBaseConfiguration configuration) @@ -76,9 +80,15 @@ public AbstractManager(String species, String assembly, CellBaseConfiguration co mongoDatastore = mongoDBManager.createMongoDBDatastore(species, assembly); dbAdaptorFactory = new MongoDBAdaptorFactory(mongoDatastore); - tokenManager = new DataAccessTokenManager(configuration.getSecretKey()); + tokenManager = new ApiKeyManager(configuration.getSecretKey()); } + protected String getApiKey(QueryOptions queryOptions) { + if (queryOptions.containsKey(API_KEY_PARAM)) { + return queryOptions.getString(API_KEY_PARAM); + } + return queryOptions.getString(TOKEN_PARAM); + } @Deprecated protected List createQueries(Query query, String csvField, String queryKey, String... args) { diff --git a/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/ClinicalManager.java b/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/ClinicalManager.java index c9e484b33..1eedb36dd 100644 --- a/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/ClinicalManager.java +++ b/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/ClinicalManager.java @@ -36,7 +36,6 @@ import java.util.*; import java.util.stream.Collectors; -import static org.opencb.cellbase.core.api.query.AbstractQuery.DATA_ACCESS_TOKEN; import static org.opencb.commons.datastore.core.QueryOptions.EXCLUDE; import static org.opencb.commons.datastore.core.QueryOptions.INCLUDE; @@ -69,7 +68,7 @@ public CellBaseDataResult search(ClinicalVariantQuery query) throws Que query.validate(); CellBaseDataResult results = getDBAdaptor().query(query); - Set validSources = tokenManager.getValidSources(query.getToken(), DataAccessTokenUtils.UNLICENSED_CLINICAL_DATA); + Set validSources = tokenManager.getValidSources(query.getApiKey(), DataAccessTokenUtils.UNLICENSED_CLINICAL_DATA); // Check if is necessary to use the token licensed variant iterator if (DataAccessTokenUtils.needFiltering(validSources, DataAccessTokenUtils.LICENSED_CLINICAL_DATA)) { @@ -106,7 +105,7 @@ public List> info(List ids, CellBaseQueryOpt @Override public CellBaseIterator iterator(ClinicalVariantQuery query) throws CellBaseException { - Set validSources = tokenManager.getValidSources(query.getToken(), DataAccessTokenUtils.UNLICENSED_CLINICAL_DATA); + Set validSources = tokenManager.getValidSources(query.getApiKey(), DataAccessTokenUtils.UNLICENSED_CLINICAL_DATA); // Check if is necessary to use the token licensed variant iterator if (DataAccessTokenUtils.needFiltering(validSources, DataAccessTokenUtils.LICENSED_CLINICAL_DATA)) { @@ -119,9 +118,7 @@ public CellBaseIterator iterator(ClinicalVariantQuery query) throws Cel public CellBaseDataResult search(Query query, QueryOptions queryOptions) throws CellBaseException { CellBaseDataResult result = clinicalDBAdaptor.nativeGet(query, queryOptions); - Set validSources = tokenManager.getValidSources(queryOptions.getString(DATA_ACCESS_TOKEN), - DataAccessTokenUtils.UNLICENSED_CLINICAL_DATA); - + Set validSources = tokenManager.getValidSources(getApiKey(queryOptions), DataAccessTokenUtils.UNLICENSED_CLINICAL_DATA); List includes = null; if (queryOptions.containsKey(INCLUDE)) { @@ -179,9 +176,9 @@ public List> getByVariant(List variants, Li QueryOptions queryOptions, int dataRelease) throws CellBaseException { List> results = clinicalDBAdaptor.getByVariant(variants, geneList, queryOptions, dataRelease); - Set validSources = tokenManager.getValidSources(queryOptions.getString(DATA_ACCESS_TOKEN), - DataAccessTokenUtils.UNLICENSED_CLINICAL_DATA); + Set validSources = tokenManager.getValidSources(getApiKey(queryOptions), DataAccessTokenUtils.UNLICENSED_CLINICAL_DATA); + // TODO: take into account includes and excludes List includes = null; if (queryOptions.containsKey(INCLUDE)) { includes = Arrays.asList(queryOptions.getString(INCLUDE).split(",")); diff --git a/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/MetaManager.java b/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/MetaManager.java index 42f9cc9b3..c1eb87aab 100644 --- a/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/MetaManager.java +++ b/cellbase-lib/src/main/java/org/opencb/cellbase/lib/managers/MetaManager.java @@ -16,18 +16,17 @@ package org.opencb.cellbase.lib.managers; +import org.opencb.cellbase.core.api.key.ApiKeyJwtPayload; +import org.opencb.cellbase.core.api.key.ApiKeyStats; import org.opencb.cellbase.core.config.CellBaseConfiguration; import org.opencb.cellbase.core.exception.CellBaseException; import org.opencb.cellbase.core.result.CellBaseDataResult; -import org.opencb.cellbase.core.token.TokenJwtPayload; -import org.opencb.cellbase.core.token.TokenStats; import org.opencb.cellbase.lib.impl.core.MetaMongoDBAdaptor; import org.opencb.commons.monitor.DatastoreStatus; import java.time.LocalDate; import java.util.Map; -@Deprecated public class MetaManager extends AbstractManager { public MetaManager(CellBaseConfiguration configuration) throws CellBaseException { @@ -57,15 +56,15 @@ public Map getDatabaseStatus(String species, String ass return this.mongoDBManager.getDatabaseStatus(species, assembly); } - public void checkQuota(String token, TokenJwtPayload payload) throws CellBaseException { - String date = getTokenStatsDate(); + public void checkQuota(String apiKey, ApiKeyJwtPayload payload) throws CellBaseException { + String date = getApiKeyStatsDate(); MetaMongoDBAdaptor metaDBAdaptor = dbAdaptorFactory.getMetaDBAdaptor(); - CellBaseDataResult quotaResult = metaDBAdaptor.getQuota(token, date); + CellBaseDataResult quotaResult = metaDBAdaptor.getQuota(apiKey, date); long numQueries = 0; if (quotaResult.getNumResults() == 0) { - metaDBAdaptor.initTokenStats(token, date); + metaDBAdaptor.initApiKeyStats(apiKey, date); } else { numQueries = quotaResult.first().getNumQueries(); } @@ -74,14 +73,14 @@ public void checkQuota(String token, TokenJwtPayload payload) throws CellBaseExc } } - public CellBaseDataResult incTokenStats(String token, long incNumQueries, long incDuration, long incBytes) { - String date = getTokenStatsDate(); + public CellBaseDataResult incApiKeyStats(String apiKey, long incNumQueries, long incDuration, long incBytes) { + String date = getApiKeyStatsDate(); MetaMongoDBAdaptor metaDBAdaptor = dbAdaptorFactory.getMetaDBAdaptor(); - return metaDBAdaptor.incTokenStats(token, date, incNumQueries, incDuration, incBytes); + return metaDBAdaptor.incApiKeyStats(apiKey, date, incNumQueries, incDuration, incBytes); } - private String getTokenStatsDate() { + private String getApiKeyStatsDate() { // Get the current year and month as yyyymm, e.g.:202309 LocalDate currentDate = LocalDate.now(); return currentDate.getYear() + String.format("%02d", currentDate.getMonthValue()); diff --git a/cellbase-lib/src/test/java/org/opencb/cellbase/lib/managers/DataAccessTokenManagerTest.java b/cellbase-lib/src/test/java/org/opencb/cellbase/lib/managers/ApiKeyManagerTest.java similarity index 55% rename from cellbase-lib/src/test/java/org/opencb/cellbase/lib/managers/DataAccessTokenManagerTest.java rename to cellbase-lib/src/test/java/org/opencb/cellbase/lib/managers/ApiKeyManagerTest.java index b92ca7c7c..56ce269a3 100644 --- a/cellbase-lib/src/test/java/org/opencb/cellbase/lib/managers/DataAccessTokenManagerTest.java +++ b/cellbase-lib/src/test/java/org/opencb/cellbase/lib/managers/ApiKeyManagerTest.java @@ -1,12 +1,11 @@ package org.opencb.cellbase.lib.managers; -import io.jsonwebtoken.Jwts; import org.apache.commons.collections4.MapUtils; import org.junit.Before; import org.junit.Test; -import org.opencb.cellbase.core.token.DataAccessTokenManager; -import org.opencb.cellbase.core.token.TokenJwtPayload; -import org.opencb.cellbase.core.token.TokenQuota; +import org.opencb.cellbase.core.api.key.ApiKeyManager; +import org.opencb.cellbase.core.api.key.ApiKeyJwtPayload; +import org.opencb.cellbase.core.api.key.ApiKeyQuota; import java.text.DateFormat; import java.text.ParseException; @@ -16,44 +15,44 @@ import java.util.Map; import static org.junit.Assert.*; -import static org.opencb.cellbase.core.token.TokenJwtPayload.DATE_FORMATTER; +import static org.opencb.cellbase.core.api.key.ApiKeyJwtPayload.DATE_FORMATTER; -public class DataAccessTokenManagerTest { +public class ApiKeyManagerTest { - DataAccessTokenManager datManager; + ApiKeyManager datManager; @Before public void before() { String randomStr = "xPacig89igHSieEnveJEi4KCfdEslhmssC3vui1JJQGgDQ0y8v"; System.out.println("Secret key = " + randomStr); - datManager = new DataAccessTokenManager(randomStr); + datManager = new ApiKeyManager(randomStr); } @Test public void test1() throws ParseException { - TokenJwtPayload payload = new TokenJwtPayload(); + ApiKeyJwtPayload payload = new ApiKeyJwtPayload(); payload.setSubject("ucam"); - payload.setVersion(TokenJwtPayload.CURRENT_VERSION); + payload.setVersion(ApiKeyJwtPayload.CURRENT_VERSION); Map sources = new HashMap<>(); sources.put("cosmic", DATE_FORMATTER.parse("25/09/2025")); sources.put("hgmd", DATE_FORMATTER.parse("01/01/2024")); payload.setSources(sources); - String token = datManager.encode(payload); - System.out.println(token); - datManager.display(token); + String apiKey = datManager.encode(payload); + System.out.println(apiKey); + datManager.display(apiKey); - TokenJwtPayload payload1 = datManager.decode(token); + ApiKeyJwtPayload payload1 = datManager.decode(apiKey); System.out.println(payload1); - datManager.validate(token); - System.out.println("valid token: pass"); + datManager.validate(apiKey); + System.out.println("valid API key: pass"); try { - token += "tototo"; - datManager.validate(token); + apiKey += "tototo"; + datManager.validate(apiKey); } catch (Exception e) { - System.out.println("invalid token: pass"); + System.out.println("invalid API key: pass"); return; } fail(); @@ -61,89 +60,89 @@ public void test1() throws ParseException { @Test public void testNotExpired() throws ParseException { - TokenJwtPayload payload = new TokenJwtPayload(); + ApiKeyJwtPayload payload = new ApiKeyJwtPayload(); payload.setSubject("ucam"); - payload.setVersion(TokenJwtPayload.CURRENT_VERSION); + payload.setVersion(ApiKeyJwtPayload.CURRENT_VERSION); Map sources = new HashMap<>(); sources.put("cosmic", DATE_FORMATTER.parse("25/09/2025")); payload.setSources(sources); - String token = datManager.encode(payload); - System.out.println(token); + String apiKey = datManager.encode(payload); + System.out.println(apiKey); - assertEquals(false, datManager.hasExpiredSource("cosmic", token)); + assertEquals(false, datManager.hasExpiredSource("cosmic", apiKey)); } @Test public void testExpired() throws ParseException { - TokenJwtPayload payload = new TokenJwtPayload(); + ApiKeyJwtPayload payload = new ApiKeyJwtPayload(); payload.setSubject("ucam"); - payload.setVersion(TokenJwtPayload.CURRENT_VERSION); + payload.setVersion(ApiKeyJwtPayload.CURRENT_VERSION); Map sources = new HashMap<>(); sources.put("cosmic", DATE_FORMATTER.parse("25/09/2021")); payload.setSources(sources); - String token = datManager.encode(payload); - System.out.println(token); + String apiKey = datManager.encode(payload); + System.out.println(apiKey); - assertEquals(true, datManager.hasExpiredSource("cosmic", token)); + assertEquals(true, datManager.hasExpiredSource("cosmic", apiKey)); } @Test(expected = IllegalArgumentException.class) public void testInvalidSource() throws ParseException { DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); - TokenJwtPayload payload = new TokenJwtPayload(); + ApiKeyJwtPayload payload = new ApiKeyJwtPayload(); payload.setSubject("ucam"); - payload.setVersion(TokenJwtPayload.CURRENT_VERSION); + payload.setVersion(ApiKeyJwtPayload.CURRENT_VERSION); Map sources = new HashMap<>(); sources.put("cosmic", formatter.parse("25/09/2021")); payload.setSources(sources); - String token = datManager.encode(payload); + String apiKey = datManager.encode(payload); - datManager.hasExpiredSource("hgmd", token); + datManager.hasExpiredSource("hgmd", apiKey); } @Test - public void testRecodeToken() throws ParseException { - TokenJwtPayload payload = new TokenJwtPayload(); + public void testRecodeApiKey() throws ParseException { + ApiKeyJwtPayload payload = new ApiKeyJwtPayload(); payload.setSubject("ucam"); - payload.setVersion(TokenJwtPayload.CURRENT_VERSION); + payload.setVersion(ApiKeyJwtPayload.CURRENT_VERSION); Map sources = new HashMap<>(); sources.put("cadd", DATE_FORMATTER.parse("25/09/2030")); sources.put("cosmic", DATE_FORMATTER.parse("25/09/2021")); payload.setSources(sources); - String token = datManager.encode(payload); - String newToken = datManager.recode(token); + String apiKey = datManager.encode(payload); + String newApiKey = datManager.recode(apiKey); - TokenJwtPayload payload1 = datManager.decode(newToken); + ApiKeyJwtPayload payload1 = datManager.decode(newApiKey); assertEquals(1, payload1.getSources().size()); assertTrue(payload1.getSources().containsKey("cadd")); } @Test(expected = IllegalArgumentException.class) public void testValidSources() throws ParseException { - TokenJwtPayload payload = new TokenJwtPayload(); + ApiKeyJwtPayload payload = new ApiKeyJwtPayload(); payload.setSubject("ucam"); - payload.setVersion(TokenJwtPayload.CURRENT_VERSION); + payload.setVersion(ApiKeyJwtPayload.CURRENT_VERSION); Map sources = new HashMap<>(); sources.put("cosmic", DATE_FORMATTER.parse("25/09/2024")); sources.put("hgmd", DATE_FORMATTER.parse("25/09/2020")); sources.put("cadd", DATE_FORMATTER.parse("25/09/2025")); payload.setSources(sources); - String token = datManager.encode(payload); + String apiKey = datManager.encode(payload); - datManager.getValidSources(token); + datManager.getValidSources(apiKey); } @Test - public void defaultTokenTest() { - String defaultToken = datManager.getDefaultToken(); - TokenJwtPayload payload = datManager.decode(defaultToken); + public void defaultApiKeyTest() { + String defaultApiKey = datManager.getDefaultApiKey(); + ApiKeyJwtPayload payload = datManager.decode(defaultApiKey); assertTrue(MapUtils.isEmpty(payload.getSources())); - assertEquals((long) TokenQuota.MAX_NUM_ANOYMOUS_QUERIES, payload.getQuota().getMaxNumQueries()); + assertEquals((long) ApiKeyQuota.MAX_NUM_ANOYMOUS_QUERIES, payload.getQuota().getMaxNumQueries()); } } \ No newline at end of file diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/GenericRestWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/GenericRestWSServer.java index 3f7a023df..00514f334 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/GenericRestWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/GenericRestWSServer.java @@ -33,8 +33,8 @@ import org.opencb.cellbase.core.exception.CellBaseException; import org.opencb.cellbase.core.result.CellBaseDataResponse; import org.opencb.cellbase.core.result.CellBaseDataResult; -import org.opencb.cellbase.core.token.DataAccessTokenManager; -import org.opencb.cellbase.core.token.TokenJwtPayload; +import org.opencb.cellbase.core.api.key.ApiKeyManager; +import org.opencb.cellbase.core.api.key.ApiKeyJwtPayload; import org.opencb.cellbase.core.utils.SpeciesUtils; import org.opencb.cellbase.lib.managers.CellBaseManagerFactory; import org.opencb.cellbase.lib.managers.DataReleaseManager; @@ -60,7 +60,7 @@ import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; -import static org.opencb.cellbase.core.api.query.AbstractQuery.DATA_ACCESS_TOKEN; +import static org.opencb.cellbase.core.api.query.AbstractQuery.*; @Path("/{version}/{species}") @Produces("text/plain") @@ -97,8 +97,8 @@ public class GenericRestWSServer implements IWSServer { // this webservice has no species, do not validate private static final String DONT_CHECK_SPECIES = "do not validate species"; - protected static String defaultToken; - protected static DataAccessTokenManager dataAccessTokenManager; + protected static String defaultApiKey; + protected static ApiKeyManager apiKeyManager; public GenericRestWSServer(@PathParam("version") String version, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { @@ -160,11 +160,11 @@ private void init() throws IOException, CellBaseException { } private void initQuery() throws CellBaseException { - // Get default token (for anonymous queries) - if (dataAccessTokenManager == null) { - dataAccessTokenManager = new DataAccessTokenManager(cellBaseConfiguration.getSecretKey()); - defaultToken = dataAccessTokenManager.getDefaultToken(); - logger.info("default token {}", defaultToken); + // Get default API key (for anonymous queries) + if (apiKeyManager == null) { + apiKeyManager = new ApiKeyManager(cellBaseConfiguration.getSecretKey()); + defaultApiKey = apiKeyManager.getDefaultApiKey(); + logger.info("default API key {}", defaultApiKey); } startTime = System.currentTimeMillis(); @@ -177,12 +177,15 @@ private void initQuery() throws CellBaseException { uriParams.remove("assembly"); } - // Set default token, if necessary - logger.info("before checking, token {}", uriParams.get(DATA_ACCESS_TOKEN)); - if (StringUtils.isEmpty(uriParams.get(DATA_ACCESS_TOKEN))) { - uriParams.put(DATA_ACCESS_TOKEN, defaultToken); + // Set default API key, if necessary + // For back-compatibility, we get 'token' parameter after checking 'apiKey' parameter + String apiKey = uriParams.containsKey(API_KEY_PARAM) ? uriParams.get(API_KEY_PARAM) : uriParams.get(TOKEN_PARAM); + logger.info("before checking, API key {}", apiKey); + if (StringUtils.isEmpty(apiKey)) { + apiKey = defaultApiKey; } - logger.info("after checking, token {}", uriParams.get(DATA_ACCESS_TOKEN)); + uriParams.put(API_KEY_PARAM, apiKey); + logger.info("after checking, API key {}", uriParams.get(API_KEY_PARAM)); checkLimit(); @@ -201,8 +204,8 @@ private void initQuery() throws CellBaseException { } } - // Check quota - checkToken(); + // Check API key (expiration date, quota,...) + checkApiKey(); } protected int getDataRelease() throws CellBaseException { @@ -229,8 +232,8 @@ protected int getDataRelease() throws CellBaseException { return defaultDataRelease; } - protected String getToken() { - return uriParams.get(DATA_ACCESS_TOKEN); + protected String getApiKey() { + return uriParams.get(API_KEY_PARAM); } /** @@ -265,28 +268,22 @@ private void checkVersion() throws CellBaseException { } } - private void checkToken() throws CellBaseException { + private void checkApiKey() throws CellBaseException { if (!uriInfo.getPath().contains("health")) { - String token = getToken(); - TokenJwtPayload payload = dataAccessTokenManager.decode(token); + String apiKey = getApiKey(); + ApiKeyJwtPayload payload = apiKeyManager.decode(apiKey); - // Check token expiration date - if (payload.getExpiration() != null - && payload.getExpiration().getTime() < new Date().getTime()) { - throw new CellBaseException("CellBase token has expired"); + // Check API key expiration date + if (payload.getExpiration() != null && payload.getExpiration().getTime() < new Date().getTime()) { + throw new CellBaseException("CellBase API key has expired"); } - // Check token quota + // Check quota MetaManager metaManager = cellBaseManagerFactory.getMetaManager(); - metaManager.checkQuota(token, payload); + metaManager.checkQuota(apiKey, payload); } } - private void incTokenStats(Response response) throws CellBaseException { - MetaManager metaManager = cellBaseManagerFactory.getMetaManager(); - metaManager.incTokenStats(getToken(), 1, 0, response.getLength()); - } - private Map convertMultiToMap(MultivaluedMap multivaluedMap) { Map convertedMap = new HashMap(); if (multivaluedMap == null) { @@ -357,7 +354,7 @@ protected Response createErrorResponse(Exception e) { } catch (CellBaseException ex) { logger.warn("Impossible to set the data release used in the query response", e); } - queryResponse.setToken(getToken()); + queryResponse.setApiKey(getApiKey()); // queryResponse.setParams(new ObjectMap(queryOptions)); queryResponse.addEvent(new Event(Event.Type.ERROR, e.toString())); @@ -388,7 +385,7 @@ protected Response createOkResponse(Object obj) { } catch (CellBaseException e) { logger.warn("Impossible to set the data release used in the query response", e); } - queryResponse.setToken(getToken()); + queryResponse.setApiKey(getApiKey()); ObjectMap params = new ObjectMap(); params.put("species", species); @@ -411,13 +408,13 @@ protected Response createOkResponse(Object obj) { Response jsonResponse = createJsonResponse(queryResponse); - // Update token stats, if necessary + // Update API key stats, if necessary try { if (!uriInfo.getPath().contains("health")) { - String token = getToken(); + String apiKey = getApiKey(); MetaManager metaManager = cellBaseManagerFactory.getMetaManager(); long bytes = (jsonResponse.getEntity() != null) ? jsonResponse.getEntity().toString().length() : 0; - metaManager.incTokenStats(token, 1, queryResponse.getTime(), bytes); + metaManager.incApiKeyStats(apiKey, 1, queryResponse.getTime(), bytes); } } catch (CellBaseException e) { return createErrorResponse(e); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/MetaWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/MetaWSServer.java index e75d30fc0..6df1e8ea9 100644 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/MetaWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/MetaWSServer.java @@ -28,8 +28,8 @@ import org.opencb.cellbase.core.exception.CellBaseException; import org.opencb.cellbase.core.models.DataRelease; import org.opencb.cellbase.core.result.CellBaseDataResult; -import org.opencb.cellbase.core.token.DataAccessTokenManager; -import org.opencb.cellbase.core.token.TokenJwtPayload; +import org.opencb.cellbase.core.api.key.ApiKeyManager; +import org.opencb.cellbase.core.api.key.ApiKeyJwtPayload; import org.opencb.cellbase.core.utils.SpeciesUtils; import org.opencb.cellbase.lib.managers.DataReleaseManager; import org.opencb.cellbase.lib.managers.MetaManager; @@ -144,13 +144,13 @@ public Response getDataRelease(@PathParam("species") @GET @Path("/getLicensedData") - @ApiOperation(httpMethod = "GET", value = "Display the licensed data sources of the input token and their expiration date", + @ApiOperation(httpMethod = "GET", value = "Display the licensed data sources of the input API key and their expiration date", response = Map.class, responseContainer = "QueryResponse") - public Response getLicensedData(@ApiParam(name = "token", required = true, value = ParamConstants.DATA_ACCESS_TOKEN_DESCRIPTION) - @QueryParam("token") String token) { + public Response getLicensedData(@ApiParam(name = "apiKey", required = true, value = ParamConstants.API_KEY_DESCRIPTION) + @QueryParam("apiKey") String apiKey) { try { - DataAccessTokenManager datManager = new DataAccessTokenManager(cellBaseConfiguration.getSecretKey()); - TokenJwtPayload payload = datManager.decode(token); + ApiKeyManager datManager = new ApiKeyManager(cellBaseConfiguration.getSecretKey()); + ApiKeyJwtPayload payload = datManager.decode(apiKey); // Convert milliseconds to date in format dd/MM/yyyy Map expDates = new HashMap<>(); @@ -167,15 +167,15 @@ public Response getLicensedData(@ApiParam(name = "token", required = true, value @GET @Path("/removeExpiredLicensedData") - @ApiOperation(httpMethod = "GET", value = "Create a new token by removing the expired licensed data sources from the input token", + @ApiOperation(httpMethod = "GET", value = "Create a new API key by removing the expired licensed data sources from the input API key", response = String.class, responseContainer = "QueryResponse") - public Response removeExpiredLicensedData(@ApiParam(name = "token", required = true, - value = ParamConstants.DATA_ACCESS_TOKEN_DESCRIPTION) @QueryParam("token") String token) { + public Response removeExpiredLicensedData(@ApiParam(name = "apiKey", required = true, + value = ParamConstants.API_KEY_DESCRIPTION) @QueryParam("apiKey") String apiKey) { try { - DataAccessTokenManager dataManager = new DataAccessTokenManager(cellBaseConfiguration.getSecretKey()); + ApiKeyManager dataManager = new ApiKeyManager(cellBaseConfiguration.getSecretKey()); return createOkResponse(new CellBaseDataResult<>(null, 1, Collections.emptyList(), 1, - Collections.singletonList(dataManager.recode(token)), 1)); + Collections.singletonList(dataManager.recode(apiKey)), 1)); } catch (Exception e) { return createErrorResponse(e); } @@ -342,17 +342,23 @@ public Response ping() { @ApiOperation(httpMethod = "GET", value = "Reports on the overall system status based on the status of such things " + "as database connections and the ability to access other APIs.", response = DownloadProperties.class, responseContainer = "QueryResponse") - public Response status(@PathParam("species") @ApiParam(name = "species", value = ParamConstants.SPECIES_DESCRIPTION, required = true) - String species, - @ApiParam(name = "assembly", value = ParamConstants.ASSEMBLY_DESCRIPTION) @QueryParam("assembly") - String assembly, - @DefaultValue("") - @QueryParam("token") - @ApiParam(name = "token", - value = "API token for health check. When passed all of the " - + "dependencies and their status will be displayed. The dependencies will be checked if " - + "this parameter is not used, but they won't be part of the response", - required = false) String token) { + public Response status( + @PathParam("species") @ApiParam(name = "species", value = ParamConstants.SPECIES_DESCRIPTION, required = true) + String species, + @ApiParam(name = "assembly", value = ParamConstants.ASSEMBLY_DESCRIPTION) @QueryParam("assembly") + String assembly, + @DefaultValue("") + @QueryParam("token") + @ApiParam(name = "token", hidden = true, + value = "API token for health check. When passed all of the " + + "dependencies and their status will be displayed. The dependencies will be checked if " + + "this parameter is not used, but they won't be part of the response") String token, + @DefaultValue("") + @QueryParam("apiKey") + @ApiParam(name = "apiKey", + value = "API key for health check. When passed all of the " + + "dependencies and their status will be displayed. The dependencies will be checked if " + + "this parameter is not used, but they won't be part of the response") String apiKey) { if (StringUtils.isEmpty(assembly)) { try { @@ -368,7 +374,7 @@ public Response status(@PathParam("species") @ApiParam(name = "species", value = } HealthCheckResponse health = monitor.run(httpServletRequest.getRequestURI(), cellBaseConfiguration, species, - assembly, token); + assembly, StringUtils.isNotEmpty(apiKey) ? apiKey : token); return createJsonResponse(health); } @@ -378,13 +384,19 @@ public Response status(@PathParam("species") @ApiParam(name = "species", value = @ApiOperation(httpMethod = "GET", value = "Reports on the overall system status based on the status of such things " + "as database connections and the ability to access other APIs.", response = HealthCheckResponse.class) - public Response status(@DefaultValue("") - @QueryParam("token") - @ApiParam(name = "token", - value = "API token for health check. When passed all of the " - + "dependencies and their status will be displayed. The dependencies will be checked if " - + "this parameter is not used, but they won't be part of the response", - required = false) String token) { + public Response status( + @DefaultValue("") + @QueryParam("token") + @ApiParam(name = "token", hidden = true, + value = "API token for health check. When passed all of the " + + "dependencies and their status will be displayed. The dependencies will be checked if " + + "this parameter is not used, but they won't be part of the response") String token, + @DefaultValue("") + @QueryParam("apiKey") + @ApiParam(name = "apiKey", + value = "API token for health check. When passed all of the " + + "dependencies and their status will be displayed. The dependencies will be checked if " + + "this parameter is not used, but they won't be part of the response") String apiKey) { /** * Hardcode the species and assembly for required heath check. This is fine and will not cause problems in the future. @@ -393,7 +405,7 @@ public Response status(@DefaultValue("") String assemblyHealthcheck = "grch38"; HealthCheckResponse health = monitor.run(httpServletRequest.getRequestURI(), cellBaseConfiguration, speciesHealthCheck, - assemblyHealthcheck, token); + assemblyHealthcheck, StringUtils.isNotEmpty(apiKey) ? apiKey : token); return createJsonResponse(health); } diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/OntologyWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/OntologyWSServer.java index 68b6d0021..24bc14c88 100644 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/OntologyWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/OntologyWSServer.java @@ -53,8 +53,9 @@ public OntologyWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", @ApiParam(name = "assembly", value = ASSEMBLY_DESCRIPTION) @QueryParam("assembly") String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); @@ -136,7 +137,7 @@ public Response getInfo(@PathParam("ids") @ApiParam(name = "ids", value = ONTOLO try { OntologyQuery query = new OntologyQuery(uriParams); List> queryResults = ontologyManager.info(Arrays.asList(ids.split(",")), query, - getDataRelease(), getToken()); + getDataRelease(), getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { return createErrorResponse(e); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/PublicationWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/PublicationWSServer.java index 4135848cc..a4234fd9d 100644 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/PublicationWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/PublicationWSServer.java @@ -52,8 +52,10 @@ public PublicationWSServer(@PathParam("apiVersion") defaultValue = ParamConstants.DEFAULT_VERSION) String apiVersion, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") + String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, uriInfo, hsr); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/SpeciesWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/SpeciesWSServer.java index c0c2f79db..dc7966054 100644 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/SpeciesWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/SpeciesWSServer.java @@ -51,8 +51,9 @@ public SpeciesWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", v String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/clinical/ClinicalWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/clinical/ClinicalWSServer.java index 3800d3bbb..3b337e7c7 100644 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/clinical/ClinicalWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/clinical/ClinicalWSServer.java @@ -51,8 +51,9 @@ public ClinicalWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/clinical/PharmacogenomicsWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/clinical/PharmacogenomicsWSServer.java index 983a45f73..23f75aff5 100644 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/clinical/PharmacogenomicsWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/clinical/PharmacogenomicsWSServer.java @@ -52,11 +52,13 @@ public PharmacogenomicsWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVe defaultValue = DEFAULT_VERSION) String apiVersion, @PathParam("species") @ApiParam(name = "species", value = SPECIES_DESCRIPTION) String species, @ApiParam(name = "assembly", value = ASSEMBLY_DESCRIPTION) @DefaultValue("") @QueryParam("assembly") - String assembly, + String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") - String token, + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") + @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") + String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); @@ -144,11 +146,11 @@ public Response getAll() { required = false, dataType = "java.util.List", paramType = "query") }) public Response getInfo(@PathParam("chemicals") @ApiParam(name = "chemicals", value = "Chemical/drug names", required = true) - String chemicals) { + String chemicals) { try { PharmaChemicalQuery pharmaQuery = new PharmaChemicalQuery(uriParams); List> queryResults = pharmacogenomicsManager.info(Arrays.asList(chemicals.split(",")), - pharmaQuery, getDataRelease(), getToken()); + pharmaQuery, getDataRelease(), getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { return createErrorResponse(e); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/GeneWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/GeneWSServer.java index c73e711d7..759aa76c1 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/GeneWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/GeneWSServer.java @@ -69,8 +69,9 @@ public GeneWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", valu String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); @@ -367,7 +368,7 @@ public Response getInfo(@PathParam("genes") @ApiParam(name = "genes", value = GE source = geneQuery.getSource().get(0); } List> queryResults = geneManager.info(Arrays.asList(genes.split(",")), geneQuery, source, - getDataRelease(), getToken()); + getDataRelease(), getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { return createErrorResponse(e); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/IdWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/IdWSServer.java index 28c5dafcd..ca91002aa 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/IdWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/IdWSServer.java @@ -59,7 +59,9 @@ public IdWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", value @ApiParam(name = "assembly", value = ASSEMBLY_DESCRIPTION) @DefaultValue("") @QueryParam("assembly") String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") + String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); if (assembly == null) { @@ -89,7 +91,7 @@ public Response getInfo(@PathParam("id") @ApiParam(name = "id", value = FEATURE_ try { XrefQuery query = new XrefQuery(uriParams); List> queryResults = xrefManager.info(Arrays.asList(id.split(",")), query, getDataRelease(), - getToken()); + getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { return createErrorResponse(e); @@ -182,7 +184,7 @@ public Response getGeneByEnsemblId(@PathParam("id") try { GeneQuery query = new GeneQuery(uriParams); List> queryResults = geneManager.info(Arrays.asList(id.split(",")), query, getDataRelease(), - getToken()); + getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { return createErrorResponse(e); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/ProteinWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/ProteinWSServer.java index be2d76db1..c34fb5008 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/ProteinWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/ProteinWSServer.java @@ -54,8 +54,9 @@ public ProteinWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", v String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); @@ -89,7 +90,7 @@ public Response getInfo(@PathParam("proteins") @ApiParam(name = "proteins", valu try { ProteinQuery query = new ProteinQuery(uriParams); List> queryResults = proteinManager.info(Arrays.asList(id.split(",")), query, getDataRelease(), - getToken()); + getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { return createErrorResponse(e); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/TranscriptWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/TranscriptWSServer.java index 11e8de47f..a9a0be05b 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/TranscriptWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/feature/TranscriptWSServer.java @@ -62,8 +62,9 @@ public TranscriptWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion" String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); @@ -106,7 +107,7 @@ public Response getInfo(@PathParam("transcripts") @ApiParam(name = "transcripts" source = query.getSource().get(0); } List> queryResults = transcriptManager.info(Arrays.asList(transcripts.split(",")), query, - source, getDataRelease(), getToken()); + source, getDataRelease(), getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { return createErrorResponse(e); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/ChromosomeWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/ChromosomeWSServer.java index a738210a9..4b83ceef9 100644 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/ChromosomeWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/ChromosomeWSServer.java @@ -56,8 +56,9 @@ public ChromosomeWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion" String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/RegionWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/RegionWSServer.java index a12a24761..a44219abb 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/RegionWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/RegionWSServer.java @@ -63,8 +63,9 @@ public RegionWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", va String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/VariantWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/VariantWSServer.java index 4ab8afc52..84c05e34c 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/VariantWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/genomic/VariantWSServer.java @@ -55,8 +55,9 @@ public VariantWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", v String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); @@ -350,7 +351,7 @@ private Response getAnnotationByVariant(String variants, : uriParams.get("consequenceTypeSource")); List> queryResults = variantManager.getAnnotationByVariant(query.toQueryOptions(), variants, normalize, decompose, leftAlign, ignorePhase, phased, imprecise, svExtraPadding, cnvExtraPadding, - checkAminoAcidChange, consequenceTypeSources, getDataRelease(), getToken()); + checkAminoAcidChange, consequenceTypeSources, getDataRelease(), getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { @@ -407,7 +408,7 @@ public Response getInfo(@PathParam("variants") @ApiParam(name = "variants", valu try { VariantQuery query = new VariantQuery(uriParams); List> queryResults = variantManager.info(Arrays.asList(id.split(",")), query, - getDataRelease(), getToken()); + getDataRelease(), getApiKey()); return createOkResponse(queryResults); } catch (Exception e) { return createErrorResponse(e); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/regulatory/RegulatoryWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/regulatory/RegulatoryWSServer.java index d41f06c10..7c391f26b 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/regulatory/RegulatoryWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/regulatory/RegulatoryWSServer.java @@ -49,8 +49,9 @@ public RegulatoryWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion" String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { super(apiVersion, species, uriInfo, hsr); diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/regulatory/TfWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/regulatory/TfWSServer.java index 4b7b04cca..a4f5e1dd4 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/regulatory/TfWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/rest/regulatory/TfWSServer.java @@ -58,11 +58,12 @@ public TfWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", value @ApiParam(name = "assembly", value = ASSEMBLY_DESCRIPTION) @DefaultValue("") @QueryParam("assembly") String assembly, @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease") int dataRelease, - @ApiParam(name = "token", value = DATA_ACCESS_TOKEN_DESCRIPTION) @DefaultValue("") @QueryParam("token") + @ApiParam(name = "token", value = API_KEY_DESCRIPTION, hidden = true) @DefaultValue("") @QueryParam("token") String token, + @ApiParam(name = "apiKey", value = API_KEY_DESCRIPTION) @DefaultValue("") @QueryParam("apiKey") String apiKey, @Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws QueryException, IOException, CellBaseException { - super(apiVersion, species, assembly, dataRelease, token, uriInfo, hsr); + super(apiVersion, species, assembly, dataRelease, token, apiKey, uriInfo, hsr); regulatoryManager = cellBaseManagerFactory.getRegulatoryManager(species, assembly); tfbsManager = cellBaseManagerFactory.getTFManager(species, assembly);