From ae13c4186c2b6e6b07d11f112295fed71f733e9a Mon Sep 17 00:00:00 2001 From: Teo D Date: Wed, 10 Feb 2021 10:03:27 +0200 Subject: [PATCH] GDB-5393 Refactor repository and server clients configuration (#127) * GDB-5393 Refactor repository and server clients configuration Provides configuration builder and unifies configuration creation. Provides authentication factory. Authentication service refactor to decouple user state Minor sonar bug fixes Test refactored according code changes New eslint rules for test files Update documentation Update README.md Update CHANGELOG.md --- .eslintrc | 13 +- CHANGELOG.md | 18 + README.md | 82 +- docs/AddStatementPayload.html | 708 ++++++------- docs/AppSettings.html | 4 +- docs/Authentication.html | 421 ++++++++ docs/AuthenticationFactory.html | 340 +++++++ docs/AuthenticationService.html | 325 +++--- docs/BaseRepositoryClient.html | 269 ++++- docs/BasicAuthentication.html | 394 ++++++++ docs/ClientConfig.html | 710 +++++++------ docs/CommonUtils.html | 4 +- docs/ConsoleLogger.html | 4 +- docs/ContentParser.html | 4 +- docs/DownloadService.html | 4 +- docs/FileUtils.html | 4 +- docs/GdbTokenAuthentication.html | 394 ++++++++ docs/GetQueryPayload.html | 4 +- docs/GetStatementsPayload.html | 4 +- docs/GraphDBServerClient.html | 4 +- docs/HttpClient.html | 4 +- docs/HttpRequestBuilder.html | 4 +- docs/HttpResponse.html | 4 +- docs/Iterable.html | 4 +- docs/JsonLDParser.html | 4 +- docs/Logger.html | 4 +- docs/LoggingUtils.html | 4 +- docs/N3Parser.html | 4 +- docs/NQuadsParser.html | 4 +- docs/NTriplesParser.html | 4 +- docs/Namespace.html | 4 +- docs/NamespaceService.html | 4 +- docs/PagedResponse.html | 4 +- docs/ParserRegistry.html | 4 +- docs/QueryPayload.html | 4 +- docs/QueryService.html | 4 +- docs/RDFRepositoryClient.html | 4 +- docs/RDFXmlParser.html | 4 +- docs/RepositoryClientConfig.html | 943 ++++++++++-------- docs/RepositoryConfig.html | 4 +- docs/RepositoryService.html | 4 +- docs/ResponseIterator.html | 4 +- docs/ServerClient.html | 269 ++++- docs/ServerClientConfig.html | 773 ++++++++------ docs/Service.html | 4 +- docs/ServiceRequest.html | 4 +- docs/SparqlJsonResultParser.html | 4 +- docs/SparqlXmlResultParser.html | 4 +- docs/StatementPayload.html | 4 +- docs/StatementsService.html | 4 +- docs/StringUtils.html | 4 +- docs/TermConverter.html | 4 +- docs/TransactionService.html | 14 +- docs/TransactionalRepositoryClient.html | 4 +- docs/TriGParser.html | 4 +- docs/TurtleParser.html | 4 +- docs/UpdateQueryPayload.html | 4 +- docs/UploadService.html | 4 +- docs/User.html | 4 +- docs/auth_user.js.html | 4 +- docs/global.html | 4 +- docs/http_client-config.js.html | 128 ++- docs/http_http-client.js.html | 4 +- docs/http_http-request-builder.js.html | 4 +- docs/http_http-response.js.html | 4 +- docs/http_media-type.js.html | 4 +- docs/http_query-content-type.js.html | 4 +- docs/http_rdf-mime-type.js.html | 4 +- docs/index.html | 85 +- docs/logging_console-logger.js.html | 4 +- docs/logging_logger.js.html | 4 +- docs/logging_logging-utils.js.html | 4 +- docs/model_namespace.js.html | 4 +- docs/model_term-converter.js.html | 4 +- docs/model_types.js.html | 4 +- docs/parser_content-parser.js.html | 4 +- docs/parser_jsonld-parser.js.html | 4 +- docs/parser_n-quads-parser.js.html | 4 +- docs/parser_n-triples-parser.js.html | 4 +- docs/parser_n3-parser.js.html | 4 +- docs/parser_parser-registry.js.html | 4 +- docs/parser_rdfxml-parser.js.html | 4 +- docs/parser_sparql-json-result-parser.js.html | 4 +- docs/parser_sparql-xml-result-parser.js.html | 4 +- docs/parser_trig-parser.js.html | 4 +- docs/parser_turtle-parser.js.html | 4 +- docs/query_get-query-payload.js.html | 4 +- docs/query_query-language.js.html | 4 +- docs/query_query-payload.js.html | 4 +- docs/query_query-type.js.html | 4 +- docs/query_update-query-payload.js.html | 4 +- docs/repository_add-statement-payload.js.html | 4 +- .../repository_base-repository-client.js.html | 33 +- .../repository_get-statements-payload.js.html | 4 +- docs/repository_rdf-repository-client.js.html | 4 +- ...epository_repository-client-config.js.html | 44 +- docs/repository_repository-config.js.html | 4 +- docs/repository_repository-type.js.html | 4 +- docs/repository_statement-payload.js.html | 4 +- docs/response_paged-response.js.html | 4 +- docs/response_response-iterator.js.html | 4 +- docs/security_authentication-factory.js.html | 79 ++ docs/security_authentication.js.html | 86 ++ docs/security_authority.js.html | 4 +- docs/security_basic-authentication.js.html | 85 ++ .../security_gdb-token-authentication.js.html | 84 ++ docs/server_app-settings.js.html | 4 +- docs/server_graphdb-server-client.js.html | 4 +- docs/server_server-client-config.js.html | 35 +- docs/server_server-client.js.html | 33 +- docs/service_authentication-service.js.html | 90 +- docs/service_download-service.js.html | 4 +- docs/service_namespace-service.js.html | 4 +- docs/service_query-service.js.html | 4 +- docs/service_repository-service.js.html | 4 +- docs/service_service-paths.js.html | 4 +- docs/service_service-request.js.html | 4 +- docs/service_service.js.html | 4 +- docs/service_statements-service.js.html | 4 +- docs/service_transaction-service.js.html | 9 +- docs/service_upload-service.js.html | 4 +- ...action_transaction-isolation-level.js.html | 4 +- ...on_transactional-repository-client.js.html | 4 +- docs/util_common-utils.js.html | 4 +- docs/util_file-utils.js.html | 4 +- docs/util_iterable.js.html | 4 +- docs/util_string-utils.js.html | 4 +- src/http/client-config.js | 122 ++- src/repository/base-repository-client.js | 29 +- src/repository/repository-client-config.js | 40 +- src/security/authentication-factory.js | 28 + src/security/authentication.js | 35 + src/security/basic-authentication.js | 34 + src/security/gdb-token-authentication.js | 33 + src/server/server-client-config.js | 31 +- src/server/server-client.js | 29 +- src/service/authentication-service.js | 84 +- src/service/transaction-service.js | 5 +- test-e2e/tests/auth-repository-client.spec.js | 10 +- test-e2e/tests/auth-server-client.spec.js | 8 +- test-e2e/tests/config.js | 55 +- test-e2e/tests/download.spec.js | 10 +- test-e2e/tests/graphdb-server-client.spec.js | 59 +- test-e2e/tests/namespaces.spec.js | 25 +- test-e2e/tests/repositories.spec.js | 17 +- test-e2e/tests/transactions.spec.js | 176 ++-- test-e2e/tests/utils.js | 44 +- .../base-repository-client-failover.spec.js | 55 +- .../repository/get-statements-payload.spec.js | 5 +- .../rdf-repository-client-adding-data.spec.js | 178 ++-- ...sitory-client-authentication-basic.spec.js | 146 +++ ...itory-client-authentication-token.spec.js} | 16 +- ...df-repository-client-deleting-data.spec.js | 86 +- .../rdf-repository-client-namespaces.spec.js | 94 +- .../rdf-repository-client-query.spec.js | 19 +- ...rdf-repository-client-reading-data.spec.js | 54 +- ...f-repository-client-streaming-data.spec.js | 48 +- ...rdf-repository-client-transactions.spec.js | 285 +++--- ...rdf-repository-client-update-query.spec.js | 23 +- ...-repository-client-uploading-files.spec.js | 96 +- test/repository/rdf-repository-client.spec.js | 56 +- .../repository-client-config.spec.js | 46 +- test/security/authentication-mocks.js | 12 + test/security/authentication.spec.js | 39 + test/server/server-client-config.spec.js | 63 +- test/server/server-client.spec.js | 99 +- 166 files changed, 6412 insertions(+), 2746 deletions(-) create mode 100644 docs/Authentication.html create mode 100644 docs/AuthenticationFactory.html create mode 100644 docs/BasicAuthentication.html create mode 100644 docs/GdbTokenAuthentication.html create mode 100644 docs/security_authentication-factory.js.html create mode 100644 docs/security_authentication.js.html create mode 100644 docs/security_basic-authentication.js.html create mode 100644 docs/security_gdb-token-authentication.js.html create mode 100644 src/security/authentication-factory.js create mode 100644 src/security/authentication.js create mode 100644 src/security/basic-authentication.js create mode 100644 src/security/gdb-token-authentication.js create mode 100644 test/repository/rdf-repository-client-authentication-basic.spec.js rename test/repository/{rdf-repository-client-authentication.spec.js => rdf-repository-client-authentication-token.spec.js} (92%) create mode 100644 test/security/authentication-mocks.js create mode 100644 test/security/authentication.spec.js diff --git a/.eslintrc b/.eslintrc index d08a29088..91e1c556a 100644 --- a/.eslintrc +++ b/.eslintrc @@ -24,5 +24,16 @@ "node": true, "browser": true, "jest": true - } + }, + "overrides": [ + { + "files": ["test/**", "test-e2e/**"], + "rules": { + "require-jsdoc": "off", + "prefer-promise-reject-errors": "off", + "valid-jsdoc": "off" + } + } + ] } + diff --git a/CHANGELOG.md b/CHANGELOG.md index d4730a138..67f8ecab0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ * `Check the GDB server version and report mismatches if the client version implements a different version unless the check is stopped.` * `Support secured endpoints exposing only HTTPS` +## 2.0.0 (2021-02-10) +* Major changes in the construction of server and repository client configurations. +* Update Readme.md + +## 1.7.0 (2021-02-10) +* Upgrade to graphDb 9.6.0 + +## 1.6.1 (2021-02-09) +* Authenticate against a secured GDB server +* Manage repositories through GraphDBServerClient +* Fix latest vulnerabilities and lib updates +* Migrate to Jenkins +* Update repository tutorials in Readme.md +* Created README for the e2e-test package + +**Bugfixes** +* Repository client authentication endpoint fix + ## 1.5.0 (2020-12-10) * Upgrade to graphDb 9.5.0 diff --git a/README.md b/README.md index 34a060c27..976391ba3 100644 --- a/README.md +++ b/README.md @@ -128,12 +128,26 @@ first. const {ServerClient, ServerClientConfig} = require('graphdb').server; const {RDFMimeType} = require('graphdb').http; -const serverConfig = new ServerClientConfig('http://rdf4j-compliant-server/', 0, { - 'Accept': RDFMimeType.SPARQL_RESULTS_JSON -}); +const serverConfig = new ServerClientConfig('http://rdf4j-compliant-server/') + .setTimeout(5000) + .setHeaders({ + 'Accept': RDFMimeType.SPARQL_RESULTS_JSON + }) + .setKeepAlive(true); + const server = new ServerClient(serverConfig); ``` +When created, configurations receive the following default parameters: +```javascript + /** + * The Server client configuration constructor + * sets configuration default value to + * timeout = 10000, + * keepAlive = true + */ +``` + * Fetch repository ids ```javascript @@ -180,8 +194,8 @@ Used to automate the security user management API: add, edit, or remove users. // Import all classes needed for work const {GraphDBServerClient, ServerClientConfig} = require('graphdb').server; // Instance the server configuration -const serverConfig = new ServerClientConfig('http://rdf4j-compliant-server/', 10000, - new Map(), 'admin', 'root', true, true); +const serverConfig = new ServerClientConfig('http://rdf4j-compliant-server/') + .useGdbTokenAuthentication('admin', 'root'); // Instance the server client const serverClient = new GraphDBServerClient(serverConfig); ``` @@ -289,13 +303,29 @@ Use with extreme caution, as the changes that are made to the application settin * Instantiating repository client ```javascript +const endpoint = 'http://GDB'; const readTimeout = 30000; const writeTimeout = 30000; -const config = new RepositoryClientConfig(['http://GDB/repositories/my-repo'], { - 'Accept': RDFMimeType.TURTLE -}, '', readTimeout, writeTimeout); +const config = new RepositoryClientConfig(endpoint) + .setEndpoints(['http://GDB/repositories/my-repo']) + .setHeaders({ + 'Accept': RDFMimeType.TURTLE + }) + .setReadTimeout(readTimeout) + .setWriteTimeout(writeTimeout); const repository = new RDFRepositoryClient(config); ``` +When created, configurations receive the following default parameters: +```javascript + /** + * The Repository client configuration constructor + * sets configuration default value to + * defaultRDFMimeType = 'application/sparql-results+json', + * keepAlive = true, + * readTimeout = 10000, + * writeTimeout = 10000 + */ +``` * Obtaining repository client instance through a ServerClient @@ -303,14 +333,20 @@ const repository = new RDFRepositoryClient(config); const {ServerClient, ServerClientConfig} = require('graphdb').server; const {RepositoryClientConfig} = require('graphdb').repository; -const config = new ServerClientConfig('http://GDB', 0, {}); +const endpoint = 'http://GDB'; +const config = new ServerClientConfig(endpoint); const server = new ServerClient(config); const readTimeout = 30000; const writeTimeout = 30000; -const repositoryClientConfig = new RepositoryClientConfig(['http://GDB/repositories/my-repo'], {}, '', readTimeout, writeTimeout); -return server.getRepository('automotive', repositoryClientConfig).then((rdfRepositoryClient) => { -// rdfRepositoryClient is a configured instance of RDFRepositoryClient + +const repositoryClientConfig = new RepositoryClientConfig(endpoint) + .setEndpoints(['http://GDB/repositories/my-repo']) + .setReadTimeout(readTimeout) + .setWriteTimeout(writeTimeout); +return server.getRepository('automotive', repositoryClientConfig) + .then((rdfRepositoryClient) => { + // rdfRepositoryClient is a configured instance of RDFRepositoryClient }); ``` @@ -436,7 +472,7 @@ return repository.update(payload).then(() => { ```javascript repository.deleteStatements(subj, pred, obj, contexts).then(() => { - + // do work }); ``` @@ -568,24 +604,28 @@ In case the server requires that requests should be authenticated, then in the ` ##### ServerClient ```javascript const headers = {'Accept': 'text/plain'}; - const config = new ServerClientConfig('/endpoint', 1000, headers, 'testuser', 'P@sw0rd'); + const config = new ServerClientConfig('/endpoint') + .setTimeout(5000) + .setHeaders(headers) + .useGdbTokenAuthentication('user', 'root'); + const client = new ServerClient(config); ``` ##### RepositoryClient ```javascript +const endpoint = 'http://host/'; const endpoints = ['http://host/repositories/repo1']; const headers = {}; const contentType = ''; const readTimeout = 1000; const writeTimeout = 1000; -const config = new RepositoryClientConfig() +const config = new RepositoryClientConfig(endpoint) .setEndpoints(endpoints) .setHeaders(headers) .setDefaultRDFMimeType(contentType) .setReadTimeout(readTimeout) .setWriteTimeout(writeTimeout) - .setUsername('testuser') - .setPass('pass123'); + .useGdbTokenAuthentication('testuser', 'pass123'); const repository = new RDFRepositoryClient(config); const httpRequest = repository.httpClients[0].request; ```` @@ -599,12 +639,18 @@ If the GDB token expires, then the first API call will be rejected with an http Instead of using GDB token, users can access secured GraphDB by passing valid base-64 encoded username:password combinations as a header. In case Basic authentication will be used, then the headers in the `ServerClientConfig` and `RepositoryClientConfig` must be configured to send the `username` and `password` which to be used for the authentication. From this moment on, with every API call is sent also an `authorization` header with the encoded credentials as value. ```javascript -config.setBasicAuthentication(true); +config.useBasicAuthentication('admin', 'root'); ``` > **Note:** > Basic Authentication is even more vulnerable to man-in-the-middle attacks than GDB token! Anyone who intercepts your requests will be able to reuse your credentials indefinitely until you change them. Since the credentials are merely base-64 encoded, they will also get your username and password. This is why it is very important to always use encryption in transit. +##### Disable authentication +If necessary, authentication can be disabled in the configuration. +```javascript +config.disableAuthentication(); +``` + ### Response Parsers Read responses of different content types might be parsed to data objects with diff --git a/docs/AddStatementPayload.html b/docs/AddStatementPayload.html index 36a61095f..250fc53c8 100644 --- a/docs/AddStatementPayload.html +++ b/docs/AddStatementPayload.html @@ -19,7 +19,7 @@

Class: AddStatementPayload

- + @@ -27,28 +27,28 @@

Class: AddStatementPayload

- +

AddStatementPayload()

- +

Object builder used for constructing a statement addition payload.

- - + +
- - - + + +

Constructor

- - + +

new AddStatementPayload()

- - + + @@ -66,51 +66,51 @@

ne
- - - - - - - - - + + + + + + + + +
Author:
  • Mihail Radkov
  • - +
  • Svilen Velikov
- - - - - + + + + +
Source:
- - - - + + + +
@@ -132,36 +132,36 @@

ne - +

- - - - - - - - + + + + + + + +

Methods

- - - - + + + +

getBaseURI() → {string}

- - + + @@ -183,42 +183,42 @@

getBaseURI<
- - - - - - - - - - - - - + + + + + + + + + + + + +
Source:
- - - - + + + +
@@ -237,7 +237,7 @@

getBaseURI<

Returns:
- +

the base URI

@@ -249,29 +249,29 @@
Returns:
Type
- + string
- - - - - + + + + +

getDataType() → {string}

- - + + @@ -294,42 +294,42 @@

getDataTyp
- - - - - - - - - - - - - + + + + + + + + + + + + +
Source:
- - - - + + + +
@@ -348,7 +348,7 @@

getDataTyp

Returns:
- +

the data type

@@ -360,29 +360,29 @@
Returns:
Type
- + string
- - - - - + + + + +

getLanguage() → {string}

- - + + @@ -405,42 +405,42 @@

getLanguag
- - - - - - - - - - - - - + + + + + + + + + + + + +
Source:
- - - - + + + +
@@ -459,7 +459,7 @@

getLanguag

Returns:
- +

the language

@@ -471,29 +471,29 @@
Returns:
Type
- + string
- - - - - + + + + +

isLiteral() → {boolean}

- - + + @@ -516,42 +516,42 @@

isLiteral - - - - - - - - - - - - - + + + + + + + + + + + + +
Source:
- - - - + + + + @@ -570,7 +570,7 @@

isLiteralReturns:

- +

true if it is a literal payload or false otherwise

@@ -583,29 +583,29 @@
Returns:
Type
- + boolean
- - - - - + + + + +

setBaseURI(baseURI) → {AddStatementPayload}

- - + + @@ -623,50 +623,50 @@

setBaseURI<

Parameters:
- + - + - + - - + + - + - + - + - - + + - +
NameTypeDescription
baseURI - - + + string - +

the base URI

@@ -677,42 +677,42 @@
Parameters:
- - - - - - - - - - - - - + + + + + + + + + + + + +
Source:
- - - - + + + +
@@ -731,7 +731,7 @@
Parameters:
Returns:
- +

the payload for method chaining

@@ -743,29 +743,29 @@
Returns:
Type
- + AddStatementPayload
- - - - - + + + + +

setDataType(dataTypeopt) → {AddStatementPayload}

- - + + @@ -783,62 +783,62 @@

setDataTyp

Parameters:
- + - + - + - + - - + + - + - + - + - + - - + + - +
NameTypeAttributesDescription
dataType - - + + string - + - + <optional>
- - - + + +

the object's data type

@@ -849,42 +849,42 @@
Parameters:
- - - - - - - - - - - - - + + + + + + + + + + + + +
Source:
- - - - + + + +
@@ -903,7 +903,7 @@
Parameters:
Returns:
- +

the payload for method chaining

@@ -915,29 +915,29 @@
Returns:
Type
- + AddStatementPayload
- - - - - + + + + +

setLanguage(languageopt) → {AddStatementPayload}

- - + + @@ -955,62 +955,62 @@

setLanguag

Parameters:
- + - + - + - + - - + + - + - + - + - + - - + + - +
NameTypeAttributesDescription
language - - + + string - + - + <optional>
- - - + + +

the object's language

@@ -1021,42 +1021,42 @@
Parameters:
- - - - - - - - - - - - - + + + + + + + + + + + + +
Source:
- - - - + + + +
@@ -1075,7 +1075,7 @@
Parameters:
Returns:
- +

the payload for method chaining

@@ -1087,29 +1087,29 @@
Returns:
Type
- + AddStatementPayload
- - - - - + + + + +

setObjectLiteral(value, typeopt, languageopt) → {AddStatementPayload}

- - + + @@ -1134,126 +1134,126 @@

setOb

Parameters:
- + - + - + - + - - + + - + - + - + - + - - + + - + - + - + - + - - + + - + - + - + - + - - + + - +
NameTypeAttributesDescription
value - - + + * - + - - - + + +

the statements object value

type - - + + string - + - + <optional>
- - - + + +

the statements object data type

language - - + + string - + - + <optional>
- - - + + +

the statements object language

@@ -1264,42 +1264,42 @@
Parameters:
- - - - - - - - - - - - - + + + + + + + + + + + + +
Source:
- - - - + + + +
@@ -1318,7 +1318,7 @@
Parameters:
Returns:
- +

the payload for method chaining

@@ -1330,25 +1330,25 @@
Returns:
Type
- + AddStatementPayload
- - - - - + + + + +

@@ -1359,16 +1359,16 @@
Returns:

- \ No newline at end of file + diff --git a/docs/AppSettings.html b/docs/AppSettings.html index 58b5b848c..33ec16332 100644 --- a/docs/AppSettings.html +++ b/docs/AppSettings.html @@ -1041,13 +1041,13 @@
Returns:

diff --git a/docs/Authentication.html b/docs/Authentication.html new file mode 100644 index 000000000..70aceb724 --- /dev/null +++ b/docs/Authentication.html @@ -0,0 +1,421 @@ + + + + + JSDoc: Class: Authentication + + + + + + + + + + +
+ +

Class: Authentication

+ + + + + + +
+ +
+ +

(abstract) Authentication(clientConfig)

+ +

An abstract class that specifies common methods for different types +of authentication. Concrete authentication types must extend +this class and override it's methods

+ + +
+ +
+
+ + + + +

Constructor

+ + + +

(abstract) new Authentication(clientConfig)

+ + + + + + +
+

Constructor.

+
+ + + + + + + + + +
Parameters:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
clientConfig + + +ClientConfig + + + +
+ + + + + + +
+ + + + + + + + + + + + + + + + + + +
Author:
+
+
    +
  • Teodossi Dossev
  • +
+
+ + + + + + + + + +
Source:
+
+ + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + +

Classes

+ +
+
Authentication
+
+
+ + + + + + + + + + + +

Methods

+ + + + + + + +

getLoginRequestBuilder()

+ + + + + + +
+

Returns authentication type related HttpRequestBuilder +login request builder

+
+ + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Source:
+
+ + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +

getResponseAuthToken()

+ + + + + + +
+

Returns authentication type related {string} +token from response

+
+ + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Source:
+
+ + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+ + + +
+ + + + + + + \ No newline at end of file diff --git a/docs/AuthenticationFactory.html b/docs/AuthenticationFactory.html new file mode 100644 index 000000000..6e57583b1 --- /dev/null +++ b/docs/AuthenticationFactory.html @@ -0,0 +1,340 @@ + + + + + JSDoc: Class: AuthenticationFactory + + + + + + + + + + +
+ +

Class: AuthenticationFactory

+ + + + + + +
+ +
+ +

AuthenticationFactory()

+ +

Factory to create concrete authentication type, based on +client configuration.

+ + +
+ +
+
+ + + + +

Constructor

+ + + +

new AuthenticationFactory()

+ + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + +
Author:
+
+
    +
  • Teodossi Dossev
  • +
+
+ + + + + + + + + +
Source:
+
+ + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + +

Methods

+ + + + + + + +

getAuthenticationType(clientConfig) → {BasicAuthentication|GdbTokenAuthentication}

+ + + + + + +
+

Concrete authentication type generator.

+
+ + + + + + + + + +
Parameters:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
clientConfig + + +ClientConfig + + + +
+ + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Source:
+
+ + + + + + + +
+ + + + + + + + + + + + + + + +
Returns:
+ + + + +
+
+ Type +
+
+ +BasicAuthentication +| + +GdbTokenAuthentication + + +
+
+ + + + + + + + + + + + + +
+ +
+ + + + +
+ + + +
+ + + + + + + \ No newline at end of file diff --git a/docs/AuthenticationService.html b/docs/AuthenticationService.html index 83c880b8b..684efa0b0 100644 --- a/docs/AuthenticationService.html +++ b/docs/AuthenticationService.html @@ -154,6 +154,8 @@
Parameters:
  • Mihail Radkov
  • Svilen Velikov
  • + +
  • Teodossi Dossev
  • @@ -167,7 +169,7 @@
    Parameters:
    Source:
    @@ -223,7 +225,7 @@

    Methods

    -

    getAuthentication() → {string|undefined}

    +

    getAuthentication(clientConfig) → {BasicAuthentication|GdbTokenAuthentication}

    @@ -231,9 +233,7 @@

    getA
    -

    Return an effective valid token as string which is going to be send as a -request header Authorization: token. If there is no logged in -user, then this method returns undefined.

    +

    Authentication type getter

    @@ -244,109 +244,53 @@

    getA - - - - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Source:
    -
    - - - - - - +
    Parameters:
    -
    - - - - - - - - - - - - - - - -

    Returns:
    + + + + + + -
    -
    - Type -
    -
    -string -| - -undefined + -
    -
    + + + + + + + + + - - + - -

    getLoggedUser() → {User}

    - + + - - - - - - - - - + +
    NameTypeDescription
    clientConfig + + +ClientConfig + +

    concrete client configuration

    @@ -382,7 +326,7 @@

    getLogge
    Source:
    @@ -410,6 +354,11 @@

    getLogge

    Returns:
    +
    +

    concrete +authentication type

    +
    +
    @@ -418,7 +367,10 @@
    Returns:
    -User +BasicAuthentication +| + +GdbTokenAuthentication
    @@ -436,7 +388,7 @@
    Returns:
    -

    login(username, pass) → {Promise.<User>}

    +

    getAuthenticationToken(user) → {string|undefined}

    @@ -444,9 +396,9 @@

    login -

    Performs a login request against secured server with provided username and -password. Upon successful authentication a User instance is created -with the user data and the auth token and returned to the client.

    +

    Return an effective valid token as string which is going to be send as a +request header Authorization: token. If there is no logged in +user, then this method returns undefined.

    @@ -482,36 +434,13 @@
    Parameters:
    - username - - - - - -string - - - - - - - - - -

    is the username of the logged in user

    - - - - - - - pass + user -string +User @@ -521,7 +450,7 @@
    Parameters:
    -

    is the password of the logged in user

    +

    logged in user

    @@ -562,7 +491,7 @@
    Parameters:
    Source:
    @@ -591,8 +520,7 @@
    Returns:
    -

    a promise resolving to an authenticated -User instance.

    +

    authentication token

    @@ -603,7 +531,10 @@
    Returns:
    -Promise.<User> +string +| + +undefined
    @@ -621,7 +552,7 @@
    Returns:
    -

    logout() → {Promise}

    +

    getLoginRequest(clientConfig) → {HttpRequestBuilder}

    @@ -629,9 +560,8 @@

    logout -

    Performs a logout of logged in user. This effectively removes the stored in -the client user. Every consecutive call against secured server will result -in Unauthorized error with status code 401.

    +

    Returns authentication type related HttpRequestBuilder +login request builder

    @@ -642,6 +572,55 @@

    logoutParameters:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescription
    clientConfig + + +ClientConfig + + + +

    concrete client configuration

    + + @@ -675,7 +654,7 @@

    logoutSource:
    @@ -704,7 +683,7 @@
    Returns:
    -

    returns a promise which resolves with undefined.

    +

    request builder

    @@ -715,7 +694,7 @@
    Returns:
    -Promise +HttpRequestBuilder
    @@ -733,13 +712,19 @@
    Returns:
    -

    setHttpClient(httpClient) → {AuthenticationService}

    +

    login(clientConfig, user) → {Promise.<User>}

    +
    +

    Performs a login request against secured server with provided username and +password. Upon successful authentication a User instance is created +with the user data and the auth token and returned to the client.

    +
    + @@ -773,13 +758,13 @@
    Parameters:
    - httpClient + clientConfig -HttpClient +ClientConfig @@ -789,7 +774,30 @@
    Parameters:
    - +

    concrete client configuration

    + + + + + + + user + + + + + +User + + + + + + + + + +

    logged in user

    @@ -830,7 +838,7 @@
    Parameters:
    Source:
    @@ -858,6 +866,11 @@
    Parameters:
    Returns:
    +
    +

    a promise resolving to an authenticated +User instance.

    +
    +
    @@ -866,7 +879,7 @@
    Returns:
    -AuthenticationService +Promise.<User>
    @@ -884,13 +897,19 @@
    Returns:
    -

    setLoggedUser(user)

    +

    logout(user) → {Promise}

    +
    +

    Performs a logout of logged in user. This effectively removes the stored in +the client user. Every consecutive call against secured server will result +in Unauthorized error with status code 401.

    +
    + @@ -940,7 +959,7 @@
    Parameters:
    - +

    logged in user

    @@ -981,7 +1000,7 @@
    Parameters:
    Source:
    @@ -1006,6 +1025,28 @@
    Parameters:
    +
    Returns:
    + + +
    +

    returns a promise which resolves with undefined.

    +
    + + + +
    +
    + Type +
    +
    + +Promise + + +
    +
    + + @@ -1027,13 +1068,13 @@
    Parameters:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/BaseRepositoryClient.html b/docs/BaseRepositoryClient.html index e63779e48..5e5a28482 100644 --- a/docs/BaseRepositoryClient.html +++ b/docs/BaseRepositoryClient.html @@ -381,6 +381,116 @@
    Returns:
    +

    getLoggedUser() → {User}

    + + + + + + +
    +

    Logged user getter.

    +
    + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    user

    +
    + + + +
    +
    + Type +
    +
    + +User + + +
    +
    + + + + + + + + + + + + +

    getLogger() → {Logger}

    @@ -1067,6 +1177,161 @@
    Parameters:
    + + + + + + +

    setLoggedUser(user) → {BaseRepositoryClient}

    + + + + + + +
    +

    User setter

    +
    + + + + + + + + + +
    Parameters:
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescription
    user + + +User + + + +
    + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + + + +
    +
    + Type +
    +
    + +BaseRepositoryClient + + +
    +
    + + + + + + + @@ -1083,13 +1348,13 @@
    Parameters:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/BasicAuthentication.html b/docs/BasicAuthentication.html new file mode 100644 index 000000000..f6de62160 --- /dev/null +++ b/docs/BasicAuthentication.html @@ -0,0 +1,394 @@ + + + + + JSDoc: Class: BasicAuthentication + + + + + + + + + + +
    + +

    Class: BasicAuthentication

    + + + + + + +
    + +
    + +

    BasicAuthentication()

    + +

    Basic authentication type class. +Used for basic authentication against secured gdb server.

    + + +
    + +
    +
    + + + + +

    Constructor

    + + + +

    new BasicAuthentication()

    + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + +
    Author:
    +
    +
      +
    • Teodossi Dossev
    • +
    +
    + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + +

    Methods

    + + + + + + + +

    getLoginRequestBuilder() → {HttpRequestBuilder}

    + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    requestBuilder

    +
    + + + +
    +
    + Type +
    +
    + +HttpRequestBuilder + + +
    +
    + + + + + + + + + + + + + +

    getResponseAuthToken() → {string}

    + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    token

    +
    + + + +
    +
    + Type +
    +
    + +string + + +
    +
    + + + + + + + + + + + + + +
    + +
    + + + + +
    + + + +
    + +
    + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time) +
    + + + + + \ No newline at end of file diff --git a/docs/ClientConfig.html b/docs/ClientConfig.html index 9c88e3bda..c4322bac3 100644 --- a/docs/ClientConfig.html +++ b/docs/ClientConfig.html @@ -28,7 +28,7 @@

    Class: ClientConfig

    -

    (abstract) ClientConfig(headersopt, usernameopt, passopt, keepAliveopt, useBasicAuthopt, endpoint)

    +

    (abstract) ClientConfig(endpoint)

    Abstract configuration wrapper used for initialization of concrete Client instances. Concrete client configuration wrappers must extend @@ -47,13 +47,17 @@

    Constructor

    -

    (abstract) new ClientConfig(headersopt, usernameopt, passopt, keepAliveopt, useBasicAuthopt, endpoint)

    +

    (abstract) new ClientConfig(endpoint)

    +
    +

    Client configuration constructor.

    +
    + @@ -75,12 +79,8 @@
    Parameters:
    Type - Attributes - - Default - Description @@ -91,230 +91,342 @@
    Parameters:
    - headers + endpoint -Map.<string, string> +string - - - <optional>
    - - - - - - - - - - - -

    An http headers map.

    +

    server base URL that will be prepend +to all server requests

    + + - - - username - - - - -string - - - - - - <optional>
    - - +
    - - - + - - - - - + -

    username which should be authenticated

    - + - - - pass - + - - - -string + + - - + - - - - <optional>
    - + +
    Author:
    +
    +
      +
    • Mihail Radkov
    • + +
    • Svilen Velikov
    • + +
    • Teodossi Dossev
    • +
    +
    + - + - - - + - - - - - + -

    the password to be used

    - + +
    Source:
    +
    + - - - keepAlive - + + + +
    + + + + + + + + + + + - - - -boolean - - - - - - <optional>
    - - - - - - - - - true - - - -

    if the logged in user should be -reauthenticated after auth token expire. This config has meaning when the -server is secured and username and passwords are provided.

    - +
    - - - useBasicAuth + + + + + + + + + + + + + + + +

    Methods

    + + - + + + +

    disableAuthentication()

    + + + + + + +
    +

    Disables authentication.

    +
    + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + - + + + + +

    getBasicAuthentication() → {boolean}

    + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    [basicAuth] if use Basic Auth

    +
    + + + +
    +
    + Type +
    +
    + boolean - - +
    +
    - - - - <optional>
    - + - - - - - - - - + + + -

    if use Basic Auth when authenticating

    - + +

    getEndpoint() → {string}

    + - - - endpoint - + - - - -string - - +
    +

    Returns the server's endpoint URL.

    +
    + - - - - - - - - - - - - -

    server base URL that will be prepend -to all server requests

    - - - - @@ -340,17 +452,6 @@
    Parameters:
    -
    Author:
    -
    -
      -
    • Mihail Radkov
    • - -
    • Svilen Velikov
    • - -
    • Teodossi Dossev
    • -
    -
    - @@ -361,7 +462,7 @@
    Parameters:
    Source:
    @@ -386,30 +487,32 @@
    Parameters:
    +
    Returns:
    + +
    +

    the endpoint URL

    +
    +
    +
    + Type +
    +
    + +string - - - - - - - +
    +
    - - - - -

    Methods

    @@ -417,17 +520,13 @@

    Methods

    -

    getEndpoint() → {string}

    +

    getGdbTokenAuthentication() → {boolean}

    -
    -

    Returns the server's endpoint URL.

    -
    - @@ -469,7 +568,7 @@

    getEndpoin
    Source:
    @@ -498,7 +597,7 @@

    Returns:
    -

    the endpoint URL

    +

    [gdbTokenAuth] if use Gdb Token Auth

    @@ -509,7 +608,7 @@
    Returns:
    -string +boolean
    @@ -579,7 +678,7 @@

    getHeaders<
    Source:
    @@ -685,7 +784,7 @@

    getKeepAl
    Source:
    @@ -791,7 +890,7 @@

    getPassSource:
    @@ -897,7 +996,7 @@

    getUsernam
    Source:
    @@ -955,13 +1054,17 @@

    Returns:
    -

    setBasicAuthentication(basicAuthopt) → {this}

    +

    setEndpoint(endpoint) → {this}

    +
    +

    Sets the server's endpoint URL.

    +
    + @@ -983,8 +1086,6 @@
    Parameters:
    Type - Attributes - @@ -997,33 +1098,23 @@
    Parameters:
    - basicAuth + endpoint -boolean +string - - - <optional>
    - - - - - - - -

    if use Basic Auth when authenticating

    +

    the endpoint URL

    @@ -1064,7 +1155,7 @@
    Parameters:
    Source:
    @@ -1093,7 +1184,7 @@
    Returns:
    -

    the concrete configuration config for method chaining

    +

    the current config for method chaining

    @@ -1122,7 +1213,7 @@
    Returns:
    -

    setEndpoint(endpoint) → {this}

    +

    setHeaders(headers) → {this}

    @@ -1130,7 +1221,7 @@

    setEndpoin
    -

    Sets the server's endpoint URL.

    +

    Sets the default headers map for each HTTP request.

    @@ -1166,13 +1257,13 @@

    Parameters:
    - endpoint + headers -string +Object.<string, string> @@ -1182,7 +1273,7 @@
    Parameters:
    -

    the endpoint URL

    +

    the default headers

    @@ -1223,7 +1314,7 @@
    Parameters:
    Source:
    @@ -1252,7 +1343,7 @@
    Returns:
    -

    the current config for method chaining

    +

    the concrete configuration config for method chaining

    @@ -1281,17 +1372,13 @@
    Returns:
    -

    setHeaders(headers) → {this}

    +

    setKeepAlive(keepAlive) → {this}

    -
    -

    Sets the default headers map for each HTTP request.

    -
    - @@ -1325,13 +1412,13 @@
    Parameters:
    - headers + keepAlive -Object.<string, string> +boolean @@ -1341,7 +1428,7 @@
    Parameters:
    -

    the default headers

    + @@ -1382,7 +1469,7 @@
    Parameters:
    Source:
    @@ -1440,68 +1527,24 @@
    Returns:
    -

    setKeepAlive(keepAlive) → {this}

    - - +

    shouldAuthenticate() → {boolean}

    - - - - - - - - - - -
    Parameters:
    - - - - - - - - - - - - - - - - - - - - - - +
    +

    Returns true if basic or gdb token authentication +is enabled. false otherwise.

    +
    - - - - - - - -
    NameTypeDescription
    keepAlive - - -boolean - -
    @@ -1537,7 +1580,7 @@
    Parameters:
    Source:
    @@ -1566,7 +1609,7 @@
    Returns:
    -

    the concrete configuration config for method chaining

    +

    is authentication enabled

    @@ -1577,7 +1620,7 @@
    Returns:
    -this +boolean
    @@ -1595,13 +1638,18 @@
    Returns:
    -

    setPass(pass) → {this}

    +

    useBasicAuthentication(usernameopt, passopt) → {this}

    +
    +

    Username and password for user logging setter. +Sets basic authentication as client authentication type.

    +
    + @@ -1623,6 +1671,8 @@
    Parameters:
    Type + Attributes + @@ -1633,6 +1683,39 @@
    Parameters:
    + + + username + + + + + +string + + + + + + + + + <optional>
    + + + + + + + + + + + + + + + pass @@ -1648,6 +1731,16 @@
    Parameters:
    + + + <optional>
    + + + + + + + @@ -1692,7 +1785,7 @@
    Parameters:
    Source:
    @@ -1750,13 +1843,19 @@
    Returns:
    -

    setUsername(username) → {this}

    +

    useGdbTokenAuthentication(usernameopt, passopt) → {this}

    +
    +

    Username and password for user logging setter. +Sets gdb token authentication as client authentication type. +*

    +
    + @@ -1778,6 +1877,8 @@
    Parameters:
    Type + Attributes + @@ -1803,6 +1904,49 @@
    Parameters:
    + + + <optional>
    + + + + + + + + + + + + + + + + + + pass + + + + + +string + + + + + + + + + <optional>
    + + + + + + + @@ -1847,7 +1991,7 @@
    Parameters:
    Source:
    @@ -1915,13 +2059,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/CommonUtils.html b/docs/CommonUtils.html index 6a2377b9c..023a6bda9 100644 --- a/docs/CommonUtils.html +++ b/docs/CommonUtils.html @@ -277,13 +277,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/ConsoleLogger.html b/docs/ConsoleLogger.html index 63665ddb4..8a4c0ed63 100644 --- a/docs/ConsoleLogger.html +++ b/docs/ConsoleLogger.html @@ -980,13 +980,13 @@
    Parameters:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/ContentParser.html b/docs/ContentParser.html index d56fe95a3..c0471ab86 100644 --- a/docs/ContentParser.html +++ b/docs/ContentParser.html @@ -746,13 +746,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/DownloadService.html b/docs/DownloadService.html index 9c2b12c90..c5f1a19f3 100644 --- a/docs/DownloadService.html +++ b/docs/DownloadService.html @@ -417,13 +417,13 @@

    getServ
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/FileUtils.html b/docs/FileUtils.html index 74945d029..9ea9c1e28 100644 --- a/docs/FileUtils.html +++ b/docs/FileUtils.html @@ -358,13 +358,13 @@

    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/GdbTokenAuthentication.html b/docs/GdbTokenAuthentication.html new file mode 100644 index 000000000..78cc889b6 --- /dev/null +++ b/docs/GdbTokenAuthentication.html @@ -0,0 +1,394 @@ + + + + + JSDoc: Class: GdbTokenAuthentication + + + + + + + + + + +
    + +

    Class: GdbTokenAuthentication

    + + + + + + +
    + +
    + +

    GdbTokenAuthentication()

    + +

    Gdb token authentication type class. +Used for gdb token authentication against secured gdb server.

    + + +
    + +
    +
    + + + + +

    Constructor

    + + + +

    new GdbTokenAuthentication()

    + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + +
    Author:
    +
    +
      +
    • Teodossi Dossev
    • +
    +
    + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + +

    Methods

    + + + + + + + +

    getLoginRequestBuilder() → {HttpRequestBuilder}

    + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    requestBuilder

    +
    + + + +
    +
    + Type +
    +
    + +HttpRequestBuilder + + +
    +
    + + + + + + + + + + + + + +

    getResponseAuthToken() → {string}

    + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    token

    +
    + + + +
    +
    + Type +
    +
    + +string + + +
    +
    + + + + + + + + + + + + + +
    + +
    + + + + +
    + + + +
    + +
    + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time) +
    + + + + + \ No newline at end of file diff --git a/docs/GetQueryPayload.html b/docs/GetQueryPayload.html index 192d5496a..f7a5ac257 100644 --- a/docs/GetQueryPayload.html +++ b/docs/GetQueryPayload.html @@ -2234,13 +2234,13 @@
    Throws:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/GetStatementsPayload.html b/docs/GetStatementsPayload.html index b9d0928f4..c5e38d625 100644 --- a/docs/GetStatementsPayload.html +++ b/docs/GetStatementsPayload.html @@ -721,13 +721,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/GraphDBServerClient.html b/docs/GraphDBServerClient.html index 9b642f03b..b44d62d32 100644 --- a/docs/GraphDBServerClient.html +++ b/docs/GraphDBServerClient.html @@ -2817,13 +2817,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/HttpClient.html b/docs/HttpClient.html index 0ad52daea..453fbc7ff 100644 --- a/docs/HttpClient.html +++ b/docs/HttpClient.html @@ -979,13 +979,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/HttpRequestBuilder.html b/docs/HttpRequestBuilder.html index 6129d58ad..dc7c430b1 100644 --- a/docs/HttpRequestBuilder.html +++ b/docs/HttpRequestBuilder.html @@ -3858,13 +3858,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/HttpResponse.html b/docs/HttpResponse.html index 5825645ba..bb6180c59 100644 --- a/docs/HttpResponse.html +++ b/docs/HttpResponse.html @@ -824,13 +824,13 @@
    Parameters:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/Iterable.html b/docs/Iterable.html index e6522b2fa..acd115090 100644 --- a/docs/Iterable.html +++ b/docs/Iterable.html @@ -587,13 +587,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/JsonLDParser.html b/docs/JsonLDParser.html index b9f2d189a..51a827e7f 100644 --- a/docs/JsonLDParser.html +++ b/docs/JsonLDParser.html @@ -469,13 +469,13 @@

    parse
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/Logger.html b/docs/Logger.html index 9c9503858..30e4ae635 100644 --- a/docs/Logger.html +++ b/docs/Logger.html @@ -126,13 +126,13 @@

    Logger


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/LoggingUtils.html b/docs/LoggingUtils.html index 0abd56c41..67aeb66a0 100644 --- a/docs/LoggingUtils.html +++ b/docs/LoggingUtils.html @@ -372,13 +372,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/N3Parser.html b/docs/N3Parser.html index 202d53ced..a53a817ed 100644 --- a/docs/N3Parser.html +++ b/docs/N3Parser.html @@ -385,13 +385,13 @@

    parse
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/NQuadsParser.html b/docs/NQuadsParser.html index a9ebbe9da..a4d35a27b 100644 --- a/docs/NQuadsParser.html +++ b/docs/NQuadsParser.html @@ -385,13 +385,13 @@

    parse
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/NTriplesParser.html b/docs/NTriplesParser.html index a0fa511d0..42f42e435 100644 --- a/docs/NTriplesParser.html +++ b/docs/NTriplesParser.html @@ -385,13 +385,13 @@

    parse
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/Namespace.html b/docs/Namespace.html index 12bf13bcb..c9ae22fb4 100644 --- a/docs/Namespace.html +++ b/docs/Namespace.html @@ -464,13 +464,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/NamespaceService.html b/docs/NamespaceService.html index e1e4ce949..40323a67a 100644 --- a/docs/NamespaceService.html +++ b/docs/NamespaceService.html @@ -1077,13 +1077,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/PagedResponse.html b/docs/PagedResponse.html index e220ae1cb..8a1b8590a 100644 --- a/docs/PagedResponse.html +++ b/docs/PagedResponse.html @@ -337,13 +337,13 @@
    Parameters:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/ParserRegistry.html b/docs/ParserRegistry.html index fcd2066df..fb4ff1b86 100644 --- a/docs/ParserRegistry.html +++ b/docs/ParserRegistry.html @@ -623,13 +623,13 @@
    Parameters:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/QueryPayload.html b/docs/QueryPayload.html index da9c2f4b7..84a60926e 100644 --- a/docs/QueryPayload.html +++ b/docs/QueryPayload.html @@ -1268,13 +1268,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/QueryService.html b/docs/QueryService.html index 46544ed27..06c46035a 100644 --- a/docs/QueryService.html +++ b/docs/QueryService.html @@ -719,13 +719,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/RDFRepositoryClient.html b/docs/RDFRepositoryClient.html index e2eb6f2e0..672bcdebc 100644 --- a/docs/RDFRepositoryClient.html +++ b/docs/RDFRepositoryClient.html @@ -4453,13 +4453,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/RDFXmlParser.html b/docs/RDFXmlParser.html index 4f9397ed4..befdf08a8 100644 --- a/docs/RDFXmlParser.html +++ b/docs/RDFXmlParser.html @@ -469,13 +469,13 @@

    parse
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/RepositoryClientConfig.html b/docs/RepositoryClientConfig.html index cd6e1879f..05fd04539 100644 --- a/docs/RepositoryClientConfig.html +++ b/docs/RepositoryClientConfig.html @@ -28,7 +28,7 @@

    Class: RepositoryClientConfig

    -

    RepositoryClientConfig(endpointsopt, headersopt, defaultRDFMimeTypeopt, readTimeoutopt, writeTimeoutopt, usernameopt, passopt, keepAliveopt, useBasicAuthopt, endpoint)

    +

    RepositoryClientConfig(endpoint)

    Configuration wrapper used for initialization of BaseRepositoryClient implementations.

    @@ -46,13 +46,22 @@

    Constructor

    -

    new RepositoryClientConfig(endpointsopt, headersopt, defaultRDFMimeTypeopt, readTimeoutopt, writeTimeoutopt, usernameopt, passopt, keepAliveopt, useBasicAuthopt, endpoint)

    +

    new RepositoryClientConfig(endpoint)

    +
    +

    Repository client configuration constructor. +Initializes endpoints and +sets configuration default values to +defaultRDFMimeType, +readTimeout and +writeTimeout

    +
    + @@ -74,8 +83,6 @@
    Parameters:
    Type - Attributes - @@ -88,302 +95,182 @@
    Parameters:
    - endpoints + endpoint -Array.<string> +string - - - <optional>
    - - - - - - - -

    is an array with repository endpoints

    +

    server base URL that will be prepend +to all server requests

    + + - - - headers - - - - -Map.<string, string> - - - - - - <optional>
    - - - - - - - - +
    -

    is a key:value mapping of http -headers and values

    - + - - - defaultRDFMimeType - + - - - -string + + - - + - - - - <optional>
    - + - + - - - + +
    Author:
    +
    +
      +
    • Mihail Radkov
    • + +
    • Svilen Velikov
    • + +
    • Teodossi Dossev
    • +
    +
    + - + -

    one of RDFMimeType values

    - + - - - readTimeout - + +
    Source:
    +
    + - - - -number + + - - + +
    - - - - <optional>
    - - - - - - - - - - - - writeTimeout - - - - -number - - - - - - <optional>
    - - - - - - - - - - - - username - - - - -string - - + + - - - - <optional>
    - + +

    Extends

    - + - - - - + -

    username which should be authenticated

    - - - - pass - + - - - -string + + - - + - - - - <optional>
    - + - + - - - + +

    Methods

    + -

    the password to be used

    - - - - - keepAlive - + +

    addEndpoint(endpoint) → {this}

    + - - - -boolean + - - - - - - <optional>
    - +
    +

    Inserts a repository endpoint URL to the rest of the endpoints.

    +
    - - - - - -

    if the logged in user should be -reauthenticated after auth token expire. This config has meaning when the -server is secured and username and passwords are provided.

    - - - - - useBasicAuth - - - - -boolean - - +
    Parameters:
    + - - - - <optional>
    - + + + + + + - + - - - + - + - - + + + + @@ -401,19 +288,10 @@
    Parameters:
    - - - + @@ -429,54 +307,99 @@
    Parameters:
    - + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + + + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    current config for method chaining

    +
    + - - +
    +
    + Type +
    +
    + +this - - +
    +
    - - -
    Author:
    -
    -
      -
    • Mihail Radkov
    • - -
    • Svilen Velikov
    • -
    -
    - - - - + + -
    Source:
    -
    - - +

    disableAuthentication()

    - - +
    +

    Disables authentication.

    +
    @@ -490,22 +413,28 @@
    Parameters:
    +
    + + - -

    Extends

    +
    Overrides:
    +
    + - + + - + + @@ -516,30 +445,25 @@

    Extends

    +
    Source:
    +
    + -

    Methods

    +
    - - - - -

    addEndpoint(endpoint) → {this}

    - - -
    -

    Inserts a repository endpoint URL to the rest of the endpoints.

    -
    @@ -549,53 +473,29 @@

    addEndpoin -

    Parameters:
    - -
    NameType

    if use Basic Auth when authenticating

    Description
    - - - - - -

    server base URL that will be prepend -to all server requests

    repository endpoint URL

    - - - - - - - + - - - + + + +

    getBasicAuthentication() → {boolean}

    + - - - - - - - - - - - - -
    NameTypeDescription
    endpoint - - -string - -

    repository endpoint URL

    + @@ -611,6 +511,11 @@
    Parameters:
    +
    Overrides:
    +
    + @@ -631,7 +536,7 @@
    Parameters:
    Source:
    @@ -660,7 +565,7 @@
    Returns:
    -

    current config for method chaining

    +

    [basicAuth] if use Basic Auth

    @@ -671,7 +576,7 @@
    Returns:
    -this +boolean
    @@ -741,7 +646,7 @@

    Source:
    @@ -852,7 +757,7 @@

    getEndpoin
    Source:
    @@ -962,7 +867,7 @@

    getEndpoi
    Source:
    @@ -1016,17 +921,13 @@

    Returns:
    -

    getHeaders() → {Object.<string, string>}

    +

    getGdbTokenAuthentication() → {boolean}

    -
    -

    Returns the default headers for each HTTP request.

    -
    - @@ -1050,7 +951,7 @@

    getHeaders<
    Overrides:
    @@ -1073,7 +974,7 @@

    getHeaders<
    Source:
    @@ -1102,7 +1003,7 @@

    Returns:
    -

    the default headers map

    +

    [gdbTokenAuth] if use Gdb Token Auth

    @@ -1113,7 +1014,7 @@
    Returns:
    -Object.<string, string> +boolean
    @@ -1131,13 +1032,17 @@
    Returns:
    -

    getKeepAlive() → {boolean}

    +

    getHeaders() → {Object.<string, string>}

    +
    +

    Returns the default headers for each HTTP request.

    +
    + @@ -1161,7 +1066,7 @@

    getKeepAl
    Overrides:
    @@ -1184,7 +1089,7 @@

    getKeepAl
    Source:
    @@ -1213,7 +1118,7 @@

    Returns:
    -

    if the user should be re-logged in after token expires

    +

    the default headers map

    @@ -1224,7 +1129,7 @@
    Returns:
    -boolean +Object.<string, string>
    @@ -1242,7 +1147,7 @@
    Returns:
    -

    getPass() → {string}

    +

    getKeepAlive() → {boolean}

    @@ -1272,7 +1177,7 @@

    getPassOverrides:
    @@ -1295,7 +1200,7 @@

    getPassSource:
    @@ -1324,7 +1229,7 @@
    Returns:
    -

    the user password

    +

    if the user should be re-logged in after token expires

    @@ -1335,7 +1240,7 @@
    Returns:
    -string +boolean
    @@ -1353,17 +1258,13 @@
    Returns:
    -

    getReadTimeout() → {number}

    +

    getPass() → {string}

    -
    -

    Returns the default read timeout for HTTP requests.

    -
    - @@ -1385,6 +1286,11 @@

    getRead +
    Overrides:
    +
    + @@ -1405,7 +1311,7 @@

    getRead
    Source:
    @@ -1433,6 +1339,10 @@

    getRead

    Returns:
    +
    +

    the user password

    +
    +
    @@ -1441,7 +1351,7 @@
    Returns:
    -number +string
    @@ -1459,13 +1369,17 @@
    Returns:
    -

    getUsername() → {string}

    +

    getReadTimeout() → {number}

    +
    +

    Returns the default read timeout for HTTP requests.

    +
    + @@ -1487,11 +1401,6 @@

    getUsernam -
    Overrides:
    -
    - @@ -1512,7 +1421,7 @@

    getUsernam
    Source:
    @@ -1540,10 +1449,6 @@

    getUsernam

    Returns:
    -
    -

    the username

    -
    -
    @@ -1552,7 +1457,7 @@
    Returns:
    -string +number
    @@ -1570,17 +1475,13 @@
    Returns:
    -

    getWriteTimeout() → {number}

    +

    getUsername() → {string}

    -
    -

    Returns the default write timeout for HTTP requests.

    -
    - @@ -1602,6 +1503,11 @@

    getWri +
    Overrides:
    +
    + @@ -1622,7 +1528,7 @@

    getWri
    Source:
    @@ -1650,6 +1556,10 @@

    getWri

    Returns:
    +
    +

    the username

    +
    +
    @@ -1658,7 +1568,7 @@
    Returns:
    -number +string
    @@ -1676,80 +1586,23 @@
    Returns:
    -

    setBasicAuthentication(basicAuthopt) → {this}

    - - - - - - - - - - - - - - -
    Parameters:
    +

    getWriteTimeout() → {number}

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    NameTypeAttributesDescription
    basicAuth - - -boolean +
    +

    Returns the default write timeout for HTTP requests.

    +
    - -
    - - <optional>
    - - - -

    if use Basic Auth when authenticating

    @@ -1765,11 +1618,6 @@
    Parameters:
    -
    Overrides:
    -
    - @@ -1790,7 +1638,7 @@
    Parameters:
    Source:
    @@ -1818,10 +1666,6 @@
    Parameters:
    Returns:
    -
    -

    the concrete configuration config for method chaining

    -
    -
    @@ -1830,7 +1674,7 @@
    Returns:
    -this +number
    @@ -1949,7 +1793,7 @@
    Parameters:
    Source:
    @@ -2113,7 +1957,7 @@
    Parameters:
    Source:
    @@ -2272,7 +2116,7 @@
    Parameters:
    Source:
    @@ -2436,7 +2280,7 @@
    Parameters:
    Source:
    @@ -2596,7 +2440,7 @@
    Parameters:
    Source:
    @@ -2654,13 +2498,17 @@
    Returns:
    -

    setPass(pass) → {this}

    +

    setReadTimeout(readTimeout) → {this}

    +
    +

    Sets the default read timeout for HTTP requests.

    +
    + @@ -2694,13 +2542,13 @@
    Parameters:
    - pass + readTimeout -string +number @@ -2710,7 +2558,7 @@
    Parameters:
    - +

    the timeout in milliseconds

    @@ -2731,11 +2579,6 @@
    Parameters:
    -
    Overrides:
    -
    - @@ -2756,7 +2599,7 @@
    Parameters:
    Source:
    @@ -2785,7 +2628,7 @@
    Returns:
    -

    the concrete configuration config for method chaining

    +

    current config for method chaining

    @@ -2814,7 +2657,7 @@
    Returns:
    -

    setReadTimeout(readTimeout) → {this}

    +

    setWriteTimeout(writeTimeout) → {this}

    @@ -2822,7 +2665,7 @@

    setRead
    -

    Sets the default read timeout for HTTP requests.

    +

    Sets the default write timeout for HTTP requests.

    @@ -2858,7 +2701,7 @@

    Parameters:
    - readTimeout + writeTimeout @@ -2915,7 +2758,7 @@
    Parameters:
    Source:
    @@ -2973,13 +2816,134 @@
    Returns:
    -

    setUsername(username) → {this}

    +

    shouldAuthenticate() → {boolean}

    + + + + + + +
    +

    Returns true if basic or gdb token authentication +is enabled. false otherwise.

    +
    + + + + + + + + + + + + + +
    + + + + + + + + +
    Overrides:
    +
    + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    is authentication enabled

    +
    + + + +
    +
    + Type +
    +
    + +boolean + + +
    +
    + + + + + + + + + + + + + +

    useBasicAuthentication(usernameopt, passopt) → {this}

    +
    +

    Username and password for user logging setter. +Sets basic authentication as client authentication type.

    +
    + @@ -3001,6 +2965,8 @@
    Parameters:
    Type + Attributes + @@ -3026,6 +2992,49 @@
    Parameters:
    + + + <optional>
    + + + + + + + + + + + + + + + + + + pass + + + + + +string + + + + + + + + + <optional>
    + + + + + + + @@ -3052,7 +3061,7 @@
    Parameters:
    Overrides:
    @@ -3075,7 +3084,7 @@
    Parameters:
    Source:
    @@ -3133,7 +3142,7 @@
    Returns:
    -

    setWriteTimeout(writeTimeout) → {this}

    +

    useGdbTokenAuthentication(usernameopt, passopt) → {this}

    @@ -3141,7 +3150,9 @@

    setWri
    -

    Sets the default write timeout for HTTP requests.

    +

    Username and password for user logging setter. +Sets gdb token authentication as client authentication type. +*

    @@ -3165,6 +3176,8 @@

    Parameters:
    Type + Attributes + @@ -3177,23 +3190,66 @@
    Parameters:
    - writeTimeout + username -number +string + + + <optional>
    + + + + + + + -

    the timeout in milliseconds

    + + + + + + + + pass + + + + + +string + + + + + + + + + <optional>
    + + + + + + + + + + + @@ -3214,6 +3270,11 @@
    Parameters:
    +
    Overrides:
    +
    + @@ -3234,7 +3295,7 @@
    Parameters:
    Source:
    @@ -3263,7 +3324,7 @@
    Returns:
    -

    current config for method chaining

    +

    the concrete configuration config for method chaining

    @@ -3302,13 +3363,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/RepositoryConfig.html b/docs/RepositoryConfig.html index f9897ace5..2e130dd3c 100644 --- a/docs/RepositoryConfig.html +++ b/docs/RepositoryConfig.html @@ -518,13 +518,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/RepositoryService.html b/docs/RepositoryService.html index 88f3ff816..6221989a6 100644 --- a/docs/RepositoryService.html +++ b/docs/RepositoryService.html @@ -431,13 +431,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/ResponseIterator.html b/docs/ResponseIterator.html index 92de043db..ba01b286c 100644 --- a/docs/ResponseIterator.html +++ b/docs/ResponseIterator.html @@ -165,13 +165,13 @@

    new R
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/ServerClient.html b/docs/ServerClient.html index 457b23139..6b77c9558 100644 --- a/docs/ServerClient.html +++ b/docs/ServerClient.html @@ -539,6 +539,116 @@

    Returns:
    +

    getLoggedUser() → {User}

    + + + + + + +
    +

    Logged user getter.

    +
    + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    user

    +
    + + + +
    +
    + Type +
    +
    + +User + + +
    +
    + + + + + + + + + + + + +

    getRepository(id, config) → {Promise.<RDFRepositoryClient>}

    @@ -1164,6 +1274,161 @@

    initLogger< + + + + + + +

    setLoggedUser(user) → {ServerClient}

    + + + + + + +
    +

    User setter

    +
    + + + + + + + + + +
    Parameters:
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescription
    user + + +User + + + +
    + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + + + +
    +
    + Type +
    +
    + +ServerClient + + +
    +
    + + + + + + + @@ -1180,13 +1445,13 @@

    initLogger<
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/ServerClientConfig.html b/docs/ServerClientConfig.html index 53d820875..1e10da69d 100644 --- a/docs/ServerClientConfig.html +++ b/docs/ServerClientConfig.html @@ -28,7 +28,7 @@

    Class: ServerClientConfig

    -

    ServerClientConfig(endpointopt, timeoutopt, headersopt, usernameopt, passopt, keepAliveopt, useBasicAuthopt)

    +

    ServerClientConfig(endpointopt)

    Configuration wrapper used for initialization of ServerClient instances.

    @@ -46,13 +46,20 @@

    Constructor

    -

    new ServerClientConfig(endpointopt, timeoutopt, headersopt, usernameopt, passopt, keepAliveopt, useBasicAuthopt)

    +

    new ServerClientConfig(endpointopt)

    +
    +

    Server client configuration constructor. +Sets configuration default value to +timeout +and keepAlive

    +
    + @@ -78,8 +85,6 @@
    Parameters:
    - Default - Description @@ -115,244 +120,232 @@
    Parameters:
    - - - -

    Endpoint url.

    + + - - - timeout - - - - -number - - - - - - <optional>
    - - +
    - - - + - - - - - + -

    Specifies the number of milliseconds before the -request times out.

    - + - - - headers - + - - - -Map.<string, string> + + - - + - - - - <optional>
    - + +
    Author:
    +
    +
      +
    • Mihail Radkov
    • + +
    • Svilen Velikov
    • + +
    • Teodossi Dossev
    • +
    +
    + - + - - - + - - - - - + -

    An http headers map.

    - + +
    Source:
    +
    + - - - username - + + + +
    + + + + + + + + + + + - - - -string - - - - - - <optional>
    - - - - - - - - - - -

    username which should be authenticated

    - + - - - pass - + +

    Extends

    - - - -string + - - + - - - - <optional>
    - - + - - - + - - - - - + -

    the password to be used

    - + - - - keepAlive - + - - - -boolean + + +

    Methods

    + - - - - - <optional>
    - + + + +

    disableAuthentication()

    + + + + + + +
    +

    Disables authentication.

    +
    + + - - - - - - - - true - - - -

    if the logged in user should be -reauthenticated after auth token expire. This config has meaning when the -server is secured and username and passwords are provided.

    - + + + + + + + +
    - - - useBasicAuth - + - - - -boolean + + +
    Overrides:
    +
    + - - + - - - - <optional>
    - + - + - - - + - - - - + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + -

    if use Basic Auth when authenticating

    - + - - +

    getBasicAuthentication() → {boolean}

    + + + + + + + + + + + + @@ -368,7 +361,10 @@
    Parameters:
    - +
    Overrides:
    +
    @@ -378,14 +374,7 @@
    Parameters:
    -
    Author:
    -
    -
      -
    • Mihail Radkov
    • - -
    • Svilen Velikov
    • -
    -
    + @@ -397,7 +386,7 @@
    Parameters:
    Source:
    @@ -422,41 +411,147 @@
    Parameters:
    +
    Returns:
    + + +
    +

    [basicAuth] if use Basic Auth

    +
    + + + +
    +
    + Type +
    +
    + +boolean + + +
    +
    + + + + + + + + + + + + + +

    getEndpoint() → {string}

    + + + + + + +
    +

    Returns the server's endpoint URL.

    +
    + + + + + + + + + +
    - -

    Extends

    - + + + +
    Overrides:
    +
    + + + + + + + + + + + + + + + + + + +
    Source:
    +
    + + + + + + + +
    + + + + + + + + + + + + + + + +
    Returns:
    + + +
    +

    the endpoint URL

    +
    - - +
    +
    + Type +
    +
    + +string - - +
    +
    - - - - -

    Methods

    @@ -464,17 +559,13 @@

    Methods

    -

    getEndpoint() → {string}

    +

    getGdbTokenAuthentication() → {boolean}

    -
    -

    Returns the server's endpoint URL.

    -
    - @@ -498,7 +589,7 @@

    getEndpoin
    Overrides:
    @@ -521,7 +612,7 @@

    getEndpoin
    Source:
    @@ -550,7 +641,7 @@

    Returns:
    -

    the endpoint URL

    +

    [gdbTokenAuth] if use Gdb Token Auth

    @@ -561,7 +652,7 @@
    Returns:
    -string +boolean
    @@ -636,7 +727,7 @@

    getHeaders<
    Source:
    @@ -747,7 +838,7 @@

    getKeepAl
    Source:
    @@ -858,7 +949,7 @@

    getPassSource:
    @@ -968,7 +1059,7 @@

    getTimeout<
    Source:
    @@ -1079,7 +1170,7 @@

    getUsernam
    Source:
    @@ -1137,13 +1228,17 @@

    Returns:
    -

    setBasicAuthentication(basicAuthopt) → {this}

    +

    setEndpoint(endpoint) → {this}

    +
    +

    Sets the server's endpoint URL.

    +
    + @@ -1165,8 +1260,6 @@
    Parameters:
    Type - Attributes - @@ -1179,33 +1272,23 @@
    Parameters:
    - basicAuth + endpoint -boolean +string - - - <optional>
    - - - - - - - -

    if use Basic Auth when authenticating

    +

    the endpoint URL

    @@ -1228,7 +1311,7 @@
    Parameters:
    Overrides:
    @@ -1251,7 +1334,7 @@
    Parameters:
    Source:
    @@ -1280,7 +1363,7 @@
    Returns:
    -

    the concrete configuration config for method chaining

    +

    the current config for method chaining

    @@ -1309,7 +1392,7 @@
    Returns:
    -

    setEndpoint(endpoint) → {this}

    +

    setHeaders(headers) → {this}

    @@ -1317,7 +1400,7 @@

    setEndpoin
    -

    Sets the server's endpoint URL.

    +

    Sets the default headers map for each HTTP request.

    @@ -1353,13 +1436,13 @@

    Parameters:
    - endpoint + headers -string +Object.<string, string> @@ -1369,7 +1452,7 @@
    Parameters:
    -

    the endpoint URL

    +

    the default headers

    @@ -1392,7 +1475,7 @@
    Parameters:
    Overrides:
    @@ -1415,7 +1498,7 @@
    Parameters:
    Source:
    @@ -1444,7 +1527,7 @@
    Returns:
    -

    the current config for method chaining

    +

    the concrete configuration config for method chaining

    @@ -1473,17 +1556,13 @@
    Returns:
    -

    setHeaders(headers) → {this}

    +

    setKeepAlive(keepAlive) → {this}

    -
    -

    Sets the default headers map for each HTTP request.

    -
    - @@ -1517,13 +1596,13 @@
    Parameters:
    - headers + keepAlive -Object.<string, string> +boolean @@ -1533,7 +1612,7 @@
    Parameters:
    -

    the default headers

    + @@ -1556,7 +1635,7 @@
    Parameters:
    Overrides:
    @@ -1579,7 +1658,7 @@
    Parameters:
    Source:
    @@ -1637,13 +1716,17 @@
    Returns:
    -

    setKeepAlive(keepAlive) → {this}

    +

    setTimeout(timeout) → {this}

    +
    +

    Sets the timeout for HTTP requests.

    +
    + @@ -1677,13 +1760,13 @@
    Parameters:
    - keepAlive + timeout -boolean +number @@ -1693,7 +1776,8 @@
    Parameters:
    - +

    the timeout in milliseconds before the +request times out.

    @@ -1714,11 +1798,6 @@
    Parameters:
    -
    Overrides:
    -
    - @@ -1739,7 +1818,7 @@
    Parameters:
    Source:
    @@ -1797,68 +1876,24 @@
    Returns:
    -

    setPass(pass) → {this}

    - - +

    shouldAuthenticate() → {boolean}

    - - - - - - - - - - -
    Parameters:
    - - - - - - - - - - - - - - - - - - - - - - +
    +

    Returns true if basic or gdb token authentication +is enabled. false otherwise.

    +
    - - - - - - - -
    NameTypeDescription
    pass - - -string - -
    @@ -1876,7 +1911,7 @@
    Parameters:
    Overrides:
    @@ -1899,7 +1934,7 @@
    Parameters:
    Source:
    @@ -1928,7 +1963,7 @@
    Returns:
    -

    the concrete configuration config for method chaining

    +

    is authentication enabled

    @@ -1939,7 +1974,7 @@
    Returns:
    -this +boolean
    @@ -1957,7 +1992,7 @@
    Returns:
    -

    setTimeout(timeout) → {this}

    +

    useBasicAuthentication(usernameopt, passopt) → {this}

    @@ -1965,7 +2000,8 @@

    setTimeout<
    -

    Sets the timeout for HTTP requests.

    +

    Username and password for user logging setter. +Sets basic authentication as client authentication type.

    @@ -1989,6 +2025,8 @@

    Parameters:
    Type + Attributes + @@ -2001,23 +2039,66 @@
    Parameters:
    - timeout + username -number +string + + + + + + + + + <optional>
    + + + + + + + + + + + + + + + + + + pass + + + + + +string + + + <optional>
    + + + + + + + -

    the timeout in milliseconds

    + @@ -2038,6 +2119,11 @@
    Parameters:
    +
    Overrides:
    +
    + @@ -2058,7 +2144,7 @@
    Parameters:
    Source:
    @@ -2116,13 +2202,19 @@
    Returns:
    -

    setUsername(username) → {this}

    +

    useGdbTokenAuthentication(usernameopt, passopt) → {this}

    +
    +

    Username and password for user logging setter. +Sets gdb token authentication as client authentication type. +*

    +
    + @@ -2144,6 +2236,8 @@
    Parameters:
    Type + Attributes + @@ -2169,6 +2263,49 @@
    Parameters:
    + + + <optional>
    + + + + + + + + + + + + + + + + + + pass + + + + + +string + + + + + + + + + <optional>
    + + + + + + + @@ -2195,7 +2332,7 @@
    Parameters:
    Overrides:
    @@ -2218,7 +2355,7 @@
    Parameters:
    Source:
    @@ -2286,13 +2423,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/Service.html b/docs/Service.html index 6679f533d..f08cdd830 100644 --- a/docs/Service.html +++ b/docs/Service.html @@ -332,13 +332,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/ServiceRequest.html b/docs/ServiceRequest.html index ef49345ac..27c0acdc3 100644 --- a/docs/ServiceRequest.html +++ b/docs/ServiceRequest.html @@ -459,13 +459,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/SparqlJsonResultParser.html b/docs/SparqlJsonResultParser.html index bdde0a55a..c71590827 100644 --- a/docs/SparqlJsonResultParser.html +++ b/docs/SparqlJsonResultParser.html @@ -606,13 +606,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/SparqlXmlResultParser.html b/docs/SparqlXmlResultParser.html index b7b1bc78b..996188bfd 100644 --- a/docs/SparqlXmlResultParser.html +++ b/docs/SparqlXmlResultParser.html @@ -606,13 +606,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/StatementPayload.html b/docs/StatementPayload.html index 5e5871c79..f078196c5 100644 --- a/docs/StatementPayload.html +++ b/docs/StatementPayload.html @@ -1363,13 +1363,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/StatementsService.html b/docs/StatementsService.html index 58b511e81..83fa1eea0 100644 --- a/docs/StatementsService.html +++ b/docs/StatementsService.html @@ -1645,13 +1645,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/StringUtils.html b/docs/StringUtils.html index 780b24064..03fc565c9 100644 --- a/docs/StringUtils.html +++ b/docs/StringUtils.html @@ -490,13 +490,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/TermConverter.html b/docs/TermConverter.html index 5841fad7b..cc04fd027 100644 --- a/docs/TermConverter.html +++ b/docs/TermConverter.html @@ -1592,13 +1592,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/TransactionService.html b/docs/TransactionService.html index 9233c621f..6d1c5e5f7 100644 --- a/docs/TransactionService.html +++ b/docs/TransactionService.html @@ -53,7 +53,7 @@

    new
    -

    Instantiates the transaction service wioth the supplied executor and +

    Instantiates the transaction service with the supplied executor and repository client config.

    @@ -167,6 +167,8 @@

    Parameters:
  • Mihail Radkov
  • Svilen Velikov
  • + +
  • Teodossi Dossev
  • @@ -180,7 +182,7 @@
    Parameters:
    Source:
    @@ -355,7 +357,7 @@
    Parameters:
    Source:
    @@ -461,7 +463,7 @@

    getServ
    Source:
    @@ -507,13 +509,13 @@

    getServ
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/TransactionalRepositoryClient.html b/docs/TransactionalRepositoryClient.html index 63954b5f1..e3d87cf8f 100644 --- a/docs/TransactionalRepositoryClient.html +++ b/docs/TransactionalRepositoryClient.html @@ -3059,13 +3059,13 @@

    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/TriGParser.html b/docs/TriGParser.html index 9c170e37d..fe379c7a9 100644 --- a/docs/TriGParser.html +++ b/docs/TriGParser.html @@ -385,13 +385,13 @@

    parse
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/TurtleParser.html b/docs/TurtleParser.html index 831366988..d133b3019 100644 --- a/docs/TurtleParser.html +++ b/docs/TurtleParser.html @@ -385,13 +385,13 @@

    parse
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/UpdateQueryPayload.html b/docs/UpdateQueryPayload.html index 882a152b1..92c1d6b1b 100644 --- a/docs/UpdateQueryPayload.html +++ b/docs/UpdateQueryPayload.html @@ -1718,13 +1718,13 @@

    validat
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/UploadService.html b/docs/UploadService.html index 572f9748c..c0a11679c 100644 --- a/docs/UploadService.html +++ b/docs/UploadService.html @@ -1345,13 +1345,13 @@

    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/User.html b/docs/User.html index 2499a5cd7..a68fef3cc 100644 --- a/docs/User.html +++ b/docs/User.html @@ -780,13 +780,13 @@
    Returns:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:16 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/auth_user.js.html b/docs/auth_user.js.html index 9e9afb3f9..1c131e934 100644 --- a/docs/auth_user.js.html +++ b/docs/auth_user.js.html @@ -103,13 +103,13 @@

    Source: auth/user.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/global.html b/docs/global.html index d4d1b1fd7..dce8beb6d 100644 --- a/docs/global.html +++ b/docs/global.html @@ -2608,13 +2608,13 @@
    Properties:

    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/http_client-config.js.html b/docs/http_client-config.js.html index 444748ebe..065c64b03 100644 --- a/docs/http_client-config.js.html +++ b/docs/http_client-config.js.html @@ -26,7 +26,11 @@

    Source: http/client-config.js

    -
    /**
    +            
    const BASIC_AUTH = 'BASIC';
    +const GDB_TOKEN = 'GDB_TOKEN';
    +const OFF = 'OFF';
    +
    +/**
      * Abstract configuration wrapper used for initialization of concrete
      * Client instances. Concrete client configuration wrappers must extend
      * this class and override it's methods if necessary.
    @@ -38,23 +42,13 @@ 

    Source: http/client-config.js

    */ class ClientConfig { /** - * @param {Map<string, string>} [headers] An http headers map. - * @param {string} [username] username which should be authenticated - * @param {string} [pass] the password to be used - * @param {boolean} [keepAlive=true] if the logged in user should be - * reauthenticated after auth token expire. This config has meaning when the - * server is secured and username and passwords are provided. - * @param {boolean} [useBasicAuth] if use Basic Auth when authenticating + * Client configuration constructor. + * * @param {string} endpoint server base URL that will be prepend * to all server requests */ - constructor(headers, username, pass, keepAlive, useBasicAuth, endpoint) { - this.headers = headers; - this.endpoint = endpoint; - this.username = username; - this.pass = pass; - this.keepAlive = keepAlive !== undefined ? keepAlive : true; - this.setBasicAuthentication(useBasicAuth); + constructor(endpoint) { + this.setEndpoint(endpoint); } /** @@ -84,15 +78,6 @@

    Source: http/client-config.js

    return this.username; } - /** - * @param {string} username - * @return {this} the concrete configuration config for method chaining - */ - setUsername(username) { - this.username = username; - return this; - } - /** * @return {string} the user password */ @@ -100,15 +85,6 @@

    Source: http/client-config.js

    return this.pass; } - /** - * @param {string} pass - * @return {this} the concrete configuration config for method chaining - */ - setPass(pass) { - this.pass = pass; - return this; - } - /** * @return {boolean} if the user should be re-logged in after token expires */ @@ -126,45 +102,101 @@

    Source: http/client-config.js

    } /** - * @param {boolean} [basicAuth] if use Basic Auth when authenticating + * Username and password for user logging setter. + * Sets basic authentication as client authentication type. + * + * @param {string} [username] + * @param {string} [pass] + * * @return {this} the concrete configuration config for method chaining */ - setBasicAuthentication(basicAuth) { - this.basicAuth = basicAuth; - this.useBasicAuthentication(); + useBasicAuthentication(username, pass) { + this.username = username; + this.pass = pass; + this.switchAuthentication(BASIC_AUTH); return this; } + + /** + * @return {boolean} [basicAuth] if use Basic Auth + */ + getBasicAuthentication() { + return this.basicAuth; + } + /** * @private + * @param {string} auth authentication type */ - useBasicAuthentication() { - if (this.basicAuth) { - const credentials = `${this.username}:${this.pass}`; - this.headers['Authorization'] = `Basic ${btoa(credentials)}`; - } + switchAuthentication(auth) { + this.basicAuth = auth === BASIC_AUTH; + this.gdbTokenAuth = auth === GDB_TOKEN; + } + + /** + * @return {boolean} [gdbTokenAuth] if use Gdb Token Auth + */ + getGdbTokenAuthentication() { + return this.gdbTokenAuth; + } + + /** + * Username and password for user logging setter. + * Sets gdb token authentication as client authentication type. + * * + * @param {string} [username] + * @param {string} [pass] + * + * @return {this} the concrete configuration config for method chaining + */ + useGdbTokenAuthentication(username, pass) { + this.username = username; + this.pass = pass; + this.switchAuthentication(GDB_TOKEN); + return this; + } + + /** + * Disables authentication. + */ + disableAuthentication() { + this.switchAuthentication(OFF); } /** * Sets the server's endpoint URL. * * @param {string} endpoint the endpoint URL - * * @return {this} the current config for method chaining */ setEndpoint(endpoint) { - this.endpoint = endpoint; - return this; + if (endpoint && + (typeof endpoint === 'string' || endpoint instanceof String)) { + this.endpoint = endpoint; + return this; + } else { + throw new Error('Invalid Endpoint parameter!'); + } } /** * Returns the server's endpoint URL. - * * @return {string} the endpoint URL */ getEndpoint() { return this.endpoint; } + + /** + * Returns <code>true</code> if basic or gdb token authentication + * is enabled. <code>false</code> otherwise. + * + * @return {boolean} is authentication enabled + */ + shouldAuthenticate() { + return this.basicAuth || this.gdbTokenAuth; + } } module.exports = ClientConfig; @@ -178,13 +210,13 @@

    Source: http/client-config.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/http_http-client.js.html b/docs/http_http-client.js.html index b3d6cac83..0a891756d 100644 --- a/docs/http_http-client.js.html +++ b/docs/http_http-client.js.html @@ -218,13 +218,13 @@

    Source: http/http-client.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/http_http-request-builder.js.html b/docs/http_http-request-builder.js.html index ea89a021c..d23f3fa5f 100644 --- a/docs/http_http-request-builder.js.html +++ b/docs/http_http-request-builder.js.html @@ -337,13 +337,13 @@

    Source: http/http-request-builder.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/http_http-response.js.html b/docs/http_http-response.js.html index 9b28cd685..99055525e 100644 --- a/docs/http_http-response.js.html +++ b/docs/http_http-response.js.html @@ -103,13 +103,13 @@

    Source: http/http-response.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/http_media-type.js.html b/docs/http_media-type.js.html index 1a792e4af..0ba348b95 100644 --- a/docs/http_media-type.js.html +++ b/docs/http_media-type.js.html @@ -50,13 +50,13 @@

    Source: http/media-type.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/http_query-content-type.js.html b/docs/http_query-content-type.js.html index a1b5255fd..d9be841f6 100644 --- a/docs/http_query-content-type.js.html +++ b/docs/http_query-content-type.js.html @@ -51,13 +51,13 @@

    Source: http/query-content-type.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/http_rdf-mime-type.js.html b/docs/http_rdf-mime-type.js.html index b04487910..4d0092349 100644 --- a/docs/http_rdf-mime-type.js.html +++ b/docs/http_rdf-mime-type.js.html @@ -74,13 +74,13 @@

    Source: http/rdf-mime-type.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/index.html b/docs/index.html index a4ba12b26..c2c7b63ce 100644 --- a/docs/index.html +++ b/docs/index.html @@ -143,11 +143,23 @@

    ServerClient

    const {ServerClient, ServerClientConfig} = require('graphdb').server;
     const {RDFMimeType} = require('graphdb').http;
     
    -const serverConfig = new ServerClientConfig('http://rdf4j-compliant-server/', 0, {
    -    'Accept': RDFMimeType.SPARQL_RESULTS_JSON
    -});
    +const serverConfig = new ServerClientConfig('http://rdf4j-compliant-server/')
    +    .setTimeout(5000)
    +    .setHeaders({
    +        'Accept': RDFMimeType.SPARQL_RESULTS_JSON
    +    })
    +    .setKeepAlive(true);
    +
     const server = new ServerClient(serverConfig);
     
    +

    When created, configurations receive the following default parameters:

    +
        /**
    +    * The Server client configuration constructor
    +    * sets configuration default value to 
    +    * timeout = 10000,
    +    * keepAlive = true
    +    */
    +
    • Fetch repository ids
    @@ -189,8 +201,8 @@

    GraphDBServerClient

    // Import all classes needed for work
     const {GraphDBServerClient, ServerClientConfig} = require('graphdb').server; 
     // Instance the server configuration
    -const serverConfig = new ServerClientConfig('http://rdf4j-compliant-server/', 10000,
    -    new Map(), 'admin', 'root', true, true);
    +const serverConfig = new ServerClientConfig('http://rdf4j-compliant-server/')
    +    .useGdbTokenAuthentication('admin', 'root');
     // Instance the server client
     const serverClient = new GraphDBServerClient(serverConfig);
     
    @@ -298,27 +310,48 @@

    RDFRepositoryClient

    • Instantiating repository client
    -
    const readTimeout = 30000;
    +
    const endpoint = 'http://GDB';
    +const readTimeout = 30000;
     const writeTimeout = 30000;
    -const config = new RepositoryClientConfig(['http://GDB/repositories/my-repo'], {
    -  'Accept': RDFMimeType.TURTLE
    -}, '', readTimeout, writeTimeout);
    +const config = new RepositoryClientConfig(endpoint)
    +    .setEndpoints(['http://GDB/repositories/my-repo'])
    +    .setHeaders({
    +      'Accept': RDFMimeType.TURTLE
    +    })
    +    .setReadTimeout(readTimeout)
    +    .setWriteTimeout(writeTimeout);
     const repository = new RDFRepositoryClient(config);
     
    +

    When created, configurations receive the following default parameters:

    +
        /**
    +    * The Repository client configuration constructor
    +    * sets configuration default value to 
    +    * defaultRDFMimeType = 'application/sparql-results+json',
    +    * keepAlive = true,
    +    * readTimeout = 10000,
    +    * writeTimeout = 10000
    +    */
    +
    • Obtaining repository client instance through a ServerClient
    const {ServerClient, ServerClientConfig} = require('graphdb').server;
     const {RepositoryClientConfig} = require('graphdb').repository;
     
    -const config = new ServerClientConfig('http://GDB', 0, {});
    +const endpoint = 'http://GDB';
    +const config = new ServerClientConfig(endpoint);
     const server = new ServerClient(config);
     
     const readTimeout = 30000;
     const writeTimeout = 30000;
    -const repositoryClientConfig = new RepositoryClientConfig(['http://GDB/repositories/my-repo'], {}, '', readTimeout, writeTimeout);
    -return server.getRepository('automotive', repositoryClientConfig).then((rdfRepositoryClient) => {
    -// rdfRepositoryClient is a configured instance of RDFRepositoryClient
    +
    +const repositoryClientConfig = new RepositoryClientConfig(endpoint)
    +    .setEndpoints(['http://GDB/repositories/my-repo'])
    +    .setReadTimeout(readTimeout)
    +    .setWriteTimeout(writeTimeout);
    +return server.getRepository('automotive', repositoryClientConfig)
    +    .then((rdfRepositoryClient) => {
    +    // rdfRepositoryClient is a configured instance of RDFRepositoryClient
     });
     

    Reading

    @@ -434,7 +467,7 @@

    Deleting

  • Delete statement from given context
  • repository.deleteStatements(subj, pred, obj, contexts).then(() => {
    -
    +    // do work
     });
     

    Transactions

    @@ -540,23 +573,27 @@

    GDB token

    In case the server requires that requests should be authenticated, then in the ServerClientConfig and RepositoryClientConfig must be configured the username and password which to be used for the authentication. If those are provided, then the client assumes that authentication is mandatory and the login with the provided credentials is performed authomatically before the first API call. After a successful login, user details which are received and the JWT auth token are stored in the AuthenticationService. From that moment on, with every API call is sent also an authorization header with the GDB token as value.

    ServerClient
     const headers = {'Accept': 'text/plain'};
    - const config = new ServerClientConfig('/endpoint', 1000, headers, 'testuser', 'P@sw0rd');
    + const config = new ServerClientConfig('/endpoint')
    +    .setTimeout(5000)
    +    .setHeaders(headers)
    +    .useGdbTokenAuthentication('user', 'root');
    + const client = new ServerClient(config);
     
    RepositoryClient
    -
    const endpoints = ['http://host/repositories/repo1'];
    +
    const endpoint = 'http://host/';
    +const endpoints = ['http://host/repositories/repo1'];
     const headers = {};
     const contentType = '';
     const readTimeout = 1000;
     const writeTimeout = 1000;
     
    -const config = new RepositoryClientConfig()
    +const config = new RepositoryClientConfig(endpoint)
       .setEndpoints(endpoints)
       .setHeaders(headers)
       .setDefaultRDFMimeType(contentType)
       .setReadTimeout(readTimeout)
       .setWriteTimeout(writeTimeout)
    -  .setUsername('testuser')
    -  .setPass('pass123');
    +  .useGdbTokenAuthentication('testuser', 'pass123');
     const repository = new RDFRepositoryClient(config);
     const httpRequest = repository.httpClients[0].request;
     
    @@ -568,12 +605,16 @@
    RepositoryClient

    Basic Authentication¶

    Instead of using GDB token, users can access secured GraphDB by passing valid base-64 encoded username:password combinations as a header. In case Basic authentication will be used, then the headers in the ServerClientConfig and RepositoryClientConfig must be configured to send the username and password which to be used for the authentication. From this moment on, with every API call is sent also an authorization header with the encoded credentials as value.

    -
    config.setBasicAuthentication(true);
    +
    config.useBasicAuthentication('admin', 'root');
     

    Note:
    Basic Authentication is even more vulnerable to man-in-the-middle attacks than GDB token! Anyone who intercepts your requests will be able to reuse your credentials indefinitely until you change them. Since the credentials are merely base-64 encoded, they will also get your username and password. This is why it is very important to always use encryption in transit.

    +
    Disable authentication
    +

    If necessary, authentication can be disabled in the configuration.

    +
    config.disableAuthentication();
    +

    Response Parsers

    Read responses of different content types might be parsed to data objects with parsers registered in the repository instance.

    @@ -678,13 +719,13 @@

    License


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/logging_console-logger.js.html b/docs/logging_console-logger.js.html index e57937b1a..f0e0a7e82 100644 --- a/docs/logging_console-logger.js.html +++ b/docs/logging_console-logger.js.html @@ -118,13 +118,13 @@

    Source: logging/console-logger.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/logging_logger.js.html b/docs/logging_logger.js.html index d54eecdab..07f625a68 100644 --- a/docs/logging_logger.js.html +++ b/docs/logging_logger.js.html @@ -47,13 +47,13 @@

    Source: logging/logger.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/logging_logging-utils.js.html b/docs/logging_logging-utils.js.html index a095b3c82..13515e826 100644 --- a/docs/logging_logging-utils.js.html +++ b/docs/logging_logging-utils.js.html @@ -65,13 +65,13 @@

    Source: logging/logging-utils.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/model_namespace.js.html b/docs/model_namespace.js.html index 7617d55d2..902014ef1 100644 --- a/docs/model_namespace.js.html +++ b/docs/model_namespace.js.html @@ -74,13 +74,13 @@

    Source: model/namespace.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/model_term-converter.js.html b/docs/model_term-converter.js.html index 36c390a1a..0a52a8bcf 100644 --- a/docs/model_term-converter.js.html +++ b/docs/model_term-converter.js.html @@ -400,13 +400,13 @@

    Source: model/term-converter.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/model_types.js.html b/docs/model_types.js.html index 24aaf64ce..d40c4561d 100644 --- a/docs/model_types.js.html +++ b/docs/model_types.js.html @@ -52,13 +52,13 @@

    Source: model/types.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_content-parser.js.html b/docs/parser_content-parser.js.html index 9be9e67ec..b961f3356 100644 --- a/docs/parser_content-parser.js.html +++ b/docs/parser_content-parser.js.html @@ -105,13 +105,13 @@

    Source: parser/content-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_jsonld-parser.js.html b/docs/parser_jsonld-parser.js.html index 0062b63fa..3781e0fbc 100644 --- a/docs/parser_jsonld-parser.js.html +++ b/docs/parser_jsonld-parser.js.html @@ -80,13 +80,13 @@

    Source: parser/jsonld-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_n-quads-parser.js.html b/docs/parser_n-quads-parser.js.html index 40bd8215f..f315263a6 100644 --- a/docs/parser_n-quads-parser.js.html +++ b/docs/parser_n-quads-parser.js.html @@ -75,13 +75,13 @@

    Source: parser/n-quads-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_n-triples-parser.js.html b/docs/parser_n-triples-parser.js.html index d3772d661..2aeb24c8b 100644 --- a/docs/parser_n-triples-parser.js.html +++ b/docs/parser_n-triples-parser.js.html @@ -78,13 +78,13 @@

    Source: parser/n-triples-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_n3-parser.js.html b/docs/parser_n3-parser.js.html index b3998649d..8eaa74698 100644 --- a/docs/parser_n3-parser.js.html +++ b/docs/parser_n3-parser.js.html @@ -75,13 +75,13 @@

    Source: parser/n3-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_parser-registry.js.html b/docs/parser_parser-registry.js.html index 7a0f3557f..10f6175b1 100644 --- a/docs/parser_parser-registry.js.html +++ b/docs/parser_parser-registry.js.html @@ -143,13 +143,13 @@

    Source: parser/parser-registry.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_rdfxml-parser.js.html b/docs/parser_rdfxml-parser.js.html index 67470cf62..a1633df1b 100644 --- a/docs/parser_rdfxml-parser.js.html +++ b/docs/parser_rdfxml-parser.js.html @@ -80,13 +80,13 @@

    Source: parser/rdfxml-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_sparql-json-result-parser.js.html b/docs/parser_sparql-json-result-parser.js.html index a1ee2aab0..b03fbc2f4 100644 --- a/docs/parser_sparql-json-result-parser.js.html +++ b/docs/parser_sparql-json-result-parser.js.html @@ -109,13 +109,13 @@

    Source: parser/sparql-json-result-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_sparql-xml-result-parser.js.html b/docs/parser_sparql-xml-result-parser.js.html index 2dc374e4e..3f5cb5e71 100644 --- a/docs/parser_sparql-xml-result-parser.js.html +++ b/docs/parser_sparql-xml-result-parser.js.html @@ -109,13 +109,13 @@

    Source: parser/sparql-xml-result-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_trig-parser.js.html b/docs/parser_trig-parser.js.html index e37f6662e..c57452f54 100644 --- a/docs/parser_trig-parser.js.html +++ b/docs/parser_trig-parser.js.html @@ -75,13 +75,13 @@

    Source: parser/trig-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/parser_turtle-parser.js.html b/docs/parser_turtle-parser.js.html index 3b093449d..15f5ed13d 100644 --- a/docs/parser_turtle-parser.js.html +++ b/docs/parser_turtle-parser.js.html @@ -75,13 +75,13 @@

    Source: parser/turtle-parser.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/query_get-query-payload.js.html b/docs/query_get-query-payload.js.html index 7b58ae052..9d07bef29 100644 --- a/docs/query_get-query-payload.js.html +++ b/docs/query_get-query-payload.js.html @@ -316,13 +316,13 @@

    Source: query/get-query-payload.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/query_query-language.js.html b/docs/query_query-language.js.html index fd753e5e4..88f971547 100644 --- a/docs/query_query-language.js.html +++ b/docs/query_query-language.js.html @@ -50,13 +50,13 @@

    Source: query/query-language.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/query_query-payload.js.html b/docs/query_query-payload.js.html index d3e68d88c..21f03236f 100644 --- a/docs/query_query-payload.js.html +++ b/docs/query_query-payload.js.html @@ -178,13 +178,13 @@

    Source: query/query-payload.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/query_query-type.js.html b/docs/query_query-type.js.html index d7a0404cd..b70a76b8e 100644 --- a/docs/query_query-type.js.html +++ b/docs/query_query-type.js.html @@ -52,13 +52,13 @@

    Source: query/query-type.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/query_update-query-payload.js.html b/docs/query_update-query-payload.js.html index e87a14083..a0b68036d 100644 --- a/docs/query_update-query-payload.js.html +++ b/docs/query_update-query-payload.js.html @@ -173,13 +173,13 @@

    Source: query/update-query-payload.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/repository_add-statement-payload.js.html b/docs/repository_add-statement-payload.js.html index a6f33f174..1bcd96f94 100644 --- a/docs/repository_add-statement-payload.js.html +++ b/docs/repository_add-statement-payload.js.html @@ -182,13 +182,13 @@

    Source: repository/add-statement-payload.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/repository_base-repository-client.js.html b/docs/repository_base-repository-client.js.html index 8c5317d85..05fdbbd5c 100644 --- a/docs/repository_base-repository-client.js.html +++ b/docs/repository_base-repository-client.js.html @@ -199,11 +199,10 @@

    Source: repository/base-repository-client.js

    */ retryExecution(httpClients, requestBuilder, currentHttpClient) { const httpClient = currentHttpClient || httpClients.next(); - const username = this.repositoryClientConfig.getUsername(); - const pass = this.repositoryClientConfig.getPass(); return this.authenticationService - .login(username, pass) - .then(() => { + .login(this.repositoryClientConfig, this.user) + .then((user) => { + this.setLoggedUser(user); this.decorateRequestConfig(requestBuilder); return httpClient.request(requestBuilder).then((response) => { return new HttpResponse(response, httpClient); @@ -245,7 +244,8 @@

    Source: repository/base-repository-client.js

    * @param {HttpRequestBuilder} requestBuilder */ decorateRequestConfig(requestBuilder) { - const token = this.authenticationService.getAuthentication(); + const token = this.authenticationService + .getAuthenticationToken(this.getLoggedUser()); if (token) { requestBuilder.addAuthorizationHeader(token); } @@ -309,6 +309,25 @@

    Source: repository/base-repository-client.js

    + 'endpoint configuration! At least one endpoint must be provided.'); } } + + /** + * Logged user getter. + * @return {User} user + */ + getLoggedUser() { + return this.user; + } + + /** + * User setter + * @param {User} user + * + * @return {BaseRepositoryClient} + */ + setLoggedUser(user) { + this.user = user; + return this; + } } module.exports = BaseRepositoryClient; @@ -322,13 +341,13 @@

    Source: repository/base-repository-client.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/repository_get-statements-payload.js.html b/docs/repository_get-statements-payload.js.html index f205b7132..45d77d81e 100644 --- a/docs/repository_get-statements-payload.js.html +++ b/docs/repository_get-statements-payload.js.html @@ -98,13 +98,13 @@

    Source: repository/get-statements-payload.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/repository_rdf-repository-client.js.html b/docs/repository_rdf-repository-client.js.html index ef7303b10..c497ed5be 100644 --- a/docs/repository_rdf-repository-client.js.html +++ b/docs/repository_rdf-repository-client.js.html @@ -448,13 +448,13 @@

    Source: repository/rdf-repository-client.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/repository_repository-client-config.js.html b/docs/repository_repository-client-config.js.html index 69cfee761..b6149d7f9 100644 --- a/docs/repository_repository-client-config.js.html +++ b/docs/repository_repository-client-config.js.html @@ -27,6 +27,9 @@

    Source: repository/repository-client-config.js

    const ClientConfig = require('../http/client-config');
    +const RDFMimeType = require('../http/rdf-mime-type');
    +
    +const defaultTimeout = 10000;
     
     /**
      * Configuration wrapper used for initialization of {@link BaseRepositoryClient}
    @@ -36,33 +39,28 @@ 

    Source: repository/repository-client-config.js

    * @extends ClientConfig * @author Mihail Radkov * @author Svilen Velikov + * @author Teodossi Dossev */ class RepositoryClientConfig extends ClientConfig { /** - * @param {string[]} [endpoints] is an array with repository endpoints - * @param {Map<string, string>} [headers] is a key:value mapping of http - * headers and values - * @param {string} [defaultRDFMimeType] one of {@link RDFMimeType} values - * @param {number} [readTimeout] - * @param {number} [writeTimeout] - * @param {string} [username] username which should be authenticated - * @param {string} [pass] the password to be used - * @param {boolean} [keepAlive] if the logged in user should be - * reauthenticated after auth token expire. This config has meaning when the - * server is secured and username and passwords are provided. - * @param {boolean} [useBasicAuth] if use Basic Auth when authenticating + * Repository client configuration constructor. + * Initializes [endpoints]{@link RepositoryClientConfig#endpoints} and + * sets configuration default values to + * [defaultRDFMimeType]{@link RepositoryClientConfig#defaultRDFMimeType}, + * [readTimeout]{@link RepositoryClientConfig#readTimeout} and + * [writeTimeout]{@link RepositoryClientConfig#writeTimeout} + * * @param {string} endpoint server base URL that will be prepend * to all server requests */ - constructor(endpoints, headers, defaultRDFMimeType, readTimeout, - writeTimeout, username, pass, keepAlive, useBasicAuth, endpoint) { - super(headers, username, pass, keepAlive, useBasicAuth, endpoint); - this.endpoints = endpoints; - this.defaultRDFMimeType = defaultRDFMimeType; - this.readTimeout = readTimeout; - this.writeTimeout = writeTimeout; - // TODO refactor to reduce constructor params - // related to https://github.com/Ontotext-AD/graphdb.js/issues/124 + constructor(endpoint) { + super(endpoint); + this.setEndpoints([]); + this.setHeaders({}); + this.setKeepAlive(true); + this.setDefaultRDFMimeType(RDFMimeType.SPARQL_RESULTS_JSON); + this.setReadTimeout(defaultTimeout); + this.setWriteTimeout(defaultTimeout); } /** @@ -176,13 +174,13 @@

    Source: repository/repository-client-config.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/repository_repository-config.js.html b/docs/repository_repository-config.js.html index 4155d9822..7916da49e 100644 --- a/docs/repository_repository-config.js.html +++ b/docs/repository_repository-config.js.html @@ -87,13 +87,13 @@

    Source: repository/repository-config.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/repository_repository-type.js.html b/docs/repository_repository-type.js.html index ffdd5740b..c1bacd124 100644 --- a/docs/repository_repository-type.js.html +++ b/docs/repository_repository-type.js.html @@ -53,13 +53,13 @@

    Source: repository/repository-type.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/repository_statement-payload.js.html b/docs/repository_statement-payload.js.html index eac1b13cd..af2c02259 100644 --- a/docs/repository_statement-payload.js.html +++ b/docs/repository_statement-payload.js.html @@ -132,13 +132,13 @@

    Source: repository/statement-payload.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/response_paged-response.js.html b/docs/response_paged-response.js.html index 14b76da1f..7f944446b 100644 --- a/docs/response_paged-response.js.html +++ b/docs/response_paged-response.js.html @@ -66,13 +66,13 @@

    Source: response/paged-response.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/response_response-iterator.js.html b/docs/response_response-iterator.js.html index 3ff72dc20..2c67deba9 100644 --- a/docs/response_response-iterator.js.html +++ b/docs/response_response-iterator.js.html @@ -47,13 +47,13 @@

    Source: response/response-iterator.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/security_authentication-factory.js.html b/docs/security_authentication-factory.js.html new file mode 100644 index 000000000..72016ed99 --- /dev/null +++ b/docs/security_authentication-factory.js.html @@ -0,0 +1,79 @@ + + + + + JSDoc: Source: security/authentication-factory.js + + + + + + + + + + +
    + +

    Source: security/authentication-factory.js

    + + + + + + +
    +
    +
    const BasicAuthentication = require('./basic-authentication');
    +const GdbTokenAuthentication = require('./gdb-token-authentication');
    +
    +/**
    + * Factory to create concrete authentication type, based on
    + * client configuration.
    + *
    + * @class
    + * @author Teodossi Dossev
    + */
    +export class AuthenticationFactory {
    +  /**
    +   * Concrete authentication type generator.
    +   * @param {ClientConfig} clientConfig
    +   * @return {BasicAuthentication | GdbTokenAuthentication}
    +   */
    +  getAuthenticationType(clientConfig) {
    +    if (clientConfig.getBasicAuthentication()) {
    +      return new BasicAuthentication(clientConfig);
    +    } else if (clientConfig.getGdbTokenAuthentication()) {
    +      return new GdbTokenAuthentication(clientConfig);
    +    } else {
    +      throw Error('Authentication is not configured properly');
    +    }
    +  }
    +}
    +
    +module.exports = AuthenticationFactory;
    +
    +
    +
    + + + + +
    + + + +
    + +
    + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time) +
    + + + + + diff --git a/docs/security_authentication.js.html b/docs/security_authentication.js.html new file mode 100644 index 000000000..0f2971090 --- /dev/null +++ b/docs/security_authentication.js.html @@ -0,0 +1,86 @@ + + + + + JSDoc: Source: security/authentication.js + + + + + + + + + + +
    + +

    Source: security/authentication.js

    + + + + + + +
    +
    +
    /**
    + * An abstract class that specifies common methods for different types
    + * of authentication. Concrete authentication types must extend
    + * this class and override it's methods
    + *
    + * @abstract
    + * @class
    + * @author Teodossi Dossev
    + */
    +export class Authentication {
    +  /**
    +   * Constructor.
    +   * @param {ClientConfig} clientConfig
    +   */
    +  constructor(clientConfig) {
    +    this.clientConfig = clientConfig;
    +  }
    +  /**
    +   * Returns authentication type related {@link HttpRequestBuilder}
    +   * login request builder
    +  */
    +  getLoginRequestBuilder() {
    +    throw new Error('Method #getLoginRequestBuilder() must be implemented!');
    +  }
    +
    +  /**
    +   * Returns authentication type related {string}
    +   * token from response
    +   */
    +  getResponseAuthToken() {
    +    throw new Error('Method #getResponseAuthToken() must be implemented!');
    +  }
    +}
    +
    +module.exports = Authentication;
    +
    +
    +
    + + + + +
    + + + +
    + +
    + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time) +
    + + + + + diff --git a/docs/security_authority.js.html b/docs/security_authority.js.html index c70953f44..6cd2367e6 100644 --- a/docs/security_authority.js.html +++ b/docs/security_authority.js.html @@ -52,13 +52,13 @@

    Source: security/authority.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/security_basic-authentication.js.html b/docs/security_basic-authentication.js.html new file mode 100644 index 000000000..1e29e375c --- /dev/null +++ b/docs/security_basic-authentication.js.html @@ -0,0 +1,85 @@ + + + + + JSDoc: Source: security/basic-authentication.js + + + + + + + + + + +
    + +

    Source: security/basic-authentication.js

    + + + + + + +
    +
    +
    const Authentication = require('./authentication');
    +const HttpRequestBuilder = require('../http/http-request-builder');
    +
    +/**
    + * Basic authentication type class.
    + * Used for basic authentication against secured gdb server.
    + *
    + * @class
    + * @author Teodossi Dossev
    + */
    +export class BasicAuthentication extends Authentication {
    +  /**
    +   * @override
    +   * @return {HttpRequestBuilder} requestBuilder
    +   */
    +  getLoginRequestBuilder() {
    +    const username = this.clientConfig.getUsername();
    +    const pass = this.clientConfig.getPass();
    +    const credentials = `${username}:${pass}`;
    +
    +    return HttpRequestBuilder.httpGet(`/rest/security/authenticatedUser`)
    +      .addAuthorizationHeader(`Basic ${btoa(credentials)}`);
    +  }
    +
    +  /**
    +   * @override
    +   * @return {string} token
    +   */
    +  getResponseAuthToken(response) {
    +    return response.config.headers['authorization'];
    +  }
    +}
    +
    +module.exports = BasicAuthentication;
    +
    +
    +
    + + + + +
    + + + +
    + +
    + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time) +
    + + + + + diff --git a/docs/security_gdb-token-authentication.js.html b/docs/security_gdb-token-authentication.js.html new file mode 100644 index 000000000..ef2a8fe00 --- /dev/null +++ b/docs/security_gdb-token-authentication.js.html @@ -0,0 +1,84 @@ + + + + + JSDoc: Source: security/gdb-token-authentication.js + + + + + + + + + + +
    + +

    Source: security/gdb-token-authentication.js

    + + + + + + +
    +
    +
    const Authentication = require('./authentication');
    +const HttpRequestBuilder = require('../http/http-request-builder');
    +
    +/**
    + * Gdb token authentication type class.
    + * Used for gdb token authentication against secured gdb server.
    + *
    + * @class
    + * @author Teodossi Dossev
    + */
    +export class GdbTokenAuthentication extends Authentication {
    +  /**
    +   * @override
    +   * @return {HttpRequestBuilder} requestBuilder
    +   */
    +  getLoginRequestBuilder() {
    +    const username = this.clientConfig.getUsername();
    +    const pass = this.clientConfig.getPass();
    +
    +    return HttpRequestBuilder.httpPost(`/rest/login/${username}`)
    +      .addGraphDBPasswordHeader(pass);
    +  }
    +
    +  /**
    +   * @override
    +   * @return {string} token
    +   */
    +  getResponseAuthToken(response) {
    +    return response.headers['authorization'];
    +  }
    +}
    +
    +module.exports = GdbTokenAuthentication;
    +
    +
    +
    + + + + +
    + + + +
    + +
    + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time) +
    + + + + + diff --git a/docs/server_app-settings.js.html b/docs/server_app-settings.js.html index 327542bc5..965202b04 100644 --- a/docs/server_app-settings.js.html +++ b/docs/server_app-settings.js.html @@ -129,13 +129,13 @@

    Source: server/app-settings.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/server_graphdb-server-client.js.html b/docs/server_graphdb-server-client.js.html index 53237222f..74ce2c0cf 100644 --- a/docs/server_graphdb-server-client.js.html +++ b/docs/server_graphdb-server-client.js.html @@ -358,13 +358,13 @@

    Source: server/graphdb-server-client.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/server_server-client-config.js.html b/docs/server_server-client-config.js.html index 69131db6c..661bc206f 100644 --- a/docs/server_server-client-config.js.html +++ b/docs/server_server-client-config.js.html @@ -28,6 +28,8 @@

    Source: server/server-client-config.js

    const ClientConfig = require('../http/client-config');
     
    +const defaultTimeout = 10000;
    +
     /**
      * Configuration wrapper used for initialization of {@link ServerClient}
      * instances.
    @@ -36,32 +38,29 @@ 

    Source: server/server-client-config.js

    * @extends ClientConfig * @author Mihail Radkov * @author Svilen Velikov + * @author Teodossi Dossev */ class ServerClientConfig extends ClientConfig { /** + * Server client configuration constructor. + * Sets configuration default value to + * [timeout]{@link ServerClientConfig#timeout} + * and [keepAlive]{@link ServerClientConfig#keepAlive} + * * @param {string} [endpoint] Endpoint url. - * @param {number} [timeout] Specifies the number of milliseconds before the - * request times out. - * @param {Map<string, string>} [headers] An http headers map. - * @param {string} [username] username which should be authenticated - * @param {string} [pass] the password to be used - * @param {boolean} [keepAlive=true] if the logged in user should be - * reauthenticated after auth token expire. This config has meaning when the - * server is secured and username and passwords are provided. - * @param {boolean} [useBasicAuth] if use Basic Auth when authenticating */ - constructor(endpoint, timeout, headers, username, pass, - keepAlive, useBasicAuth) { - super(headers, username, pass, keepAlive, useBasicAuth, endpoint); - this.timeout = timeout; - // TODO refactor to reduce constructor params - // related to https://github.com/Ontotext-AD/graphdb.js/issues/124 + constructor(endpoint) { + super(endpoint); + this.setHeaders({}); + this.setKeepAlive(true); + this.setTimeout(defaultTimeout); } /** * Sets the timeout for HTTP requests. * - * @param {number} timeout the timeout in milliseconds + * @param {number} timeout the timeout in milliseconds before the + * request times out. * @return {this} the concrete configuration config for method chaining */ setTimeout(timeout) { @@ -90,13 +89,13 @@

    Source: server/server-client-config.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/server_server-client.js.html b/docs/server_server-client.js.html index cb9553c7b..cdccdf47e 100644 --- a/docs/server_server-client.js.html +++ b/docs/server_server-client.js.html @@ -178,10 +178,9 @@

    Source: server/server-client.js

    */ execute(requestBuilder) { const startTime = Date.now(); - const username = this.config.getUsername(); - const pass = this.config.getPass(); - return this.authenticationService.login(username, pass) + return this.authenticationService.login(this.config, this.getLoggedUser()) .then((user) => { + this.setLoggedUser(user); this.decorateRequestConfig(requestBuilder); return this.httpClient.request(requestBuilder); }) @@ -217,7 +216,7 @@

    Source: server/server-client.js

    * @return {Promise} returns a promise which resolves with undefined. */ logout() { - return this.authenticationService.logout(); + return this.authenticationService.logout(this.getLoggedUser()); } /** @@ -227,11 +226,31 @@

    Source: server/server-client.js

    * @param {HttpRequestBuilder} requestBuilder */ decorateRequestConfig(requestBuilder) { - const token = this.authenticationService.getAuthentication(); + const token = this.authenticationService + .getAuthenticationToken(this.getLoggedUser()); if (token) { requestBuilder.addAuthorizationHeader(token); } } + + /** + * Logged user getter. + * @return {User} user + */ + getLoggedUser() { + return this.user; + } + + /** + * User setter + * @param {User} user + * + * @return {ServerClient} + */ + setLoggedUser(user) { + this.user = user; + return this; + } } module.exports = ServerClient; @@ -245,13 +264,13 @@

    Source: server/server-client.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_authentication-service.js.html b/docs/service_authentication-service.js.html index 9e7b0d380..bef196442 100644 --- a/docs/service_authentication-service.js.html +++ b/docs/service_authentication-service.js.html @@ -26,14 +26,15 @@

    Source: service/authentication-service.js

    -
    const HttpRequestBuilder = require('../http/http-request-builder');
    -const User = require('../auth/user');
    +            
    const User = require('../auth/user');
    +const AuthenticationFactory = require('../security/authentication-factory');
     
     /**
      * Service dealing with user authentication in a secured server.
      *
      * @author Mihail Radkov
      * @author Svilen Velikov
    + * @author Teodossi Dossev
      */
     class AuthenticationService {
       /**
    @@ -43,6 +44,7 @@ 

    Source: service/authentication-service.js

    */ constructor(httpClient) { this.httpClient = httpClient; + this.authenticationFactory = new AuthenticationFactory(); } /** @@ -50,25 +52,24 @@

    Source: service/authentication-service.js

    * password. Upon successful authentication a {@link User} instance is created * with the user data and the auth token and returned to the client. * - * @param {string} username is the username of the logged in user - * @param {string} pass is the password of the logged in user + * @param {ClientConfig} clientConfig concrete client configuration + * @param {User} user logged in user * * @return {Promise<User>} a promise resolving to an authenticated * {@link User} instance. */ - login(username, pass) { - if (!this.shouldAuthenticate(username, pass)) { - return Promise.resolve(); + login(clientConfig, user) { + if (!clientConfig.shouldAuthenticate() || + !this.isAlreadyAuthenticated(clientConfig, user)) { + return Promise.resolve(user); } - const requestBuilder = - HttpRequestBuilder.httpPost(`/rest/login/${username}`) - .addGraphDBPasswordHeader(pass); - return this.httpClient.request(requestBuilder).then((response) => { - const token = response.headers['authorization']; - const user = new User(token, pass, response.data); - this.setLoggedUser(user); - return user; - }); + + const authentication = this.getAuthentication(clientConfig); + return this.httpClient.request(this.getLoginRequest(clientConfig)) + .then((response) => { + const token = authentication.getResponseAuthToken(response); + return new User(token, clientConfig.getPass(), response.data); + }); } /** @@ -76,10 +77,12 @@

    Source: service/authentication-service.js

    * the client user. Every consecutive call against secured server will result * in <code>Unauthorized</code> error with status code <code>401</code>. * + * @param {User} user logged in user + * * @return {Promise} returns a promise which resolves with undefined. */ - logout() { - this.getLoggedUser() && this.getLoggedUser().clearToken(); + logout(user) { + user.clearToken(); return Promise.resolve(); } @@ -88,10 +91,11 @@

    Source: service/authentication-service.js

    * request header <code>Authorization: token</code>. If there is no logged in * user, then this method returns <code>undefined</code>. * - * @return {string|undefined} + * @param {User} user logged in user + * @return {string|undefined} authentication token */ - getAuthentication() { - return this.getLoggedUser() && this.getLoggedUser().getToken(); + getAuthenticationToken(user) { + return user && user.getToken(); } /** @@ -99,40 +103,36 @@

    Source: service/authentication-service.js

    * yet. If that's the case, authentication should be made. * * @private - * - * @param {string} username is the username of the logged in user - * @param {string} pass is the password of the logged in user + * @param {ClientConfig} clientConfig concrete client config + * @param {User} user logged in user * * @return {boolean} true if authentication should be made */ - shouldAuthenticate(username, pass) { - const hasCredentials = username && pass; - const isAuthenticated = this.getLoggedUser() - && this.getLoggedUser().getToken(); + isAlreadyAuthenticated(clientConfig, user) { + const hasCredentials = clientConfig.getUsername() && clientConfig.getPass(); + const isAuthenticated = user && user.getToken(); return hasCredentials && !isAuthenticated; } /** - * @param {User} user - */ - setLoggedUser(user) { - this.loggedUser = user; - } - - /** - * @return {User} + * Returns authentication type related {@link HttpRequestBuilder} + * login request builder + * + * @param {ClientConfig} clientConfig concrete client configuration + * @return {HttpRequestBuilder} request builder */ - getLoggedUser() { - return this.loggedUser; + getLoginRequest(clientConfig) { + return this.getAuthentication(clientConfig).getLoginRequestBuilder(); } /** - * @param {HttpClient} httpClient - * @return {AuthenticationService} + * Authentication type getter + * @param {ClientConfig} clientConfig concrete client configuration + * @return {BasicAuthentication|GdbTokenAuthentication} concrete + * authentication type */ - setHttpClient(httpClient) { - this.httpClient = httpClient; - return this; + getAuthentication(clientConfig) { + return this.authenticationFactory.getAuthenticationType(clientConfig); } } @@ -147,13 +147,13 @@

    Source: service/authentication-service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_download-service.js.html b/docs/service_download-service.js.html index e512d5508..1d23f5d7c 100644 --- a/docs/service_download-service.js.html +++ b/docs/service_download-service.js.html @@ -96,13 +96,13 @@

    Source: service/download-service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_namespace-service.js.html b/docs/service_namespace-service.js.html index 66ce19e41..ae323eeb9 100644 --- a/docs/service_namespace-service.js.html +++ b/docs/service_namespace-service.js.html @@ -222,13 +222,13 @@

    Source: service/namespace-service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_query-service.js.html b/docs/service_query-service.js.html index 7b351798e..f1045ff42 100644 --- a/docs/service_query-service.js.html +++ b/docs/service_query-service.js.html @@ -159,13 +159,13 @@

    Source: service/query-service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_repository-service.js.html b/docs/service_repository-service.js.html index 596ab564c..c05be28d1 100644 --- a/docs/service_repository-service.js.html +++ b/docs/service_repository-service.js.html @@ -87,13 +87,13 @@

    Source: service/repository-service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_service-paths.js.html b/docs/service_service-paths.js.html index 952844a83..04b92adcf 100644 --- a/docs/service_service-paths.js.html +++ b/docs/service_service-paths.js.html @@ -70,13 +70,13 @@

    Source: service/service-paths.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_service-request.js.html b/docs/service_service-request.js.html index 418efa91d..14baa5247 100644 --- a/docs/service_service-request.js.html +++ b/docs/service_service-request.js.html @@ -80,13 +80,13 @@

    Source: service/service-request.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_service.js.html b/docs/service_service.js.html index 92f7075c4..3178c7f60 100644 --- a/docs/service_service.js.html +++ b/docs/service_service.js.html @@ -83,13 +83,13 @@

    Source: service/service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_statements-service.js.html b/docs/service_statements-service.js.html index 083e1c1aa..3109d34bd 100644 --- a/docs/service_statements-service.js.html +++ b/docs/service_statements-service.js.html @@ -326,13 +326,13 @@

    Source: service/statements-service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_transaction-service.js.html b/docs/service_transaction-service.js.html index 7c614a2fa..7673dea2a 100644 --- a/docs/service_transaction-service.js.html +++ b/docs/service_transaction-service.js.html @@ -43,10 +43,11 @@

    Source: service/transaction-service.js

    * * @author Mihail Radkov * @author Svilen Velikov + * @author Teodossi Dossev */ class TransactionService extends Service { /** - * Instantiates the transaction service wioth the supplied executor and + * Instantiates the transaction service with the supplied executor and * repository client config. * * @param {Function} httpRequestExecutor used to execute HTTP requests @@ -106,7 +107,7 @@

    Source: service/transaction-service.js

    */ getTransactionalClientConfig(locationUrl) { const config = this.repositoryClientConfig; - return new RepositoryClientConfig() + return new RepositoryClientConfig(config.getEndpoint()) .setEndpoints([locationUrl]) .setHeaders(config.getHeaders()) .setDefaultRDFMimeType(config.getDefaultRDFMimeType()) @@ -133,13 +134,13 @@

    Source: service/transaction-service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/service_upload-service.js.html b/docs/service_upload-service.js.html index b9aeee3f7..91ad4c85a 100644 --- a/docs/service_upload-service.js.html +++ b/docs/service_upload-service.js.html @@ -251,13 +251,13 @@

    Source: service/upload-service.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/transaction_transaction-isolation-level.js.html b/docs/transaction_transaction-isolation-level.js.html index 35ac20cc4..e345adc02 100644 --- a/docs/transaction_transaction-isolation-level.js.html +++ b/docs/transaction_transaction-isolation-level.js.html @@ -54,13 +54,13 @@

    Source: transaction/transaction-isolation-level.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/transaction_transactional-repository-client.js.html b/docs/transaction_transactional-repository-client.js.html index 2e2d914b0..a7df562f0 100644 --- a/docs/transaction_transactional-repository-client.js.html +++ b/docs/transaction_transactional-repository-client.js.html @@ -375,13 +375,13 @@

    Source: transaction/transactional-repository-client.js
    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/util_common-utils.js.html b/docs/util_common-utils.js.html index 695d91bfd..2eb4f9958 100644 --- a/docs/util_common-utils.js.html +++ b/docs/util_common-utils.js.html @@ -55,13 +55,13 @@

    Source: util/common-utils.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/util_file-utils.js.html b/docs/util_file-utils.js.html index fa4db279f..40f3a58b4 100644 --- a/docs/util_file-utils.js.html +++ b/docs/util_file-utils.js.html @@ -71,13 +71,13 @@

    Source: util/file-utils.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/util_iterable.js.html b/docs/util_iterable.js.html index b4f760542..678d25b17 100644 --- a/docs/util_iterable.js.html +++ b/docs/util_iterable.js.html @@ -99,13 +99,13 @@

    Source: util/iterable.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/docs/util_string-utils.js.html b/docs/util_string-utils.js.html index 1666c8f83..dadba56a7 100644 --- a/docs/util_string-utils.js.html +++ b/docs/util_string-utils.js.html @@ -70,13 +70,13 @@

    Source: util/string-utils.js


    - Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 07:10:15 GMT+0100 (Central European Standard Time) + Documentation generated by JSDoc 3.6.6 on Wed Feb 10 2021 09:07:38 GMT+0200 (Eastern European Standard Time)
    diff --git a/src/http/client-config.js b/src/http/client-config.js index 83a9304e9..d47dd0a7f 100644 --- a/src/http/client-config.js +++ b/src/http/client-config.js @@ -1,3 +1,7 @@ +const BASIC_AUTH = 'BASIC'; +const GDB_TOKEN = 'GDB_TOKEN'; +const OFF = 'OFF'; + /** * Abstract configuration wrapper used for initialization of concrete * Client instances. Concrete client configuration wrappers must extend @@ -10,23 +14,13 @@ */ class ClientConfig { /** - * @param {Map} [headers] An http headers map. - * @param {string} [username] username which should be authenticated - * @param {string} [pass] the password to be used - * @param {boolean} [keepAlive=true] if the logged in user should be - * reauthenticated after auth token expire. This config has meaning when the - * server is secured and username and passwords are provided. - * @param {boolean} [useBasicAuth] if use Basic Auth when authenticating + * Client configuration constructor. + * * @param {string} endpoint server base URL that will be prepend * to all server requests */ - constructor(headers, username, pass, keepAlive, useBasicAuth, endpoint) { - this.headers = headers; - this.endpoint = endpoint; - this.username = username; - this.pass = pass; - this.keepAlive = keepAlive !== undefined ? keepAlive : true; - this.setBasicAuthentication(useBasicAuth); + constructor(endpoint) { + this.setEndpoint(endpoint); } /** @@ -56,15 +50,6 @@ class ClientConfig { return this.username; } - /** - * @param {string} username - * @return {this} the concrete configuration config for method chaining - */ - setUsername(username) { - this.username = username; - return this; - } - /** * @return {string} the user password */ @@ -72,15 +57,6 @@ class ClientConfig { return this.pass; } - /** - * @param {string} pass - * @return {this} the concrete configuration config for method chaining - */ - setPass(pass) { - this.pass = pass; - return this; - } - /** * @return {boolean} if the user should be re-logged in after token expires */ @@ -98,45 +74,101 @@ class ClientConfig { } /** - * @param {boolean} [basicAuth] if use Basic Auth when authenticating + * Username and password for user logging setter. + * Sets basic authentication as client authentication type. + * + * @param {string} [username] + * @param {string} [pass] + * * @return {this} the concrete configuration config for method chaining */ - setBasicAuthentication(basicAuth) { - this.basicAuth = basicAuth; - this.useBasicAuthentication(); + useBasicAuthentication(username, pass) { + this.username = username; + this.pass = pass; + this.switchAuthentication(BASIC_AUTH); return this; } + + /** + * @return {boolean} [basicAuth] if use Basic Auth + */ + getBasicAuthentication() { + return this.basicAuth; + } + /** * @private + * @param {string} auth authentication type */ - useBasicAuthentication() { - if (this.basicAuth) { - const credentials = `${this.username}:${this.pass}`; - this.headers['Authorization'] = `Basic ${btoa(credentials)}`; - } + switchAuthentication(auth) { + this.basicAuth = auth === BASIC_AUTH; + this.gdbTokenAuth = auth === GDB_TOKEN; + } + + /** + * @return {boolean} [gdbTokenAuth] if use Gdb Token Auth + */ + getGdbTokenAuthentication() { + return this.gdbTokenAuth; + } + + /** + * Username and password for user logging setter. + * Sets gdb token authentication as client authentication type. + * * + * @param {string} [username] + * @param {string} [pass] + * + * @return {this} the concrete configuration config for method chaining + */ + useGdbTokenAuthentication(username, pass) { + this.username = username; + this.pass = pass; + this.switchAuthentication(GDB_TOKEN); + return this; + } + + /** + * Disables authentication. + */ + disableAuthentication() { + this.switchAuthentication(OFF); } /** * Sets the server's endpoint URL. * * @param {string} endpoint the endpoint URL - * * @return {this} the current config for method chaining */ setEndpoint(endpoint) { - this.endpoint = endpoint; - return this; + if (endpoint && + (typeof endpoint === 'string' || endpoint instanceof String)) { + this.endpoint = endpoint; + return this; + } else { + throw new Error('Invalid Endpoint parameter!'); + } } /** * Returns the server's endpoint URL. - * * @return {string} the endpoint URL */ getEndpoint() { return this.endpoint; } + + /** + * Returns true if basic or gdb token authentication + * is enabled. false otherwise. + * + * @return {boolean} is authentication enabled + */ + shouldAuthenticate() { + return this.basicAuth || this.gdbTokenAuth; + } } module.exports = ClientConfig; diff --git a/src/repository/base-repository-client.js b/src/repository/base-repository-client.js index 0f7885914..a0ce1c935 100644 --- a/src/repository/base-repository-client.js +++ b/src/repository/base-repository-client.js @@ -171,11 +171,10 @@ class BaseRepositoryClient { */ retryExecution(httpClients, requestBuilder, currentHttpClient) { const httpClient = currentHttpClient || httpClients.next(); - const username = this.repositoryClientConfig.getUsername(); - const pass = this.repositoryClientConfig.getPass(); return this.authenticationService - .login(username, pass) - .then(() => { + .login(this.repositoryClientConfig, this.user) + .then((user) => { + this.setLoggedUser(user); this.decorateRequestConfig(requestBuilder); return httpClient.request(requestBuilder).then((response) => { return new HttpResponse(response, httpClient); @@ -217,7 +216,8 @@ class BaseRepositoryClient { * @param {HttpRequestBuilder} requestBuilder */ decorateRequestConfig(requestBuilder) { - const token = this.authenticationService.getAuthentication(); + const token = this.authenticationService + .getAuthenticationToken(this.getLoggedUser()); if (token) { requestBuilder.addAuthorizationHeader(token); } @@ -281,6 +281,25 @@ class BaseRepositoryClient { + 'endpoint configuration! At least one endpoint must be provided.'); } } + + /** + * Logged user getter. + * @return {User} user + */ + getLoggedUser() { + return this.user; + } + + /** + * User setter + * @param {User} user + * + * @return {BaseRepositoryClient} + */ + setLoggedUser(user) { + this.user = user; + return this; + } } module.exports = BaseRepositoryClient; diff --git a/src/repository/repository-client-config.js b/src/repository/repository-client-config.js index aec43296f..d84ff12bd 100644 --- a/src/repository/repository-client-config.js +++ b/src/repository/repository-client-config.js @@ -1,4 +1,7 @@ const ClientConfig = require('../http/client-config'); +const RDFMimeType = require('../http/rdf-mime-type'); + +const defaultTimeout = 10000; /** * Configuration wrapper used for initialization of {@link BaseRepositoryClient} @@ -8,33 +11,28 @@ const ClientConfig = require('../http/client-config'); * @extends ClientConfig * @author Mihail Radkov * @author Svilen Velikov + * @author Teodossi Dossev */ class RepositoryClientConfig extends ClientConfig { /** - * @param {string[]} [endpoints] is an array with repository endpoints - * @param {Map} [headers] is a key:value mapping of http - * headers and values - * @param {string} [defaultRDFMimeType] one of {@link RDFMimeType} values - * @param {number} [readTimeout] - * @param {number} [writeTimeout] - * @param {string} [username] username which should be authenticated - * @param {string} [pass] the password to be used - * @param {boolean} [keepAlive] if the logged in user should be - * reauthenticated after auth token expire. This config has meaning when the - * server is secured and username and passwords are provided. - * @param {boolean} [useBasicAuth] if use Basic Auth when authenticating + * Repository client configuration constructor. + * Initializes [endpoints]{@link RepositoryClientConfig#endpoints} and + * sets configuration default values to + * [defaultRDFMimeType]{@link RepositoryClientConfig#defaultRDFMimeType}, + * [readTimeout]{@link RepositoryClientConfig#readTimeout} and + * [writeTimeout]{@link RepositoryClientConfig#writeTimeout} + * * @param {string} endpoint server base URL that will be prepend * to all server requests */ - constructor(endpoints, headers, defaultRDFMimeType, readTimeout, - writeTimeout, username, pass, keepAlive, useBasicAuth, endpoint) { - super(headers, username, pass, keepAlive, useBasicAuth, endpoint); - this.endpoints = endpoints; - this.defaultRDFMimeType = defaultRDFMimeType; - this.readTimeout = readTimeout; - this.writeTimeout = writeTimeout; - // TODO refactor to reduce constructor params - // related to https://github.com/Ontotext-AD/graphdb.js/issues/124 + constructor(endpoint) { + super(endpoint); + this.setEndpoints([]); + this.setHeaders({}); + this.setKeepAlive(true); + this.setDefaultRDFMimeType(RDFMimeType.SPARQL_RESULTS_JSON); + this.setReadTimeout(defaultTimeout); + this.setWriteTimeout(defaultTimeout); } /** diff --git a/src/security/authentication-factory.js b/src/security/authentication-factory.js new file mode 100644 index 000000000..15b401fde --- /dev/null +++ b/src/security/authentication-factory.js @@ -0,0 +1,28 @@ +const BasicAuthentication = require('./basic-authentication'); +const GdbTokenAuthentication = require('./gdb-token-authentication'); + +/** + * Factory to create concrete authentication type, based on + * client configuration. + * + * @class + * @author Teodossi Dossev + */ +export class AuthenticationFactory { + /** + * Concrete authentication type generator. + * @param {ClientConfig} clientConfig + * @return {BasicAuthentication | GdbTokenAuthentication} + */ + getAuthenticationType(clientConfig) { + if (clientConfig.getBasicAuthentication()) { + return new BasicAuthentication(clientConfig); + } else if (clientConfig.getGdbTokenAuthentication()) { + return new GdbTokenAuthentication(clientConfig); + } else { + throw Error('Authentication is not configured properly'); + } + } +} + +module.exports = AuthenticationFactory; diff --git a/src/security/authentication.js b/src/security/authentication.js new file mode 100644 index 000000000..c455e8e9c --- /dev/null +++ b/src/security/authentication.js @@ -0,0 +1,35 @@ +/** + * An abstract class that specifies common methods for different types + * of authentication. Concrete authentication types must extend + * this class and override it's methods + * + * @abstract + * @class + * @author Teodossi Dossev + */ +export class Authentication { + /** + * Constructor. + * @param {ClientConfig} clientConfig + */ + constructor(clientConfig) { + this.clientConfig = clientConfig; + } + /** + * Returns authentication type related {@link HttpRequestBuilder} + * login request builder + */ + getLoginRequestBuilder() { + throw new Error('Method #getLoginRequestBuilder() must be implemented!'); + } + + /** + * Returns authentication type related {string} + * token from response + */ + getResponseAuthToken() { + throw new Error('Method #getResponseAuthToken() must be implemented!'); + } +} + +module.exports = Authentication; diff --git a/src/security/basic-authentication.js b/src/security/basic-authentication.js new file mode 100644 index 000000000..bf3f9d967 --- /dev/null +++ b/src/security/basic-authentication.js @@ -0,0 +1,34 @@ +const Authentication = require('./authentication'); +const HttpRequestBuilder = require('../http/http-request-builder'); + +/** + * Basic authentication type class. + * Used for basic authentication against secured gdb server. + * + * @class + * @author Teodossi Dossev + */ +export class BasicAuthentication extends Authentication { + /** + * @override + * @return {HttpRequestBuilder} requestBuilder + */ + getLoginRequestBuilder() { + const username = this.clientConfig.getUsername(); + const pass = this.clientConfig.getPass(); + const credentials = `${username}:${pass}`; + + return HttpRequestBuilder.httpGet(`/rest/security/authenticatedUser`) + .addAuthorizationHeader(`Basic ${btoa(credentials)}`); + } + + /** + * @override + * @return {string} token + */ + getResponseAuthToken(response) { + return response.config.headers['authorization']; + } +} + +module.exports = BasicAuthentication; diff --git a/src/security/gdb-token-authentication.js b/src/security/gdb-token-authentication.js new file mode 100644 index 000000000..8eb9f8348 --- /dev/null +++ b/src/security/gdb-token-authentication.js @@ -0,0 +1,33 @@ +const Authentication = require('./authentication'); +const HttpRequestBuilder = require('../http/http-request-builder'); + +/** + * Gdb token authentication type class. + * Used for gdb token authentication against secured gdb server. + * + * @class + * @author Teodossi Dossev + */ +export class GdbTokenAuthentication extends Authentication { + /** + * @override + * @return {HttpRequestBuilder} requestBuilder + */ + getLoginRequestBuilder() { + const username = this.clientConfig.getUsername(); + const pass = this.clientConfig.getPass(); + + return HttpRequestBuilder.httpPost(`/rest/login/${username}`) + .addGraphDBPasswordHeader(pass); + } + + /** + * @override + * @return {string} token + */ + getResponseAuthToken(response) { + return response.headers['authorization']; + } +} + +module.exports = GdbTokenAuthentication; diff --git a/src/server/server-client-config.js b/src/server/server-client-config.js index ccc47c5ef..14778fb15 100644 --- a/src/server/server-client-config.js +++ b/src/server/server-client-config.js @@ -1,5 +1,7 @@ const ClientConfig = require('../http/client-config'); +const defaultTimeout = 10000; + /** * Configuration wrapper used for initialization of {@link ServerClient} * instances. @@ -8,32 +10,29 @@ const ClientConfig = require('../http/client-config'); * @extends ClientConfig * @author Mihail Radkov * @author Svilen Velikov + * @author Teodossi Dossev */ class ServerClientConfig extends ClientConfig { /** + * Server client configuration constructor. + * Sets configuration default value to + * [timeout]{@link ServerClientConfig#timeout} + * and [keepAlive]{@link ServerClientConfig#keepAlive} + * * @param {string} [endpoint] Endpoint url. - * @param {number} [timeout] Specifies the number of milliseconds before the - * request times out. - * @param {Map} [headers] An http headers map. - * @param {string} [username] username which should be authenticated - * @param {string} [pass] the password to be used - * @param {boolean} [keepAlive=true] if the logged in user should be - * reauthenticated after auth token expire. This config has meaning when the - * server is secured and username and passwords are provided. - * @param {boolean} [useBasicAuth] if use Basic Auth when authenticating */ - constructor(endpoint, timeout, headers, username, pass, - keepAlive, useBasicAuth) { - super(headers, username, pass, keepAlive, useBasicAuth, endpoint); - this.timeout = timeout; - // TODO refactor to reduce constructor params - // related to https://github.com/Ontotext-AD/graphdb.js/issues/124 + constructor(endpoint) { + super(endpoint); + this.setHeaders({}); + this.setKeepAlive(true); + this.setTimeout(defaultTimeout); } /** * Sets the timeout for HTTP requests. * - * @param {number} timeout the timeout in milliseconds + * @param {number} timeout the timeout in milliseconds before the + * request times out. * @return {this} the concrete configuration config for method chaining */ setTimeout(timeout) { diff --git a/src/server/server-client.js b/src/server/server-client.js index 6cefde6da..b857a0060 100644 --- a/src/server/server-client.js +++ b/src/server/server-client.js @@ -150,10 +150,9 @@ class ServerClient { */ execute(requestBuilder) { const startTime = Date.now(); - const username = this.config.getUsername(); - const pass = this.config.getPass(); - return this.authenticationService.login(username, pass) + return this.authenticationService.login(this.config, this.getLoggedUser()) .then((user) => { + this.setLoggedUser(user); this.decorateRequestConfig(requestBuilder); return this.httpClient.request(requestBuilder); }) @@ -189,7 +188,7 @@ class ServerClient { * @return {Promise} returns a promise which resolves with undefined. */ logout() { - return this.authenticationService.logout(); + return this.authenticationService.logout(this.getLoggedUser()); } /** @@ -199,11 +198,31 @@ class ServerClient { * @param {HttpRequestBuilder} requestBuilder */ decorateRequestConfig(requestBuilder) { - const token = this.authenticationService.getAuthentication(); + const token = this.authenticationService + .getAuthenticationToken(this.getLoggedUser()); if (token) { requestBuilder.addAuthorizationHeader(token); } } + + /** + * Logged user getter. + * @return {User} user + */ + getLoggedUser() { + return this.user; + } + + /** + * User setter + * @param {User} user + * + * @return {ServerClient} + */ + setLoggedUser(user) { + this.user = user; + return this; + } } module.exports = ServerClient; diff --git a/src/service/authentication-service.js b/src/service/authentication-service.js index dfcc3c7aa..1de5d1dc0 100644 --- a/src/service/authentication-service.js +++ b/src/service/authentication-service.js @@ -1,11 +1,12 @@ -const HttpRequestBuilder = require('../http/http-request-builder'); const User = require('../auth/user'); +const AuthenticationFactory = require('../security/authentication-factory'); /** * Service dealing with user authentication in a secured server. * * @author Mihail Radkov * @author Svilen Velikov + * @author Teodossi Dossev */ class AuthenticationService { /** @@ -15,6 +16,7 @@ class AuthenticationService { */ constructor(httpClient) { this.httpClient = httpClient; + this.authenticationFactory = new AuthenticationFactory(); } /** @@ -22,25 +24,24 @@ class AuthenticationService { * password. Upon successful authentication a {@link User} instance is created * with the user data and the auth token and returned to the client. * - * @param {string} username is the username of the logged in user - * @param {string} pass is the password of the logged in user + * @param {ClientConfig} clientConfig concrete client configuration + * @param {User} user logged in user * * @return {Promise} a promise resolving to an authenticated * {@link User} instance. */ - login(username, pass) { - if (!this.shouldAuthenticate(username, pass)) { - return Promise.resolve(); + login(clientConfig, user) { + if (!clientConfig.shouldAuthenticate() || + !this.isAlreadyAuthenticated(clientConfig, user)) { + return Promise.resolve(user); } - const requestBuilder = - HttpRequestBuilder.httpPost(`/rest/login/${username}`) - .addGraphDBPasswordHeader(pass); - return this.httpClient.request(requestBuilder).then((response) => { - const token = response.headers['authorization']; - const user = new User(token, pass, response.data); - this.setLoggedUser(user); - return user; - }); + + const authentication = this.getAuthentication(clientConfig); + return this.httpClient.request(this.getLoginRequest(clientConfig)) + .then((response) => { + const token = authentication.getResponseAuthToken(response); + return new User(token, clientConfig.getPass(), response.data); + }); } /** @@ -48,10 +49,12 @@ class AuthenticationService { * the client user. Every consecutive call against secured server will result * in Unauthorized error with status code 401. * + * @param {User} user logged in user + * * @return {Promise} returns a promise which resolves with undefined. */ - logout() { - this.getLoggedUser() && this.getLoggedUser().clearToken(); + logout(user) { + user.clearToken(); return Promise.resolve(); } @@ -60,10 +63,11 @@ class AuthenticationService { * request header Authorization: token. If there is no logged in * user, then this method returns undefined. * - * @return {string|undefined} + * @param {User} user logged in user + * @return {string|undefined} authentication token */ - getAuthentication() { - return this.getLoggedUser() && this.getLoggedUser().getToken(); + getAuthenticationToken(user) { + return user && user.getToken(); } /** @@ -71,40 +75,36 @@ class AuthenticationService { * yet. If that's the case, authentication should be made. * * @private - * - * @param {string} username is the username of the logged in user - * @param {string} pass is the password of the logged in user + * @param {ClientConfig} clientConfig concrete client config + * @param {User} user logged in user * * @return {boolean} true if authentication should be made */ - shouldAuthenticate(username, pass) { - const hasCredentials = username && pass; - const isAuthenticated = this.getLoggedUser() - && this.getLoggedUser().getToken(); + isAlreadyAuthenticated(clientConfig, user) { + const hasCredentials = clientConfig.getUsername() && clientConfig.getPass(); + const isAuthenticated = user && user.getToken(); return hasCredentials && !isAuthenticated; } /** - * @param {User} user - */ - setLoggedUser(user) { - this.loggedUser = user; - } - - /** - * @return {User} + * Returns authentication type related {@link HttpRequestBuilder} + * login request builder + * + * @param {ClientConfig} clientConfig concrete client configuration + * @return {HttpRequestBuilder} request builder */ - getLoggedUser() { - return this.loggedUser; + getLoginRequest(clientConfig) { + return this.getAuthentication(clientConfig).getLoginRequestBuilder(); } /** - * @param {HttpClient} httpClient - * @return {AuthenticationService} + * Authentication type getter + * @param {ClientConfig} clientConfig concrete client configuration + * @return {BasicAuthentication|GdbTokenAuthentication} concrete + * authentication type */ - setHttpClient(httpClient) { - this.httpClient = httpClient; - return this; + getAuthentication(clientConfig) { + return this.authenticationFactory.getAuthenticationType(clientConfig); } } diff --git a/src/service/transaction-service.js b/src/service/transaction-service.js index 4b69f7556..f1aeb5603 100644 --- a/src/service/transaction-service.js +++ b/src/service/transaction-service.js @@ -15,10 +15,11 @@ const TransactionalRepositoryClient = * * @author Mihail Radkov * @author Svilen Velikov + * @author Teodossi Dossev */ class TransactionService extends Service { /** - * Instantiates the transaction service wioth the supplied executor and + * Instantiates the transaction service with the supplied executor and * repository client config. * * @param {Function} httpRequestExecutor used to execute HTTP requests @@ -78,7 +79,7 @@ class TransactionService extends Service { */ getTransactionalClientConfig(locationUrl) { const config = this.repositoryClientConfig; - return new RepositoryClientConfig() + return new RepositoryClientConfig(config.getEndpoint()) .setEndpoints([locationUrl]) .setHeaders(config.getHeaders()) .setDefaultRDFMimeType(config.getDefaultRDFMimeType()) diff --git a/test-e2e/tests/auth-repository-client.spec.js b/test-e2e/tests/auth-repository-client.spec.js index f0c30ae17..74cb08a01 100644 --- a/test-e2e/tests/auth-repository-client.spec.js +++ b/test-e2e/tests/auth-repository-client.spec.js @@ -5,15 +5,11 @@ const Utils = require('utils'); const Config = require('config'); describe('Should test repository client auth', () => { - const authConfig = Config.restApiConfig; - authConfig.setUsername('admin'); - authConfig.setPass('root'); - authConfig.setEndpoint('http://localhost:7200'); - authConfig.setBasicAuthentication(true); + const authConfig = Config.restApiBasicAuthConfig; const rdfBasicAuthClient = new RDFRepositoryClient(authConfig); - authConfig.setBasicAuthentication(false); - const rdfTokenAuthClient = new RDFRepositoryClient(authConfig); + const authTokenConfig = Config.restApiTokenAuthConfig; + const rdfTokenAuthClient = new RDFRepositoryClient(authTokenConfig); beforeAll((done) => { diff --git a/test-e2e/tests/auth-server-client.spec.js b/test-e2e/tests/auth-server-client.spec.js index 18b1ddb42..93accaf96 100644 --- a/test-e2e/tests/auth-server-client.spec.js +++ b/test-e2e/tests/auth-server-client.spec.js @@ -6,9 +6,6 @@ const Config = require('config'); const NEW_REPO = 'New_repo'; describe('Should test server client auth', () => { - const config = new ServerClientConfig(Config.serverAddress, 10000, - new Map(), 'admin', 'root', true, true); - beforeAll((done) => { Utils.toggleSecurity(true).then(() => { done(); @@ -26,12 +23,15 @@ describe('Should test server client auth', () => { }); test('Should add and delete repository with BASIC auth', (done) => { + const config = new ServerClientConfig(Config.serverAddress) + .useBasicAuthentication('admin', 'root'); const serverClient = new GraphDBServerClient(config); createRepository(serverClient, done); }); test('Should add and delete repository with TOKEN auth', (done) => { - config.setBasicAuthentication(false); + const config = new ServerClientConfig(Config.serverAddress) + .useGdbTokenAuthentication('admin', 'root'); const serverClient = new GraphDBServerClient(config); createRepository(serverClient, done); }); diff --git a/test-e2e/tests/config.js b/test-e2e/tests/config.js index c0e24ccf9..49f0f5b19 100644 --- a/test-e2e/tests/config.js +++ b/test-e2e/tests/config.js @@ -1,41 +1,44 @@ -const {RepositoryClientConfig} = require('graphdb').repository; +/* eslint-disable max-len */ const {RDFMimeType} = require('graphdb').http; const {ServerClientConfig} = require('graphdb').server; +const {RepositoryClientConfig} = require('graphdb').repository; // Variables used in tests const serverAddress = 'http://localhost:7200'; const testRepoPath = './tests/data/repositories/GDB_Free/repository1.ttl'; const testRepo2Path = './tests/data/repositories/GDB_Free/repository2.ttl'; -const restApiConfig = new RepositoryClientConfig( - - [`${serverAddress}/repositories/Test_repo`], { +const restApiConfig = new RepositoryClientConfig(serverAddress) + .setEndpoints([`${serverAddress}/repositories/Test_repo`]) + .setHeaders({ 'Accept': RDFMimeType.SPARQL_RESULTS_XML - }, - '', 10000, 10000); - -const restApiBasicAuthConfig = new RepositoryClientConfig( - [`${serverAddress}/repositories/Test_repo`], { - 'Accept': RDFMimeType.SPARQL_RESULTS_XML, - 'Authorization': 'Basic YWRtaW46cm9vdA==' - }, - '', 10000, 10000); - -const serverBasicAuthConfig = new ServerClientConfig( - serverAddress, - 10000, - { - 'Accept': RDFMimeType.SPARQL_RESULTS_JSON, - 'Authorization': 'Basic YWRtaW46cm9vdA==' }); -const serverConfig = new ServerClientConfig( - serverAddress, - 10000, - { +const restApiBasicAuthConfig = new RepositoryClientConfig(serverAddress) + .setEndpoints([`${serverAddress}/repositories/Test_repo`]) + .setHeaders({ + 'Accept': RDFMimeType.SPARQL_RESULTS_XML + }) + .useBasicAuthentication('admin', 'root'); + +const restApiTokenAuthConfig = new RepositoryClientConfig(serverAddress) + .setEndpoints([`${serverAddress}/repositories/Test_repo`]) + .setHeaders({ + 'Accept': RDFMimeType.SPARQL_RESULTS_XML + }) + .useGdbTokenAuthentication('admin', 'root'); + + +const serverBasicAuthConfig = new ServerClientConfig(serverAddress) + .setHeaders({ 'Accept': RDFMimeType.SPARQL_RESULTS_JSON - }); + }) + .useBasicAuthentication('admin', 'root'); +const serverConfig = new ServerClientConfig(serverAddress) + .setHeaders({ + 'Accept': RDFMimeType.SPARQL_RESULTS_JSON + }); module.exports = {restApiConfig, serverAddress, testRepoPath, testRepo2Path, - restApiBasicAuthConfig, serverBasicAuthConfig, serverConfig}; + restApiBasicAuthConfig, restApiTokenAuthConfig, serverBasicAuthConfig, serverConfig}; diff --git a/test-e2e/tests/download.spec.js b/test-e2e/tests/download.spec.js index 65de705b1..ca3e2a651 100644 --- a/test-e2e/tests/download.spec.js +++ b/test-e2e/tests/download.spec.js @@ -1,11 +1,11 @@ -const {RDFRepositoryClient, GetStatementsPayload, AddStatementPayload} = require('graphdb').repository; +const {RDFRepositoryClient, + GetStatementsPayload, AddStatementPayload} = require('graphdb').repository; const {RDFMimeType} = require('graphdb').http; const Utils = require('utils'); const Config = require('config'); describe('Should test download method', () => { - - let rdfClient = new RDFRepositoryClient(Config.restApiConfig); + const rdfClient = new RDFRepositoryClient(Config.restApiConfig); beforeAll(() => { return Utils.createRepo(Config.testRepoPath); @@ -16,13 +16,13 @@ describe('Should test download method', () => { }); test('Should download data as stream', () => { - let addPayload = new AddStatementPayload() + const addPayload = new AddStatementPayload() .setSubject('http://domain/resource/resource-1') .setPredicate('http://domain/property/relation-1') .setObject('Title') .setLanguage('en'); - let payload = new GetStatementsPayload() + const payload = new GetStatementsPayload() .setResponseType(RDFMimeType.TURTLE) .setSubject('') .setPredicate(''); diff --git a/test-e2e/tests/graphdb-server-client.spec.js b/test-e2e/tests/graphdb-server-client.spec.js index 317b1f9b9..c46c52ef4 100644 --- a/test-e2e/tests/graphdb-server-client.spec.js +++ b/test-e2e/tests/graphdb-server-client.spec.js @@ -1,10 +1,10 @@ -const {RDFRepositoryClient, RepositoryType, - RepositoryConfig} = require('graphdb').repository; +const {RDFRepositoryClient, + RepositoryType, RepositoryConfig} = require('graphdb').repository; const {RDFMimeType} = require('graphdb').http; const { - GraphDBServerClient, ServerClientConfig, - AppSettings -} = require('graphdb').server; + GraphDBServerClient, + AppSettings, + ServerClientConfig} = require('graphdb').server; const path = require('path'); const Utils = require('utils'); const Config = require('config'); @@ -14,8 +14,8 @@ const NEW_REPO = 'New_repo'; describe('Should test graphDB server client', () => { const rdfClient = new RDFRepositoryClient(Config.restApiConfig); - const serverConfig = new ServerClientConfig(Config.serverAddress, 10000, - new Map(), 'admin', 'root', true, true); + const serverConfig = new ServerClientConfig(Config.serverAddress) + .useGdbTokenAuthentication('admin', 'root'); const serverClient = new GraphDBServerClient(serverConfig); beforeAll((done) => { @@ -26,6 +26,8 @@ describe('Should test graphDB server client', () => { return Utils.toggleSecurity(true); }).then(() => { done(); + }).catch((e) => { + throw new Error(e); }); }); @@ -35,30 +37,42 @@ describe('Should test graphDB server client', () => { return Utils.deleteRepo(TEST_REPO); }).then(() => { done(); + }).catch((e) => { + throw new Error(e); }); }); - test('Should get repo type default config', () => { + afterEach(() => { + serverClient.logout(serverConfig); + }); + + test('Should get repo type default config', (done) => { const expectedResponse = Utils.loadFile('./data/graphdb-server-client/' + 'expected_response_default_config_free_repo.txt'); return serverClient.getDefaultConfig(RepositoryType.FREE) .then((response) => { expect(response.response.data) .toStrictEqual(JSON.parse(expectedResponse)); + done(); + }).catch((e) => { + throw new Error(e); }); }); - test('Should get repo config', () => { + test('Should get repo config', (done) => { const expectedResponse = Utils.loadFile('./data/graphdb-server-client/' + 'expected_response_repo_config.txt'); return serverClient.getRepositoryConfig(TEST_REPO) .then((response) => { expect(response.response.data) .toStrictEqual(JSON.parse(expectedResponse)); + done(); + }).catch((e) => { + throw new Error(e); }); }); - test('Should get repo config as turtle', () => { + test('Should get repo config as turtle', (done) => { let expected; const sampleRdf = path.resolve(__dirname, './data/graphdb-server-client/' + 'expected_response_repo_config_turtle.txt'); @@ -68,11 +82,12 @@ describe('Should test graphDB server client', () => { .then((stream) => { stream.on('data', (data) => { expect(data).toEqual(expected); + done(); }); }); }); - test('Should create and delete repo', () => { + test('Should create and delete repo', (done) => { const config = new RepositoryConfig(NEW_REPO, '', new Map(), '', 'Repo title', RepositoryType.FREE); @@ -94,10 +109,13 @@ describe('Should test graphDB server client', () => { }).then((response) => { const expected = [TEST_REPO]; expect(response).toEqual(expected); + done(); + }).catch((e) => { + throw new Error(e); }); }); - test('Should check and toggle security repo', () => { + test('Should check and toggle security repo', (done) => { return serverClient.isSecurityEnabled() .then((response) => { return expect(response.response.data).toBe(true); @@ -112,11 +130,14 @@ describe('Should test graphDB server client', () => { }).then(() => { return serverClient.isSecurityEnabled(); }).then((response) => { - return expect(response.response.data).toBe(true); + expect(response.response.data).toBe(true); + done(); + }).catch((e) => { + throw new Error(e); }); }); - test('Should update free access', () => { + test('Should update free access', (done) => { const authorities = [ 'WRITE_REPO_Test_repo', 'READ_REPO_Test_repo' @@ -142,11 +163,14 @@ describe('Should test graphDB server client', () => { }).then(() => { return serverClient.getFreeAccess(); }).then((response) => { - return expect(response.response.data.enabled).toStrictEqual(false); + expect(response.response.data.enabled).toStrictEqual(false); + done(); + }).catch((e) => { + throw new Error(e); }); }); - test('Should create, read, update and delete users', () => { + test('Should create, read, update and delete users', (done) => { const expextedAppSettings = new AppSettings(true, true, true, false); const newAppSettings = new AppSettings(false, false, false, true); @@ -175,7 +199,8 @@ describe('Should test graphDB server client', () => { }).then(() => { return serverClient.deleteUser('test_user'); }).then((response) => { - return expect(response.response.status).toBe(204); + expect(response.response.status).toBe(204); + done(); }).catch((e) => { serverClient.deleteUser('test_user'); throw new Error(e); diff --git a/test-e2e/tests/namespaces.spec.js b/test-e2e/tests/namespaces.spec.js index 8c28eedf7..85eb449bf 100644 --- a/test-e2e/tests/namespaces.spec.js +++ b/test-e2e/tests/namespaces.spec.js @@ -46,21 +46,24 @@ describe('Should test namespaces in secured environment', () => { new RDFRepositoryClient(Config.restApiBasicAuthConfig); beforeAll((done) => { - Utils.createRepo(Config.testRepoPath).then(() => { - const wineRdf = path.resolve(__dirname, './data/wine.rdf'); - return rdfSecuredClient - .addFile(wineRdf, RDFMimeType.RDF_XML, null, null); - }).then(() => { - return Utils.toggleSecurity(true); - }).then(() => { - done(); - }); + Utils.createRepo(Config.testRepoPath) + .then(() => { + return Utils.toggleSecurity(true); + }).then(() => { + const wineRdf = path.resolve(__dirname, './data/wine.rdf'); + return rdfSecuredClient + .addFile(wineRdf, RDFMimeType.RDF_XML, null, null); + }).then(() => { + return done(); + }).catch((e) => { + throw new Error(e); + }); }); - afterAll(() => { + afterAll((done) => { return Utils.toggleSecurity(false).then(() => { return Utils.deleteRepo('Test_repo'); - }); + }).then(()=> done()); }); test('Should list namespaces', () => { diff --git a/test-e2e/tests/repositories.spec.js b/test-e2e/tests/repositories.spec.js index 8dd96f348..d83a496bd 100644 --- a/test-e2e/tests/repositories.spec.js +++ b/test-e2e/tests/repositories.spec.js @@ -1,10 +1,10 @@ +/* eslint-disable max-len */ +const {ServerClientConfig, ServerClient} = require('graphdb').server; const {RepositoryClientConfig} = require('graphdb').repository; -const {ServerClient, ServerClientConfig} = require('graphdb').server; const Utils = require('utils'); const Config = require('config'); describe('Should test repositories', () => { - beforeAll(() => { return Utils.createRepo(Config.testRepoPath).then(() => { return Utils.createRepo(Config.testRepo2Path); @@ -16,12 +16,15 @@ describe('Should test repositories', () => { }); test('Should verify repositories', () => { - let config = new ServerClientConfig(Config.serverAddress, 10000, {}); - let client = new ServerClient(config); - let repositoryClientConfig = new RepositoryClientConfig([`${Config.serverAddress}/repositories/`], {}, '', 3001, 3001); + const config = new ServerClientConfig(Config.serverAddress); + const client = new ServerClient(config); + const repositoryClientConfig = new RepositoryClientConfig(Config.serverAddress) + .setEndpoints([`${Config.serverAddress}/repositories/`]) + .setReadTimeout(3001) + .setWriteTimeout(3001); return client.getRepositoryIDs().then((response) => { - let expected = ['Test_repo', 'Test_repo_2']; + const expected = ['Test_repo', 'Test_repo_2']; expect(response.sort()).toEqual(expected); return client.hasRepository('Test_repo'); }).then((response) => { @@ -37,7 +40,7 @@ describe('Should test repositories', () => { expect(response.repositoryClientConfig.readTimeout).toBe(3001); expect(response.repositoryClientConfig.writeTimeout).toBe(3001); expect(response.repositoryClientConfig.headers).toStrictEqual({}); - expect(response.repositoryClientConfig.defaultRDFMimeType).toBe(''); + expect(response.repositoryClientConfig.defaultRDFMimeType).toBe('application/sparql-results+json'); }); }); }); diff --git a/test-e2e/tests/transactions.spec.js b/test-e2e/tests/transactions.spec.js index e2a916b59..55207cbbd 100644 --- a/test-e2e/tests/transactions.spec.js +++ b/test-e2e/tests/transactions.spec.js @@ -1,16 +1,17 @@ const path = require('path'); const Utils = require('utils'); -const {RDFRepositoryClient, GetStatementsPayload, AddStatementPayload} = require('graphdb').repository; +const {RDFRepositoryClient, + GetStatementsPayload, AddStatementPayload} = require('graphdb').repository; const {RDFMimeType, QueryContentType} = require('graphdb').http; const N3 = require('n3'); const {DataFactory} = N3; const {namedNode, literal, quad} = DataFactory; const Config = require('config'); -const {GetQueryPayload, QueryType, QueryLanguage, UpdateQueryPayload} = require('graphdb').query; +const {GetQueryPayload, + QueryType, QueryLanguage, UpdateQueryPayload} = require('graphdb').query; const {XSD} = require('graphdb').model.Types; describe('Should test transactions', () => { - beforeAll(() => { return Utils.createRepo(Config.testRepoPath); }); @@ -19,37 +20,39 @@ describe('Should test transactions', () => { return Utils.deleteRepo('Test_repo'); }); - let rdfClient = new RDFRepositoryClient(Config.restApiConfig); + const rdfClient = new RDFRepositoryClient(Config.restApiConfig); test('Should begin a transaction and check size', () => { - let wineRdf = path.resolve(__dirname, './data/wine.rdf'); + const wineRdf = path.resolve(__dirname, './data/wine.rdf'); let transactionalClient; - return rdfClient.addFile(wineRdf, RDFMimeType.RDF_XML, null, null).then(() => { - return rdfClient.beginTransaction(); - }).then(transaction => { - transactionalClient = transaction; - return transactionalClient.getSize(); - }).then((resp) => { - expect(resp).toBe(1839); - }).then(() => { - expect(transactionalClient.isActive()).toBe(true); - return transactionalClient.commit(); - }).then(() => { - expect(transactionalClient.isActive()).toBe(false); - }).then(() => { - return rdfClient.deleteAllStatements(); - }).then(() => { - return rdfClient.deleteNamespaces(); - }); + return rdfClient.addFile(wineRdf, RDFMimeType.RDF_XML, null, null) + .then(() => { + return rdfClient.beginTransaction(); + }).then((transaction) => { + transactionalClient = transaction; + return transactionalClient.getSize(); + }).then((resp) => { + expect(resp).toBe(1839); + }).then(() => { + expect(transactionalClient.isActive()).toBe(true); + return transactionalClient.commit(); + }).then(() => { + expect(transactionalClient.isActive()).toBe(false); + }).then(() => { + return rdfClient.deleteAllStatements(); + }).then(() => { + return rdfClient.deleteNamespaces(); + }); }); test('Should begin a transaction add file and commit it', () => { let transactionalClient; - let rowsRdf = path.resolve(__dirname, './data/rows.rdf'); + const rowsRdf = path.resolve(__dirname, './data/rows.rdf'); - return rdfClient.beginTransaction().then(transaction => { + return rdfClient.beginTransaction().then((transaction) => { transactionalClient = transaction; - return transactionalClient.addFile(rowsRdf, RDFMimeType.RDF_XML, null, null); + return transactionalClient + .addFile(rowsRdf, RDFMimeType.RDF_XML, null, null); }).then(() => { return rdfClient.getSize(); }).then((resp) => { @@ -69,11 +72,12 @@ describe('Should test transactions', () => { test('Should begin a transaction add file and rollback it', () => { let transactionalClient; - let rowsRdf = path.resolve(__dirname, './data/rows.rdf'); + const rowsRdf = path.resolve(__dirname, './data/rows.rdf'); - return rdfClient.beginTransaction().then(transaction => { + return rdfClient.beginTransaction().then((transaction) => { transactionalClient = transaction; - return transactionalClient.addFile(rowsRdf, RDFMimeType.RDF_XML, null, null); + return transactionalClient + .addFile(rowsRdf, RDFMimeType.RDF_XML, null, null); }).then(() => { return transactionalClient.rollback(); }).then(() => { @@ -85,19 +89,20 @@ describe('Should test transactions', () => { test('Should upload data in transaction, commit it and delete it', () => { let transactionalClient; - let params = new GetStatementsPayload() + const params = new GetStatementsPayload() .setResponseType(RDFMimeType.RDF_JSON) .setSubject('') .setPredicate('') .setContext(''); - let sampleRdf = path.resolve(__dirname, './data/sample-turtle.ttl'); - let turtleStream = Utils.getReadStream(sampleRdf); - let context = ''; + const sampleRdf = path.resolve(__dirname, './data/sample-turtle.ttl'); + const turtleStream = Utils.getReadStream(sampleRdf); + const context = ''; return rdfClient.beginTransaction().then((transaction) => { transactionalClient = transaction; - return transactionalClient.upload(turtleStream, RDFMimeType.TURTLE, context, null); + return transactionalClient + .upload(turtleStream, RDFMimeType.TURTLE, context, null); }).then(() => { return rdfClient.get(params); }).then((resp) => { @@ -107,14 +112,14 @@ describe('Should test transactions', () => { return rdfClient.get(params); }).then((resp) => { expect(resp).toEqual({ - "http://learningsparql.com/ns/data/i0432": { - "http://learningsparql.com/ns/addressbook/firstName": [ + 'http://learningsparql.com/ns/data/i0432': { + 'http://learningsparql.com/ns/addressbook/firstName': [ { - "value": "Richard", - "type": "literal", - "datatype": "http://www.w3.org/2001/XMLSchema#string", - "graphs": [ - "http://domain/graph/data-graph-3" + 'value': 'Richard', + 'type': 'literal', + 'datatype': 'http://www.w3.org/2001/XMLSchema#string', + 'graphs': [ + 'http://domain/graph/data-graph-3' ] } ] @@ -123,7 +128,7 @@ describe('Should test transactions', () => { return rdfClient.beginTransaction(); }).then((transaction) => { transactionalClient = transaction; - return transactionalClient.deleteData(' "Richard" .') + return transactionalClient.deleteData(' "Richard" .'); }).then(() => { return transactionalClient.commit(); }).then(() => { @@ -137,18 +142,18 @@ describe('Should test transactions', () => { }); test('Should add and delete data', () => { - let addPayload = new AddStatementPayload() + const addPayload = new AddStatementPayload() .setSubject('http://domain/resource/resource-1') .setPredicate('http://domain/property/relation-1') .setObjectLiteral('Title', XSD.STRING, 'en'); - let getPayload = new GetStatementsPayload() + const getPayload = new GetStatementsPayload() .setResponseType(RDFMimeType.RDF_JSON) .setSubject('') .setPredicate(''); let transactionalClient; - return rdfClient.beginTransaction().then(transaction => { + return rdfClient.beginTransaction().then((transaction) => { transactionalClient = transaction; return transactionalClient.add(addPayload); }).then(() => { @@ -157,22 +162,22 @@ describe('Should test transactions', () => { return rdfClient.get(getPayload); }).then((resp) => { expect(resp).toEqual({ - "http://domain/resource/resource-1": { - "http://domain/property/relation-1": [ + 'http://domain/resource/resource-1': { + 'http://domain/property/relation-1': [ { - "value": "Title", - "type": "literal", - "lang": "en" + 'value': 'Title', + 'type': 'literal', + 'lang': 'en' } ] } - }) + }); }).then(() => { return rdfClient.beginTransaction(); }).then((transaction) => { transactionalClient = transaction; // Deletion works only with turtle/trig currently - let data = ' "Title"@en.'; + const data = ' "Title"@en.'; return transactionalClient.deleteData(data); }).then(() => { return transactionalClient.commit(); @@ -184,18 +189,18 @@ describe('Should test transactions', () => { }); test('Should get data in a transaction', () => { - let addPayload = new AddStatementPayload() + const addPayload = new AddStatementPayload() .setSubject('http://domain/resource/resource-1') .setPredicate('http://domain/property/relation-1') .setObjectLiteral('Title', XSD.STRING, 'en'); - let params = new GetStatementsPayload() + const params = new GetStatementsPayload() .setResponseType(RDFMimeType.RDF_JSON) .setSubject('') .setPredicate(''); let transactionalClient; - return rdfClient.beginTransaction().then(transaction => { + return rdfClient.beginTransaction().then((transaction) => { transactionalClient = transaction; return transactionalClient.add(addPayload); }).then(() => { @@ -207,12 +212,12 @@ describe('Should test transactions', () => { return transactionalClient.get(params); }).then((resp) => { expect(resp).toEqual({ - "http://domain/resource/resource-1": { - "http://domain/property/relation-1": [ + 'http://domain/resource/resource-1': { + 'http://domain/property/relation-1': [ { - "value": "Title", - "type": "literal", - "lang": "en" + 'value': 'Title', + 'type': 'literal', + 'lang': 'en' } ] } @@ -225,19 +230,21 @@ describe('Should test transactions', () => { test('Should add quads', () => { let transactionalClient; - let quads = [ + const quads = [ getQuad('resource-1', 'relation-1', 'uri-1'), getQuad('resource-1', 'relation-2', 'uri-2'), - getQuadLiteral('resource-1', 'boolean-property', 'true', namedNode('xsd:boolean')), + getQuadLiteral('resource-1', 'boolean-property', 'true', + namedNode('xsd:boolean')), getQuadLiteral('resource-1', 'title', 'Title', 'en'), getQuadLiteral('resource-1', 'title', 'Titel', 'de') ]; - let getResource1 = new GetStatementsPayload() + const getResource1 = new GetStatementsPayload() .setResponseType(RDFMimeType.RDF_JSON) .setSubject(''); - let expectedResponseResource1 = Utils.loadFile('./data/transactions/expected_response_resource1.json'); + const expectedResponseResource1 = Utils + .loadFile('./data/transactions/expected_response_resource1.json'); return rdfClient.beginTransaction().then((transaction) => { transactionalClient = transaction; @@ -252,14 +259,13 @@ describe('Should test transactions', () => { }); describe('Should test queries in transactions', () => { - beforeAll(() => { - let wineRdf = path.resolve(__dirname, './data/wine.rdf'); + const wineRdf = path.resolve(__dirname, './data/wine.rdf'); return rdfClient.addFile(wineRdf, RDFMimeType.RDF_XML, null, null); }); test('Should test SELECT query in transaction', () => { - let payloadWithInferenceTrue = new GetQueryPayload() + const payloadWithInferenceTrue = new GetQueryPayload() .setQuery('select * where { ?p ?o}') .setQueryType(QueryType.SELECT) .setContentType(QueryContentType.SPARQL_QUERY) @@ -275,7 +281,8 @@ describe('Should test transactions', () => { }).then((resp) => { return Utils.readStream(resp); }).then((stream) => { - let expectedResponse = Utils.loadFile('./data/queries/expected_results_payload_inference_true.json'); + const expectedResponse = Utils.loadFile( + './data/queries/expected_results_payload_inference_true.json'); expect(JSON.parse(stream)).toEqual(JSON.parse(expectedResponse)); return transactionalClient.commit(); }).then(() => { @@ -286,14 +293,16 @@ describe('Should test transactions', () => { }); test('Should test query rollback and commit in a transaction', () => { - let query = Utils.loadFile('./data/queries/insert_query.sparql'); - let expected = Utils.loadFile('./data/queries/expected_results_named_graph.json'); - let expectedEmptyGraph = Utils.loadFile('./data/queries/expected_results_named_graph_empty.json'); + const query = Utils.loadFile('./data/queries/insert_query.sparql'); + const expected = Utils + .loadFile('./data/queries/expected_results_named_graph.json'); + const expectedEmptyGraph = Utils + .loadFile('./data/queries/expected_results_named_graph_empty.json'); - let insertData = new UpdateQueryPayload() + const insertData = new UpdateQueryPayload() .setQuery(query); - let selectData = new GetQueryPayload() + const selectData = new GetQueryPayload() .setQuery('SELECT ?s ?p ?o FROM WHERE {?s ?p ?o}') .setQueryType(QueryType.SELECT) .setResponseType(RDFMimeType.SPARQL_RESULTS_JSON) @@ -330,13 +339,14 @@ describe('Should test transactions', () => { }); test('Should test downloading data in a transaction', () => { - let query = Utils.loadFile('./data/queries/insert_query.sparql'); - let expected = Utils.loadFile('./data/queries/expected_response_transaction_download.json'); + const query = Utils.loadFile('./data/queries/insert_query.sparql'); + const expected = Utils + .loadFile('./data/queries/expected_response_transaction_download.json'); - let insertData = new UpdateQueryPayload() + const insertData = new UpdateQueryPayload() .setQuery(query); - let payload = new GetStatementsPayload() + const payload = new GetStatementsPayload() .setResponseType(RDFMimeType.RDF_JSON) .setSubject('') .setPredicate(''); @@ -349,18 +359,18 @@ describe('Should test transactions', () => { }).then(() => { return transactionalClient.download(payload); }).then((stream) => { - return Utils.readStream(stream) + return Utils.readStream(stream); }).then((data) => { - expect(JSON.parse(data)).toEqual(JSON.parse(expected)) + expect(JSON.parse(data)).toEqual(JSON.parse(expected)); }).then(() => { return transactionalClient.rollback(); }).then(() => { - return rdfClient.beginTransaction() + return rdfClient.beginTransaction(); }).then((transaction) => { transactionalClient = transaction; return transactionalClient.download(payload); }).then((stream) => { - return Utils.readStream(stream) + return Utils.readStream(stream); }).then((data) => { expect(JSON.parse(data)).toEqual({}); return transactionalClient.commit(); @@ -371,14 +381,16 @@ describe('Should test transactions', () => { function getQuad(s, p, o, g) { if (g) { - return quad(namedNode(subj(s)), namedNode(pred(p)), namedNode(obj(o)), namedNode(context(g))); + return quad(namedNode(subj(s)), namedNode(pred(p)), + namedNode(obj(o)), namedNode(context(g))); } return quad(namedNode(subj(s)), namedNode(pred(p)), namedNode(obj(o))); } function getQuadLiteral(s, p, o, t, g) { if (g) { - return quad(namedNode(subj(s)), namedNode(pred(p)), literal(o, t), namedNode(context(g))); + return quad(namedNode(subj(s)), namedNode(pred(p)), + literal(o, t), namedNode(context(g))); } return quad(namedNode(subj(s)), namedNode(pred(p)), literal(o, t)); } diff --git a/test-e2e/tests/utils.js b/test-e2e/tests/utils.js index f15e3852c..b6f8131b8 100644 --- a/test-e2e/tests/utils.js +++ b/test-e2e/tests/utils.js @@ -41,31 +41,15 @@ function getReadStream(filePath) { } function createRepo(path) { - const data = new FormData(); - data.append("config", fs.createReadStream(path)); - - return axios({ - method: 'post', - url: `${Config.serverAddress}/rest/repositories?local=true`, - data: data, - timeout: 5000, - headers: data.getHeaders() - }); -} - - -function createSecuredRepo(path) { const data = new FormData(); data.append('config', fs.createReadStream(path)); - const headers = data.getHeaders(); - headers['Authorization'] = 'Basic YWRtaW46cm9vdA=='; return axios({ method: 'post', url: `${Config.serverAddress}/rest/repositories?local=true`, data: data, timeout: 5000, - headers + headers: data.getHeaders() }); } @@ -77,17 +61,19 @@ function deleteRepo(name) { } function toggleSecurity(enable) { - return axios({ - method: 'post', - headers: { 'Content-Type': 'application/json', 'Connection': 'keep-alive', 'Accept': '*/*'}, - url: `${Config.serverAddress}/rest/security?useSecurity=${enable}`, - data: `${enable}`, - timeout: 5000, - auth: { - username: 'admin', - password: 'root' - } - }); + return axios({ + method: 'post', + headers: { + 'Content-Type': 'application/json', + 'Connection': 'keep-alive', + 'Accept': '*/*', + 'Authorization': 'Basic YWRtaW46cm9vdA==' + }, + url: `${Config.serverAddress}/rest/security?useSecurity=${enable}`, + data: `${enable}`, + timeout: 5000 + }); } -module.exports = {loadFile, readStream, getReadStream, createRepo, deleteRepo, toggleSecurity, createSecuredRepo}; +module.exports = {loadFile, readStream, getReadStream, + createRepo, deleteRepo, toggleSecurity}; diff --git a/test/repository/base-repository-client-failover.spec.js b/test/repository/base-repository-client-failover.spec.js index a20d82f29..e83f7769e 100644 --- a/test/repository/base-repository-client-failover.spec.js +++ b/test/repository/base-repository-client-failover.spec.js @@ -7,14 +7,13 @@ const httpClientStub = require('../http/http-client.stub'); jest.mock('http/http-client'); describe('BaseRepositoryClient', () => { - let repoClientConfig; let repositoryClient; let requestBuilder; describe('Automatic failover - retrying with different repo endpoint', () => { beforeEach(() => { - repoClientConfig = new RepositoryClientConfig() + repoClientConfig = new RepositoryClientConfig('http://localhost:8083') .setEndpoints([ 'http://localhost:8081/repositories/test1', 'http://localhost:8082/repositories/test2', @@ -29,15 +28,16 @@ describe('BaseRepositoryClient', () => { requestBuilder = HttpRequestBuilder.httpGet('/service'); }); - test('should automatically switch to another repository endpoint if the status is allowed for retry', () => { - let httpClient1 = repositoryClient.httpClients[0]; + test('should automatically switch to another repository endpoint ' + + 'if the status is allowed for retry', () => { + const httpClient1 = repositoryClient.httpClients[0]; stubHttpClient(httpClient1, 503); - let httpClient2 = repositoryClient.httpClients[1]; + const httpClient2 = repositoryClient.httpClients[1]; stubHttpClient(httpClient2, 503); // The last retry on the last client should be successful - let httpClient3 = repositoryClient.httpClients[2]; + const httpClient3 = repositoryClient.httpClients[2]; stubHttpClient(httpClient3, 200); return repositoryClient.execute(requestBuilder).then(() => { @@ -47,14 +47,15 @@ describe('BaseRepositoryClient', () => { }); }); - test('should reject if all repository endpoint have unsuccessful responses', () => { - let httpClient1 = repositoryClient.httpClients[0]; + test('should reject if all repository endpoint have ' + + 'unsuccessful responses', () => { + const httpClient1 = repositoryClient.httpClients[0]; stubHttpClient(httpClient1, 503); - let httpClient2 = repositoryClient.httpClients[1]; + const httpClient2 = repositoryClient.httpClients[1]; stubHttpClient(httpClient2, 503); - let httpClient3 = repositoryClient.httpClients[2]; + const httpClient3 = repositoryClient.httpClients[2]; stubHttpClient(httpClient3, 503); return repositoryClient.execute(requestBuilder).catch(() => { @@ -64,15 +65,16 @@ describe('BaseRepositoryClient', () => { }); }); - test('should automatically switch to another repository endpoint if the previous is/are unreachable', () => { - let httpClient1 = repositoryClient.httpClients[0]; + test('should automatically switch to another repository endpoint ' + + 'if the previous is/are unreachable', () => { + const httpClient1 = repositoryClient.httpClients[0]; stubHttpClientWithoutResponse(httpClient1); - let httpClient2 = repositoryClient.httpClients[1]; + const httpClient2 = repositoryClient.httpClients[1]; stubHttpClientWithoutResponse(httpClient2); // Should manage to get response from the 3rd endpoint - let httpClient3 = repositoryClient.httpClients[2]; + const httpClient3 = repositoryClient.httpClients[2]; stubHttpClient(httpClient3, 200); return repositoryClient.execute(requestBuilder).then(() => { @@ -84,13 +86,13 @@ describe('BaseRepositoryClient', () => { test('should reject if all repository endpoints are unreachable', () => { // Stub with request but without response object - let httpClient1 = repositoryClient.httpClients[0]; + const httpClient1 = repositoryClient.httpClients[0]; stubHttpClientWithoutResponse(httpClient1); - let httpClient2 = repositoryClient.httpClients[1]; + const httpClient2 = repositoryClient.httpClients[1]; stubHttpClientWithoutResponse(httpClient2); - let httpClient3 = repositoryClient.httpClients[2]; + const httpClient3 = repositoryClient.httpClients[2]; stubHttpClientWithoutResponse(httpClient3); return repositoryClient.execute(requestBuilder).catch(() => { @@ -102,11 +104,12 @@ describe('BaseRepositoryClient', () => { test('should reject if the error is not from the HTTP request', () => { // - let httpClient1 = repositoryClient.httpClients[0]; - httpClient1.request.mockRejectedValue(new Error('Error before/after request')); + const httpClient1 = repositoryClient.httpClients[0]; + httpClient1.request + .mockRejectedValue(new Error('Error before/after request')); - let httpClient2 = repositoryClient.httpClients[1]; - let httpClient3 = repositoryClient.httpClients[2]; + const httpClient2 = repositoryClient.httpClients[1]; + const httpClient3 = repositoryClient.httpClients[2]; return repositoryClient.execute(requestBuilder).catch(() => { expect(httpClient1.request).toHaveBeenCalledTimes(1); @@ -117,11 +120,11 @@ describe('BaseRepositoryClient', () => { test('should reject if there is no provided error', () => { // No error/response - let httpClient1 = repositoryClient.httpClients[0]; + const httpClient1 = repositoryClient.httpClients[0]; httpClient1.request.mockRejectedValue(); - let httpClient2 = repositoryClient.httpClients[1]; - let httpClient3 = repositoryClient.httpClients[2]; + const httpClient2 = repositoryClient.httpClients[1]; + const httpClient3 = repositoryClient.httpClients[2]; return repositoryClient.execute(requestBuilder).catch(() => { expect(httpClient1.request).toHaveBeenCalledTimes(1); @@ -132,7 +135,7 @@ describe('BaseRepositoryClient', () => { it('should reject if it cannot properly execute requests', () => { const err = new Error('Cannot request'); - let httpClient1 = repositoryClient.httpClients[0]; + const httpClient1 = repositoryClient.httpClients[0]; httpClient1.request = () => { throw err; }; @@ -160,9 +163,7 @@ describe('BaseRepositoryClient', () => { request: {} }); } - }); - class TestRepositoryClient extends BaseRepositoryClient { } diff --git a/test/repository/get-statements-payload.spec.js b/test/repository/get-statements-payload.spec.js index c9ac88f33..53ebd8112 100644 --- a/test/repository/get-statements-payload.spec.js +++ b/test/repository/get-statements-payload.spec.js @@ -3,11 +3,12 @@ const RDFMimeType = require('http/rdf-mime-type'); describe('GetStatementsPayload', () => { test('should set responseType=application/rdf+json by default', () => { - expect(new GetStatementsPayload().get().responseType).toEqual('application/rdf+json'); + expect(new GetStatementsPayload().get().responseType) + .toEqual('application/rdf+json'); }); test('should populate properties in the underlying payload', () => { - let payload = new GetStatementsPayload() + const payload = new GetStatementsPayload() .setResponseType(RDFMimeType.RDF_XML) .setSubject('') .setPredicate('') diff --git a/test/repository/rdf-repository-client-adding-data.spec.js b/test/repository/rdf-repository-client-adding-data.spec.js index 372c0013b..e6c0fe2f4 100644 --- a/test/repository/rdf-repository-client-adding-data.spec.js +++ b/test/repository/rdf-repository-client-adding-data.spec.js @@ -19,13 +19,12 @@ jest.mock('http/http-client'); * Tests statements insertion via RDFRepositoryClient */ describe('RDFRepositoryClient - adding data', () => { - let repoClientConfig; let rdfRepositoryClient; beforeEach(() => { - repoClientConfig = new RepositoryClientConfig() - .addEndpoint('http://localhost:8080/repositories/test') + repoClientConfig = new RepositoryClientConfig('http://localhost:8080') + .setEndpoints(['http://localhost:8080/repositories/test']) .setReadTimeout(100) .setWriteTimeout(200); @@ -35,99 +34,127 @@ describe('RDFRepositoryClient - adding data', () => { }); describe('add(payload)', () => { - test('should properly convert triple payload to quad and send a request', () => { + test('should properly convert triple payload to quad and ' + + 'send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('relation-1')) .setObject(obj('uri-1')); - const expected = testUtils.loadFile('repository/data/add-statements-triple.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-triple.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert triple payload with blank nodes to quad and send a request', () => { + test('should properly convert triple payload with blank nodes ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject('_:1') .setPredicate(pred('relation-1')) .setObject('_:2'); - const expected = testUtils.loadFile('repository/data/add-statements-triple-bnodes.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-triple-bnodes.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert triple literal payload with language to quad and send a request', () => { + test('should properly convert triple literal payload with language ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('relation-1')) .setObject('Title') .setLanguage('en'); - const expected = testUtils.loadFile('repository/data/add-statements-literal-language.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-literal-language.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert triple literal payload with data type to quad and send a request', () => { + test('should properly convert triple literal payload with data type ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('property-boolean')) .setObject('true') .setDataType('xsd:boolean'); - const expected = testUtils.loadFile('repository/data/add-statements-literal-boolean.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-literal-boolean.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert string literal payload to quad and send a request', () => { + test('should properly convert string literal payload ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('property-string')) .setObjectLiteral('Some value'); - const expected = testUtils.loadFile('repository/data/add-statements-literal.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-literal.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert string literal with language payload to quad and send a request', () => { + test('should properly convert string literal with language payload ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('relation-1')) .setObjectLiteral('Title', XSD.STRING, 'en'); - const expected = testUtils.loadFile('repository/data/add-statements-literal-language.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-literal-language.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert integer literal payload to quad and send a request', () => { + test('should properly convert integer literal payload ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('property-int')) .setObjectLiteral(4); - const expected = testUtils.loadFile('repository/data/add-statements-literal-integer.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-literal-integer.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert float literal payload to quad and send a request', () => { + test('should properly convert float literal payload ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('property-float')) .setObjectLiteral(3.1415); - const expected = testUtils.loadFile('repository/data/add-statements-literal-decimal.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-literal-decimal.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert boolean literal payload to quad and send a request', () => { + test('should properly convert boolean literal payload ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('property-boolean')) .setObjectLiteral(true); - const expected = testUtils.loadFile('repository/data/add-statements-literal-boolean.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected)); + const expected = testUtils + .loadFile('repository/data/add-statements-literal-boolean.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected)); }); - test('should properly convert triple payload with single context to quad and send a request', () => { + test('should properly convert triple payload with single context ' + + 'to quad and send a request', () => { const payload = new AddStatementPayload() .setSubject(subj('resource-1')) .setPredicate(pred('relation-1')) @@ -135,11 +162,14 @@ describe('RDFRepositoryClient - adding data', () => { .setContext(context('data-graph-1')); const expectedGraph = encodedContext('data-graph-1'); - const expected = testUtils.loadFile('repository/data/add-statements-context.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected, expectedGraph)); + const expected = testUtils + .loadFile('repository/data/add-statements-context.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected, expectedGraph)); }); - test('should properly convert triple payload with multiple contexts to several quads and send a request', () => { + test('should properly convert triple payload with multiple contexts ' + + 'to several quads and send a request', () => { const graphs = [context('data-graph-1'), context('data-graph-2')]; const payload = new AddStatementPayload() .setSubject(subj('resource-1')) @@ -148,20 +178,26 @@ describe('RDFRepositoryClient - adding data', () => { .setLanguage('en') .setContext(graphs); - const expectedGraphs = [encodedContext('data-graph-1'), encodedContext('data-graph-2')]; - const expected = testUtils.loadFile('repository/data/add-statements-contexts.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected, expectedGraphs)); + const expectedGraphs = + [encodedContext('data-graph-1'), encodedContext('data-graph-2')]; + const expected = testUtils + .loadFile('repository/data/add-statements-contexts.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected, expectedGraphs)); }); - test('should allow to specify base URI for resolving of relative URIs', () => { + test('should allow to specify base URI for resolving ' + + 'of relative URIs', () => { const payload = new AddStatementPayload() .setBaseURI('http://base/uri') .setSubject(subj('resource-1')) .setPredicate(pred('relation-1')) .setObject(obj('uri-1')); - const expected = testUtils.loadFile('repository/data/add-statements-triple.txt').trim(); - return rdfRepositoryClient.add(payload).then(() => verifyAddPayload(expected, undefined, 'http://base/uri')) + const expected = testUtils + .loadFile('repository/data/add-statements-triple.txt').trim(); + return rdfRepositoryClient.add(payload) + .then(() => verifyAddPayload(expected, undefined, 'http://base/uri')); }); test('should resolve to empty response (HTTP 204)', () => { @@ -173,7 +209,8 @@ describe('RDFRepositoryClient - adding data', () => { }); test('should throw error when a payload is not provided', () => { - expect(() => rdfRepositoryClient.add()).toThrow(Error('Cannot add statement without payload')); + expect(() => rdfRepositoryClient.add()) + .toThrow(Error('Cannot add statement without payload')); }); test('should reject adding the payload if it is empty', () => { @@ -190,7 +227,8 @@ describe('RDFRepositoryClient - adding data', () => { verifyNoPayload(); }); - test('should reject adding the payload when the server request is unsuccessful', () => { + test('should reject adding the payload when the server request ' + + 'is unsuccessful', () => { rdfRepositoryClient.httpClients[0].request.mockRejectedValue({}); const payload = new AddStatementPayload() .setSubject(subj('resource-1')) @@ -210,17 +248,21 @@ describe('RDFRepositoryClient - adding data', () => { test('should convert the quads to turtle and send a request', () => { const quads = getQuadsDataSet(); - const expected = testUtils.loadFile('repository/data/add-statements-complex.txt').trim(); + const expected = testUtils + .loadFile('repository/data/add-statements-complex.txt').trim(); - return rdfRepositoryClient.addQuads(quads).then(() => verifyAddPayload(expected)); + return rdfRepositoryClient.addQuads(quads) + .then(() => verifyAddPayload(expected)); }); - test('should allow to specify base URI and context when adding quads', () => { + test('should allow to specify base URI and context ' + + 'when adding quads', () => { const quads = getQuadsDataSet(); const graph = context('data-graph-1'); const baseUri = 'http://base/uri'; - const expected = testUtils.loadFile('repository/data/add-statements-complex.txt').trim(); + const expected = testUtils + .loadFile('repository/data/add-statements-complex.txt').trim(); const expectedGraph = '<' + graph + '>'; return rdfRepositoryClient.addQuads(quads, graph, baseUri) .then(() => verifyAddPayload(expected, expectedGraph, baseUri)); @@ -231,28 +273,36 @@ describe('RDFRepositoryClient - adding data', () => { return expect(rdfRepositoryClient.addQuads(quads)).resolves.toEqual(); }); - test('should reject adding quads when the server request is unsuccessful', () => { - rdfRepositoryClient.httpClients[0].request.mockRejectedValue('error-adding'); + test('should reject adding quads when the server request ' + + 'is unsuccessful', () => { + rdfRepositoryClient.httpClients[0].request + .mockRejectedValue('error-adding'); const quads = [getQuad('resource-1', 'relation-1', 'uri-1')]; - return expect(rdfRepositoryClient.addQuads(quads)).rejects.toEqual('error-adding'); + return expect(rdfRepositoryClient.addQuads(quads)).rejects + .toEqual('error-adding'); }); }); describe('putQuads(quads)', () => { - test('should convert the quads to turtle and send an overwrite request', () => { + test('should convert the quads to turtle and send an ' + + 'overwrite request', () => { const quads = getQuadsDataSet(); - const expected = testUtils.loadFile('repository/data/add-statements-complex.txt').trim(); + const expected = testUtils + .loadFile('repository/data/add-statements-complex.txt').trim(); - return rdfRepositoryClient.putQuads(quads).then(() => verifyPutPayload(expected)); + return rdfRepositoryClient.putQuads(quads) + .then(() => verifyPutPayload(expected)); }); - test('should allow to specify base URI and context when putting quads', () => { + test('should allow to specify base URI and context when ' + + 'putting quads', () => { const quads = getQuadsDataSet(); const graph = context('data-graph-1'); const baseUri = 'http://base/uri'; - const expected = testUtils.loadFile('repository/data/add-statements-complex.txt').trim(); + const expected = testUtils + .loadFile('repository/data/add-statements-complex.txt').trim(); const expectedGraph = '<' + graph + '>'; return rdfRepositoryClient.putQuads(quads, graph, baseUri) .then(() => verifyPutPayload(expected, expectedGraph, baseUri)); @@ -263,10 +313,13 @@ describe('RDFRepositoryClient - adding data', () => { return expect(rdfRepositoryClient.putQuads(quads)).resolves.toEqual(); }); - test('should reject putting quads when the server request is unsuccessful', () => { - rdfRepositoryClient.httpClients[0].request.mockRejectedValue('error-overwriting'); + test('should reject putting quads when the server request ' + + 'is unsuccessful', () => { + rdfRepositoryClient.httpClients[0].request + .mockRejectedValue('error-overwriting'); const quads = [getQuad('resource-1', 'relation-1', 'uri-1')]; - return expect(rdfRepositoryClient.putQuads(quads)).rejects.toEqual('error-overwriting'); + return expect(rdfRepositoryClient.putQuads(quads)).rejects + .toEqual('error-overwriting'); }); }); @@ -304,7 +357,8 @@ describe('RDFRepositoryClient - adding data', () => { return [ getQuad('resource-1', 'relation-1', 'uri-1'), getQuad('resource-1', 'relation-2', 'uri-2'), - getQuadLiteral('resource-1', 'boolean-property', 'true', namedNode('xsd:boolean')), + getQuadLiteral('resource-1', 'boolean-property', 'true', + namedNode('xsd:boolean')), getQuadLiteral('resource-1', 'title', 'Title', 'en'), getQuadLiteral('resource-1', 'title', 'Titel', 'de'), @@ -313,7 +367,7 @@ describe('RDFRepositoryClient - adding data', () => { getQuadLiteral('resource-2', 'title', 'Title', 'en', 'data-graph-2'), getQuadLiteral('resource-2', 'title', 'Titel', 'de', 'data-graph-2'), - getQuad('resource-3', 'relation-1', 'uri-4', 'data-graph-1'), + getQuad('resource-3', 'relation-1', 'uri-4', 'data-graph-1') ]; } @@ -321,14 +375,16 @@ describe('RDFRepositoryClient - adding data', () => { function getQuad(s, p, o, g) { if (g) { - return quad(namedNode(subj(s)), namedNode(pred(p)), namedNode(obj(o)), namedNode(context(g))); + return quad(namedNode(subj(s)), namedNode(pred(p)), + namedNode(obj(o)), namedNode(context(g))); } return quad(namedNode(subj(s)), namedNode(pred(p)), namedNode(obj(o))); } function getQuadLiteral(s, p, o, t, g) { if (g) { - return quad(namedNode(subj(s)), namedNode(pred(p)), literal(o, t), namedNode(context(g))); + return quad(namedNode(subj(s)), namedNode(pred(p)), + literal(o, t), namedNode(context(g))); } return quad(namedNode(subj(s)), namedNode(pred(p)), literal(o, t)); } diff --git a/test/repository/rdf-repository-client-authentication-basic.spec.js b/test/repository/rdf-repository-client-authentication-basic.spec.js new file mode 100644 index 000000000..07fa74ee7 --- /dev/null +++ b/test/repository/rdf-repository-client-authentication-basic.spec.js @@ -0,0 +1,146 @@ +const HttpClient = require('http/http-client'); +const RDFRepositoryClient = require('repository/rdf-repository-client'); +const RepositoryClientConfig = require('repository/repository-client-config'); +const GetStatementsPayload = require('repository/get-statements-payload'); +const RDFMimeType = require('http/rdf-mime-type'); +const HttpRequestBuilder = require('http/http-request-builder'); + +const httpClientStub = require('../http/http-client.stub'); + +jest.mock('http/http-client'); + +import data from './data/read-statements'; +import userdata from '../auth/data/logged-user-data'; + +describe('RDFRepositoryClient - authentication', () => { + let config; + let repository; + let httpRequest; + let httpLoginRequest; + + beforeEach(() => { + HttpClient.mockImplementation(() => httpClientStub()); + + const endpoints = ['http://host/repositories/repo1']; + const headers = {}; + const contentType = ''; + const readTimeout = 1000; + const writeTimeout = 1000; + const endpoint = 'http://localhost:7200'; + + config = new RepositoryClientConfig(endpoint) + .setEndpoints(endpoints) + .setHeaders(headers) + .setDefaultRDFMimeType(contentType) + .setReadTimeout(readTimeout) + .setWriteTimeout(writeTimeout) + .useBasicAuthentication('testuser', 'pass123'); + repository = new RDFRepositoryClient(config); + httpRequest = repository.httpClient.request; + + httpRequest.mockResolvedValue({ + config: {headers: {}} + }); + + httpLoginRequest = repository.httpClients[0].request; + httpLoginRequest.mockResolvedValue({ + data: data.repositories.repo1.statements + .GET['single_application/rdf+xml'], + headers: {} + }); + }); + + afterAll(() => { + repository.disableAuthentication(); + }); + + const payload = new GetStatementsPayload() + .setSubject('') + .setPredicate('') + .setResponseType(RDFMimeType.RDF_XML); + const expectedResponse = '7931000'; + + test('should fetch and return single statement as plain string', () => { + return repository.get(payload).then((response) => { + // check the response + expect(response).toEqual(expectedResponse); + + // verify that exact requests have been made + const loginMock = repository.httpClient.request; + const requestMock = repository.httpClients[0].request; + + // expect 2 invocations: first login, second getRepositoryIDs + expect(loginMock).toHaveBeenCalledTimes(1); + expect(requestMock).toHaveBeenCalledTimes(1); + + // first request was a login with expected parameters + const expectedLoginRequest = HttpRequestBuilder + .httpGet('/rest/security/authenticatedUser') + .addAuthorizationHeader('Basic dGVzdHVzZXI6cGFzczEyMw=='); + expect(loginMock).toHaveBeenNthCalledWith(1, expectedLoginRequest); + + // second request was the API call with expected parameters + const expectedAPIRequest = HttpRequestBuilder.httpGet('/statements') + .setParams({ + subj: '', + pred: '' + }) + .addAcceptHeader(payload.getResponseType()); + expect(requestMock).toHaveBeenNthCalledWith(1, expectedAPIRequest); + }); + }); + + test('should try relogin after token gets expired', () => { + mockClient(); + + return repository.get(payload).then(() => { + return repository.get(payload); + }).then(() => { + // verify that exact requests have been made + const loginMock = repository.httpClient.request; + const requestMock = repository.httpClients[0].request; + + // expect 2 invocations:ClientConfigBuilder + // first login + // second getRepositoryIDs + // expecting 5 invocations: + // login + // first API call + // second API call which fails with 401 unauthorized + // re-login + // third API call + expect(loginMock).toHaveBeenCalledTimes(3); + expect(requestMock).toHaveBeenCalledTimes(3); + }); + + function mockClient() { + let calls = 0; + + repository.httpClients[0].request = + jest.fn().mockImplementation((request) => { + if (request.getMethod() === 'get') { + calls++; + if (repository.getLoggedUser() + && calls === 2) { + // emulate token expiration + repository.getLoggedUser().clearToken(); + return Promise.reject({ + response: { + status: 401 + } + }); + } + return Promise.resolve({data: data.repositories.GET}); + } else if (request.getMethod() === 'post') { + return Promise.resolve({ + headers: { + authorization: 'token123' + }, + data: userdata + }); + } + return Promise.reject(); + }); + } + }); +}); diff --git a/test/repository/rdf-repository-client-authentication.spec.js b/test/repository/rdf-repository-client-authentication-token.spec.js similarity index 92% rename from test/repository/rdf-repository-client-authentication.spec.js rename to test/repository/rdf-repository-client-authentication-token.spec.js index 74741fa00..07c8ed818 100644 --- a/test/repository/rdf-repository-client-authentication.spec.js +++ b/test/repository/rdf-repository-client-authentication-token.spec.js @@ -28,15 +28,13 @@ describe('RDFRepositoryClient - authentication', () => { const writeTimeout = 1000; const endpoint = 'http://localhost:7200'; - config = new RepositoryClientConfig() + config = new RepositoryClientConfig(endpoint) .setEndpoints(endpoints) .setHeaders(headers) .setDefaultRDFMimeType(contentType) .setReadTimeout(readTimeout) .setWriteTimeout(writeTimeout) - .setUsername('testuser') - .setPass('pass123') - .setEndpoint(endpoint); + .useGdbTokenAuthentication('testuser', 'pass123'); repository = new RDFRepositoryClient(config); httpRequest = repository.httpClient.request; @@ -91,14 +89,14 @@ describe('RDFRepositoryClient - authentication', () => { test('should try relogin after token gets expired', () => { mockClient(); - return repository.get(payload).then((response) => { + return repository.get(payload).then(() => { return repository.get(payload); - }).then((response) => { + }).then(() => { // verify that exact requests have been made const loginMock = repository.httpClient.request; const requestMock = repository.httpClients[0].request; - // expect 2 invocations: + // expect 2 invocations:ClientConfigBuilder // first login // second getRepositoryIDs // expecting 5 invocations: @@ -118,10 +116,10 @@ describe('RDFRepositoryClient - authentication', () => { jest.fn().mockImplementation((request) => { if (request.getMethod() === 'get') { calls++; - if (repository.authenticationService.getLoggedUser() + if (repository.getLoggedUser() && calls === 2) { // emulate token expiration - repository.authenticationService.getLoggedUser().clearToken(); + repository.getLoggedUser().clearToken(); return Promise.reject({ response: { status: 401 diff --git a/test/repository/rdf-repository-client-deleting-data.spec.js b/test/repository/rdf-repository-client-deleting-data.spec.js index 36b7159b9..add5004c5 100644 --- a/test/repository/rdf-repository-client-deleting-data.spec.js +++ b/test/repository/rdf-repository-client-deleting-data.spec.js @@ -10,7 +10,6 @@ jest.mock('http/http-client'); * Tests statements deletion via RDFRepositoryClient */ describe('RDFRepositoryClient - Deleting statements', () => { - const subj = ''; const pred = ''; const obj = ''; @@ -21,8 +20,8 @@ describe('RDFRepositoryClient - Deleting statements', () => { let httpRequest; beforeEach(() => { - repoClientConfig = new RepositoryClientConfig() - .addEndpoint('http://localhost:8080/repositories/test') + repoClientConfig = new RepositoryClientConfig('http://localhost:8080') + .setEndpoints(['http://localhost:8080/repositories/test']) .setReadTimeout(100) .setWriteTimeout(200); @@ -36,43 +35,56 @@ describe('RDFRepositoryClient - Deleting statements', () => { test('should allow to delete all statements for given subject', () => { return rdfRepositoryClient.deleteStatements(subj).then(() => { expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements').setParams({ - subj, pred: undefined, obj: undefined, context: undefined - })); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements') + .setParams({ + subj, pred: undefined, obj: undefined, context: undefined + })); }); }); test('should allow to delete specific statement', () => { return rdfRepositoryClient.deleteStatements(subj, pred, obj).then(() => { expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements').setParams({ - subj, pred, obj, context: undefined - })); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements') + .setParams({ + subj, pred, obj, context: undefined + })); }); }); - test('should allow to delete specific statements in specific graphs', () => { - let contexts = [context, '']; - return rdfRepositoryClient.deleteStatements(subj, pred, obj, contexts).then(() => { - expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements').setParams({ - subj, pred, obj, context: contexts - })); - }); + test('should allow to delete specific statements in ' + + 'specific graphs', () => { + const contexts = [context, '']; + return rdfRepositoryClient.deleteStatements(subj, pred, obj, contexts) + .then(() => { + expect(httpRequest).toHaveBeenCalledTimes(1); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements') + .setParams({ + subj, pred, obj, context: contexts + })); + }); }); test('should allow to delete all statements from specific graph', () => { - return rdfRepositoryClient.deleteStatements(null, null, null, context).then(() => { - expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements').setParams({ - subj: undefined, pred: undefined, obj: undefined, context - })); - }); + return rdfRepositoryClient.deleteStatements(null, null, null, context) + .then(() => { + expect(httpRequest).toHaveBeenCalledTimes(1); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements') + .setParams({ + subj: undefined, pred: undefined, obj: undefined, context + })); + }); }); - test('should reject deleting statements when the server request is unsuccessful', () => { + test('should reject deleting statements when the server request ' + + 'is unsuccessful', () => { httpRequest.mockRejectedValue('error-deleting'); - return expect(rdfRepositoryClient.deleteStatements(subj)).rejects.toEqual('error-deleting'); + return expect(rdfRepositoryClient.deleteStatements(subj)).rejects + .toEqual('error-deleting'); }); test('should convert parameters to N-Triple encoded resources', () => { @@ -82,14 +94,17 @@ describe('RDFRepositoryClient - Deleting statements', () => { 'http://domain/value/1', 'http://domain/graph/1').then(() => { expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements').setParams({ - subj, pred, obj, context - })); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements') + .setParams({ + subj, pred, obj, context + })); }); }); test('should resolve to empty response (HTTP 204)', () => { - return expect(rdfRepositoryClient.deleteStatements(subj)).resolves.toEqual(); + return expect(rdfRepositoryClient.deleteStatements(subj)).resolves + .toEqual(); }); }); @@ -97,18 +112,21 @@ describe('RDFRepositoryClient - Deleting statements', () => { test('should properly request all statements deletion', () => { return rdfRepositoryClient.deleteAllStatements().then(() => { expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements')); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/statements')); }); }); - test('should reject deleting all statements when the server request is unsuccessful', () => { + test('should reject deleting all statements when the server request is ' + + 'unsuccessful', () => { httpRequest.mockRejectedValue('error-deleting-all'); - return expect(rdfRepositoryClient.deleteAllStatements()).rejects.toEqual('error-deleting-all'); + return expect(rdfRepositoryClient.deleteAllStatements()).rejects + .toEqual('error-deleting-all'); }); test('should resolve to empty response (HTTP 204)', () => { - return expect(rdfRepositoryClient.deleteAllStatements()).resolves.toEqual(); + return expect(rdfRepositoryClient.deleteAllStatements()).resolves + .toEqual(); }); }); - }); diff --git a/test/repository/rdf-repository-client-namespaces.spec.js b/test/repository/rdf-repository-client-namespaces.spec.js index 74efe4bc5..5463bf354 100644 --- a/test/repository/rdf-repository-client-namespaces.spec.js +++ b/test/repository/rdf-repository-client-namespaces.spec.js @@ -14,14 +14,13 @@ jest.mock('http/http-client'); * Tests the namespace management via RDFRepositoryClient: fetching, params etc. */ describe('RDFRepositoryClient - Namespace management', () => { - let repoClientConfig; let rdfRepositoryClient; let httpRequest; beforeEach(() => { - repoClientConfig = new RepositoryClientConfig() - .addEndpoint('http://localhost:8080/repositories/test') + repoClientConfig = new RepositoryClientConfig('http://localhost:8080') + .setEndpoints(['http://localhost:8080/repositories/test']) .setReadTimeout(100) .setWriteTimeout(200); @@ -36,20 +35,23 @@ describe('RDFRepositoryClient - Namespace management', () => { return rdfRepositoryClient.getNamespaces().then((namespaces) => { expect(namespaces).toBeDefined(); expect(namespaces.length).toEqual(16); - namespaces.forEach(namespace => { + namespaces.forEach((namespace) => { expect(namespace).toBeInstanceOf(Namespace); expect(namespace.getPrefix()).toBeDefined(); expect(namespace.getNamespace().termType).toEqual('NamedNode'); }); expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpGet('/namespaces').setHeaders({ - 'Accept': RDFMimeType.SPARQL_RESULTS_JSON - })); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpGet('/namespaces') + .setHeaders({ + 'Accept': RDFMimeType.SPARQL_RESULTS_JSON + })); }); }); - test('should reject retrieving all namespaces when the server request is unsuccessful', () => { + test('should reject retrieving all namespaces when the server request is ' + + 'unsuccessful', () => { httpRequest.mockRejectedValue({}); return expect(rdfRepositoryClient.getNamespaces()).rejects.toBeTruthy(); }); @@ -57,12 +59,13 @@ describe('RDFRepositoryClient - Namespace management', () => { describe('getNamespace(prefix)', () => { test('should retrieve specific namespace', () => { - return rdfRepositoryClient.getNamespace('rdfs').then(namespace => { + return rdfRepositoryClient.getNamespace('rdfs').then((namespace) => { expect(namespace.termType).toEqual('NamedNode'); expect(namespace.value).toEqual('http://www.w3.org/2000/01/rdf-schema#'); expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpGet('/namespaces/rdfs')); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpGet('/namespaces/rdfs')); }); }); @@ -71,9 +74,11 @@ describe('RDFRepositoryClient - Namespace management', () => { expect(httpRequest).toHaveBeenCalledTimes(0); }); - test('should reject retrieving a namespace when the server request is unsuccessful', () => { + test('should reject retrieving a namespace when the server request is ' + + 'unsuccessful', () => { httpRequest.mockRejectedValue({}); - return expect(rdfRepositoryClient.getNamespace('rdfs')).rejects.toBeTruthy(); + return expect(rdfRepositoryClient.getNamespace('rdfs')).rejects + .toBeTruthy(); }); }); @@ -82,7 +87,8 @@ describe('RDFRepositoryClient - Namespace management', () => { test('should save a namespace from string', () => { return rdfRepositoryClient.saveNamespace('new', newNamespace).then(() => { - const expectedRequest = HttpRequestBuilder.httpPut('/namespaces/new').setData(newNamespace); + const expectedRequest = HttpRequestBuilder.httpPut('/namespaces/new') + .setData(newNamespace); expect(httpRequest).toHaveBeenCalledTimes(1); expect(httpRequest).toHaveBeenCalledWith(expectedRequest); }); @@ -90,37 +96,47 @@ describe('RDFRepositoryClient - Namespace management', () => { test('should save a namespace from NamedNode', () => { const namespaceTerm = DataFactory.namedNode(newNamespace); - return rdfRepositoryClient.saveNamespace('new', namespaceTerm).then(() => { - const expectedRequest = HttpRequestBuilder.httpPut('/namespaces/new').setData(namespaceTerm.value); - expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(expectedRequest); - }); + return rdfRepositoryClient.saveNamespace('new', namespaceTerm) + .then(() => { + const expectedRequest = HttpRequestBuilder.httpPut('/namespaces/new') + .setData(namespaceTerm.value); + expect(httpRequest).toHaveBeenCalledTimes(1); + expect(httpRequest).toHaveBeenCalledWith(expectedRequest); + }); }); test('should not save a namespace if not provided with prefix', () => { - expect(() => rdfRepositoryClient.saveNamespace('', 'http://new.namespace.com/schema#')).toThrow(Error); + expect(() => rdfRepositoryClient + .saveNamespace('', 'http://new.namespace.com/schema#')).toThrow(Error); }); test('should not save a namespace if not provided with namespace', () => { - // namespace could be either string or named node -> check with empty and undefined + // namespace could be either string + // or named node -> check with empty and undefined expect(() => rdfRepositoryClient.saveNamespace('new', '')).toThrow(Error); - expect(() => rdfRepositoryClient.saveNamespace('new', undefined)).toThrow(Error) + expect(() => rdfRepositoryClient.saveNamespace('new', undefined)) + .toThrow(Error); }); - test('should reject saving a namespace when the server request is unsuccessful', () => { + test('should reject saving a namespace when the server request is ' + + 'unsuccessful', () => { httpRequest.mockRejectedValue({}); - return expect(rdfRepositoryClient.saveNamespace('new', 'http://new.namespace.com/schema#')).rejects.toBeTruthy(); + return expect(rdfRepositoryClient + .saveNamespace('new', 'http://new.namespace.com/schema#')).rejects + .toBeTruthy(); }); test('should resolve to empty response (HTTP 204)', () => { - return expect(rdfRepositoryClient.saveNamespace('new', newNamespace)).resolves.toEqual(); + return expect(rdfRepositoryClient + .saveNamespace('new', newNamespace)).resolves.toEqual(); }); }); describe('deleteNamespace(prefix)', () => { test('should delete a namespace', () => { return rdfRepositoryClient.deleteNamespace('rdfs').then(() => { - const expectedRequest = HttpRequestBuilder.httpDelete('/namespaces/rdfs'); + const expectedRequest = HttpRequestBuilder + .httpDelete('/namespaces/rdfs'); expect(httpRequest).toHaveBeenCalledTimes(1); expect(httpRequest).toHaveBeenCalledWith(expectedRequest); }); @@ -130,13 +146,16 @@ describe('RDFRepositoryClient - Namespace management', () => { expect(() => rdfRepositoryClient.deleteNamespace('')).toThrow(Error); }); - test('should reject deleting a namespace when the server request is unsuccessful', () => { + test('should reject deleting a namespace when the server request is ' + + 'unsuccessful', () => { httpRequest.mockRejectedValue({}); - return expect(rdfRepositoryClient.deleteNamespace('rdfs')).rejects.toBeTruthy(); + return expect(rdfRepositoryClient.deleteNamespace('rdfs')).rejects + .toBeTruthy(); }); test('should resolve to empty response (HTTP 204)', () => { - return expect(rdfRepositoryClient.deleteNamespace('rdfs')).resolves.toEqual(); + return expect(rdfRepositoryClient.deleteNamespace('rdfs')).resolves + .toEqual(); }); }); @@ -144,13 +163,16 @@ describe('RDFRepositoryClient - Namespace management', () => { test('should delete all namespaces', () => { return rdfRepositoryClient.deleteNamespaces().then(() => { expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/namespaces')); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('/namespaces')); }); }); - test('should reject deleting all namespaces when the server request is unsuccessful', () => { + test('should reject deleting all namespaces when the server request is ' + + 'unsuccessful', () => { httpRequest.mockRejectedValue({}); - return expect(rdfRepositoryClient.deleteNamespaces()).rejects.toBeTruthy(); + return expect(rdfRepositoryClient.deleteNamespaces()).rejects + .toBeTruthy(); }); test('should resolve to empty response (HTTP 204)', () => { @@ -159,7 +181,7 @@ describe('RDFRepositoryClient - Namespace management', () => { }); function stubHttpClient() { - let stub = httpClientStub(); + const stub = httpClientStub(); // Stub get to handle namespaces GET stub.request = jest.fn().mockImplementation((requestBuilder) => { @@ -174,17 +196,17 @@ describe('RDFRepositoryClient - Namespace management', () => { } // concrete - let prefix = url.substring(url.lastIndexOf('/') + 1); - let namespace = namespaceData.GET.results.bindings.find(b => b.prefix.value === prefix); + const prefix = url.substring(url.lastIndexOf('/') + 1); + const namespace = namespaceData.GET.results.bindings + .find((b) => b.prefix.value === prefix); if (namespace) { return Promise.resolve({data: namespace.namespace.value}); } // missing - return Promise.reject({}); + return Promise.reject(new Error()); }); return stub; } - }); diff --git a/test/repository/rdf-repository-client-query.spec.js b/test/repository/rdf-repository-client-query.spec.js index 30d039581..11e221b11 100644 --- a/test/repository/rdf-repository-client-query.spec.js +++ b/test/repository/rdf-repository-client-query.spec.js @@ -25,8 +25,8 @@ describe('RDFRepositoryClient - query', () => { beforeEach(() => { HttpClient.mockImplementation(() => httpClientStub()); - config = new RepositoryClientConfig() - .addEndpoint('http://host/repositories/repo1') + config = new RepositoryClientConfig('http://host') + .setEndpoints(['http://host/repositories/repo1']) .setReadTimeout(1000) .setWriteTimeout(1000); repository = new RDFRepositoryClient(config); @@ -215,7 +215,8 @@ describe('RDFRepositoryClient - query', () => { .setOffset(0) .setTimeout(5); - const expectedData = 'query=select%20*%20where%20%7B%3Fs%20%3Fp%20%3Fo%7D&queryLn=sparql&infer=true&distinct=true&limit=100&offset=0&timeout=5'; + const expectedData = 'query=select%20*%20where%20%7B%3Fs%20%3Fp%20%3Fo%7D' + + '&queryLn=sparql&infer=true&distinct=true&limit=100&offset=0&timeout=5'; const expectedRequestConfig = HttpRequestBuilder.httpPost('') .setData(expectedData) .setHeaders({ @@ -231,7 +232,8 @@ describe('RDFRepositoryClient - query', () => { }); describe('on payload misconfiguration', () => { - test('should throw error if responseType is not properly configured for CONSTRUCT query', () => { + test('should throw error if responseType is not properly configured for ' + + 'CONSTRUCT query', () => { const payload = new GetQueryPayload() .setQuery('select * where {?s ?p ?o}') .setQueryType(QueryType.SELECT) @@ -240,7 +242,8 @@ describe('RDFRepositoryClient - query', () => { return expect(() => repository.query(payload)).toThrow(Error); }); - test('should throw error if responseType is not properly configured for DESCRIBE query', () => { + test('should throw error if responseType is not properly configured for ' + + 'DESCRIBE query', () => { const payload = new GetQueryPayload() .setQuery('PREFIX books: DESCRIBE books:book6') .setQueryType(QueryType.DESCRIBE) @@ -249,7 +252,8 @@ describe('RDFRepositoryClient - query', () => { return expect(() => repository.query(payload)).toThrow(Error); }); - test('should throw error if responseType is not properly configured for CONSTRUCT query', () => { + test('should throw error if responseType is not properly configured for ' + + 'CONSTRUCT query', () => { const payload = new GetQueryPayload() .setQuery('construct {?s ?p ?o} where {?s ?p ?o}') .setQueryType(QueryType.CONSTRUCT) @@ -258,7 +262,8 @@ describe('RDFRepositoryClient - query', () => { return expect(() => repository.query(payload)).toThrow(Error); }); - test('should throw error if responseType is not properly configured for ASK query', () => { + test('should throw error if responseType is not properly configured for ' + + 'ASK query', () => { const payload = new GetQueryPayload() .setQuery('ask {?s ?p ?o}') .setQueryType(QueryType.ASK) diff --git a/test/repository/rdf-repository-client-reading-data.spec.js b/test/repository/rdf-repository-client-reading-data.spec.js index 801282861..5daaf37a8 100644 --- a/test/repository/rdf-repository-client-reading-data.spec.js +++ b/test/repository/rdf-repository-client-reading-data.spec.js @@ -30,11 +30,12 @@ jest.mock('http/http-client'); import data from './data/read-statements'; -const jsonldDataFile = path.resolve(__dirname, './data/read-statements-jsonld.txt'); -const rdfxmlDataFile = path.resolve(__dirname, './data/read-statements-rdfxml.txt'); +const jsonldDataFile = + path.resolve(__dirname, './data/read-statements-jsonld.txt'); +const rdfxmlDataFile = + path.resolve(__dirname, './data/read-statements-rdfxml.txt'); describe('RDFRepositoryClient - reading statements', () => { - let config; let repository; let httpRequest; @@ -48,7 +49,7 @@ describe('RDFRepositoryClient - reading statements', () => { const readTimeout = 1000; const writeTimeout = 1000; - config = new RepositoryClientConfig() + config = new RepositoryClientConfig('http://host') .setEndpoints(endpoints) .setHeaders(headers) .setDefaultRDFMimeType(contentType) @@ -78,7 +79,8 @@ describe('RDFRepositoryClient - reading statements', () => { .setResponseType(type); } - test('should fetch statement in N-Triples format and return it converted to quads', () => { + test('should fetch statement in N-Triples format and return it ' + + 'converted to quads', () => { repository.registerParser(new NTriplesParser()); mockHttpRequest(RDFMimeType.N_TRIPLES); @@ -87,7 +89,8 @@ describe('RDFRepositoryClient - reading statements', () => { return expect(repository.get(payload)).resolves.toEqual(expected); }); - test('should fetch statement in N3 format and return it converted to quads', () => { + test('should fetch statement in N3 format and return it ' + + 'converted to quads', () => { repository.registerParser(new N3Parser()); mockHttpRequest(RDFMimeType.N3); @@ -96,7 +99,8 @@ describe('RDFRepositoryClient - reading statements', () => { return expect(repository.get(payload)).resolves.toEqual(expected); }); - test('should fetch statement in TriG format and return it converted to quads', () => { + test('should fetch statement in TriG format and return it ' + + 'converted to quads', () => { repository.registerParser(new TriGParser()); mockHttpRequest(RDFMimeType.TRIG); @@ -105,7 +109,8 @@ describe('RDFRepositoryClient - reading statements', () => { return expect(repository.get(payload)).resolves.toEqual(expected); }); - test('should fetch statement in N-Quads format and return it converted to quads', () => { + test('should fetch statement in N-Quads format and return it ' + + 'converted to quads', () => { repository.registerParser(new NQuadsParser()); mockHttpRequest(RDFMimeType.N_QUADS); @@ -114,7 +119,8 @@ describe('RDFRepositoryClient - reading statements', () => { return expect(repository.get(payload)).resolves.toEqual(expected); }); - test('should fetch statement in Turtle format and return it converted to quads', () => { + test('should fetch statement in Turtle format and return it ' + + 'converted to quads', () => { repository.registerParser(new TurtleParser()); mockHttpRequest(RDFMimeType.TURTLE); @@ -123,7 +129,8 @@ describe('RDFRepositoryClient - reading statements', () => { return expect(repository.get(payload)).resolves.toEqual(expected); }); - test('should fetch statement in jsonld format and return it converted to quads', () => { + test('should fetch statement in jsonld format and return it ' + + 'converted to quads', () => { httpRequest.mockResolvedValue({ data: FileUtils.getReadStream(jsonldDataFile) }); @@ -132,7 +139,8 @@ describe('RDFRepositoryClient - reading statements', () => { // prepare expected outcome data let expected; - const stream = new JsonLDParser().parse(FileUtils.getReadStream(jsonldDataFile)); + const stream = new JsonLDParser() + .parse(FileUtils.getReadStream(jsonldDataFile)); return testUtils.readObjectsStream(stream) .then((parsed) => { expected = parsed; @@ -146,7 +154,8 @@ describe('RDFRepositoryClient - reading statements', () => { }); }); - test('should fetch statement in rdfxml format and return it converted to quads', () => { + test('should fetch statement in rdfxml format and return it ' + + 'converted to quads', () => { httpRequest.mockResolvedValue({ data: FileUtils.getReadStream(rdfxmlDataFile) }); @@ -155,7 +164,8 @@ describe('RDFRepositoryClient - reading statements', () => { // prepare expected outcome data let expected; - const stream = new RDFXmlParser().parse(FileUtils.getReadStream(rdfxmlDataFile)); + const stream = new RDFXmlParser() + .parse(FileUtils.getReadStream(rdfxmlDataFile)); return testUtils.readObjectsStream(stream) .then((parsed) => { expected = parsed; @@ -174,10 +184,12 @@ describe('RDFRepositoryClient - reading statements', () => { test('should reject with error if response fails', () => { httpRequest.mockRejectedValue({response: 'Server error'}); - return expect(repository.get(new GetStatementsPayload())).rejects.toEqual({response: 'Server error'}); + return expect(repository.get(new GetStatementsPayload())).rejects + .toEqual({response: 'Server error'}); }); - test('should populate http header and parameters according to provided data', () => { + test('should populate http header and parameters according to ' + + 'provided data', () => { httpRequest.mockResolvedValue({data: ''}); const payload = new GetStatementsPayload() @@ -193,7 +205,8 @@ describe('RDFRepositoryClient - reading statements', () => { }); }); - test('should convert the provided payload to N-Triple resources if not already encoded', () => { + test('should convert the provided payload to N-Triple resources if not ' + + 'already encoded', () => { const payload = new GetStatementsPayload() .setResponseType(RDFMimeType.RDF_JSON) .setSubject('http://eunis.eea.europa.eu/countries/AZ') @@ -224,7 +237,8 @@ describe('RDFRepositoryClient - reading statements', () => { test('should fetch and return single statement as plain string', () => { httpRequest.mockResolvedValue({ - data: data.repositories.repo1.statements.GET['single_application/rdf+xml'] + data: data.repositories.repo1.statements + .GET['single_application/rdf+xml'] }); const payload = new GetStatementsPayload() @@ -255,7 +269,8 @@ describe('RDFRepositoryClient - reading statements', () => { }); describe('download', () => { - test('should fetch data and return readable stream to the client', (done) => { + test('should fetch data and return readable stream to ' + + 'the client', (done) => { const source = streamSource(); const stream = new ObjectReadableMock(source); const expected = expectedStream(); @@ -294,7 +309,8 @@ describe('RDFRepositoryClient - reading statements', () => { }); }); - test('should convert the download request to N-Triple resources if not already encoded', () => { + test('should convert the download request to N-Triple resources if ' + + 'not already encoded', () => { const payload = new GetStatementsPayload() .setResponseType(RDFMimeType.TURTLE) .setSubject('http://eunis.eea.europa.eu/countries/AZ') diff --git a/test/repository/rdf-repository-client-streaming-data.spec.js b/test/repository/rdf-repository-client-streaming-data.spec.js index 105336a95..6e337480c 100644 --- a/test/repository/rdf-repository-client-streaming-data.spec.js +++ b/test/repository/rdf-repository-client-streaming-data.spec.js @@ -23,7 +23,7 @@ describe('RdfRepositoryClient - streaming data', () => { HttpClient.mockImplementation(() => httpClientStub()); - repoClientConfig = new RepositoryClientConfig() + repoClientConfig = new RepositoryClientConfig('http://host') .setEndpoints(endpoints) .setHeaders(headers) .setDefaultRDFMimeType(contentType) @@ -52,17 +52,22 @@ describe('RdfRepositoryClient - streaming data', () => { }); }); - test('should make a POST request with proper parameters and headers', () => { - return rdfRepositoryClient.upload({}, contentType, context, baseURI).then(() => { - verifyUploadRequest(); - }); + test('should make a POST request with proper parameters ' + + 'and headers', () => { + return rdfRepositoryClient.upload({}, contentType, context, baseURI) + .then(() => { + verifyUploadRequest(); + }); }); - test('should make a POST request with properly encoded context parameter', () => { + test('should make a POST request with properly encoded context ' + + 'parameter', () => { // Not encoded as N-Triple - return rdfRepositoryClient.upload({}, contentType, 'urn:x-local:graph1', baseURI).then(() => { - verifyUploadRequest(); - }); + return rdfRepositoryClient + .upload({}, contentType, 'urn:x-local:graph1', baseURI) + .then(() => { + verifyUploadRequest(); + }); }); function verifyUploadRequest() { @@ -85,12 +90,14 @@ describe('RdfRepositoryClient - streaming data', () => { const baseURI = ''; const contentType = RDFMimeType.TURTLE; - test('should overwrite statements using provided data as a stream', (done) => { + test('should overwrite statements using provided data as ' + + 'a stream', (done) => { const source = streamSource(); const stream = new ObjectReadableMock(source); const expectedIt = source[Symbol.iterator](); - return rdfRepositoryClient.overwrite(stream, contentType, context, baseURI) + return rdfRepositoryClient + .overwrite(stream, contentType, context, baseURI) .then(() => { stream.on('data', (chunk) => { expect(chunk).toEqual(expectedIt.next().value); @@ -100,16 +107,21 @@ describe('RdfRepositoryClient - streaming data', () => { }); test('should make a PUT request with proper parameters and headers', () => { - return rdfRepositoryClient.overwrite({}, contentType, context, baseURI).then(() => { - verifyOverwriteRequest(); - }); + return rdfRepositoryClient + .overwrite({}, contentType, context, baseURI) + .then(() => { + verifyOverwriteRequest(); + }); }); - test('should make a PUT request with properly encoded context parameter', () => { + test('should make a PUT request with properly encoded ' + + 'context parameter', () => { // Not encoded as N-Triple - return rdfRepositoryClient.overwrite({}, contentType, 'urn:x-local:graph1', baseURI).then(() => { - verifyOverwriteRequest(); - }); + return rdfRepositoryClient + .overwrite({}, contentType, 'urn:x-local:graph1', baseURI) + .then(() => { + verifyOverwriteRequest(); + }); }); function verifyOverwriteRequest() { diff --git a/test/repository/rdf-repository-client-transactions.spec.js b/test/repository/rdf-repository-client-transactions.spec.js index cd0c8dce4..598dffe7d 100644 --- a/test/repository/rdf-repository-client-transactions.spec.js +++ b/test/repository/rdf-repository-client-transactions.spec.js @@ -1,8 +1,10 @@ const HttpClient = require('http/http-client'); const RDFRepositoryClient = require('repository/rdf-repository-client'); const RepositoryClientConfig = require('repository/repository-client-config'); -const TransactionalRepositoryClient = require('transaction/transactional-repository-client'); -const TransactionIsolationLevel = require('transaction/transaction-isolation-level'); +const TransactionalRepositoryClient = + require('transaction/transactional-repository-client'); +const TransactionIsolationLevel = + require('transaction/transaction-isolation-level'); const GetStatementsPayload = require('repository/get-statements-payload'); const RDFMimeType = require('http/rdf-mime-type'); const FileUtils = require('util/file-utils'); @@ -23,7 +25,6 @@ const path = require('path'); jest.mock('http/http-client'); describe('RDFRepositoryClient - transactions', () => { - let repoClientConfig; let rdfRepositoryClient; let httpRequest; @@ -36,10 +37,11 @@ describe('RDFRepositoryClient - transactions', () => { const context = ''; const baseURI = ''; - const testFilePath = path.resolve(__dirname, './data/add-statements-complex.txt'); + const testFilePath = path.resolve(__dirname, + './data/add-statements-complex.txt'); beforeEach(() => { - repoClientConfig = new RepositoryClientConfig() + repoClientConfig = new RepositoryClientConfig('http://localhost:8080') .setEndpoints([ 'http://localhost:8080/repositories/test', 'http://localhost:8081/repositories/test' @@ -63,53 +65,66 @@ describe('RDFRepositoryClient - transactions', () => { describe('beginTransaction()', () => { test('should start a transaction and produce transactional client', () => { - return rdfRepositoryClient.beginTransaction().then(transactionalClient => { - expect(transactionalClient).toBeInstanceOf(TransactionalRepositoryClient); - - const transactionalConfig = transactionalClient.repositoryClientConfig; - expect(transactionalConfig).toBeDefined(); - expect(transactionalConfig.endpoints).toEqual([transactionUrl]); - expect(transactionalConfig.defaultRDFContentType).toEqual(repoClientConfig.defaultRDFContentType); - expect(transactionalConfig.headers).toEqual(repoClientConfig.headers); - expect(transactionalConfig.readTimeout).toEqual(repoClientConfig.readTimeout); - expect(transactionalConfig.writeTimeout).toEqual(repoClientConfig.writeTimeout); - - // Transactions must be executed against single endpoint - expect(transactionalClient.httpClients).toBeDefined(); - expect(transactionalClient.httpClients.length).toEqual(1); - expect(transactionalClient.httpClients[0].baseUrl).toEqual(transactionUrl); - expect(transactionalClient.httpClients[0].setDefaultHeaders).toHaveBeenCalledWith(defaultHeaders); - - expect(transactionalClient.isActive()).toEqual(true); - - expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpPost('/transactions')); - }); + return rdfRepositoryClient.beginTransaction() + .then((transactionalClient) => { + expect(transactionalClient). + toBeInstanceOf(TransactionalRepositoryClient); + + const transactionalConfig = transactionalClient + .repositoryClientConfig; + expect(transactionalConfig).toBeDefined(); + expect(transactionalConfig.endpoints).toEqual([transactionUrl]); + expect(transactionalConfig.defaultRDFContentType) + .toEqual(repoClientConfig.defaultRDFContentType); + expect(transactionalConfig.headers).toEqual(repoClientConfig.headers); + expect(transactionalConfig.readTimeout) + .toEqual(repoClientConfig.readTimeout); + expect(transactionalConfig.writeTimeout) + .toEqual(repoClientConfig.writeTimeout); + + // Transactions must be executed against single endpoint + expect(transactionalClient.httpClients).toBeDefined(); + expect(transactionalClient.httpClients.length).toEqual(1); + expect(transactionalClient.httpClients[0].baseUrl) + .toEqual(transactionUrl); + expect(transactionalClient.httpClients[0].setDefaultHeaders) + .toHaveBeenCalledWith(defaultHeaders); + + expect(transactionalClient.isActive()).toEqual(true); + + expect(httpRequest).toHaveBeenCalledTimes(1); + expect(httpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpPost('/transactions')); + }); }); test('should start a transaction with specified isolation level', () => { - return rdfRepositoryClient.beginTransaction(TransactionIsolationLevel.READ_UNCOMMITTED).then(transactionalClient => { - expect(transactionalClient).toBeInstanceOf(TransactionalRepositoryClient); + return rdfRepositoryClient + .beginTransaction(TransactionIsolationLevel.READ_UNCOMMITTED) + .then((transactionalClient) => { + expect(transactionalClient) + .toBeInstanceOf(TransactionalRepositoryClient); - const expectedRequest = HttpRequestBuilder.httpPost('/transactions') - .setParams({ - 'isolation-level': TransactionIsolationLevel.READ_UNCOMMITTED - }); - expect(httpRequest).toHaveBeenCalledTimes(1); - expect(httpRequest).toHaveBeenCalledWith(expectedRequest); - }); + const expectedRequest = HttpRequestBuilder.httpPost('/transactions') + .setParams({ + 'isolation-level': TransactionIsolationLevel.READ_UNCOMMITTED + }); + expect(httpRequest).toHaveBeenCalledTimes(1); + expect(httpRequest).toHaveBeenCalledWith(expectedRequest); + }); }); test('should start a transaction that can be committed', () => { let transactionalClient; - return rdfRepositoryClient.beginTransaction().then(client => { + return rdfRepositoryClient.beginTransaction().then((client) => { transactionalClient = client; return transactionalClient.commit(); }).then(() => { const expectedRequest = HttpRequestBuilder.httpPut('').setParams({ action: 'COMMIT' }); - const transactionalHttpRequest = transactionalClient.httpClients[0].request; + const transactionalHttpRequest = + transactionalClient.httpClients[0].request; expect(transactionalHttpRequest).toHaveBeenCalledTimes(1); expect(transactionalHttpRequest).toHaveBeenCalledWith(expectedRequest); expect(transactionalClient.isActive()).toEqual(false); @@ -118,13 +133,15 @@ describe('RDFRepositoryClient - transactions', () => { test('should start a transaction that can be rollbacked', () => { let transactionalClient; - return rdfRepositoryClient.beginTransaction().then(client => { + return rdfRepositoryClient.beginTransaction().then((client) => { transactionalClient = client; return transactionalClient.rollback(); }).then(() => { - const transactionalHttpRequest = transactionalClient.httpClients[0].request; + const transactionalHttpRequest = + transactionalClient.httpClients[0].request; expect(transactionalHttpRequest).toHaveBeenCalledTimes(1); - expect(transactionalHttpRequest).toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('')); + expect(transactionalHttpRequest) + .toHaveBeenCalledWith(HttpRequestBuilder.httpDelete('')); expect(transactionalClient.isActive()).toEqual(false); }); }); @@ -132,12 +149,13 @@ describe('RDFRepositoryClient - transactions', () => { test('should reject if it cannot start a transaction', () => { const err = new Error('Cannot begin transaction'); httpRequest.mockRejectedValue(err); - return expect(rdfRepositoryClient.beginTransaction()).rejects.toEqual(err); + return expect(rdfRepositoryClient.beginTransaction()) + .rejects.toEqual(err); }); test('should disallow using inactive transaction after commit', () => { let transactionalClient; - return rdfRepositoryClient.beginTransaction().then(client => { + return rdfRepositoryClient.beginTransaction().then((client) => { transactionalClient = client; return transactionalClient.commit(); }).then(() => { @@ -147,20 +165,22 @@ describe('RDFRepositoryClient - transactions', () => { }); }); - test('should reject if the transactional client cannot commit in case of server error', () => { + test('should reject if the transactional client cannot commit ' + + 'in case of server error', () => { const err = new Error('cannot commit'); let transactionalClient; - return rdfRepositoryClient.beginTransaction().then(client => { + return rdfRepositoryClient.beginTransaction().then((client) => { transactionalClient = client; transactionalClient.httpClients[0].request.mockRejectedValue(err); return expect(transactionalClient.commit()).rejects.toEqual(err); }); }); - test('should disallow using inactive transaction after commit failure', () => { + test('should disallow using inactive transaction after ' + + 'commit failure', () => { const err = new Error('cannot commit'); let transactionalClient; - return rdfRepositoryClient.beginTransaction().then(client => { + return rdfRepositoryClient.beginTransaction().then((client) => { transactionalClient = client; transactionalClient.httpClients[0].request.mockRejectedValue(err); return transactionalClient.commit(); @@ -173,7 +193,7 @@ describe('RDFRepositoryClient - transactions', () => { test('should disallow using inactive transaction after rollback', () => { let transactionalClient; - return rdfRepositoryClient.beginTransaction().then(client => { + return rdfRepositoryClient.beginTransaction().then((client) => { transactionalClient = client; return transactionalClient.rollback(); }).then(() => { @@ -183,20 +203,22 @@ describe('RDFRepositoryClient - transactions', () => { }); }); - test('should reject if the transactional client cannot rollback in case of server error', () => { + test('should reject if the transactional client cannot rollback ' + + 'in case of server error', () => { const err = new Error('cannot rollback'); let transactionalClient; - return rdfRepositoryClient.beginTransaction().then(client => { + return rdfRepositoryClient.beginTransaction().then((client) => { transactionalClient = client; transactionalClient.httpClients[0].request.mockRejectedValue(err); return expect(transactionalClient.rollback()).rejects.toEqual(err); }); }); - test('should disallow using inactive transaction after rollback failure', () => { + test('should disallow using inactive transaction after ' + + 'rollback failure', () => { const err = new Error('cannot rollback'); let transactionalClient; - return rdfRepositoryClient.beginTransaction().then(client => { + return rdfRepositoryClient.beginTransaction().then((client) => { transactionalClient = client; transactionalClient.httpClients[0].request.mockRejectedValue(err); return transactionalClient.rollback(); @@ -211,19 +233,19 @@ describe('RDFRepositoryClient - transactions', () => { // Reset headers const response = {headers: {}}; httpRequest.mockResolvedValue(response); - return expect(rdfRepositoryClient.beginTransaction()).rejects.toEqual(Error('Couldn\'t obtain transaction ID')); + return expect(rdfRepositoryClient.beginTransaction()).rejects + .toEqual(Error('Couldn\'t obtain transaction ID')); }); }); describe('Having started transaction', () => { - let transaction; let transactionHttpRequest; const data = ' "Title"@en.'; beforeEach(() => { - return rdfRepositoryClient.beginTransaction().then(tr => { + return rdfRepositoryClient.beginTransaction().then((tr) => { transaction = tr; transactionHttpRequest = transaction.httpClients[0].request; }); @@ -232,7 +254,7 @@ describe('RDFRepositoryClient - transactions', () => { describe('getSize()', () => { test('should retrieve the repository size', () => { transactionHttpRequest.mockResolvedValue({data: 123}); - return transaction.getSize().then(size => { + return transaction.getSize().then((size) => { expect(size).toEqual(123); const expectedRequest = HttpRequestBuilder.httpPut('').setParams({ @@ -246,7 +268,7 @@ describe('RDFRepositoryClient - transactions', () => { test('should retrieve the repository size in specific context', () => { transactionHttpRequest.mockResolvedValue({data: 123}); - return transaction.getSize('').then(size => { + return transaction.getSize('').then((size) => { expect(size).toEqual(123); const expectedRequest = HttpRequestBuilder.httpPut('').setParams({ @@ -258,9 +280,11 @@ describe('RDFRepositoryClient - transactions', () => { }); }); - test('should reject if the transaction cannot retrieve the repository size', () => { + test('should reject if the transaction cannot retrieve ' + + 'the repository size', () => { transactionHttpRequest.mockRejectedValue('Error during size retrieve'); - return expect(transaction.getSize()).rejects.toEqual('Error during size retrieve'); + return expect(transaction.getSize()).rejects + .toEqual('Error during size retrieve'); }); }); @@ -292,9 +316,11 @@ describe('RDFRepositoryClient - transactions', () => { }); }); - test('should reject if the transaction cannot retrieve statements', () => { + test('should reject if the transaction cannot ' + + 'retrieve statements', () => { transactionHttpRequest.mockRejectedValue('Error during retrieve'); - return expect(transaction.get(getStatementPayload())).rejects.toEqual('Error during retrieve'); + return expect(transaction.get(getStatementPayload())).rejects + .toEqual('Error during retrieve'); }); }); @@ -331,7 +357,8 @@ describe('RDFRepositoryClient - transactions', () => { }); }); - test('should reject if the transaction cannot perform a query request', () => { + test('should reject if the transaction cannot perform ' + + 'a query request', () => { const err = new Error('Cannot query'); transactionHttpRequest.mockRejectedValue(err); return expect(transaction.query(payload)).rejects.toEqual(err); @@ -358,7 +385,8 @@ describe('RDFRepositoryClient - transactions', () => { }); }); - test('should reject if the transaction cannot perform an update request', () => { + test('should reject if the transaction cannot perform ' + + 'an update request', () => { const err = new Error('Cannot update'); transactionHttpRequest.mockRejectedValue(err); return expect(transaction.update(updatePayload)).rejects.toEqual(err); @@ -377,14 +405,17 @@ describe('RDFRepositoryClient - transactions', () => { .setContext('http://domain/graph/data-graph-1') .setBaseURI(baseURI); - test('should convert the payload to proper Turtle and send it to the server', () => { - const expectedData = testUtils.loadFile('repository/data/add-statements-context.txt').trim(); + test('should convert the payload to proper Turtle and ' + + 'send it to the server', () => { + const expectedData = testUtils + .loadFile('repository/data/add-statements-context.txt').trim(); return transaction.add(payload).then(() => { expectInsertedData(expectedData, '', baseURI); }); }); - test('should convert the literal payload to proper Turtle and send it to the server', () => { + test('should convert the literal payload to proper Turtle and ' + + 'send it to the server', () => { payload = new AddStatementPayload() .setSubject('http://domain/resource/resource-1') .setPredicate('http://domain/property/property-1') @@ -393,14 +424,17 @@ describe('RDFRepositoryClient - transactions', () => { .setContext('http://domain/graph/data-graph-1') .setBaseURI(baseURI); - const expectedData = testUtils.loadFile('repository/data/add-statements-context-literal.txt').trim(); + const expectedData = testUtils + .loadFile('repository/data/add-statements-context-literal.txt') + .trim(); return transaction.add(payload).then(() => { expectInsertedData(expectedData, '', baseURI); }); }); test('should throw error when a payload is not provided', () => { - expect(() => transaction.add()).toThrow(Error('Cannot add statement without payload')); + expect(() => transaction.add()) + .toThrow(Error('Cannot add statement without payload')); expectNoInsertedData(); }); @@ -410,7 +444,8 @@ describe('RDFRepositoryClient - transactions', () => { expectNoInsertedData(); }); - test('should reject adding the payload if it lacks required terms', () => { + test('should reject adding the payload if it lacks ' + + 'required terms', () => { const payload = new AddStatementPayload() .setSubject('http://domain/resource/resource-1') .setPredicate('http://domain/property/property-1'); @@ -420,7 +455,8 @@ describe('RDFRepositoryClient - transactions', () => { test('should reject if the transaction cannot insert statements', () => { transactionHttpRequest.mockRejectedValue('Error during add'); - return expect(transaction.add(payload)).rejects.toEqual('Error during add'); + return expect(transaction.add(payload)).rejects + .toEqual('Error during add'); }); test('should resolve to empty response (HTTP 204)', () => { @@ -440,7 +476,8 @@ describe('RDFRepositoryClient - transactions', () => { }); }); - test('should support adding quads in given context and base URI for resolving', () => { + test('should support adding quads in given context and base URI ' + + 'for resolving', () => { const q = quad( namedNode('http://domain/resource/resource-1'), namedNode('http://domain/property/relation-1'), @@ -458,7 +495,8 @@ describe('RDFRepositoryClient - transactions', () => { literal('Title', 'en')); transactionHttpRequest.mockRejectedValue('Error during quads add'); - return expect(transaction.addQuads([q])).rejects.toEqual('Error during quads add'); + return expect(transaction.addQuads([q])).rejects + .toEqual('Error during quads add'); }); test('should resolve to empty response (HTTP 204)', () => { @@ -470,7 +508,8 @@ describe('RDFRepositoryClient - transactions', () => { }); }); - function expectInsertedData(expectedData, expectedContext, expectedBaseURI) { + function expectInsertedData(expectedData, expectedContext, + expectedBaseURI) { const expectedRequest = HttpRequestBuilder.httpPut('') .setData(expectedData) .setHeaders({ @@ -514,7 +553,8 @@ describe('RDFRepositoryClient - transactions', () => { test('should reject if the transaction cannot delete data', () => { transactionHttpRequest.mockRejectedValue('Error during delete'); - return expect(transaction.deleteData(data)).rejects.toEqual('Error during delete'); + return expect(transaction.deleteData(data)).rejects + .toEqual('Error during delete'); }); test('should resolve to empty response (HTTP 204)', () => { @@ -527,12 +567,13 @@ describe('RDFRepositoryClient - transactions', () => { transactionHttpRequest.mockResolvedValue({ data: FileUtils.getReadStream(testFilePath) }); - return transaction.download(getStatementPayload()).then((dataStream) => { - return testUtils.readStream(dataStream); - }).then((data) => { - const turtleData = testUtils.loadFile(testFilePath).trim(); - expect(data).toEqual(turtleData); - }); + return transaction.download(getStatementPayload()) + .then((dataStream) => { + return testUtils.readStream(dataStream); + }).then((data) => { + const turtleData = testUtils.loadFile(testFilePath).trim(); + expect(data).toEqual(turtleData); + }); }); test('should properly request to download data', () => { @@ -561,7 +602,8 @@ describe('RDFRepositoryClient - transactions', () => { test('should reject if the transaction cannot download data', () => { const err = new Error('Cannot download data'); transactionHttpRequest.mockRejectedValue(err); - return expect(transaction.download(getStatementPayload())).rejects.toEqual(err); + return expect(transaction.download(getStatementPayload())).rejects + .toEqual(err); }); }); @@ -569,63 +611,83 @@ describe('RDFRepositoryClient - transactions', () => { test('should upload data stream in given context and base URI', () => { const turtleStream = FileUtils.getReadStream(testFilePath); - return transaction.upload(turtleStream, RDFMimeType.TRIG, context, baseURI).then(() => { - expect(transactionHttpRequest).toHaveBeenCalledTimes(1); - const requestBuilder = transactionHttpRequest.mock.calls[0][0]; - verifyUploadRequestBuilder(requestBuilder); - return testUtils.readStream(requestBuilder.getData()); - }).then((streamData) => { - const turtleData = testUtils.loadFile(testFilePath).trim(); - expect(streamData).toEqual(turtleData); - }); + return transaction + .upload(turtleStream, RDFMimeType.TRIG, context, baseURI) + .then(() => { + expect(transactionHttpRequest).toHaveBeenCalledTimes(1); + const requestBuilder = transactionHttpRequest.mock.calls[0][0]; + verifyUploadRequestBuilder(requestBuilder); + return testUtils.readStream(requestBuilder.getData()); + }).then((streamData) => { + const turtleData = testUtils.loadFile(testFilePath).trim(); + expect(streamData).toEqual(turtleData); + }); }); - test('should reject if the server cannot consume the upload request', () => { + test('should reject if the server cannot consume ' + + 'the upload request', () => { const error = new Error('cannot-upload'); transactionHttpRequest.mockRejectedValue(error); const turtleStream = FileUtils.getReadStream(testFilePath); - const promise = transaction.upload(turtleStream, RDFMimeType.TRIG, context, null); + const promise = transaction + .upload(turtleStream, RDFMimeType.TRIG, context, null); return expect(promise).rejects.toEqual(error); }); test('should resolve to empty response (HTTP 204)', () => { const turtleStream = FileUtils.getReadStream(testFilePath); - return expect(transaction.upload(turtleStream, RDFMimeType.TRIG, context, baseURI)).resolves.toEqual(); + return expect(transaction + .upload(turtleStream, RDFMimeType.TRIG, context, baseURI)).resolves + .toEqual(); }); }); describe('addFile()', () => { - const testFilePath = path.resolve(__dirname, './data/add-statements-complex.txt'); - - test('should upload file with data as stream in given context and base URI', () => { - return transaction.addFile(testFilePath, RDFMimeType.TRIG, context, baseURI).then(() => { - expect(transactionHttpRequest).toHaveBeenCalledTimes(1); - const requestBuilder = transactionHttpRequest.mock.calls[0][0]; - verifyUploadRequestBuilder(requestBuilder); - return testUtils.readStream(requestBuilder.getData()); - }).then((streamData) => { - const turtleData = testUtils.loadFile(testFilePath).trim(); - expect(streamData).toEqual(turtleData); - }); + const testFilePath = path + .resolve(__dirname, './data/add-statements-complex.txt'); + + test('should upload file with data as stream in given context ' + + 'and base URI', () => { + return transaction + .addFile(testFilePath, RDFMimeType.TRIG, context, baseURI) + .then(() => { + expect(transactionHttpRequest).toHaveBeenCalledTimes(1); + const requestBuilder = transactionHttpRequest.mock.calls[0][0]; + verifyUploadRequestBuilder(requestBuilder); + return testUtils.readStream(requestBuilder.getData()); + }).then((streamData) => { + const turtleData = testUtils.loadFile(testFilePath).trim(); + expect(streamData).toEqual(turtleData); + }); }); - test('should reject if the server cannot consume the file upload request', () => { + test('should reject if the server cannot consume the file ' + + 'upload request', () => { const error = new Error('cannot-upload'); transactionHttpRequest.mockRejectedValue(error); - const promise = transaction.addFile(testFilePath, RDFMimeType.TRIG, context, null); + const promise = transaction + .addFile(testFilePath, RDFMimeType.TRIG, context, null); return expect(promise).rejects.toEqual(error); }); test('should disallow uploading missing files', () => { - expect(() => transaction.addFile(null, RDFMimeType.TRIG, context, baseURI)).toThrow(Error); - expect(() => transaction.addFile('', RDFMimeType.TRIG, context, baseURI)).toThrow(Error); - expect(() => transaction.addFile('missing-file-123', RDFMimeType.TRIG, context, baseURI)).toThrow(Error); + expect(() => transaction + .addFile(null, RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); + expect(() => transaction + .addFile('', RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); + expect(() => transaction + .addFile('missing-file-123', RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); }); test('should resolve to empty response (HTTP 204)', () => { - return expect(transaction.addFile(testFilePath, RDFMimeType.TRIG, context, baseURI)).resolves.toEqual(); + return expect(transaction + .addFile(testFilePath, RDFMimeType.TRIG, context, baseURI)).resolves + .toEqual(); }); }); @@ -655,5 +717,4 @@ describe('RDFRepositoryClient - transactions', () => { .setInference(true); } }); - }); diff --git a/test/repository/rdf-repository-client-update-query.spec.js b/test/repository/rdf-repository-client-update-query.spec.js index 14fdcd8e4..5d5c7a9aa 100644 --- a/test/repository/rdf-repository-client-update-query.spec.js +++ b/test/repository/rdf-repository-client-update-query.spec.js @@ -1,6 +1,6 @@ const HttpClient = require('http/http-client'); -const RDFRepositoryClient = require('repository/rdf-repository-client'); const RepositoryClientConfig = require('repository/repository-client-config'); +const RDFRepositoryClient = require('repository/rdf-repository-client'); const UpdateQueryPayload = require('query/update-query-payload'); const QueryContentType = require('http/query-content-type'); const HttpRequestBuilder = require('http/http-request-builder'); @@ -16,15 +16,16 @@ describe('RDFRepositoryClient - update query', () => { beforeEach(() => { HttpClient.mockImplementation(() => httpClientStub()); - config = new RepositoryClientConfig() - .addEndpoint('http://host/repositories/repo1') + config = new RepositoryClientConfig('http://host') + .setEndpoints(['http://host/repositories/repo1']) .setReadTimeout(1000) .setWriteTimeout(1000); repository = new RDFRepositoryClient(config); httpRequest = repository.httpClients[0].request; }); - test('should make a POST request with Content-Type/sparql-update header and unencoded sparql query as body', () => { + test('should make a POST request with Content-Type/sparql-update header ' + + 'and unencoded sparql query as body', () => { const payload = new UpdateQueryPayload() .setQuery('INSERT {?s ?p ?o} WHERE {?s ?p ?o}'); @@ -40,7 +41,8 @@ describe('RDFRepositoryClient - update query', () => { }); }); - test('should make a POST request with Content-Type/x-www-form-urlencoded header and encoded query plus parameters as body', () => { + test('should make a POST request with Content-Type/x-www-form-urlencoded ' + + 'header and encoded query plus parameters as body', () => { const payload = new UpdateQueryPayload() .setQuery('INSERT {?s ?p ?o} WHERE {?s ?p ?o}') .setContentType(QueryContentType.X_WWW_FORM_URLENCODED) @@ -51,7 +53,13 @@ describe('RDFRepositoryClient - update query', () => { .setInsertGraphs('') .setTimeout(5); - const expectedData = 'update=INSERT%20%7B%3Fs%20%3Fp%20%3Fo%7D%20WHERE%20%7B%3Fs%20%3Fp%20%3Fo%7D&infer=true&using-graph-uri=%3Chttp%3A%2F%2Fexample.org%2Fgraph1%3E&using-named-graph-uri=%3Chttp%3A%2F%2Fexample.org%2Fgraph2%3E&remove-graph-uri=%3Chttp%3A%2F%2Fexample.org%2Fgraph3%3E&insert-graph-uri=%3Chttp%3A%2F%2Fexample.org%2Fgraph4%3E&timeout=5'; + const expectedData = + 'update=INSERT%20%7B%3Fs%20%3Fp%20%3Fo%7D%20WHERE' + + '%20%7B%3Fs%20%3Fp%20%3Fo%7D&infer=true&using-graph-uri=' + + '%3Chttp%3A%2F%2Fexample.org%2Fgraph1%3E&using-named-graph-uri=' + + '%3Chttp%3A%2F%2Fexample.org%2Fgraph2%3E&remove-graph-uri=' + + '%3Chttp%3A%2F%2Fexample.org%2Fgraph3%3E&insert-graph-uri=' + + '%3Chttp%3A%2F%2Fexample.org%2Fgraph4%3E&timeout=5'; const expectedRequestConfig = HttpRequestBuilder.httpPost('/statements') .setData(expectedData) .setHeaders({ @@ -69,7 +77,8 @@ describe('RDFRepositoryClient - update query', () => { const payload = new UpdateQueryPayload() .setContentType(QueryContentType.X_WWW_FORM_URLENCODED); - return expect(() => repository.update(payload)).toThrow(Error('Parameter query is mandatory!')); + return expect(() => repository.update(payload)) + .toThrow(Error('Parameter query is mandatory!')); }); }); diff --git a/test/repository/rdf-repository-client-uploading-files.spec.js b/test/repository/rdf-repository-client-uploading-files.spec.js index 81d779573..eafe7c410 100644 --- a/test/repository/rdf-repository-client-uploading-files.spec.js +++ b/test/repository/rdf-repository-client-uploading-files.spec.js @@ -12,14 +12,14 @@ const path = require('path'); jest.mock('http/http-client'); describe('RdfRepositoryClient - uploading files', () => { - let repoClientConfig; let rdfRepositoryClient; let httpRequest; const context = ''; const baseURI = ''; - let testFilePath = path.resolve(__dirname, './data/add-statements-complex.txt'); + const testFilePath = path + .resolve(__dirname, './data/add-statements-complex.txt'); beforeEach(() => { const endpoints = ['http://host/repositories/repo1']; @@ -29,7 +29,7 @@ describe('RdfRepositoryClient - uploading files', () => { const writeTimeout = 1000; HttpClient.mockImplementation(() => httpClientStub()); - repoClientConfig = new RepositoryClientConfig() + repoClientConfig = new RepositoryClientConfig('http://host') .setEndpoints(endpoints) .setHeaders(headers) .setDefaultRDFMimeType(contentType) @@ -40,68 +40,91 @@ describe('RdfRepositoryClient - uploading files', () => { }); describe('addFile(file)', () => { - - test('should open a readable stream of the file and send it to the server', () => { - return rdfRepositoryClient.addFile(testFilePath, RDFMimeType.TRIG, context, baseURI).then(() => { - expect(httpRequest).toHaveBeenCalledTimes(1); - const requestBuilder = httpRequest.mock.calls[0][0]; - verifyUploadRequestBuilder(requestBuilder, 'post'); - return testUtils.readStream(requestBuilder.getData()); - }).then((streamData) => { - const expectedData = testUtils.loadFile(testFilePath).trim(); - expect(streamData).toEqual(expectedData); - }); + test('should open a readable stream of the file and send it ' + + 'to the server', () => { + return rdfRepositoryClient + .addFile(testFilePath, RDFMimeType.TRIG, context, baseURI) + .then(() => { + expect(httpRequest).toHaveBeenCalledTimes(1); + const requestBuilder = httpRequest.mock.calls[0][0]; + verifyUploadRequestBuilder(requestBuilder, 'post'); + return testUtils.readStream(requestBuilder.getData()); + }).then((streamData) => { + const expectedData = testUtils.loadFile(testFilePath).trim(); + expect(streamData).toEqual(expectedData); + }); }); test('should reject if the server cannot consume the request', () => { const error = new Error('cannot-upload-file'); httpRequest.mockRejectedValue(error); - const promise = rdfRepositoryClient.addFile(testFilePath, RDFMimeType.TRIG, context, baseURI); + const promise = rdfRepositoryClient + .addFile(testFilePath, RDFMimeType.TRIG, context, baseURI); return expect(promise).rejects.toEqual(error); }); test('should disallow uploading missing files', () => { - expect(() => rdfRepositoryClient.addFile(null, RDFMimeType.TRIG, context, baseURI)).toThrow(Error); - expect(() => rdfRepositoryClient.addFile('', RDFMimeType.TRIG, context, baseURI)).toThrow(Error); - expect(() => rdfRepositoryClient.addFile('missing-file-123', RDFMimeType.TRIG, context, baseURI)).toThrow(Error); + expect(() => rdfRepositoryClient + .addFile(null, RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); + expect(() => rdfRepositoryClient + .addFile('', RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); + expect(() => rdfRepositoryClient + .addFile('missing-file-123', RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); }); test('should resolve to empty response (HTTP 204)', () => { - return expect(rdfRepositoryClient.addFile(testFilePath, RDFMimeType.TRIG, context, baseURI)).resolves.toEqual(); + return expect(rdfRepositoryClient + .addFile(testFilePath, RDFMimeType.TRIG, context, baseURI)).resolves + .toEqual(); }); }); describe('putFile(file)', () => { - - test('should open a readable stream of the file and send it to the server to overwrite the data', () => { - return rdfRepositoryClient.putFile(testFilePath, RDFMimeType.TRIG, context, baseURI).then(() => { - expect(httpRequest).toHaveBeenCalledTimes(1); - const requestBuilder = httpRequest.mock.calls[0][0]; - verifyUploadRequestBuilder(requestBuilder, 'put'); - return testUtils.readStream(requestBuilder.getData()); - }).then((streamData) => { - const expectedData = testUtils.loadFile(testFilePath).trim(); - expect(streamData).toEqual(expectedData); - }); + test('should open a readable stream of the file and send it to ' + + 'the server to overwrite the data', () => { + return rdfRepositoryClient + .putFile(testFilePath, RDFMimeType.TRIG, context, baseURI) + .then(() => { + expect(httpRequest).toHaveBeenCalledTimes(1); + const requestBuilder = httpRequest.mock.calls[0][0]; + verifyUploadRequestBuilder(requestBuilder, 'put'); + return testUtils.readStream(requestBuilder.getData()); + }).then((streamData) => { + const expectedData = testUtils.loadFile(testFilePath).trim(); + expect(streamData).toEqual(expectedData); + }); }); - test('should reject if the server cannot consume the overwrite request', () => { + test('should reject if the server cannot consume the ' + + 'overwrite request', () => { const error = new Error('cannot-upload-file'); httpRequest.mockRejectedValue(error); - const promise = rdfRepositoryClient.putFile(testFilePath, RDFMimeType.TRIG, context, baseURI); + const promise = rdfRepositoryClient + .putFile(testFilePath, RDFMimeType.TRIG, context, baseURI); return expect(promise).rejects.toEqual(error); }); test('should disallow overwriting with missing files', () => { - expect(() => rdfRepositoryClient.putFile(null, RDFMimeType.TRIG, context, baseURI)).toThrow(Error); - expect(() => rdfRepositoryClient.putFile('', RDFMimeType.TRIG, context, baseURI)).toThrow(Error); - expect(() => rdfRepositoryClient.putFile('missing-file-123', RDFMimeType.TRIG, context, baseURI)).toThrow(Error); + expect(() => rdfRepositoryClient + .putFile(null, RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); + expect(() => rdfRepositoryClient + .putFile('', RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); + expect(() => rdfRepositoryClient + .putFile('missing-file-123', RDFMimeType.TRIG, context, baseURI)) + .toThrow(Error); }); test('should resolve to empty response (HTTP 204)', () => { - return expect(rdfRepositoryClient.putFile(testFilePath, RDFMimeType.TRIG, context, baseURI)).resolves.toEqual(); + return expect(rdfRepositoryClient + .putFile(testFilePath, RDFMimeType.TRIG, context, baseURI)).resolves + .toEqual(); }); }); @@ -119,5 +142,4 @@ describe('RdfRepositoryClient - uploading files', () => { }); expect(requestBuilder.getResponseType()).toEqual('stream'); } - }); diff --git a/test/repository/rdf-repository-client.spec.js b/test/repository/rdf-repository-client.spec.js index f572fef83..d8cae0419 100644 --- a/test/repository/rdf-repository-client.spec.js +++ b/test/repository/rdf-repository-client.spec.js @@ -11,15 +11,14 @@ jest.mock('http/http-client'); * Tests the initialization logic in RDFRepositoryClient */ describe('RDFRepositoryClient', () => { - HttpClient.mockImplementation(() => httpClientStub()); - let defaultHeaders = { + const defaultHeaders = { 'Accept': 'application/json' }; test('should initialize according the provided client configuration', () => { - let repoClientConfig = new RepositoryClientConfig() + const repoClientConfig = new RepositoryClientConfig('http://localhost:8080') .setEndpoints([ 'http://localhost:8080/repositories/test' ]) @@ -28,20 +27,25 @@ describe('RDFRepositoryClient', () => { .setReadTimeout(100) .setWriteTimeout(200); - let rdfRepositoryClient = new RDFRepositoryClient(repoClientConfig); + const rdfRepositoryClient = new RDFRepositoryClient(repoClientConfig); expect(rdfRepositoryClient.repositoryClientConfig).toBeDefined(); - expect(rdfRepositoryClient.repositoryClientConfig).toEqual(repoClientConfig); + expect(rdfRepositoryClient.repositoryClientConfig) + .toEqual(repoClientConfig); expect(rdfRepositoryClient.httpClients).toBeDefined(); expect(rdfRepositoryClient.httpClients.length).toEqual(1); - expect(rdfRepositoryClient.httpClients[0].setDefaultHeaders).toHaveBeenCalledWith(defaultHeaders); - expect(rdfRepositoryClient.httpClients[0].setDefaultReadTimeout).toHaveBeenCalledWith(100); - expect(rdfRepositoryClient.httpClients[0].setDefaultWriteTimeout).toHaveBeenCalledWith(200); + expect(rdfRepositoryClient.httpClients[0].setDefaultHeaders) + .toHaveBeenCalledWith(defaultHeaders); + expect(rdfRepositoryClient.httpClients[0].setDefaultReadTimeout) + .toHaveBeenCalledWith(100); + expect(rdfRepositoryClient.httpClients[0].setDefaultWriteTimeout) + .toHaveBeenCalledWith(200); }); - test('should initialize with multiple endpoints from the client configuration', () => { - let repoClientConfig = new RepositoryClientConfig() + test('should initialize with multiple endpoints from the client ' + + 'configuration', () => { + const repoClientConfig = new RepositoryClientConfig('http://localhost:8080') .setEndpoints([ 'http://localhost:8081/repositories/test1', 'http://localhost:8082/repositories/test2', @@ -52,7 +56,7 @@ describe('RDFRepositoryClient', () => { .setReadTimeout(100) .setWriteTimeout(200); - let rdfRepositoryClient = new RDFRepositoryClient(repoClientConfig); + const rdfRepositoryClient = new RDFRepositoryClient(repoClientConfig); expect(rdfRepositoryClient.httpClients).toBeDefined(); expect(rdfRepositoryClient.httpClients.length).toEqual(3); @@ -62,21 +66,23 @@ describe('RDFRepositoryClient', () => { }); }); - test('should not allow to be instantiated with improper configuration', () => { + test('should not allow to be instantiated with improper ' + + 'configuration', () => { expect(() => new RDFRepositoryClient()).toThrow(Error); expect(() => new RDFRepositoryClient({})).toThrow(Error); - expect(() => new RDFRepositoryClient(new ServerClientConfig('', 1, {}))).toThrow(Error); - expect(() => new RDFRepositoryClient(new RepositoryClientConfig([]))).toThrow(Error); + expect(() => new RDFRepositoryClient( + new ServerClientConfig('', 1, {}))).toThrow(Error); + expect(() => new RDFRepositoryClient( + new RepositoryClientConfig([]))).toThrow(Error); }); describe('getSize()', () => { - let rdfRepositoryClient; let httpRequest; beforeEach(() => { - const repoClientConfig = new RepositoryClientConfig() - .addEndpoint('http://localhost:8080/repositories/test') + const repoClientConfig = new RepositoryClientConfig('http://localhost:8080') + .setEndpoints(['http://localhost:8080/repositories/test']) .setHeaders(defaultHeaders) .setDefaultRDFMimeType('application/json') .setReadTimeout(100) @@ -91,7 +97,8 @@ describe('RDFRepositoryClient', () => { return expect(rdfRepositoryClient.getSize()).resolves.toEqual(123); }); - test('should properly request the number of statements in the repository', () => { + test('should properly request the number of statements ' + + 'in the repository', () => { return rdfRepositoryClient.getSize().then(() => { const expected = HttpRequestBuilder.httpGet('/size'); expect(httpRequest).toHaveBeenCalledTimes(1); @@ -99,18 +106,21 @@ describe('RDFRepositoryClient', () => { }); }); - test('should properly request the number of statements in the repository for the specified contexts', () => { + test('should properly request the number of statements ' + + 'in the repository for the specified contexts', () => { return rdfRepositoryClient.getSize(['context-1']).then(() => { - const expected = HttpRequestBuilder.httpGet('/size').addParam('context', ['']); + const expected = HttpRequestBuilder.httpGet('/size') + .addParam('context', ['']); expect(httpRequest).toHaveBeenCalledTimes(1); expect(httpRequest).toHaveBeenCalledWith(expected); }); }); - test('should reject size retrieving when the server request is unsuccessful', () => { + test('should reject size retrieving when the server request ' + + 'is unsuccessful', () => { httpRequest.mockRejectedValue('get-size-error'); - return expect(rdfRepositoryClient.getSize()).rejects.toEqual('get-size-error'); + return expect(rdfRepositoryClient.getSize()).rejects + .toEqual('get-size-error'); }); }); - }); diff --git a/test/repository/repository-client-config.spec.js b/test/repository/repository-client-config.spec.js index 1dce6bca9..5322e3e96 100644 --- a/test/repository/repository-client-config.spec.js +++ b/test/repository/repository-client-config.spec.js @@ -2,6 +2,7 @@ const RepositoryClientConfig = require('repository/repository-client-config'); const RDFMimeType = require('http/rdf-mime-type'); describe('RepositoryClientConfig', () => { + const endpoint = 'http://localhost:8081'; const endpoints = [ 'http://localhost:8081/repositories/test1', 'http://localhost:8082/repositories/test2', @@ -14,34 +15,29 @@ describe('RepositoryClientConfig', () => { const readTimeout = 1000; const writeTimeout = 2000; - test('should instantiate with the provided configuration parameters', () => { - const config = new RepositoryClientConfig(endpoints, headers, - defaultRDFMimeType, readTimeout, writeTimeout, 'testuser', 'P@ssw0rd', - false); - expect(config.getEndpoints()).toEqual(endpoints); - expect(config.getHeaders()).toEqual(headers); - expect(config.getDefaultRDFMimeType()).toEqual(defaultRDFMimeType); - expect(config.getReadTimeout()).toEqual(readTimeout); - expect(config.getWriteTimeout()).toEqual(writeTimeout); - expect(config.getUsername()).toEqual('testuser'); - expect(config.getPass()).toEqual('P@ssw0rd'); - expect(config.getKeepAlive()).toBeFalsy(); - - const securedHeaders = {'Accept': 'application/json', - 'Authorization': 'Basic dGVzdHVzZXI6UEBzc3cwcmQ='}; - config.setBasicAuthentication(true); - expect(config.getHeaders()).toEqual(securedHeaders); + test('should instantiate with the default configuration parameters', () => { + const config = new RepositoryClientConfig(endpoint); + expect(config.getEndpoint()).toEqual(endpoint); + expect(config.getHeaders()).toEqual({}); + expect(config.getDefaultRDFMimeType()) + .toEqual('application/sparql-results+json'); + expect(config.getEndpoints()).toEqual([]); + expect(config.getReadTimeout()).toEqual(10000); + expect(config.getWriteTimeout()).toEqual(10000); + expect(config.getUsername()).toEqual(undefined); + expect(config.getPass()).toEqual(undefined); + expect(config.getBasicAuthentication()).toBeFalsy(); + expect(config.getKeepAlive()).toBeTruthy(); }); test('should support initialization via fluent API', () => { - const config = new RepositoryClientConfig() + const config = new RepositoryClientConfig(endpoint) .setEndpoints(endpoints) .setHeaders(headers) .setDefaultRDFMimeType(defaultRDFMimeType) .setReadTimeout(readTimeout) .setWriteTimeout(writeTimeout) - .setUsername('testuser') - .setPass('P@ssw0rd') + .useGdbTokenAuthentication('testuser', 'P@ssw0rd') .setKeepAlive(false); expect(config.getEndpoints()).toEqual(endpoints); expect(config.getHeaders()).toEqual(headers); @@ -50,11 +46,19 @@ describe('RepositoryClientConfig', () => { expect(config.getWriteTimeout()).toEqual(writeTimeout); expect(config.getUsername()).toEqual('testuser'); expect(config.getPass()).toEqual('P@ssw0rd'); + expect(config.getBasicAuthentication()).toBeFalsy(); + expect(config.getGdbTokenAuthentication()).toBeTruthy(); expect(config.getKeepAlive()).toBeFalsy(); + + config.useBasicAuthentication('testuser2', 'P@ssw0rd2'); + expect(config.getUsername()).toEqual('testuser2'); + expect(config.getPass()).toEqual('P@ssw0rd2'); + expect(config.getBasicAuthentication()).toBeTruthy(); + expect(config.getGdbTokenAuthentication()).toBeFalsy(); }); test('should allow addition of repository endpoints', () => { - const config = new RepositoryClientConfig(); + const config = new RepositoryClientConfig(endpoint); endpoints.forEach((endpoint) => config.addEndpoint(endpoint)); expect(config.getEndpoints()).toEqual(endpoints); }); diff --git a/test/security/authentication-mocks.js b/test/security/authentication-mocks.js new file mode 100644 index 000000000..d8ce53726 --- /dev/null +++ b/test/security/authentication-mocks.js @@ -0,0 +1,12 @@ +const Authentication = require('security/authentication'); + +/** + * For testing purposes. + */ +class AuthenticationWithNoImplementedMethods extends Authentication { + constructor() { + super({}); + } +} + +module.exports = {AuthenticationWithNoImplementedMethods}; diff --git a/test/security/authentication.spec.js b/test/security/authentication.spec.js new file mode 100644 index 000000000..bc1fdd930 --- /dev/null +++ b/test/security/authentication.spec.js @@ -0,0 +1,39 @@ +const AuthenticationWithNoImplementedMethods = + require('./authentication-mocks').AuthenticationWithNoImplementedMethods; +const AuthenticationFactory = require('security/authentication-factory'); +const ServerClientConfig = require('server/server-client-config'); +const BasicAuthentication = require('security/basic-authentication'); +const GdbTokenAuthentication = require('security/gdb-token-authentication'); + + +describe('Authentication', () => { + test('should throw error if auth methods are not implemented', () => { + const auth = new AuthenticationWithNoImplementedMethods(); + expect(() => { + auth.getLoginRequestBuilder(); + }).toThrow(Error('Method #getLoginRequestBuilder() must be implemented!')); + + expect(() => { + auth.getResponseAuthToken(); + }).toThrow(Error('Method #getResponseAuthToken() must be implemented!')); + }); + + test('should instantiate correct authentication type', () => { + const config = new ServerClientConfig('http://endpoint'); + config.useBasicAuthentication('user, pass'); + const factory = new AuthenticationFactory(); + + expect(factory.getAuthenticationType(config) instanceof BasicAuthentication) + .toBe(true); + + config.useGdbTokenAuthentication('user, pass'); + expect(factory.getAuthenticationType(config) instanceof + GdbTokenAuthentication) + .toBe(true); + + config.disableAuthentication(); + expect(() => { + factory.getAuthenticationType(config); + }).toThrow(Error('Authentication is not configured properly')); + }); +}); diff --git a/test/server/server-client-config.spec.js b/test/server/server-client-config.spec.js index 83168ffa5..5f0ae3e66 100644 --- a/test/server/server-client-config.spec.js +++ b/test/server/server-client-config.spec.js @@ -1,43 +1,60 @@ const ServerClientConfig = require('server/server-client-config'); describe('ServerClientConfig', () => { - test('should initialize with the supplied parameters', () => { - const headers = {'Accept': 'text/plain'}; - let config = new ServerClientConfig('/endpoint', 1000, - headers, 'testuser', 'P@sw0rd'); - expect(config.getEndpoint()).toEqual('/endpoint'); - expect(config.getTimeout()).toEqual(1000); - expect(config.getHeaders()).toEqual(headers); - expect(config.getUsername()).toEqual('testuser'); - expect(config.getPass()).toEqual('P@sw0rd'); - expect(config.getKeepAlive()).toBeTruthy(); + const endpoint = 'http://endpoint'; - config = new ServerClientConfig('/endpoint', 1000, - headers, 'testuser', 'P@sw0rd', false); - expect(config.getKeepAlive()).toBeFalsy(); + test('should initialize with the default parameters', () => { + const config = new ServerClientConfig(endpoint); + + expect(config.getEndpoint()).toEqual(endpoint); + expect(config.getHeaders()).toEqual({}); + expect(config.getTimeout()).toEqual(10000); + expect(config.getUsername()).toEqual(undefined); + expect(config.getPass()).toEqual(undefined); + expect(config.getBasicAuthentication()).toBeFalsy(); + expect(config.getKeepAlive()).toBeTruthy(); }); test('should support initialization via fluent API ', () => { - let headers = {'Accept': 'text/plain'}; - const config = new ServerClientConfig() - .setEndpoint('/endpoint') + const headers = {'Accept': 'text/plain'}; + const config = new ServerClientConfig(endpoint) .setTimeout(1000) .setHeaders(headers) - .setUsername('testuser') - .setPass('P@sw0rd'); - expect(config.getEndpoint()).toEqual('/endpoint'); + .useBasicAuthentication('testuser', 'P@sw0rd'); + expect(config.getEndpoint()).toEqual('http://endpoint'); expect(config.getTimeout()).toEqual(1000); expect(config.getHeaders()).toEqual(headers); expect(config.getUsername()).toEqual('testuser'); expect(config.getPass()).toEqual('P@sw0rd'); + expect(config.getBasicAuthentication()).toBeTruthy(); + expect(config.getGdbTokenAuthentication()).toBeFalsy(); expect(config.getKeepAlive()).toBeTruthy(); config.setKeepAlive(false); expect(config.getKeepAlive()).toBeFalsy(); - headers = {'Accept': 'text/plain', - 'Authorization': 'Basic dGVzdHVzZXI6UEBzdzByZA=='}; - config.setBasicAuthentication(true); - expect(config.getHeaders()).toEqual(headers); + config.useGdbTokenAuthentication('testuser2', 'P@sw0rd2'); + expect(config.getUsername()).toEqual('testuser2'); + expect(config.getPass()).toEqual('P@sw0rd2'); + expect(config.getBasicAuthentication()).toBeFalsy(); + expect(config.getGdbTokenAuthentication()).toBeTruthy(); + }); + + test('should switch and disable authentication', () => { + const config = new ServerClientConfig(endpoint); + expect(config.getBasicAuthentication()).toBeFalsy(); + expect(config.getGdbTokenAuthentication()).toBeFalsy(); + + config.useGdbTokenAuthentication('user', 'pass'); + expect(config.getBasicAuthentication()).toBeFalsy(); + expect(config.getGdbTokenAuthentication()).toBeTruthy(); + + config.useBasicAuthentication('user', 'pass'); + expect(config.getBasicAuthentication()).toBeTruthy(); + expect(config.getGdbTokenAuthentication()).toBeFalsy(); + + config.disableAuthentication(); + expect(config.getBasicAuthentication()).toBeFalsy(); + expect(config.getGdbTokenAuthentication()).toBeFalsy(); }); }); diff --git a/test/server/server-client.spec.js b/test/server/server-client.spec.js index 93cfc99da..0b2f8ee38 100644 --- a/test/server/server-client.spec.js +++ b/test/server/server-client.spec.js @@ -1,7 +1,7 @@ const ServerClient = require('server/server-client'); const ServerClientConfig = require('server/server-client-config'); -const RDFRepositoryClient = require('repository/rdf-repository-client'); const RepositoryClientConfig = require('repository/repository-client-config'); +const RDFRepositoryClient = require('repository/rdf-repository-client'); const HttpRequestBuilder = require('http/http-request-builder'); const RDFMimeType = require('http/rdf-mime-type'); const User = require('auth/user'); @@ -22,9 +22,10 @@ describe('ServerClient', () => { expect(new ServerClient(config)).not.toBeNull(); }); - test('should initialize with the provided server client configuration', () => { + test('should initialize with the provided server client' + + ' configuration', () => { expect(server.config).toEqual(config); - expect(server.config.getEndpoint()).toEqual('server/url'); + expect(server.config.getEndpoint()).toEqual('http://server/url'); }); }); @@ -32,12 +33,13 @@ describe('ServerClient', () => { test('should login and then execute request with auth token', () => { createSecuredClient(); - return server.getRepositoryIDs().then((ids) => { + return server.getRepositoryIDs().then(() => { const requestMock = server.httpClient.request; // expect 2 invocations: first login, second getRepositoryIDs expect(requestMock).toHaveBeenCalledTimes(2); - const expectedLoginRequest = HttpRequestBuilder.httpPost('/rest/login/testuser') + const expectedLoginRequest = HttpRequestBuilder + .httpPost('/rest/login/testuser') .addGraphDBPasswordHeader('pass123'); expect(requestMock).toHaveBeenNthCalledWith(1, expectedLoginRequest); @@ -54,7 +56,7 @@ describe('ServerClient', () => { return server.getRepositoryIDs() .then(() => { return server.getRepositoryIDs(); - }).then((ids) => { + }).then(() => { const requestMock = server.httpClient.request; // expecting 5 invocations: // login @@ -67,7 +69,7 @@ describe('ServerClient', () => { }); test('should not pass auth token if there is no authenticated user', () => { - return server.getRepositoryIDs().then((ids) => { + return server.getRepositoryIDs().then(() => { const expectedRequest = HttpRequestBuilder.httpGet('/repositories') .addAcceptHeader(RDFMimeType.SPARQL_RESULTS_JSON); const requestMock = server.httpClient.request; @@ -78,17 +80,19 @@ describe('ServerClient', () => { test('should maintain logged in User after successful login', () => { createSecuredClient(); - return server.getRepositoryIDs().then((ids) => { + return server.getRepositoryIDs().then(() => { const expectedUser = new User('token123', 'pass123', userdata); - expect(server.authenticationService.getLoggedUser()).toEqual(expectedUser); + expect(server.user).toEqual(expectedUser); }); }); - test('should not perform login if username and password are not provided', () => { - return server.getRepositoryIDs().then((ids) => { + test('should not perform login if username and password are not' + + ' provided', () => { + return server.getRepositoryIDs().then(() => { expect(server.loggedUser).toBeUndefined(); const requestMock = server.httpClient.request; - // expect 1 invocation for the getRepositoryIDs API call but not for the login + // expect 1 invocation for the + // getRepositoryIDs API call but not for the login expect(requestMock).toHaveBeenCalledTimes(1); }); }); @@ -97,9 +101,9 @@ describe('ServerClient', () => { createSecuredClient(); return server.getRepositoryIDs() - .then((ids) => server.logout()) + .then(() => server.logout()) .then(() => { - expect(server.authenticationService.getLoggedUser().getToken()).toBeUndefined(); + expect(server.getLoggedUser().getToken()).toBeUndefined(); }); }); }); @@ -121,7 +125,8 @@ describe('ServerClient', () => { return expect(server.getRepositoryIDs()).resolves.toEqual(expected); }); - test('should resolve with an empty array if no repositories are present', () => { + test('should resolve with an empty array if no repositories are' + + ' present', () => { server.httpClient.request.mockResolvedValue({ data: { results: { @@ -148,39 +153,49 @@ describe('ServerClient', () => { }); test('should reject with error if repository id is not provided', () => { - expect(() => server.hasRepository()).toThrow(Error('Repository id is required parameter!')); + expect(() => server.hasRepository()) + .toThrow(Error('Repository id is required parameter!')); }); test('should reject with error if request fails', () => { server.httpClient.request.mockRejectedValue('Server error'); - return expect(server.hasRepository('automotive')).rejects.toEqual('Server error'); + return expect(server.hasRepository('automotive')) + .rejects.toEqual('Server error'); }); }); describe('getRepository', () => { test('should reject with error if repository id is not provided', () => { - expect(() => server.getRepository()).toThrow(Error('Repository id is required parameter!')); + expect(() => server.getRepository()) + .toThrow(Error('Repository id is required parameter!')); }); test('should reject with error if repository config is not provided', () => { - expect(() => server.getRepository('automotive')).toThrow(Error('RepositoryClientConfig is required parameter!')); + expect(() => server.getRepository('automotive')) + .toThrow(Error('RepositoryClientConfig is required parameter!')); }); test('should reject with error if repository config is not of desired type', () => { - expect(() => server.getRepository('automotive', {})).toThrow(Error('RepositoryClientConfig is required parameter!')); + expect(() => server.getRepository('automotive', {})) + .toThrow(Error('RepositoryClientConfig is required parameter!')); }); - test('should reject with error if repository with provided id does not exists', () => { - const repositoryClientConfig = new RepositoryClientConfig(['endpoint'], {}, '', 3000, 3000); - return expect(server.getRepository('non_existing', repositoryClientConfig)).rejects.toEqual(Error('Repository with id non_existing does not exists.')); + test('should reject with error if repository with provided id does' + + ' not exists', () => { + const config = new RepositoryClientConfig('http://server/url').setEndpoints(['endpoint']); + return expect(server.getRepository('non_existing', config)).rejects + .toEqual(Error('Repository with id non_existing does not exists.')); }); test('should resolve with a RDFRepositoryClient instance if repository with provided id exists', () => { - const repositoryClientConfig = new RepositoryClientConfig().setEndpoints(['endpoint']); - const expected = new RDFRepositoryClient(repositoryClientConfig); - return server.getRepository('automotive', repositoryClientConfig).then((actual) => { - expect(actual.repositoryClientConfig).toEqual(expected.repositoryClientConfig); - }); + const config = new RepositoryClientConfig('http://server/url') + .setEndpoints(['endpoint']); + const expected = new RDFRepositoryClient(config); + return server.getRepository('automotive', config) + .then((actual) => { + expect(actual.repositoryClientConfig) + .toEqual(expected.repositoryClientConfig); + }); }); }); @@ -188,7 +203,8 @@ describe('ServerClient', () => { test('should make request with required parameter', () => { return server.deleteRepository('automotive').then(() => { expect(server.httpClient.request).toHaveBeenCalledTimes(1); - const expectedRequest = HttpRequestBuilder.httpDelete('/repositories/automotive'); + const expectedRequest = HttpRequestBuilder + .httpDelete('/repositories/automotive'); expect(server.httpClient.request).toHaveBeenCalledWith(expectedRequest); }); }); @@ -198,18 +214,19 @@ describe('ServerClient', () => { }); test('should reject with error if repository id is not provided', () => { - expect(() => server.deleteRepository()).toThrow(Error('Repository id is required parameter!')); + expect(() => server.deleteRepository()) + .toThrow(Error('Repository id is required parameter!')); }); test('should reject with an error if request fails', () => { server.httpClient.request.mockRejectedValue('Server error'); - return expect(server.deleteRepository('automotive')).rejects.toEqual('Server error'); + return expect(server.deleteRepository('automotive')).rejects + .toEqual('Server error'); }); }); function createUnsecuredClient() { - config = new TestServerConfig() - .setEndpoint('server/url') + config = new ServerClientConfig('http://server/url') .setTimeout(0) .setHeaders({}); server = new ServerClient(config); @@ -217,12 +234,10 @@ describe('ServerClient', () => { } function createSecuredClient() { - config = new TestServerConfig() - .setEndpoint('server/url') + config = new ServerClientConfig('http://server/url') .setTimeout(0) .setHeaders({}) - .setUsername('testuser') - .setPass('pass123'); + .useGdbTokenAuthentication('testuser', 'pass123'); server = new ServerClient(config); mockClient(); } @@ -233,9 +248,9 @@ describe('ServerClient', () => { server.httpClient.request = jest.fn().mockImplementation((request) => { if (request.getMethod() === 'get') { calls++; - if (server.authenticationService.getLoggedUser() && calls === 2) { + if (server.user && calls === 2) { // emulate token expiration - server.authenticationService.getLoggedUser().clearToken(); + server.logout(); return Promise.reject({ response: { status: 401 @@ -257,9 +272,3 @@ describe('ServerClient', () => { }); } }); - -/** - * Test implementation for the {@link ServerClientConfig} - */ -class TestServerConfig extends ServerClientConfig { -}