1
0
mirror of https://github.com/owncloud/android-library.git synced 2026-08-13 17:32:56 +00:00

Replace log_oc with timber

Finish replacing logOC with timber
This commit is contained in:
Abel García de Prada
2020-01-08 09:27:37 +01:00
parent 2778762217
commit c5ac449fed
41 changed files with 212 additions and 759 deletions
@@ -26,8 +26,7 @@ public class DynamicSessionManager implements OwnCloudClientManager {
@Override
public OwnCloudClient getClientFor(OwnCloudAccount account, Context context)
throws AccountUtils.AccountNotFoundException,
OperationCanceledException, AuthenticatorException, IOException {
throws OperationCanceledException, AuthenticatorException, IOException {
OwnCloudVersion ownCloudVersion = null;
if (account.getSavedAccount() != null) {
@@ -38,12 +38,11 @@ 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.network.RedirectionPath;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.common.utils.RandomUtils;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import okhttp3.Cookie;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import timber.log.Timber;
import java.io.IOException;
import java.io.InputStream;
@@ -58,7 +57,6 @@ public class OwnCloudClient extends HttpClient {
public static final String STATUS_PATH = "/status.php";
public static final String FILES_WEB_PATH = "/index.php/apps/files";
private static final String TAG = OwnCloudClient.class.getSimpleName();
private static final int MAX_REDIRECTIONS_COUNT = 3;
private static final int MAX_REPEAT_COUNT_WITH_FRESH_CREDENTIALS = 1;
@@ -86,7 +84,7 @@ public class OwnCloudClient extends HttpClient {
mBaseUri = baseUri;
mInstanceNumber = sIntanceCounter++;
Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient");
Timber.d(" #" + mInstanceNumber + "Creating OwnCloudClient");
clearCredentials();
clearCookies();
@@ -163,7 +161,7 @@ public class OwnCloudClient extends HttpClient {
// Header to allow tracing requests in apache and ownCloud logs
addHeaderForAllRequests(OC_X_REQUEST_ID, requestId);
Log_OC.d(TAG, "Executing " + method.getClass().getSimpleName() + " in request with id " + requestId);
Timber.d("Executing " + method.getClass().getSimpleName() + " in request with id " + requestId);
}
public RedirectionPath followRedirection(HttpBaseMethod method) throws Exception {
@@ -175,15 +173,14 @@ public class OwnCloudClient extends HttpClient {
(status == HttpConstants.HTTP_MOVED_PERMANENTLY ||
status == HttpConstants.HTTP_MOVED_TEMPORARILY ||
status == HttpConstants.HTTP_TEMPORARY_REDIRECT)
) {
) {
final String location = method.getResponseHeader(HttpConstants.LOCATION_HEADER) != null
? method.getResponseHeader(HttpConstants.LOCATION_HEADER)
: method.getResponseHeader(HttpConstants.LOCATION_HEADER_LOWER);
if (location != null) {
Log_OC.d(TAG + " #" + mInstanceNumber,
"Location to redirect: " + location);
Timber.d("#" + mInstanceNumber + "Location to redirect: " + location);
redirectionPath.addLocation(location);
@@ -216,7 +213,7 @@ public class OwnCloudClient extends HttpClient {
redirectionsCount++;
} else {
Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
Timber.d(" #" + mInstanceNumber + "No location to redirect!");
status = HttpConstants.HTTP_NOT_FOUND;
}
}
@@ -237,8 +234,7 @@ public class OwnCloudClient extends HttpClient {
responseBodyAsStream.close();
} catch (IOException io) {
Log_OC.e(TAG, "Unexpected exception while exhausting not interesting HTTP response;" +
" will be IGNORED", io);
Timber.e(io, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED");
}
}
}
@@ -296,38 +292,6 @@ public class OwnCloudClient extends HttpClient {
}
}
private void logCookie(Cookie cookie) {
Log_OC.d(TAG, "Cookie name: " + cookie.name());
Log_OC.d(TAG, " value: " + cookie.value());
Log_OC.d(TAG, " domain: " + cookie.domain());
Log_OC.d(TAG, " path: " + cookie.path());
Log_OC.d(TAG, " expiryDate: " + cookie.expiresAt());
Log_OC.d(TAG, " secure: " + cookie.secure());
}
private void logCookiesAtRequest(Headers headers, String when) {
int counter = 0;
for (final String cookieHeader : headers.toMultimap().get("cookie")) {
Log_OC.d(TAG + " #" + mInstanceNumber,
"Cookies at request (" + when + ") (" + counter++ + "): "
+ cookieHeader);
}
if (counter == 0) {
Log_OC.d(TAG + " #" + mInstanceNumber, "No cookie at request before");
}
}
private void logSetCookiesAtResponse(Headers headers) {
int counter = 0;
for (final String cookieHeader : headers.toMultimap().get("set-cookie")) {
Log_OC.d(TAG + " #" + mInstanceNumber,
"Set-Cookie (" + counter++ + "): " + cookieHeader);
}
if (counter == 0) {
Log_OC.d(TAG + " #" + mInstanceNumber, "No set-cookie");
}
}
public String getCookiesString() {
StringBuilder cookiesString = new StringBuilder();
List<Cookie> cookieList = getCookiesFromUrl(HttpUrl.parse(mBaseUri.toString()));
@@ -392,11 +356,7 @@ public class OwnCloudClient extends HttpClient {
credentialsWereRefreshed = true;
} catch (AccountsException | IOException e) {
Log_OC.e(
TAG,
"Error while trying to refresh auth token for " + mAccount.getSavedAccount().name,
e
);
Timber.e(e, "Error while trying to refresh auth token for %s", mAccount.getSavedAccount().name);
}
}
@@ -451,10 +411,6 @@ public class OwnCloudClient extends HttpClient {
return true;
}
public OwnCloudClientManager getOwnCloudClientManager() {
return mOwnCloudClientManager;
}
void setOwnCloudClientManager(OwnCloudClientManager clientManager) {
mOwnCloudClientManager = clientManager;
}
@@ -29,8 +29,6 @@ import android.net.Uri;
public class OwnCloudClientFactory {
final private static String TAG = OwnCloudClientFactory.class.getSimpleName();
/**
* Creates a OwnCloudClient to access a URL and sets the desired parameters for ownCloud
* client connections.
@@ -49,4 +47,4 @@ public class OwnCloudClientFactory {
return client;
}
}
}
@@ -29,31 +29,25 @@ import android.accounts.OperationCanceledException;
import android.content.Context;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.utils.Log_OC;
import timber.log.Timber;
import java.io.IOException;
public class SimpleFactoryManager implements OwnCloudClientManager {
private static final String TAG = SimpleFactoryManager.class.getSimpleName();
@Override
public OwnCloudClient getClientFor(OwnCloudAccount account, Context context) throws
OperationCanceledException, AuthenticatorException, IOException {
Log_OC.d(TAG, "getClientFor(OwnCloudAccount ... : ");
Timber.d("getClientFor(OwnCloudAccount ... : ");
OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(
account.getBaseUri(),
context.getApplicationContext(),
true);
Log_OC.v(TAG, " new client {" +
(account.getName() != null ?
account.getName() :
AccountUtils.buildAccountName(account.getBaseUri(), "")
) + ", " + client.hashCode() + "}");
Timber.v(" new client {" + (account.getName() != null ? account.getName() :
AccountUtils.buildAccountName(account.getBaseUri(), "")) + ", " + client.hashCode() + "}");
if (account.getCredentials() == null) {
account.loadCredentials(context);
@@ -75,5 +69,4 @@ public class SimpleFactoryManager implements OwnCloudClientManager {
public void saveAllClients(Context context, String accountType) {
// nothing to do - not taking care of tracking instances!
}
}
@@ -30,11 +30,10 @@ import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.http.HttpClient;
import com.owncloud.android.lib.common.utils.Log_OC;
import timber.log.Timber;
import java.io.IOException;
import java.util.Iterator;
@@ -54,8 +53,6 @@ import java.util.concurrent.ConcurrentMap;
public class SingleSessionManager implements OwnCloudClientManager {
private static final String TAG = SingleSessionManager.class.getSimpleName();
private ConcurrentMap<String, OwnCloudClient> mClientsWithKnownUsername = new ConcurrentHashMap<>();
private ConcurrentMap<String, OwnCloudClient> mClientsWithUnknownUsername = new ConcurrentHashMap<>();
@@ -64,9 +61,7 @@ public class SingleSessionManager implements OwnCloudClientManager {
public OwnCloudClient getClientFor(OwnCloudAccount account, Context context) throws OperationCanceledException,
AuthenticatorException, IOException {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log_OC.d(TAG, "getClientFor starting ");
}
Timber.d("getClientFor starting ");
if (account == null) {
throw new IllegalArgumentException("Cannot get an OwnCloudClient for a null account");
}
@@ -84,21 +79,16 @@ public class SingleSessionManager implements OwnCloudClientManager {
if (accountName != null) {
client = mClientsWithUnknownUsername.remove(sessionName);
if (client != null) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log_OC.v(TAG, "reusing client for session " + sessionName);
}
Timber.v("reusing client for session %s", sessionName);
mClientsWithKnownUsername.put(accountName, client);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log_OC.v(TAG, "moved client to account " + accountName);
}
Timber.v("moved client to account %s", accountName);
}
} else {
client = mClientsWithUnknownUsername.get(sessionName);
}
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log_OC.v(TAG, "reusing client for account " + accountName);
}
Timber.v("reusing client for account %s", accountName);
reusingKnown = true;
}
@@ -117,37 +107,28 @@ public class SingleSessionManager implements OwnCloudClientManager {
if (accountName != null) {
mClientsWithKnownUsername.put(accountName, client);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log_OC.v(TAG, "new client for account " + accountName);
}
Timber.v("new client for account %s", accountName);
} else {
mClientsWithUnknownUsername.put(sessionName, client);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log_OC.v(TAG, "new client for session " + sessionName);
}
Timber.v("new client for session %s", sessionName);
}
} else {
if (!reusingKnown && Log.isLoggable(TAG, Log.VERBOSE)) {
Log_OC.v(TAG, "reusing client for session " + sessionName);
if (!reusingKnown) {
Timber.v("reusing client for session %s", sessionName);
}
keepCredentialsUpdated(client);
keepCookiesUpdated(context, account, client);
keepUriUpdated(account, client);
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log_OC.d(TAG, "getClientFor finishing ");
}
Timber.d("getClientFor finishing ");
return client;
}
@Override
public OwnCloudClient removeClientFor(OwnCloudAccount account) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log_OC.d(TAG, "removeClientFor starting ");
}
Timber.d("removeClientFor starting ");
if (account == null) {
return null;
@@ -158,31 +139,22 @@ public class SingleSessionManager implements OwnCloudClientManager {
if (accountName != null) {
client = mClientsWithKnownUsername.remove(accountName);
if (client != null) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log_OC.v(TAG, "Removed client for account " + accountName);
}
Timber.v("Removed client for account %s", accountName);
return client;
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log_OC.v(TAG, "No client tracked for account " + accountName);
}
Timber.v("No client tracked for account %s", accountName);
}
}
mClientsWithUnknownUsername.clear();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log_OC.d(TAG, "removeClientFor finishing ");
}
Timber.d("removeClientFor finishing ");
return null;
}
@Override
public void saveAllClients(Context context, String accountType) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log_OC.d(TAG, "Saving sessions... ");
}
Timber.d("Saving sessions... ");
Iterator<String> accountNames = mClientsWithKnownUsername.keySet().iterator();
String accountName;
@@ -193,9 +165,7 @@ public class SingleSessionManager implements OwnCloudClientManager {
AccountUtils.saveClient(mClientsWithKnownUsername.get(accountName), account, context);
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log_OC.d(TAG, "All sessions saved");
}
Timber.d("All sessions saved");
}
private void keepCredentialsUpdated(OwnCloudClient reusedClient) {
@@ -36,10 +36,10 @@ import android.net.Uri;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.authentication.OwnCloudCredentials;
import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import okhttp3.Cookie;
import timber.log.Timber;
import java.io.IOException;
import java.util.ArrayList;
@@ -47,8 +47,6 @@ import java.util.List;
public class AccountUtils {
private static final String TAG = AccountUtils.class.getSimpleName();
/**
* Constructs full url to host and webdav resource basing on host version
*
@@ -104,7 +102,7 @@ public class AccountUtils {
try {
username = account.name.substring(0, account.name.lastIndexOf('@'));
} catch (Exception e) {
Log_OC.e(TAG, "Couldn't get a username for the given account", e);
Timber.e(e, "Couldn't get a username for the given account");
}
return username;
}
@@ -124,7 +122,7 @@ public class AccountUtils {
version = new OwnCloudVersion(versionString);
} catch (Exception e) {
Log_OC.e(TAG, "Couldn't get a the server version for an account", e);
Timber.e(e, "Couldn't get a the server version for an account");
}
return version;
}
@@ -216,7 +214,7 @@ public class AccountUtils {
String cookiesString = client.getCookiesString();
if (!"".equals(cookiesString)) {
ac.setUserData(savedAccount, Constants.KEY_COOKIES, cookiesString);
Log_OC.d(TAG, "Saving Cookies: " + cookiesString);
Timber.d("Saving Cookies: %s", cookiesString);
}
}
}
@@ -230,10 +228,10 @@ public class AccountUtils {
*/
public static void restoreCookies(Account account, OwnCloudClient client, Context context) {
if (account == null) {
Log_OC.d(TAG, "Cannot restore cookie for null account");
Timber.d("Cannot restore cookie for null account");
} else {
Log_OC.d(TAG, "Restoring cookies for " + account.name);
Timber.d("Restoring cookies for %s", account.name);
// Account Manager
AccountManager am = AccountManager.get(context.getApplicationContext());
@@ -26,7 +26,7 @@
package com.owncloud.android.lib.common.authentication.oauth;
import com.owncloud.android.lib.common.utils.Log_OC;
import timber.log.Timber;
import java.util.HashMap;
import java.util.Map;
@@ -61,7 +61,7 @@ public class OAuth2QueryParser {
mOAuth2ParsedAuthorizationResponse.put(key, value);
}
Log_OC.v(TAG, "[" + i + "," + j + "] = " + p);
Timber.v("[" + i + "," + j + "] = " + p);
j++;
}
i++;
@@ -30,17 +30,16 @@ import com.owncloud.android.lib.common.http.methods.nonwebdav.PostMethod;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
import com.owncloud.android.lib.common.utils.Log_OC;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import org.json.JSONObject;
import timber.log.Timber;
import java.net.URL;
import java.util.Map;
public class OAuth2RefreshAccessTokenOperation extends RemoteOperation<Map<String, String>> {
private static final String TAG = OAuth2RefreshAccessTokenOperation.class.getSimpleName();
private final String mAccessTokenEndpointPath;
private final OAuth2ResponseParser mResponseParser;
private String mClientId;
@@ -96,7 +95,7 @@ public class OAuth2RefreshAccessTokenOperation extends RemoteOperation<Map<Strin
switchClientCredentials(oldCredentials);
final String responseData = postMethod.getResponseBodyAsString();
Log_OC.d(TAG, "OAUTH2: raw response from POST TOKEN: " + responseData);
Timber.d("OAUTH2: raw response from POST TOKEN: %s", responseData);
if (responseData != null && responseData.length() > 0) {
final JSONObject tokenJson = new JSONObject(responseData);
@@ -26,7 +26,7 @@
package com.owncloud.android.lib.common.authentication.oauth;
import com.owncloud.android.lib.common.utils.Log_OC;
import timber.log.Timber;
public class OwnCloudOAuth2Provider implements OAuth2Provider {
@@ -72,7 +72,7 @@ public class OwnCloudOAuth2Provider implements OAuth2Provider {
public void setAccessTokenEndpointPath(String accessTokenEndpointPath) {
if (accessTokenEndpointPath == null || accessTokenEndpointPath.length() <= 0) {
Log_OC.w(NAME, "Setting invalid access token endpoint path, going on with default");
Timber.w("Setting invalid access token endpoint path, going on with default");
mAccessTokenEndpointPath = ACCESS_TOKEN_ENDPOINT_PATH;
} else {
mAccessTokenEndpointPath = accessTokenEndpointPath;
@@ -85,7 +85,7 @@ public class OwnCloudOAuth2Provider implements OAuth2Provider {
public void setAuthorizationCodeEndpointPath(String authorizationCodeEndpointPath) {
if (authorizationCodeEndpointPath == null || authorizationCodeEndpointPath.length() <= 0) {
Log_OC.w(NAME, "Setting invalid authorization code endpoint path, going on with default");
Timber.w("Setting invalid authorization code endpoint path, going on with default");
mAuthorizationCodeEndpointPath = AUTHORIZATION_CODE_ENDPOINT_PATH;
} else {
mAuthorizationCodeEndpointPath = authorizationCodeEndpointPath;
@@ -31,12 +31,12 @@ import com.owncloud.android.lib.common.http.interceptors.HttpInterceptor;
import com.owncloud.android.lib.common.http.interceptors.RequestHeaderInterceptor;
import com.owncloud.android.lib.common.network.AdvancedX509TrustManager;
import com.owncloud.android.lib.common.network.NetworkUtils;
import com.owncloud.android.lib.common.utils.Log_OC;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import timber.log.Timber;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
@@ -57,8 +57,6 @@ import java.util.concurrent.TimeUnit;
* @author David González Verdugo
*/
public class HttpClient {
private static final String TAG = HttpClient.class.toString();
private static OkHttpClient sOkHttpClient;
private static HttpInterceptor sOkHttpInterceptor;
private static Context sContext;
@@ -76,10 +74,10 @@ public class HttpClient {
sslContext = SSLContext.getInstance("TLSv1.2");
} catch (NoSuchAlgorithmException tlsv12Exception) {
try {
Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.1");
Timber.w("TLSv1.2 is not supported in this device; falling through TLSv1.1");
sslContext = SSLContext.getInstance("TLSv1.1");
} catch (NoSuchAlgorithmException tlsv11Exception) {
Log_OC.w(TAG, "TLSv1.1 is not supported in this device; falling through TLSv1.0");
Timber.w("TLSv1.1 is not supported in this device; falling through TLSv1.0");
sslContext = SSLContext.getInstance("TLSv1");
// should be available in any device; see reference of supported protocols in
// http://developer.android.com/reference/javax/net/ssl/SSLSocket.html
@@ -97,10 +95,8 @@ public class HttpClient {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
// Avoid duplicated cookies
Set<Cookie> nonDuplicatedCookiesSet = new HashSet<>();
nonDuplicatedCookiesSet.addAll(cookies);
List<Cookie> nonDuplicatedCookiesList = new ArrayList<>();
nonDuplicatedCookiesList.addAll(nonDuplicatedCookiesSet);
Set<Cookie> nonDuplicatedCookiesSet = new HashSet<>(cookies);
List<Cookie> nonDuplicatedCookiesList = new ArrayList<>(nonDuplicatedCookiesSet);
sCookieStore.put(url.host(), nonDuplicatedCookiesList);
}
@@ -127,7 +123,7 @@ public class HttpClient {
sOkHttpClient = clientBuilder.build();
} catch (Exception e) {
Log_OC.e(TAG, "Could not setup SSL system.", e);
Timber.e(e, "Could not setup SSL system.");
}
}
return sOkHttpClient;
@@ -171,22 +167,6 @@ public class HttpClient {
sContext = context;
}
public void disableAutomaticCookiesHandling() {
OkHttpClient.Builder clientBuilder = getOkHttpClient().newBuilder();
clientBuilder.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
// DO NOTHING
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
return new ArrayList<>();
}
});
sOkHttpClient = clientBuilder.build();
}
public List<Cookie> getCookiesFromUrl(HttpUrl httpUrl) {
return sCookieStore.get(httpUrl.host());
}
@@ -194,4 +174,4 @@ public class HttpClient {
public void clearCookies() {
sCookieStore.clear();
}
}
}
@@ -24,7 +24,7 @@
package com.owncloud.android.lib.common.network;
import com.owncloud.android.lib.common.utils.Log_OC;
import timber.log.Timber;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
@@ -136,7 +136,7 @@ public class AdvancedX509TrustManager implements X509TrustManager {
try {
return (mKnownServersKeyStore.getCertificateAlias(cert) != null);
} catch (KeyStoreException e) {
Log_OC.d(TAG, "Fail while checking certificate in the known-servers store");
Timber.e(e, "Fail while checking certificate in the known-servers store");
return false;
}
}
@@ -24,9 +24,9 @@
package com.owncloud.android.lib.common.network;
import com.owncloud.android.lib.common.utils.Log_OC;
import okhttp3.MediaType;
import okio.BufferedSink;
import timber.log.Timber;
import java.io.File;
import java.io.IOException;
@@ -84,17 +84,17 @@ public class ChunkFromFileRequestBody extends FileRequestBody {
long maxCount = Math.min(mOffset + mChunkSize, mChannel.size());
while (mChannel.position() < maxCount) {
Log_OC.v("Sink buffer size: " + sink.buffer().size());
Timber.v("Sink buffer size: %s", sink.buffer().size());
readCount = mChannel.read(mBuffer);
Log_OC.v("Read " + readCount + " bytes from file channel to " + mBuffer.toString());
Timber.v("Read " + readCount + " bytes from file channel to " + mBuffer.toString());
sink.buffer().write(mBuffer.array(), 0, readCount);
sink.flush();
Log_OC.v("Write " + readCount + " bytes to sink buffer with size " + sink.buffer().size());
Timber.v("Write " + readCount + " bytes to sink buffer with size " + sink.buffer().size());
mBuffer.clear();
if (mTransferred < maxCount) { // condition to avoid accumulate progress for repeated chunks
@@ -108,10 +108,10 @@ public class ChunkFromFileRequestBody extends FileRequestBody {
}
}
Log_OC.v("Chunk with size " + mChunkSize + " written in request body");
Timber.v("Chunk with size " + mChunkSize + " written in request body");
} catch (Exception exception) {
Log_OC.e(exception.getMessage());
Timber.e(exception);
}
}
@@ -26,8 +26,7 @@ package com.owncloud.android.lib.common.network;
import android.content.Context;
import com.owncloud.android.lib.common.utils.Log_OC;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import timber.log.Timber;
import java.io.File;
import java.io.FileInputStream;
@@ -42,25 +41,6 @@ import java.security.cert.CertificateException;
public class NetworkUtils {
/**
* Default timeout for waiting data from the server
*/
public static final int DEFAULT_DATA_TIMEOUT = 60000;
/**
* Default timeout for establishing a connection
*/
public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
/**
* Standard name for protocol TLS version 1.2 in Java Secure Socket Extension (JSSE) API
*/
public static final String PROTOCOL_TLSv1_2 = "TLSv1.2";
/**
* Standard name for protocol TLS version 1.0 in JSSE API
*/
public static final String PROTOCOL_TLSv1_0 = "TLSv1";
final private static String TAG = NetworkUtils.class.getSimpleName();
private static X509HostnameVerifier mHostnameVerifier = null;
private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
@@ -88,7 +68,7 @@ public class NetworkUtils {
//mKnownServersStore = KeyStore.getInstance("BKS");
mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
Timber.d("Searching known-servers store at %s", localTrustStoreFile.getAbsolutePath());
if (localTrustStoreFile.exists()) {
InputStream in = new FileInputStream(localTrustStoreFile);
try {
@@ -109,22 +89,9 @@ public class NetworkUtils {
KeyStore knownServers = getKnownServersStore(context);
knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
FileOutputStream fos = null;
try {
fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
try (FileOutputStream fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE)) {
knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
} finally {
fos.close();
}
}
public static boolean isCertInKnownServersStore(Certificate cert, Context context)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
KeyStore knownServers = getKnownServersStore(context);
Log_OC.d(TAG, "Certificate - HashCode: " + cert.hashCode() + " "
+ Boolean.toString(knownServers.isCertificateEntry(Integer.toString(cert.hashCode()))));
return knownServers.isCertificateEntry(Integer.toString(cert.hashCode()));
}
}
@@ -1,145 +0,0 @@
/* ownCloud Android Library is available under MIT license
* Copyright (C) 2016 ownCloud GmbH.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.owncloud.android.lib.common.network;
import com.owncloud.android.lib.common.utils.Log_OC;
import javax.net.ssl.SSLSocket;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicReference;
/**
* Enables the support of Server Name Indication if existing
* in the underlying network implementation.
* <p>
* Build as a singleton.
*
* @author David A. Velasco
*/
public class ServerNameIndicator {
private static final String TAG = ServerNameIndicator.class.getSimpleName();
private static final AtomicReference<ServerNameIndicator> mSingleInstance = new AtomicReference<ServerNameIndicator>();
private static final String METHOD_NAME = "setHostname";
private final WeakReference<Class<?>> mSSLSocketClassRef;
private final WeakReference<Method> mSetHostnameMethodRef;
/**
* Private constructor, class is a singleton.
*
* @param sslSocketClass Underlying implementation class of {@link SSLSocket} used to connect with the server.
* @param setHostnameMethod Name of the method to call to enable the SNI support.
*/
private ServerNameIndicator(Class<?> sslSocketClass, Method setHostnameMethod) {
mSSLSocketClassRef = new WeakReference<Class<?>>(sslSocketClass);
mSetHostnameMethodRef = (setHostnameMethod == null) ? null : new WeakReference<Method>(setHostnameMethod);
}
/**
* Calls the {@code #setHostname(String)} method of the underlying implementation
* of {@link SSLSocket} if exists.
* <p>
* Creates and initializes the single instance of the class when needed
*
* @param hostname The name of the server host of interest.
* @param sslSocket Client socket to connect with the server.
*/
public static void setServerNameIndication(String hostname, SSLSocket sslSocket) {
final Method setHostnameMethod = getMethod(sslSocket);
if (setHostnameMethod != null) {
try {
setHostnameMethod.invoke(sslSocket, hostname);
Log_OC.i(TAG, "SNI done, hostname: " + hostname);
} catch (IllegalArgumentException e) {
Log_OC.e(TAG, "Call to SSLSocket#setHost(String) failed ", e);
} catch (IllegalAccessException e) {
Log_OC.e(TAG, "Call to SSLSocket#setHost(String) failed ", e);
} catch (InvocationTargetException e) {
Log_OC.e(TAG, "Call to SSLSocket#setHost(String) failed ", e);
}
} else {
Log_OC.i(TAG, "SNI not supported");
}
}
/**
* Gets the method to invoke trying to minimize the effective
* application of reflection.
*
* @param sslSocket Instance of the SSL socket to use in connection with server.
* @return Method to call to indicate the server name of interest to the server.
*/
private static Method getMethod(SSLSocket sslSocket) {
final Class<?> sslSocketClass = sslSocket.getClass();
final ServerNameIndicator instance = mSingleInstance.get();
if (instance == null) {
return initFrom(sslSocketClass);
} else if (instance.mSSLSocketClassRef.get() != sslSocketClass) {
// the underlying class changed
return initFrom(sslSocketClass);
} else if (instance.mSetHostnameMethodRef == null) {
// SNI not supported
return null;
} else {
final Method cachedSetHostnameMethod = instance.mSetHostnameMethodRef.get();
return (cachedSetHostnameMethod == null) ? initFrom(sslSocketClass) : cachedSetHostnameMethod;
}
}
/**
* Singleton initializer.
* <p>
* Uses reflection to extract and 'cache' the method to invoke to indicate the desited host name to the server side.
*
* @param sslSocketClass Underlying class providing the implementation of {@link SSLSocket}.
* @return Method to call to indicate the server name of interest to the server.
*/
private static Method initFrom(Class<?> sslSocketClass) {
Log_OC.i(TAG, "SSLSocket implementation: " + sslSocketClass.getCanonicalName());
Method setHostnameMethod = null;
try {
setHostnameMethod = sslSocketClass.getMethod(METHOD_NAME, String.class);
} catch (SecurityException e) {
Log_OC.e(TAG, "Could not access to SSLSocket#setHostname(String) method ", e);
} catch (NoSuchMethodException e) {
Log_OC.i(TAG, "Could not find SSLSocket#setHostname(String) method - SNI not supported");
}
mSingleInstance.set(new ServerNameIndicator(sslSocketClass, setHostnameMethod));
return setHostnameMethod;
}
}
@@ -1,167 +0,0 @@
/* ownCloud Android Library is available under MIT license
* Copyright (C) 2017 ownCloud GmbH.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.owncloud.android.lib.common.network;
import com.owncloud.android.lib.common.utils.Log_OC;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicReference;
/**
* Enforces, if possible, a write timeout for a socket.
* <p>
* Built as a singleton.
* <p>
* Tries to hit something like this:
* https://android.googlesource.com/platform/external/conscrypt/+/lollipop-release/src/main/java/org/conscrypt/OpenSSLSocketImpl.java#1005
* <p>
* Minimizes the chances of getting stalled in PUT/POST request if the network interface is lost while
* writing the entity into the outwards sockect.
* <p>
* It happens. See https://github.com/owncloud/android/issues/1684#issuecomment-295306015
*
* @author David A. Velasco
*/
public class WriteTimeoutEnforcer {
private static final String TAG = WriteTimeoutEnforcer.class.getSimpleName();
private static final AtomicReference<WriteTimeoutEnforcer> mSingleInstance = new AtomicReference<>();
private static final String METHOD_NAME = "setSoWriteTimeout";
private final WeakReference<Class<?>> mSocketClassRef;
private final WeakReference<Method> mSetSoWriteTimeoutMethodRef;
/**
* Private constructor, class is a singleton.
*
* @param socketClass Underlying implementation class of {@link Socket} used to connect
* with the server.
* @param setSoWriteTimeoutMethod Name of the method to call to set a write timeout in the socket.
*/
private WriteTimeoutEnforcer(Class<?> socketClass, Method setSoWriteTimeoutMethod) {
mSocketClassRef = new WeakReference<Class<?>>(socketClass);
mSetSoWriteTimeoutMethodRef =
(setSoWriteTimeoutMethod == null) ?
null :
new WeakReference<>(setSoWriteTimeoutMethod)
;
}
/**
* Calls the {@code #setSoWrite(int)} method of the underlying implementation
* of {@link Socket} if exists.
* <p>
* Creates and initializes the single instance of the class when needed
*
* @param writeTimeoutMilliseconds Write timeout to set, in milliseconds.
* @param socket Client socket to connect with the server.
*/
public static void setSoWriteTimeout(int writeTimeoutMilliseconds, Socket socket) {
final Method setSoWriteTimeoutMethod = getMethod(socket);
if (setSoWriteTimeoutMethod != null) {
try {
setSoWriteTimeoutMethod.invoke(socket, writeTimeoutMilliseconds);
Log_OC.i(
TAG,
"Write timeout set in socket, writeTimeoutMilliseconds: "
+ writeTimeoutMilliseconds
);
} catch (IllegalArgumentException e) {
Log_OC.e(TAG, "Call to (SocketImpl)#setSoWriteTimeout(int) failed ", e);
} catch (IllegalAccessException e) {
Log_OC.e(TAG, "Call to (SocketImpl)#setSoWriteTimeout(int) failed ", e);
} catch (InvocationTargetException e) {
Log_OC.e(TAG, "Call to (SocketImpl)#setSoWriteTimeout(int) failed ", e);
}
} else {
Log_OC.i(TAG, "Write timeout for socket not supported");
}
}
/**
* Gets the method to invoke trying to minimize the cost of reflection reusing objects cached
* in static members.
*
* @param socket Instance of the socket to use in connection with server.
* @return Method to call to set a write timeout in the socket.
*/
private static Method getMethod(Socket socket) {
final Class<?> socketClass = socket.getClass();
final WriteTimeoutEnforcer instance = mSingleInstance.get();
if (instance == null) {
return initFrom(socketClass);
} else if (instance.mSocketClassRef.get() != socketClass) {
// the underlying class changed
return initFrom(socketClass);
} else if (instance.mSetSoWriteTimeoutMethodRef == null) {
// method not supported
return null;
} else {
final Method cachedSetSoWriteTimeoutMethod = instance.mSetSoWriteTimeoutMethodRef.get();
return (cachedSetSoWriteTimeoutMethod == null) ?
initFrom(socketClass) :
cachedSetSoWriteTimeoutMethod
;
}
}
/**
* Singleton initializer.
* <p>
* Uses reflection to extract and 'cache' the method to invoke to set a write timouet in a socket.
*
* @param socketClass Underlying class providing the implementation of {@link Socket}.
* @return Method to call to set a write timeout in the socket.
*/
private static Method initFrom(Class<?> socketClass) {
Log_OC.i(TAG, "Socket implementation: " + socketClass.getCanonicalName());
Method setSoWriteTimeoutMethod = null;
try {
setSoWriteTimeoutMethod = socketClass.getMethod(METHOD_NAME, int.class);
} catch (SecurityException e) {
Log_OC.e(TAG, "Could not access to (SocketImpl)#setSoWriteTimeout(int) method ", e);
} catch (NoSuchMethodException e) {
Log_OC.i(
TAG,
"Could not find (SocketImpl)#setSoWriteTimeout(int) method - write timeout not supported"
);
}
mSingleInstance.set(new WriteTimeoutEnforcer(socketClass, setSoWriteTimeoutMethod));
return setSoWriteTimeoutMethod;
}
}
@@ -11,8 +11,8 @@ import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.utils.Log_OC;
import okhttp3.OkHttpClient;
import timber.log.Timber;
import java.io.IOException;
@@ -27,7 +27,6 @@ public abstract class RemoteOperation<T> implements Runnable {
* OCS API header value
*/
public static final String OCS_API_HEADER_VALUE = "true";
private static final String TAG = RemoteOperation.class.getSimpleName();
/**
* ownCloud account in the remote ownCloud server to operate
*/
@@ -41,22 +40,22 @@ public abstract class RemoteOperation<T> implements Runnable {
/**
* Object to interact with the remote server
*/
protected OwnCloudClient mClient = null;
private OwnCloudClient mClient = null;
/**
* Object to interact with the remote server
*/
protected OkHttpClient mHttpClient = null;
private OkHttpClient mHttpClient = null;
/**
* Callback object to notify about the execution of the remote operation
*/
protected OnRemoteOperationListener mListener = null;
private OnRemoteOperationListener mListener = null;
/**
* Handler to the thread where mListener methods will be called
*/
protected Handler mListenerHandler = null;
private Handler mListenerHandler = null;
/**
* Asynchronously executes the remote operation
@@ -76,12 +75,10 @@ public abstract class RemoteOperation<T> implements Runnable {
OnRemoteOperationListener listener, Handler listenerHandler) {
if (account == null) {
throw new IllegalArgumentException
("Trying to execute a remote operation with a NULL Account");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account");
}
if (context == null) {
throw new IllegalArgumentException
("Trying to execute a remote operation with a NULL Context");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context");
}
// mAccount and mContext in the runnerThread to create below
mAccount = account;
@@ -109,8 +106,7 @@ public abstract class RemoteOperation<T> implements Runnable {
*/
public Thread execute(OwnCloudClient client, OnRemoteOperationListener listener, Handler listenerHandler) {
if (client == null) {
throw new IllegalArgumentException
("Trying to execute a remote operation with a NULL OwnCloudClient");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL OwnCloudClient");
}
mClient = client;
if (client.getAccount() != null) {
@@ -120,8 +116,7 @@ public abstract class RemoteOperation<T> implements Runnable {
if (listener == null) {
throw new IllegalArgumentException
("Trying to execute a remote operation asynchronously " +
"without a listener to notify the result");
("Trying to execute a remote operation asynchronously without a listener to notify the result");
}
mListener = listener;
@@ -134,7 +129,7 @@ public abstract class RemoteOperation<T> implements Runnable {
return runnerThread;
}
protected void grantOwnCloudClient() throws
private void grantOwnCloudClient() throws
AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
if (mClient == null) {
if (mAccount != null && mContext != null) {
@@ -177,12 +172,10 @@ public abstract class RemoteOperation<T> implements Runnable {
*/
public RemoteOperationResult<T> execute(Account account, Context context) {
if (account == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL " +
"Account");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account");
}
if (context == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL " +
"Context");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context");
}
mAccount = account;
mContext = context.getApplicationContext();
@@ -192,7 +185,7 @@ public abstract class RemoteOperation<T> implements Runnable {
/**
* Synchronously executes the remote operation
*
* <p>
* Do not call this method from the main thread.
*
* @param client Client object to reach an ownCloud server during the execution of
@@ -201,8 +194,7 @@ public abstract class RemoteOperation<T> implements Runnable {
*/
public RemoteOperationResult<T> execute(OwnCloudClient client) {
if (client == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL " +
"OwnCloudClient");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL OwnCloudClient");
}
mClient = client;
if (client.getAccount() != null) {
@@ -224,8 +216,7 @@ public abstract class RemoteOperation<T> implements Runnable {
*/
public RemoteOperationResult<T> execute(OkHttpClient client, Context context) {
if (client == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL " +
"OwnCloudClient");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL OwnCloudClient");
}
mHttpClient = client;
mContext = context;
@@ -249,7 +240,7 @@ public abstract class RemoteOperation<T> implements Runnable {
result = run(mClient);
} catch (AccountsException | IOException e) {
Log_OC.e(TAG, "Error while trying to access to " + mAccount.name, e);
Timber.e(e, "Error while trying to access to %s", mAccount.name);
result = new RemoteOperationResult<>(e);
}
@@ -33,9 +33,9 @@ import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.http.HttpConstants;
import com.owncloud.android.lib.common.http.methods.HttpBaseMethod;
import com.owncloud.android.lib.common.network.CertificateCombinedException;
import com.owncloud.android.lib.common.utils.Log_OC;
import okhttp3.Headers;
import org.json.JSONException;
import timber.log.Timber;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
@@ -60,7 +60,6 @@ public class RemoteOperationResult<T>
*/
private static final long serialVersionUID = 4968939884332372230L;
private static final String TAG = RemoteOperationResult.class.getSimpleName();
private boolean mSuccess = false;
private int mHttpCode = -1;
private String mHttpPhrase = null;
@@ -192,7 +191,7 @@ public class RemoteOperationResult<T>
}
} catch (Exception e) {
Log_OC.w(TAG, "Error reading exception from server: " + e.getMessage());
Timber.w("Error reading exception from server: %s", e.getMessage());
// mCode stays as set in this(success, httpCode, headers)
}
}
@@ -293,11 +292,7 @@ public class RemoteOperationResult<T>
break;
default:
mCode = ResultCode.UNHANDLED_HTTP_CODE; // UNKNOWN ERROR
Log_OC.d(TAG,
"RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " +
mHttpCode + " " + mHttpPhrase
);
Timber.d("RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + mHttpCode + " " + mHttpPhrase);
}
}
}
@@ -308,7 +303,6 @@ public class RemoteOperationResult<T>
*
* @param bodyResponse okHttp response body
* @param resultCode our own custom result code
* @throws IOException
*/
private void parseErrorMessageAndSetCode(String bodyResponse, ResultCode resultCode) {
@@ -317,12 +311,12 @@ public class RemoteOperationResult<T>
ErrorMessageParser xmlParser = new ErrorMessageParser();
try {
String errorMessage = xmlParser.parseXMLResponse(is);
if (errorMessage != "" && errorMessage != null) {
if (errorMessage != null && !errorMessage.equals("")) {
mCode = resultCode;
mHttpPhrase = errorMessage;
}
} catch (Exception e) {
Log_OC.w(TAG, "Error reading exception from server: " + e.getMessage());
Timber.w("Error reading exception from server: %s", e.getMessage());
// mCode stays as set in this(success, httpCode, headers)
}
}
@@ -376,7 +370,7 @@ public class RemoteOperationResult<T>
previousCause = cause;
cause = cause.getCause();
}
if (cause != null && cause instanceof CertificateCombinedException) {
if (cause instanceof CertificateCombinedException) {
result = (CertificateCombinedException) cause;
}
return result;
@@ -13,7 +13,7 @@ object LoggingHelper {
}
if (!directory.exists())
directory.mkdirs()
Timber.plant(FileLoggingTree(directory, filename = storagePath, delegator = Log_OC::class.java))
Timber.plant(FileLoggingTree(directory, filename = storagePath, delegator = Timber::class.java))
}
fun stopLogging() {