1
0
mirror of https://github.com/owncloud/android-library.git synced 2025-06-07 16:06:08 +00:00

make OwnCloudClient extend the warpper HttpClient

This commit is contained in:
theScrabi 2018-06-27 14:25:41 +02:00 committed by davigonz
parent 75905b5f74
commit 6e4ded84d9
10 changed files with 196 additions and 374 deletions

View File

@ -25,6 +25,7 @@
package com.owncloud.android.lib.common; package com.owncloud.android.lib.common;
import android.accounts.Account;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.accounts.AccountsException; import android.accounts.AccountsException;
import android.content.Context; import android.content.Context;
@ -33,26 +34,23 @@ import android.net.Uri;
import com.owncloud.android.lib.common.authentication.OwnCloudCredentials; import com.owncloud.android.lib.common.authentication.OwnCloudCredentials;
import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory; import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory.OwnCloudAnonymousCredentials; import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory.OwnCloudAnonymousCredentials;
import com.owncloud.android.lib.common.http.HttpClient;
import com.owncloud.android.lib.common.http.HttpConstants;
import com.owncloud.android.lib.common.http.methods.HttpBaseMethod; import com.owncloud.android.lib.common.http.methods.HttpBaseMethod;
import com.owncloud.android.lib.common.http.methods.nonwebdav.HttpMethod;
import com.owncloud.android.lib.common.network.RedirectionPath; import com.owncloud.android.lib.common.network.RedirectionPath;
import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.status.OwnCloudVersion; import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.params.HttpParams;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.Headers;
import okhttp3.HttpUrl;
public class OwnCloudClient extends HttpClient { public class OwnCloudClient extends HttpClient {
@ -90,53 +88,11 @@ public class OwnCloudClient extends HttpClient {
*/ */
private OwnCloudClientManager mOwnCloudClientManager = null; private OwnCloudClientManager mOwnCloudClientManager = null;
/**
* When 'true', the method {@link #executeMethod(HttpMethod)} tries to silently refresh credentials
* if fails due to lack of authorization, if credentials support authorization refresh.
*/
private boolean mSilentRefreshOfAccountCredentials = true;
private String mRedirectedLocation; private String mRedirectedLocation;
private boolean mFollowRedirects; private boolean mFollowRedirects;
/**
* Constructor
*/
// public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) {
//
// super(connectionMgr);
//
// if (baseUri == null) {
// throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
// }
// mBaseUri = baseUri;
//
// mInstanceNumber = sIntanceCounter++;
// Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient");
//
// String userAgent = OwnCloudClientManagerFactory.getUserAgent();
// getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
// getParams().setParameter(
// PARAM_PROTOCOL_VERSION,
// HttpVersion.HTTP_1_1
// );
//
// getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
// getParams().setParameter(
// PARAM_SINGLE_COOKIE_HEADER, // to avoid problems with some web servers
// PARAM_SINGLE_COOKIE_HEADER_VALUE
// );
//
// applyProxySettings();
//
// clearCredentials();
// }
public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) {
super(connectionMgr);
public OwnCloudClient(Uri baseUri) {
if (baseUri == null) { if (baseUri == null) {
throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL"); throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
} }
@ -157,25 +113,6 @@ public class OwnCloudClient extends HttpClient {
clearCredentials(); clearCredentials();
} }
private void applyProxySettings() {
String proxyHost = System.getProperty("http.proxyHost");
String proxyPortSt = System.getProperty("http.proxyPort");
int proxyPort = 0;
try {
if (proxyPortSt != null && proxyPortSt.length() > 0) {
proxyPort = Integer.parseInt(proxyPortSt);
}
} catch (Exception e) {
Log_OC.w(TAG, "Proxy port could not be read, keeping default value " + proxyPort);
}
if (proxyHost != null && proxyHost.length() > 0) {
HostConfiguration hostCfg = getHostConfiguration();
hostCfg.setProxy(proxyHost, proxyPort);
Log_OC.d(TAG, "Proxy settings: " + proxyHost + ":" + proxyPort);
}
}
public void setCredentials(OwnCloudCredentials credentials) { public void setCredentials(OwnCloudCredentials credentials) {
if (credentials != null) { if (credentials != null) {
mCredentials = credentials; mCredentials = credentials;
@ -192,91 +129,6 @@ public class OwnCloudClient extends HttpClient {
mCredentials.applyTo(this); mCredentials.applyTo(this);
} }
/**
* Requests the received method with the received timeout (milliseconds).
*
* Executes the method through the inherited HttpClient.executedMethod(method).
*
* Sets the socket and connection timeouts only for the method received.
*
* The timeouts are both in milliseconds; 0 means 'infinite';
* < 0 means 'do not change the default'
*
* @param method HTTP method request.
* @param readTimeout Timeout to set for data reception
* @param connectionTimeout Timeout to set for connection establishment
*/
public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws IOException {
int oldSoTimeout = getParams().getSoTimeout();
int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
try {
if (readTimeout >= 0) {
method.getParams().setSoTimeout(readTimeout); // this should be enough...
getParams().setSoTimeout(readTimeout); // ... but HTTPS needs this
}
if (connectionTimeout >= 0) {
getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
}
return executeMethod(method);
} finally {
getParams().setSoTimeout(oldSoTimeout);
getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
}
}
/**
* Requests the received method.
*
* Executes the method through the inherited HttpClient.executedMethod(method).
*
* @param method HTTP method request.
*/
@Override
public int executeMethod(HttpMethod method) throws IOException {
boolean repeatWithFreshCredentials;
int repeatCounter = 0;
int status;
do {
// Update User Agent
HttpParams params = method.getParams();
String userAgent = OwnCloudClientManagerFactory.getUserAgent();
params.setParameter(HttpMethodParams.USER_AGENT, userAgent);
preventCrashDueToInvalidPort(method);
Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " +
method.getName() + " " + method.getPath());
//logCookiesAtRequest(method.getRequestHeaders(), "before");
//logCookiesAtState("before");
method.setFollowRedirects(false);
status = super.executeMethod(method);
checkFirstRedirection(method);
// TODO
// if (mOkHttpClient.followRedirects()) {
// status = followRedirection(method).getLastStatus();
// }
repeatWithFreshCredentials = checkUnauthorizedAccess(status, repeatCounter);
if (repeatWithFreshCredentials) {
repeatCounter++;
}
} while (repeatWithFreshCredentials);
//logCookiesAtRequest(method.getRequestHeaders(), "after");
//logCookiesAtState("after");
//logSetCookiesAtResponse(method.getResponseHeaders());
return status;
}
public int executeHttpMethod (HttpBaseMethod method) throws Exception { public int executeHttpMethod (HttpBaseMethod method) throws Exception {
boolean repeatWithFreshCredentials; boolean repeatWithFreshCredentials;
@ -297,14 +149,11 @@ public class OwnCloudClient extends HttpClient {
} }
private void checkFirstRedirection(HttpMethod method) { private void checkFirstRedirection(HttpMethod method) {
Header[] httpHeaders = method.getResponseHeaders(); final String location = method.getResponseHeaders()
.get("location");
for (Header httpHeader : httpHeaders) { if(location != null && !location.isEmpty()) {
mRedirectedLocation = location;
if ("location".equals(httpHeader.getName().toLowerCase())) {
mRedirectedLocation = httpHeader.getValue();
break;
}
} }
} }
@ -322,11 +171,10 @@ public class OwnCloudClient extends HttpClient {
* *
* @param method HTTP method to run. * @param method HTTP method to run.
* @throws IllegalArgumentException If 'method' targets an invalid port in an HTTP URI. * @throws IllegalArgumentException If 'method' targets an invalid port in an HTTP URI.
* @throws URIException If the URI to the target server cannot be built.
*/ */
private void preventCrashDueToInvalidPort(HttpMethod method) throws URIException { private void preventCrashDueToInvalidPort(HttpMethod method) {
int port = method.getURI().getPort(); final int port = method.getUrl().port();
String scheme = method.getURI().getScheme().toLowerCase(); String scheme = method.getUrl().scheme().toLowerCase();
if ("http".equals(scheme) && port > 0xFFFF) { if ("http".equals(scheme) && port > 0xFFFF) {
// < 0 is not tested because -1 is used when no port number is specified in the URL; // < 0 is not tested because -1 is used when no port number is specified in the URL;
// no problem, the network library will convert that in the default HTTP port // no problem, the network library will convert that in the default HTTP port
@ -334,57 +182,52 @@ public class OwnCloudClient extends HttpClient {
} }
} }
public RedirectionPath followRedirection(HttpMethod method) throws IOException { public RedirectionPath followRedirection(HttpMethod method) throws Exception {
int redirectionsCount = 0; int redirectionsCount = 0;
int status = method.getStatusCode(); int status = method.getStatusCode();
RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT); RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT);
while (redirectionsCount < MAX_REDIRECTIONS_COUNT && while (redirectionsCount < MAX_REDIRECTIONS_COUNT &&
(status == HttpStatus.SC_MOVED_PERMANENTLY || (status == HttpConstants.HTTP_MOVED_PERMANENTLY ||
status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpConstants.HTTP_MOVED_TEMPORARILY ||
status == HttpStatus.SC_TEMPORARY_REDIRECT) status == HttpConstants.HTTP_TEMPORARY_REDIRECT)
) { ) {
Header location = method.getResponseHeader("Location"); final String location = method.getResponseHeader("Location") != null
if (location == null) { ? method.getResponseHeader("Location")
location = method.getResponseHeader("location"); : method.getResponseHeader("location");
}
if (location != null) { if (location != null) {
String locationStr = location.getValue();
Log_OC.d(TAG + " #" + mInstanceNumber, Log_OC.d(TAG + " #" + mInstanceNumber,
"Location to redirect: " + locationStr); "Location to redirect: " + location);
result.addLocation(locationStr); result.addLocation(location);
// Release the connection to avoid reach the max number of connections per host // Release the connection to avoid reach the max number of connections per host
// due to it will be set a different url // due to it will be set a different url
exhaustResponse(method.getResponseBodyAsStream()); exhaustResponse(method.getResponseAsStream());
method.releaseConnection();
method.setUrl(HttpUrl.parse(location));
final String destination = method.getRequestHeader("Destination") != null
? method.getRequestHeader("Destination")
: method.getRequestHeader("destination");
method.setURI(new URI(locationStr, true));
Header destination = method.getRequestHeader("Destination");
if (destination == null) {
destination = method.getRequestHeader("destination");
}
if (destination != null) { if (destination != null) {
int suffixIndex = locationStr.lastIndexOf(WEBDAV_PATH_4_0); final int suffixIndex = location.lastIndexOf(WEBDAV_PATH_4_0);
String redirectionBase = locationStr.substring(0, suffixIndex); final String redirectionBase = location.substring(0, suffixIndex);
String destinationStr = destination.getValue(); final String destinationPath = destination.substring(mBaseUri.toString().length());
String destinationPath = destinationStr.substring(mBaseUri.toString().length()); final String redirectedDestination = redirectionBase + destinationPath;
String redirectedDestination = redirectionBase + destinationPath;
destination.setValue(redirectedDestination); method.setRequestHeader("destination", destination);
method.setRequestHeader(destination);
} }
status = super.executeMethod(method); status = executeHttpMethod(method);
result.addStatus(status); result.addStatus(status);
redirectionsCount++; redirectionsCount++;
} else { } else {
Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!"); Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
status = HttpStatus.SC_NOT_FOUND; status = HttpConstants.HTTP_NOT_FOUND;
} }
} }
return result; return result;
@ -408,19 +251,6 @@ public class OwnCloudClient extends HttpClient {
} }
} }
/**
* Sets the connection and wait-for-data timeouts to be applied by default to the methods
* performed by this client.
*/
public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
if (defaultDataTimeout >= 0) {
getParams().setSoTimeout(defaultDataTimeout);
}
if (defaultConnectionTimeout >= 0) {
getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
}
}
public Uri getOldFilesWebdavUri() { public Uri getOldFilesWebdavUri() {
return Uri.parse(mBaseUri + WEBDAV_PATH_4_0); return Uri.parse(mBaseUri + WEBDAV_PATH_4_0);
} }
@ -459,81 +289,56 @@ public class OwnCloudClient extends HttpClient {
return mCredentials; return mCredentials;
} }
private void logCookiesAtRequest(Header[] headers, String when) { private void logCookiesAtRequest(Headers headers, String when) {
int counter = 0; int counter = 0;
for (int i = 0; i < headers.length; i++) { for (final String cookieHeader : headers.toMultimap().get("cookie")) {
if (headers[i].getName().toLowerCase().equals("cookie")) { Log_OC.d(TAG + " #" + mInstanceNumber,
Log_OC.d(TAG + " #" + mInstanceNumber, "Cookies at request (" + when + ") (" + counter++ + "): "
"Cookies at request (" + when + ") (" + counter++ + "): " + + cookieHeader);
headers[i].getValue());
}
} }
if (counter == 0) { if (counter == 0) {
Log_OC.d(TAG + " #" + mInstanceNumber, "No cookie at request before"); Log_OC.d(TAG + " #" + mInstanceNumber, "No cookie at request before");
} }
} }
private void logCookiesAtState(String string) { private void logSetCookiesAtResponse(Headers headers) {
Cookie[] cookies = getState().getCookies();
if (cookies.length == 0) {
Log_OC.d(TAG + " #" + mInstanceNumber, "No cookie at STATE before");
} else {
Log_OC.d(TAG + " #" + mInstanceNumber, "Cookies at STATE (before)");
for (int i = 0; i < cookies.length; i++) {
Log_OC.d(TAG + " #" + mInstanceNumber, " (" + i + "):" +
"\n name: " + cookies[i].getName() +
"\n value: " + cookies[i].getValue() +
"\n domain: " + cookies[i].getDomain() +
"\n path: " + cookies[i].getPath()
);
}
}
}
private void logSetCookiesAtResponse(Header[] headers) {
int counter = 0; int counter = 0;
for (int i = 0; i < headers.length; i++) { for (final String cookieHeader : headers.toMultimap().get("set-cookie")) {
if (headers[i].getName().toLowerCase().equals("set-cookie")) { Log_OC.d(TAG + " #" + mInstanceNumber,
Log_OC.d(TAG + " #" + mInstanceNumber, "Set-Cookie (" + counter++ + "): " + cookieHeader);
"Set-Cookie (" + counter++ + "): " + headers[i].getValue());
}
} }
if (counter == 0) { if (counter == 0) {
Log_OC.d(TAG + " #" + mInstanceNumber, "No set-cookie"); Log_OC.d(TAG + " #" + mInstanceNumber, "No set-cookie");
} }
} }
public String getCookiesString() { public List<Cookie> getCookiesFromCurrentAccount() {
Cookie[] cookies = getState().getCookies(); return getOkHttpClient().cookieJar().loadForRequest(HttpUrl.parse(
String cookiesString = ""; getAccount().getBaseUri().toString()));
for (Cookie cookie : cookies) { }
cookiesString = cookiesString + cookie.toString() + ";";
// logCookie(cookie); public String getCookiesString() {
String cookiesString = "";
for (Cookie cookie : getCookiesFromCurrentAccount()) {
cookiesString += cookie.toString() + ";";
} }
return cookiesString; return cookiesString;
} }
public int getConnectionTimeout() { public void setCookiesForCurrentAccount(List<Cookie> cookies) {
return getHttpConnectionManager().getParams().getConnectionTimeout(); getOkHttpClient().cookieJar().saveFromResponse(HttpUrl.parse(
} getAccount().getBaseUri().toString()), cookies);
public int getDataTimeout() {
return getParams().getSoTimeout();
} }
private void logCookie(Cookie cookie) { private void logCookie(Cookie cookie) {
Log_OC.d(TAG, "Cookie name: " + cookie.getName()); Log_OC.d(TAG, "Cookie name: " + cookie.name());
Log_OC.d(TAG, " value: " + cookie.getValue()); Log_OC.d(TAG, " value: " + cookie.value());
Log_OC.d(TAG, " domain: " + cookie.getDomain()); Log_OC.d(TAG, " domain: " + cookie.domain());
Log_OC.d(TAG, " path: " + cookie.getPath()); Log_OC.d(TAG, " path: " + cookie.path());
Log_OC.d(TAG, " version: " + cookie.getVersion()); Log_OC.d(TAG, " expiryDate: " + cookie.expiresAt());
Log_OC.d(TAG, " expiryDate: " + Log_OC.d(TAG, " secure: " + cookie.secure());
(cookie.getExpiryDate() != null ? cookie.getExpiryDate().toString() : "--"));
Log_OC.d(TAG, " comment: " + cookie.getComment());
Log_OC.d(TAG, " secure: " + cookie.getSecure());
} }
@ -545,10 +350,6 @@ public class OwnCloudClient extends HttpClient {
return mVersion; return mVersion;
} }
public void setContext(Context context) {
this.mContext = context;
}
public Context getContext() { public Context getContext() {
return mContext; return mContext;
} }
@ -561,18 +362,6 @@ public class OwnCloudClient extends HttpClient {
return mAccount; return mAccount;
} }
/**
* Enables or disables silent refresh of credentials, if supported by credentials themselves.
*/
public void setSilentRefreshOfAccountCredentials(boolean silentRefreshOfAccountCredentials) {
mSilentRefreshOfAccountCredentials = silentRefreshOfAccountCredentials;
}
public boolean getSilentRefreshOfAccountCredentials() {
return mSilentRefreshOfAccountCredentials;
}
/** /**
* Checks the status code of an execution and decides if should be repeated with fresh credentials. * Checks the status code of an execution and decides if should be repeated with fresh credentials.
* *
@ -632,7 +421,7 @@ public class OwnCloudClient extends HttpClient {
*/ */
private boolean shouldInvalidateAccountCredentials(int httpStatusCode) { private boolean shouldInvalidateAccountCredentials(int httpStatusCode) {
boolean should = (httpStatusCode == HttpStatus.SC_UNAUTHORIZED || isIdPRedirection()); // invalid credentials boolean should = (httpStatusCode == HttpConstants.HTTP_UNAUTHORIZED || isIdPRedirection()); // invalid credentials
should &= (mCredentials != null && // real credentials should &= (mCredentials != null && // real credentials
!(mCredentials instanceof OwnCloudCredentialsFactory.OwnCloudAnonymousCredentials)); !(mCredentials instanceof OwnCloudCredentialsFactory.OwnCloudAnonymousCredentials));

View File

@ -173,7 +173,7 @@ public class OwnCloudClientFactory {
" in the system will be used for HTTPS connections", e); " in the system will be used for HTTPS connections", e);
} }
OwnCloudClient client = new OwnCloudClient(uri, NetworkUtils.getMultiThreadedConnManager()); OwnCloudClient client = new OwnCloudClient(uri);
client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);

View File

@ -115,7 +115,6 @@ public class SingleSessionManager implements OwnCloudClientManager {
account.getBaseUri(), account.getBaseUri(),
context.getApplicationContext(), context.getApplicationContext(),
true); // TODO remove dependency on OwnCloudClientFactory true); // TODO remove dependency on OwnCloudClientFactory
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.setAccount(account); client.setAccount(account);
client.setContext(context); client.setContext(context);
client.setOwnCloudClientManager(this); client.setOwnCloudClientManager(this);

View File

@ -26,8 +26,8 @@
package com.owncloud.android.lib.common.accounts; package com.owncloud.android.lib.common.accounts;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.httpclient.Cookie; import java.util.List;
import android.accounts.Account; import android.accounts.Account;
import android.accounts.AccountManager; import android.accounts.AccountManager;
@ -43,6 +43,8 @@ import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory
import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.status.OwnCloudVersion; import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import okhttp3.Cookie;
public class AccountUtils { public class AccountUtils {
private static final String TAG = AccountUtils.class.getSimpleName(); private static final String TAG = AccountUtils.class.getSimpleName();
@ -217,7 +219,6 @@ public class AccountUtils {
} }
/** /**
* Restore the client cookies persisted in an account stored in the system AccountManager. * Restore the client cookies persisted in an account stored in the system AccountManager.
* *
@ -239,19 +240,18 @@ public class AccountUtils {
String cookiesString = am.getUserData(account, Constants.KEY_COOKIES); String cookiesString = am.getUserData(account, Constants.KEY_COOKIES);
if (cookiesString != null) { if (cookiesString != null) {
String[] cookies = cookiesString.split(";"); String[] rawCookies = cookiesString.split(";");
if (cookies.length > 0) { List<Cookie> cookieList = new ArrayList<>(rawCookies.length);
for (int i = 0; i < cookies.length; i++) { for(String rawCookie : rawCookies) {
Cookie cookie = new Cookie(); final int equalPos = rawCookie.indexOf('=');
int equalPos = cookies[i].indexOf('='); cookieList.add(new Cookie.Builder()
cookie.setName(cookies[i].substring(0, equalPos)); .name(rawCookie.substring(0, equalPos))
cookie.setValue(cookies[i].substring(equalPos + 1)); .value(rawCookie.substring(equalPos + 1))
cookie.setDomain(serverUri.getHost()); // VERY IMPORTANT .domain(serverUri.getHost())
cookie.setPath(serverUri.getPath()); // VERY IMPORTANT .path(serverUri.getPath())
.build());
client.getState().addCookie(cookie);
}
} }
client.setCookiesForCurrentAccount(cookieList);
} }
} }
} }

View File

@ -82,12 +82,6 @@ public class OwnCloudBasicCredentials implements OwnCloudCredentials {
.addRequestInterceptor( .addRequestInterceptor(
new BasicAuthInterceptor(mUsername, mPassword) new BasicAuthInterceptor(mUsername, mPassword)
); );
//TODO Update from here down
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
client.getParams().setAuthenticationPreemptive(mAuthenticationPreemptive);
client.getParams().setCredentialCharset(OwnCloudCredentialsFactory.CREDENTIAL_CHARSET);
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(mUsername, mPassword));
} }
@Override @Override

View File

@ -70,17 +70,6 @@ public class OwnCloudBearerCredentials implements OwnCloudCredentials {
HttpClient.getOkHttpInterceptor() HttpClient.getOkHttpInterceptor()
.addRequestInterceptor(new BarearAuthInterceptor(mAccessToken)); .addRequestInterceptor(new BarearAuthInterceptor(mAccessToken));
List<String> authPrefs = new ArrayList<>(1);
authPrefs.add(BearerAuthScheme.AUTH_POLICY);
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
client.getParams().setAuthenticationPreemptive(true); // true enforces BASIC AUTH ; library is stupid
client.getParams().setCredentialCharset(OwnCloudCredentialsFactory.CREDENTIAL_CHARSET);
client.getState().setCredentials(
AuthScope.ANY,
new BearerCredentials(mAccessToken)
);
} }
@Override @Override

View File

@ -25,6 +25,13 @@
package com.owncloud.android.lib.common.authentication; package com.owncloud.android.lib.common.authentication;
import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.http.HttpClient;
import com.owncloud.android.lib.common.http.interceptors.BarearAuthInterceptor;
import com.owncloud.android.lib.common.http.interceptors.BasicAuthInterceptor;
import com.owncloud.android.lib.common.http.interceptors.HttpInterceptor;
import com.owncloud.android.lib.common.http.interceptors.SamlAuthInterceptor;
import java.util.ArrayList;
public class OwnCloudCredentialsFactory { public class OwnCloudCredentialsFactory {
@ -64,8 +71,16 @@ public class OwnCloudCredentialsFactory {
@Override @Override
public void applyTo(OwnCloudClient client) { public void applyTo(OwnCloudClient client) {
client.getState().clearCredentials(); ArrayList<HttpInterceptor.RequestInterceptor> requestInterceptors = HttpClient.getOkHttpInterceptor().getRequestInterceptors();
client.getState().clearCookies();
// Clear previous basic credentials
for (HttpInterceptor.RequestInterceptor requestInterceptor : requestInterceptors) {
if (requestInterceptor instanceof BasicAuthInterceptor
|| requestInterceptor instanceof BarearAuthInterceptor
|| requestInterceptor instanceof SamlAuthInterceptor) {
requestInterceptors.remove(requestInterceptor);
}
}
} }
@Override @Override

View File

@ -50,10 +50,6 @@ public class OwnCloudSamlSsoCredentials implements OwnCloudCredentials {
@Override @Override
public void applyTo(OwnCloudClient client) { public void applyTo(OwnCloudClient client) {
client.getParams().setAuthenticationPreemptive(false);
client.getParams().setCredentialCharset(OwnCloudCredentialsFactory.CREDENTIAL_CHARSET);
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
final ArrayList<HttpInterceptor.RequestInterceptor> requestInterceptors = final ArrayList<HttpInterceptor.RequestInterceptor> requestInterceptors =
HttpClient.getOkHttpInterceptor().getRequestInterceptors(); HttpClient.getOkHttpInterceptor().getRequestInterceptors();

View File

@ -25,6 +25,7 @@
package com.owncloud.android.lib.common.http; package com.owncloud.android.lib.common.http;
import android.content.Context; import android.content.Context;
import java.util.concurrent.TimeUnit;
import com.facebook.stetho.okhttp3.StethoInterceptor; import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.owncloud.android.lib.BuildConfig; import com.owncloud.android.lib.BuildConfig;
@ -39,9 +40,7 @@ import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
import java.util.Arrays; import java.util.Arrays;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
@ -59,6 +58,10 @@ public class HttpClient {
private static HttpInterceptor sOkHttpInterceptor; private static HttpInterceptor sOkHttpInterceptor;
private static Context sContext; private static Context sContext;
public HttpClient() {
}
public static void setContext(Context context) { public static void setContext(Context context) {
sContext = context; sContext = context;
} }
@ -99,4 +102,21 @@ public class HttpClient {
} }
return sOkHttpInterceptor; return sOkHttpInterceptor;
} }
/**
* Sets the connection and wait-for-data timeouts to be applied by default to the methods
* performed by this client.
*/
public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
OkHttpClient.Builder clientBuilder = getOkHttpClient().newBuilder();
if (defaultDataTimeout >= 0) {
clientBuilder
.readTimeout(defaultDataTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(defaultDataTimeout, TimeUnit.MILLISECONDS);
}
if (defaultConnectionTimeout >= 0) {
clientBuilder.connectTimeout(defaultConnectionTimeout, TimeUnit.MILLISECONDS);
}
sOkHttpClient = clientBuilder.build();
}
} }

View File

@ -60,59 +60,19 @@ public abstract class HttpBaseMethod {
.build(); .build();
} }
// Connection parameters
public void setReadTimeout(long readTimeout, TimeUnit timeUnit) {
mOkHttpClient = mOkHttpClient.newBuilder() public void abort() {
.readTimeout(readTimeout, timeUnit) mCall.cancel();
.build();
} }
public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) { public boolean isAborted() {
mOkHttpClient = mOkHttpClient.newBuilder() return mCall.isCanceled();
.readTimeout(connectionTimeout, timeUnit)
.build();
} }
public void setFollowRedirects(boolean followRedirects) { //////////////////////////////
mOkHttpClient = mOkHttpClient.newBuilder() // Getter
.followRedirects(followRedirects) //////////////////////////////
.build();
}
public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) {
mOkHttpClient = mOkHttpClient.newBuilder()
.retryOnConnectionFailure(retryOnConnectionFailure)
.build();
}
public boolean getRetryOnConnectionFailure() {
return mOkHttpClient.retryOnConnectionFailure();
}
// Request
public String getRequestHeader(String name) {
return mRequest.header(name);
}
public Headers getRequestHeaders() {
return mRequest.headers();
}
public void addRequestHeader(String name, String value) {
mRequest = mRequest.newBuilder()
.addHeader(name, value)
.build();
}
public void setRequestHeader(String name, String value) {
mRequest = mRequest.newBuilder()
.header(name, value)
.build();
}
public void setRequestBody(RequestBody requestBody) {
mRequestBody = requestBody;
}
// Response // Response
public int getStatusCode() { public int getStatusCode() {
@ -139,11 +99,71 @@ public abstract class HttpBaseMethod {
return mResponse.header(headerName); return mResponse.header(headerName);
} }
public void abort() { public HttpUrl getUrl() {
mCall.cancel(); return mRequest.url();
} }
public boolean isAborted() { public boolean getRetryOnConnectionFailure() {
return mCall.isCanceled(); return mOkHttpClient.retryOnConnectionFailure();
}
// Request
public String getRequestHeader(String name) {
return mRequest.header(name);
}
public Headers getRequestHeaders() {
return mRequest.headers();
}
//////////////////////////////
// Setter
//////////////////////////////
// Connection parameters
public void setReadTimeout(long readTimeout, TimeUnit timeUnit) {
mOkHttpClient = mOkHttpClient.newBuilder()
.readTimeout(readTimeout, timeUnit)
.build();
}
public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) {
mOkHttpClient = mOkHttpClient.newBuilder()
.readTimeout(connectionTimeout, timeUnit)
.build();
}
public void setFollowRedirects(boolean followRedirects) {
mOkHttpClient = mOkHttpClient.newBuilder()
.followRedirects(followRedirects)
.build();
}
public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) {
mOkHttpClient = mOkHttpClient.newBuilder()
.retryOnConnectionFailure(retryOnConnectionFailure)
.build();
}
public void addRequestHeader(String name, String value) {
mRequest = mRequest.newBuilder()
.addHeader(name, value)
.build();
}
public void setRequestHeader(String name, String value) {
mRequest = mRequest.newBuilder()
.header(name, value)
.build();
}
public void setRequestBody(RequestBody requestBody) {
mRequestBody = requestBody;
}
public void setUrl(HttpUrl url) {
mRequest = mRequest.newBuilder()
.url(url)
.build();
} }
} }