Skip to content

Commit

Permalink
Merge pull request #504 from afkbrb/issue-268-update
Browse files Browse the repository at this point in the history
Issue#268 update
  • Loading branch information
wetneb committed Jun 1, 2020
2 parents 5ad13b7 + 869f282 commit 6ce1449
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 55 deletions.
2 changes: 1 addition & 1 deletion wdtk-wikibaseapi/pom.xml
Expand Up @@ -41,7 +41,7 @@
<dependency>
<groupId>se.akerfeldt</groupId>
<artifactId>okhttp-signpost</artifactId>
<version>1.1.0</version>
<version>${okhttpSignpostVersion}</version>
</dependency>

</dependencies>
Expand Down
Expand Up @@ -9,9 +9,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand Down Expand Up @@ -44,7 +44,7 @@
*
*/
public class BasicApiConnection extends ApiConnection {

/**
* Name of the HTTP parameter to submit a password to the API.
*/
Expand All @@ -57,7 +57,7 @@ public class BasicApiConnection extends ApiConnection {
* Name of the HTTP parameter to submit a login token to the API.
*/
protected final static String PARAM_LOGIN_TOKEN = "lgtoken";

/**
* String value in the result field of the JSON response if the login was
* successful.
Expand Down Expand Up @@ -118,7 +118,7 @@ public class BasicApiConnection extends ApiConnection {
* String value in the result field of the JSON response if token is wrong.
*/
protected final static String LOGIN_WRONG_TOKEN = "WrongToken";

/**
* Name of the HTTP parameter to submit cookies to the API.
*/
Expand All @@ -139,7 +139,7 @@ public class BasicApiConnection extends ApiConnection {
* Map of cookies that are currently set.
*/
final Map<String, String> cookies;

/**
* Creates an object to manage a connection to the Web API of a Wikibase
* site.
Expand All @@ -152,10 +152,10 @@ public BasicApiConnection(String apiBaseUrl) {
super(apiBaseUrl);
this.cookies = new HashMap<>();
}

/**
* Deserializes an existing BasicApiConnection from JSON.
*
*
* @param apiBaseUrl
* base URL of the API to use, e.g. "https://www.wikidata.org/w/api.php/"
* @param cookies
Expand All @@ -177,7 +177,7 @@ protected BasicApiConnection(
this.cookies = cookies;
this.loggedIn = loggedIn;
}

/**
* Creates an API connection to test.wikidata.org.
*
Expand All @@ -186,7 +186,7 @@ protected BasicApiConnection(
public static BasicApiConnection getTestWikidataApiConnection() {
return new BasicApiConnection(ApiConnection.URL_TEST_WIKIDATA_API);
}

/**
* Creates an API connection to wikidata.org.
*
Expand All @@ -204,7 +204,7 @@ public static BasicApiConnection getWikidataApiConnection() {
public static BasicApiConnection getWikimediaCommonsApiConnection() {
return new BasicApiConnection(ApiConnection.URL_WIKIMEDIA_COMMONS_API);
}

/**
* Logs in using the specified user credentials. After successful login, the
* API connection remains in a logged in state, and future actions will be
Expand Down Expand Up @@ -232,7 +232,7 @@ public void login(String username, String password)
throw new LoginFailedException(e1.getMessage(), e1);
}
}

/**
* Issues a Web API query to confirm that the previous login attempt was
* successful, and sets the internal state of the API connection accordingly
Expand Down Expand Up @@ -290,15 +290,15 @@ public boolean isLoggedIn() {
public String getCurrentUser() {
return super.getCurrentUser();
}

/**
* Returns the map of cookies currently used in this connection.
*/
@JsonProperty("cookies")
public Map<String, String> getCookies() {
return Collections.unmodifiableMap(this.cookies);
}

/**
* Clears the set of cookies. This will cause a logout.
*
Expand All @@ -308,19 +308,19 @@ public void clearCookies() throws IOException, MediaWikiApiErrorException {
logout();
this.cookies.clear();
}

/**
* Reads out the Set-Cookie Header Fields and fills the cookie map of the
* API connection with it.
*/
void fillCookies(Map<String, List<String>> headerFields) {
List<String> headerCookies = new ArrayList<>();
for (Map.Entry<String, List<String>> headers : headerFields.entrySet()) {
if (HEADER_FIELD_SET_COOKIE.equalsIgnoreCase(headers.getKey())) {
headerCookies.addAll(headers.getValue());
if (HEADER_FIELD_SET_COOKIE.equalsIgnoreCase(headers.getKey())) {
headerCookies.addAll(headers.getValue());
}
}
}
if (!headerCookies.isEmpty()) {
if (!headerCookies.isEmpty()) {
for (String cookie : headerCookies) {
String[] cookieResponse = cookie.split(";\\p{Space}??");
for (String cookieLine : cookieResponse) {
Expand All @@ -335,11 +335,11 @@ void fillCookies(Map<String, List<String>> headerFields) {
}
}
}

/**
* Returns the string representation of the currently stored cookies. This
* data is added to the connection before making requests.
*
*
* @return cookie string
*/
protected String getCookieString() {
Expand All @@ -360,7 +360,7 @@ protected String getCookieString() {
return result.toString();
}


/**
* Returns a user-readable message for a given API response.
*
Expand Down Expand Up @@ -400,7 +400,7 @@ protected String getLoginErrorMessage(String loginResult) {
return "Login Error: " + loginResult;
}
}

/**
* Configures a given {@link HttpURLConnection} object to send requests.
* Takes the request method (either "POST" or "GET") and query string.
Expand All @@ -421,7 +421,7 @@ protected void setupConnection(String requestMethod, String queryString,
connection.setRequestProperty(PARAM_COOKIE,
getCookieString());
}

/**
* Logs the current user out.
*
Expand Down
Expand Up @@ -54,28 +54,13 @@ public class OAuthApiConnection extends ApiConnection {

private OkHttpClient client;

private static final MediaType MEDIA_TYPE = MediaType.parse("application/x-www-form-urlencoded");

/**
* Constructs a plain connection without OAuth functionality to the given MediaWiki API endpoint.
* <p>
* Use this constructor if you will only make anonymous requests which don't require logging in.
* <p>
* {@link OAuthApiConnection#isLoggedIn()} will always return false if using this constructor.
*
* @param apiBaseUrl the MediaWiki API endpoint, such as "https://www.wikidata.org/w/api.php"
*/
public OAuthApiConnection(String apiBaseUrl) {
super(apiBaseUrl);
client = new OkHttpClient.Builder().build();
loggedIn = false;
}
private static final MediaType URLENCODED_MEDIA_TYPE = MediaType.parse("application/x-www-form-urlencoded");

/**
* Constructs an OAuth connection to the given MediaWiki API endpoint.
* <p>
* {@link ApiConnection#isLoggedIn()} will return true
* if this constructor is used and {@link ApiConnection#logout()} hasn't been called.
* until {@link ApiConnection#logout()} is called.
* <p>
* NOTICE: The constructor doesn't check if the OAuth credentials
* (i.e., the consumer key/secret and the access token/secret) are valid.
Expand Down Expand Up @@ -132,7 +117,7 @@ public InputStream sendRequest(String requestMethod, Map<String, String> paramet
if ("GET".equalsIgnoreCase(requestMethod)) {
request = new Request.Builder().url(apiBaseUrl + "?" + queryString).build();
} else if ("POST".equalsIgnoreCase(requestMethod)) {
request = new Request.Builder().url(apiBaseUrl).post(RequestBody.create(MEDIA_TYPE, queryString)).build();
request = new Request.Builder().url(apiBaseUrl).post(RequestBody.create(URLENCODED_MEDIA_TYPE, queryString)).build();
} else {
throw new IllegalArgumentException("Expected the requestMethod to be either GET or POST, but got " + requestMethod);
}
Expand Down Expand Up @@ -244,16 +229,16 @@ public void setReadTimeout(int timeout) {
}

private void updateTimeoutSetting() {
if (!loggedIn) throw new IllegalStateException("Cannot update connection settings after logging out");

// avoid instantiating new objects if possible
if (connectTimeout < 0 && readTimeout < 0) return;

OkHttpClient.Builder builder = new OkHttpClient.Builder();

if (loggedIn) {
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(consumerKey, consumerSecret);
consumer.setTokenWithSecret(accessToken, accessSecret);
builder.addInterceptor(new SigningInterceptor(consumer));
}
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(consumerKey, consumerSecret);
consumer.setTokenWithSecret(accessToken, accessSecret);
builder.addInterceptor(new SigningInterceptor(consumer));

if (connectTimeout >= 0) {
builder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
Expand Down
Expand Up @@ -51,16 +51,16 @@ public class OAuthApiConnectionTest {
private static final String LOGGED_IN_SERIALIZED = "{\"baseUrl\":\"http://kubernetes.docker.internal:55178/w/api.php\",\"consumerKey\":\"consumer_key\",\"consumerSecret\":\"consumer_secret\",\"accessToken\":\"access_token\",\"accessSecret\":\"access_secret\",\"connectTimeout\":-1,\"readTimeout\":-1,\"loggedIn\":true,\"username\":\"foo\"}";

@Test
public void testAnonymousRequest() throws IOException, MediaWikiApiErrorException, InterruptedException {
public void testFetchOnlineData() throws IOException, MediaWikiApiErrorException, InterruptedException {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().addHeader("Content-Type", "application/json; charset=utf-8")
.setBody("{\"entities\":{\"Q8\":{\"pageid\":134,\"ns\":0,\"title\":\"Q8\",\"lastrevid\":1174289176,\"modified\":\"2020-05-05T12:39:07Z\",\"type\":\"item\",\"id\":\"Q8\",\"labels\":{\"fr\":{\"language\":\"fr\",\"value\":\"bonheur\"}},\"descriptions\":{\"fr\":{\"language\":\"fr\",\"value\":\"état émotionnel\"}},\"aliases\":{\"fr\":[{\"language\":\"fr\",\"value\":\":)\"},{\"language\":\"fr\",\"value\":\"\uD83D\uDE04\"},{\"language\":\"fr\",\"value\":\"\uD83D\uDE03\"}]},\"sitelinks\":{\"enwiki\":{\"site\":\"enwiki\",\"title\":\"Happiness\",\"badges\":[]}}}},\"success\":1}"));
server.start();
HttpUrl apiBaseUrl = server.url("/w/api.php");
// We don't need to login here.
ApiConnection connection = new OAuthApiConnection(apiBaseUrl.toString());
assertFalse(connection.isLoggedIn());
assertEquals("", connection.getCurrentUser());
ApiConnection connection = new OAuthApiConnection(apiBaseUrl.toString(),
CONSUMER_KEY, CONSUMER_SECRET,
ACCESS_TOKEN, ACCESS_SECRET);
assertTrue(connection.isLoggedIn());

// We can still fetch unprotected data without logging in.
WikibaseDataFetcher wbdf = new WikibaseDataFetcher(connection, Datamodel.SITE_WIKIDATA);
Expand All @@ -81,7 +81,7 @@ public void testAnonymousRequest() throws IOException, MediaWikiApiErrorExceptio
"and its English Wikipedia page has the title Happiness.", result);

RecordedRequest request = server.takeRequest();
assertNull(request.getHeader("Authorization"));
assertNotNull(request.getHeader("Authorization"));

server.shutdown();
}
Expand Down Expand Up @@ -186,7 +186,9 @@ public void testConnectionTimeout() {

@Test
public void testReadTimeout() {
ApiConnection connection = new OAuthApiConnection(ApiConnection.URL_WIKIDATA_API);
ApiConnection connection = new OAuthApiConnection(ApiConnection.URL_WIKIDATA_API,
CONSUMER_KEY, CONSUMER_SECRET,
ACCESS_TOKEN, ACCESS_SECRET);
connection.setReadTimeout(2000);
assertEquals(-1, connection.getConnectTimeout());
assertEquals(2000, connection.getReadTimeout());
Expand Down

0 comments on commit 6ce1449

Please sign in to comment.