Class ApiConnection

java.lang.Object
org.wikidata.wdtk.wikibaseapi.ApiConnection
Direct Known Subclasses:
BasicApiConnection, OAuthApiConnection

public abstract class ApiConnection extends Object
Class to build up and hold a connection to a Wikibase API.
Author:
Michael Guenther, Antonin Delpeuch, Lu Liu
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    protected 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.
    protected final Map<String,String>
    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

    Constructors
    Constructor
    Description
    ApiConnection(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 Type
    Method
    Description
    void
    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 own OkHttpClient.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
    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
    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.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • URL_WIKIDATA_API

      public static final String URL_WIKIDATA_API
      URL of the API of wikidata.org.
      See Also:
    • URL_TEST_WIKIDATA_API

      public static final String URL_TEST_WIKIDATA_API
      URL of the API of test.wikidata.org.
      See Also:
    • URL_WIKIMEDIA_COMMONS_API

      public static final String URL_WIKIMEDIA_COMMONS_API
      URL of the API of commons.wikimedia.org.
      See Also:
    • PARAM_ACTION

      protected static final String PARAM_ACTION
      Name of the HTTP parameter to submit an action to the API.
      See Also:
    • PARAM_FORMAT

      protected static final String PARAM_FORMAT
      Name of the HTTP parameter to submit the requested result format to the API.
      See Also:
    • ASSERT_PARAMETER

      protected static final String 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

      protected final String apiBaseUrl
      URL to access the Wikibase API.
    • loggedIn

      protected boolean loggedIn
      True after successful login.
    • username

      protected String username
      User name used to log in.
    • tokens

      protected final Map<String,String> tokens
      Map of requested tokens.
    • connectTimeout

      protected int connectTimeout
      Maximum time to wait for when establishing a connection, in milliseconds. For negative values, no timeout is set.
    • readTimeout

      protected int readTimeout
      Maximum time to wait for a server response once the connection was established. For negative values, no timeout is set.
  • Constructor Details

    • ApiConnection

      public ApiConnection(String apiBaseUrl)
      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

      public ApiConnection(String apiBaseUrl, Map<String,String> tokens)
      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 own OkHttpClient.Builder instances. An example:
                  return new OkHttpClient.Builder()
                              .connectTimeout(5, TimeUnit.MILLISECONDS)
                              .readTimeout(5, TimeUnit.MILLISECONDS)
                              .cookieJar(...);
       
    • getApiBaseUrl

      public String 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, use checkCredentials().
      Returns:
      true if the connection is in a logged in state
    • checkCredentials

      public void checkCredentials() throws IOException, MediaWikiApiErrorException
      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 throws AssertUserFailedException if the check failed. This does not update the state of the connection object.
      Throws:
      MediaWikiApiErrorException
      IOException
    • getCurrentUser

      public String 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

      public Map<String,String> 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

      public abstract void logout() throws IOException, MediaWikiApiErrorException
      Logs the current user out.
      Throws:
      IOException
      MediaWikiApiErrorException
    • sendJsonRequest

      public com.fasterxml.jackson.databind.JsonNode sendJsonRequest(String requestMethod, Map<String,String> parameters) throws IOException, MediaWikiApiErrorException
      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 GET
      parameters - 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,org.apache.commons.lang3.tuple.ImmutablePair<String,File>> files) throws IOException, MediaWikiApiErrorException
      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 GET
      parameters - 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,org.apache.commons.lang3.tuple.ImmutablePair<String,File>> files) throws IOException
      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 GET
      parameters - 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

      public static String implodeObjects(Iterable<?> objects)
      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