Package org.wikidata.wdtk.wikibaseapi
Class ApiConnection
java.lang.Object
org.wikidata.wdtk.wikibaseapi.ApiConnection
- Direct Known Subclasses:
BasicApiConnection
,OAuthApiConnection
Class to build up and hold a connection to a Wikibase API.
- Author:
- Michael Guenther, Antonin Delpeuch, Lu Liu
-
Field Summary
Modifier and TypeFieldDescriptionprotected final String
URL to access the Wikibase API.protected static final String
MediaWiki assert parameter to ensure we are editing while logged in.protected int
Maximum time to wait for when establishing a connection, in milliseconds.protected boolean
True after successful login.protected static final String
Name of the HTTP parameter to submit an action to the API.protected static final String
Name of the HTTP parameter to submit the requested result format to the API.protected int
Maximum time to wait for a server response once the connection was established.Map of requested tokens.static final String
URL of the API of test.wikidata.org.static final String
URL of the API of wikidata.org.static final String
URL of the API of commons.wikimedia.org.protected static final okhttp3.MediaType
protected String
User name used to log in. -
Constructor Summary
ConstructorDescriptionApiConnection
(String apiBaseUrl) Creates an object to manage a connection to the Web API of a Wikibase site.ApiConnection
(String apiBaseUrl, Map<String, String> tokens) Creates an object to manage a connection to the Web API of a Wikibase site. -
Method Summary
Modifier and TypeMethodDescriptionvoid
Checks that the credentials are still valid for the user currently logged in.protected void
checkErrors
(com.fasterxml.jackson.databind.JsonNode root) Checks if an API response contains an error and throws a suitable exception in this case.Getter for the apiBaseUrl.protected abstract okhttp3.OkHttpClient.Builder
Subclasses can customize their ownOkHttpClient.Builder
instances.int
Maximum time to wait for when establishing a connection, in milliseconds.Returns the username of the user who is currently logged in.int
Maximum time to wait for a server response once the connection was established.Returns the map of tokens (such as csrf token and login token) currently used in this connection.static String
implodeObjects
(Iterable<?> objects) Builds a string that serializes a list of objects separated by the pipe character.boolean
Returns true if a user is logged in.abstract void
logout()
Logs the current user out.protected void
logWarnings
(com.fasterxml.jackson.databind.JsonNode root) Extracts and logs any warnings that are returned in an API response.com.fasterxml.jackson.databind.JsonNode
sendJsonRequest
(String requestMethod, Map<String, String> parameters) Sends a request to the API with the given parameters and the given request method and returns the result JSON tree.com.fasterxml.jackson.databind.JsonNode
sendJsonRequest
(String requestMethod, Map<String, String> parameters, Map<String, org.apache.commons.lang3.tuple.ImmutablePair<String, File>> files) Sends a request to the API with the given parameters and the given request method and returns the result JSON tree.sendRequest
(String requestMethod, Map<String, String> parameters, Map<String, org.apache.commons.lang3.tuple.ImmutablePair<String, File>> files) Sends a request to the API with the given parameters and the given request method and returns the result string.void
setConnectTimeout
(int timeout) Sets the maximum time to wait for when establishing a connection, in milliseconds.void
setReadTimeout
(int timeout) Sets the maximum time to wait for a server response once the connection was established, in milliseconds.
-
Field Details
-
URL_WIKIDATA_API
URL of the API of wikidata.org.- See Also:
-
URL_TEST_WIKIDATA_API
URL of the API of test.wikidata.org.- See Also:
-
URL_WIKIMEDIA_COMMONS_API
URL of the API of commons.wikimedia.org.- See Also:
-
PARAM_ACTION
Name of the HTTP parameter to submit an action to the API.- See Also:
-
PARAM_FORMAT
Name of the HTTP parameter to submit the requested result format to the API.- See Also:
-
ASSERT_PARAMETER
MediaWiki assert parameter to ensure we are editing while logged in.- See Also:
-
URLENCODED_MEDIA_TYPE
protected static final okhttp3.MediaType URLENCODED_MEDIA_TYPE -
apiBaseUrl
URL to access the Wikibase API. -
loggedIn
protected boolean loggedInTrue after successful login. -
username
User name used to log in. -
tokens
Map of requested tokens. -
connectTimeout
protected int connectTimeoutMaximum time to wait for when establishing a connection, in milliseconds. For negative values, no timeout is set. -
readTimeout
protected int readTimeoutMaximum time to wait for a server response once the connection was established. For negative values, no timeout is set.
-
-
Constructor Details
-
ApiConnection
Creates an object to manage a connection to the Web API of a Wikibase site.- Parameters:
apiBaseUrl
- base URI to the API, e.g., "https://www.wikidata.org/w/api.php/"
-
ApiConnection
Creates an object to manage a connection to the Web API of a Wikibase site.- Parameters:
apiBaseUrl
- base URI to the API, e.g., "https://www.wikidata.org/w/api.php/"tokens
- CSRF tokens already acquired by the connection
-
-
Method Details
-
getClientBuilder
protected abstract okhttp3.OkHttpClient.Builder getClientBuilder()Subclasses can customize their ownOkHttpClient.Builder
instances. An example:return new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.MILLISECONDS) .readTimeout(5, TimeUnit.MILLISECONDS) .cookieJar(...);
-
getApiBaseUrl
Getter for the apiBaseUrl. -
isLoggedIn
public boolean isLoggedIn()Returns true if a user is logged in. This does not perform any request to the server: it just returns our own internal state. To check if our authentication credentials are still considered valid by the remote server, usecheckCredentials()
.- Returns:
- true if the connection is in a logged in state
-
checkCredentials
Checks that the credentials are still valid for the user currently logged in. This can fail if (for instance) the cookies expired, or were invalidated by a logout from a different client. This method queries the APIĀ and throwsAssertUserFailedException
if the check failed. This does not update the state of the connection object. -
getCurrentUser
Returns the username of the user who is currently logged in. If there is no user logged in the result is an empty string.- Returns:
- name of the logged in user
-
getTokens
Returns the map of tokens (such as csrf token and login token) currently used in this connection. -
setConnectTimeout
public void setConnectTimeout(int timeout) Sets the maximum time to wait for when establishing a connection, in milliseconds. For negative values, no timeout is set.- See Also:
-
setReadTimeout
public void setReadTimeout(int timeout) Sets the maximum time to wait for a server response once the connection was established, in milliseconds. For negative values, no timeout is set.- See Also:
-
getConnectTimeout
public int getConnectTimeout()Maximum time to wait for when establishing a connection, in milliseconds. For negative values, no timeout is set, which is the default behaviour (for backwards compatibility).- See Also:
-
getReadTimeout
public int getReadTimeout()Maximum time to wait for a server response once the connection was established. For negative values, no timeout is set, which is the default behaviour (for backwards compatibility).- See Also:
-
logout
Logs the current user out. -
sendJsonRequest
public com.fasterxml.jackson.databind.JsonNode sendJsonRequest(String requestMethod, Map<String, String> parameters) throws IOException, MediaWikiApiErrorExceptionSends a request to the API with the given parameters and the given request method and returns the result JSON tree. It automatically fills the cookie map with cookies in the result header after the request. It logs the request warnings and adds makes sure that "format": "json" parameter is set.- Parameters:
requestMethod
- either POST or GETparameters
- Maps parameter keys to values. Out of this map the function will create a query string for the request.- Returns:
- API result
- Throws:
IOException
MediaWikiApiErrorException
- if the API returns an error
-
sendJsonRequest
public com.fasterxml.jackson.databind.JsonNode sendJsonRequest(String requestMethod, Map<String, String> parameters, Map<String, throws IOException, MediaWikiApiErrorExceptionorg.apache.commons.lang3.tuple.ImmutablePair<String, File>> files) Sends a request to the API with the given parameters and the given request method and returns the result JSON tree. It automatically fills the cookie map with cookies in the result header after the request. It logs the request warnings and adds makes sure that "format": "json" parameter is set.- Parameters:
requestMethod
- either POST or GETparameters
- Maps parameter keys to values. Out of this map the function will create a query string for the request.files
- If GET, this should be null. If POST, this can contain a list of files to upload, indexed by the parameter to pass them with. The first component of the pair is the filename exposed to the server, and the second component is the path to the local file to upload. Set to null or empty map to avoid uploading any file.- Returns:
- API result
- Throws:
IOException
MediaWikiApiErrorException
- if the API returns an error
-
sendRequest
public InputStream sendRequest(String requestMethod, Map<String, String> parameters, Map<String, throws IOExceptionorg.apache.commons.lang3.tuple.ImmutablePair<String, File>> files) Sends a request to the API with the given parameters and the given request method and returns the result string. It automatically fills the cookie map with cookies in the result header after the request. Warning: You probably want to use ApiConnection.sendJsonRequest that execute the request using JSON content format, throws the errors and logs the warnings.- Parameters:
requestMethod
- either POST or GETparameters
- Maps parameter keys to values. Out of this map the function will create a query string for the request.files
- If GET, this should be null. If POST, this can contain a list of files to upload, indexed by the parameter to pass them with. The first component of the pair is the filename exposed to the server, and the second component is the path to the local file to upload. Set to null or empty map to avoid uploading any file.- Returns:
- API result
- Throws:
IOException
-
checkErrors
protected void checkErrors(com.fasterxml.jackson.databind.JsonNode root) throws MediaWikiApiErrorException Checks if an API response contains an error and throws a suitable exception in this case.- Parameters:
root
- root node of the JSON result- Throws:
MediaWikiApiErrorException
-
logWarnings
protected void logWarnings(com.fasterxml.jackson.databind.JsonNode root) Extracts and logs any warnings that are returned in an API response.- Parameters:
root
- root node of the JSON result
-
implodeObjects
Builds a string that serializes a list of objects separated by the pipe character. The toString methods are used to turn objects into strings. This operation is commonly used to build parameter lists for API requests.- Parameters:
objects
- the objects to implode- Returns:
- string of imploded objects
-