From 93026e818024e3082a52a5292a62e26baf3a5888 Mon Sep 17 00:00:00 2001 From: agarcia Date: Mon, 29 Jun 2020 20:30:59 +0200 Subject: [PATCH] First step to replace interceptor --- .../android/lib/common/OwnCloudClient.java | 44 ++- .../lib/common/SingleSessionManager.java | 5 - .../OwnCloudBasicCredentials.java | 20 +- .../OwnCloudBearerCredentials.java | 17 +- .../authentication/OwnCloudCredentials.java | 6 +- .../OwnCloudCredentialsFactory.java | 8 +- .../android/lib/common/http/HttpClient.java | 25 -- .../http/interceptors/HttpInterceptor.java | 74 +--- .../RequestHeaderInterceptor.java | 54 --- .../common/http/methods/HttpBaseMethod.java | 191 ---------- .../lib/common/http/methods/HttpBaseMethod.kt | 163 +++++++++ .../http/methods/nonwebdav/DeleteMethod.kt | 4 +- .../http/methods/nonwebdav/GetMethod.kt | 4 +- .../{HttpMethod.java => HttpMethod.kt} | 22 +- .../http/methods/nonwebdav/PostMethod.kt | 8 +- .../http/methods/nonwebdav/PutMethod.kt | 8 +- .../common/http/methods/webdav/CopyMethod.kt | 13 +- .../common/http/methods/webdav/DavMethod.java | 162 --------- .../common/http/methods/webdav/DavMethod.kt | 164 +++++++++ .../common/http/methods/webdav/MkColMethod.kt | 11 +- .../common/http/methods/webdav/MoveMethod.kt | 14 +- .../http/methods/webdav/OCDavResource.kt | 340 ++++++++++++++++++ .../http/methods/webdav/PropfindMethod.kt | 7 +- .../common/http/methods/webdav/PutMethod.kt | 16 +- .../lib/common/network/WebdavUtils.java | 3 - .../shares/CreateRemoteShareOperation.kt | 8 +- .../shares/GetRemoteShareesOperation.kt | 2 +- .../shares/GetRemoteSharesForFileOperation.kt | 4 +- .../shares/RemoveRemoteShareOperation.kt | 6 +- .../shares/UpdateRemoteShareOperation.kt | 8 +- .../status/GetRemoteCapabilitiesOperation.kt | 2 +- .../status/GetRemoteStatusOperation.kt | 2 +- .../implementation/OCServerInfoService.kt | 3 +- .../users/GetRemoteUserAvatarOperation.kt | 8 +- .../users/GetRemoteUserInfoOperation.kt | 2 +- 35 files changed, 783 insertions(+), 645 deletions(-) delete mode 100644 owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/RequestHeaderInterceptor.java delete mode 100644 owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.java create mode 100644 owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt rename owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/{HttpMethod.java => HttpMethod.kt} (79%) delete mode 100644 owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.java create mode 100644 owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt create mode 100644 owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/OCDavResource.kt diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/OwnCloudClient.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/OwnCloudClient.java index 7e2691d3..2b2b5a7c 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/OwnCloudClient.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/OwnCloudClient.java @@ -89,11 +89,6 @@ public class OwnCloudClient extends HttpClient { if (!(mCredentials instanceof OwnCloudAnonymousCredentials)) { mCredentials = OwnCloudCredentialsFactory.getAnonymousCredentials(); } - mCredentials.applyTo(this); - } - - void applyCredentials() { - mCredentials.applyTo(this); } public int executeHttpMethod(HttpBaseMethod method) throws Exception { @@ -102,8 +97,17 @@ public class OwnCloudClient extends HttpClient { int status; do { - setRequestId(method); + String requestId = RandomUtils.generateRandomUUID(); + // Header to allow tracing requests in apache and ownCloud logs + Timber.d("Executing in request with id %s", requestId); + method.setRequestHeader(HttpConstants.OC_X_REQUEST_ID,requestId); + method.setRequestHeader(HttpConstants.USER_AGENT_HEADER, SingleSessionManager.getUserAgent()); + method.setRequestHeader(HttpConstants.PARAM_SINGLE_COOKIE_HEADER, "true"); + method.setRequestHeader(HttpConstants.ACCEPT_ENCODING_HEADER, HttpConstants.ACCEPT_ENCODING_IDENTITY); + if(mCredentials.getHeaderAuth()!=null){ + method.setRequestHeader(HttpConstants.AUTHORIZATION_HEADER,mCredentials.getHeaderAuth()); + } status = method.execute(); if (mFollowRedirects) { @@ -125,8 +129,17 @@ public class OwnCloudClient extends HttpClient { int status; do { - setRequestId(method); + String requestId = RandomUtils.generateRandomUUID(); + // Header to allow tracing requests in apache and ownCloud logs + Timber.d("Executing in request with id %s", requestId); + method.setRequestHeader(OC_X_REQUEST_ID,requestId); + method.setRequestHeader(HttpConstants.USER_AGENT_HEADER, SingleSessionManager.getUserAgent()); + method.setRequestHeader(HttpConstants.PARAM_SINGLE_COOKIE_HEADER, "true"); + method.setRequestHeader(HttpConstants.ACCEPT_ENCODING_HEADER, HttpConstants.ACCEPT_ENCODING_IDENTITY); + if(mCredentials.getHeaderAuth()!=null){ + method.setRequestHeader(HttpConstants.AUTHORIZATION_HEADER,mCredentials.getHeaderAuth()); + } status = method.execute(); repeatWithFreshCredentials = checkUnauthorizedAccess(status, repeatCounter); @@ -138,19 +151,6 @@ public class OwnCloudClient extends HttpClient { return status; } - private void setRequestId(HttpBaseMethod method) { - // Clean previous request id. This is a bit hacky but is the only way to add request headers in WebDAV - // methods by using Dav4Android - deleteHeaderForAllRequests(OC_X_REQUEST_ID); - - String requestId = RandomUtils.generateRandomUUID(); - - // Header to allow tracing requests in apache and ownCloud logs - addHeaderForAllRequests(OC_X_REQUEST_ID, requestId); - - Timber.d("Executing in request with id %s", requestId); - } - public RedirectionPath followRedirection(HttpBaseMethod method) throws Exception { int redirectionsCount = 0; int status = method.getStatusCode(); @@ -215,9 +215,6 @@ public class OwnCloudClient extends HttpClient { public void exhaustResponse(InputStream responseBodyAsStream) { if (responseBodyAsStream != null) { try { - while (responseBodyAsStream.read(sExhaustBuffer) >= 0) { - ; - } responseBodyAsStream.close(); } catch (IOException io) { @@ -273,7 +270,6 @@ public class OwnCloudClient extends HttpClient { public void setCredentials(OwnCloudCredentials credentials) { if (credentials != null) { mCredentials = credentials; - mCredentials.applyTo(this); } else { clearCredentials(); } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/SingleSessionManager.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/SingleSessionManager.java index a12f4796..e011a7fa 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/SingleSessionManager.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/SingleSessionManager.java @@ -130,7 +130,6 @@ public class SingleSessionManager { Timber.v("reusing client for session %s", sessionName); } - keepCredentialsUpdated(client); keepCookiesUpdated(context, account, client); keepUriUpdated(account, client); } @@ -177,10 +176,6 @@ public class SingleSessionManager { Timber.d("All sessions saved"); } - private void keepCredentialsUpdated(OwnCloudClient reusedClient) { - reusedClient.applyCredentials(); - } - private void keepCookiesUpdated(Context context, OwnCloudAccount account, OwnCloudClient reusedClient) { AccountManager am = AccountManager.get(context.getApplicationContext()); if (am != null && account.getSavedAccount() != null) { diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudBasicCredentials.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudBasicCredentials.java index bde053ce..96e8a233 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudBasicCredentials.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudBasicCredentials.java @@ -40,21 +40,6 @@ public class OwnCloudBasicCredentials implements OwnCloudCredentials { mPassword = password != null ? password : ""; } - public OwnCloudBasicCredentials(String username, String password, boolean preemptiveMode) { - mUsername = username != null ? username : ""; - mPassword = password != null ? password : ""; - } - - @Override - public void applyTo(OwnCloudClient client) { - // Clear previous basic credentials - HttpClient.deleteHeaderForAllRequests(HttpConstants.AUTHORIZATION_HEADER); - HttpClient.deleteHeaderForAllRequests(HttpConstants.COOKIE_HEADER); - - HttpClient.addHeaderForAllRequests(HttpConstants.AUTHORIZATION_HEADER, - Credentials.basic(mUsername, mPassword, UTF_8)); - } - @Override public String getUsername() { return mUsername; @@ -65,6 +50,11 @@ public class OwnCloudBasicCredentials implements OwnCloudCredentials { return mPassword; } + @Override + public String getHeaderAuth() { + return Credentials.basic(mUsername, mPassword, Util.UTF_8); + } + @Override public boolean authTokenExpires() { return false; diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudBearerCredentials.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudBearerCredentials.java index e455cb39..0dbf326a 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudBearerCredentials.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudBearerCredentials.java @@ -23,8 +23,6 @@ */ package com.owncloud.android.lib.common.authentication; -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.http.HttpClient; import com.owncloud.android.lib.common.http.HttpConstants; public class OwnCloudBearerCredentials implements OwnCloudCredentials { @@ -37,16 +35,6 @@ public class OwnCloudBearerCredentials implements OwnCloudCredentials { mAccessToken = accessToken != null ? accessToken : ""; } - @Override - public void applyTo(OwnCloudClient client) { - // Clear previous credentials - HttpClient.deleteHeaderForAllRequests(HttpConstants.AUTHORIZATION_HEADER); - HttpClient.deleteHeaderForAllRequests(HttpConstants.COOKIE_HEADER); - - HttpClient.addHeaderForAllRequests(HttpConstants.AUTHORIZATION_HEADER, - HttpConstants.BEARER_AUTHORIZATION_KEY + mAccessToken); - } - @Override public String getUsername() { // not relevant for authentication, but relevant for informational purposes @@ -58,6 +46,11 @@ public class OwnCloudBearerCredentials implements OwnCloudCredentials { return mAccessToken; } + @Override + public String getHeaderAuth() { + return HttpConstants.BEARER_AUTHORIZATION_KEY + mAccessToken; + } + @Override public boolean authTokenExpires() { return true; diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudCredentials.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudCredentials.java index 978dde8b..6ee06b58 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudCredentials.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudCredentials.java @@ -24,16 +24,14 @@ package com.owncloud.android.lib.common.authentication; -import com.owncloud.android.lib.common.OwnCloudClient; - public interface OwnCloudCredentials { - void applyTo(OwnCloudClient ownCloudClient); - String getUsername(); String getAuthToken(); + String getHeaderAuth(); + boolean authTokenExpires(); boolean authTokenCanBeRefreshed(); diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudCredentialsFactory.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudCredentialsFactory.java index 75b523cc..3d5dae91 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudCredentialsFactory.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/authentication/OwnCloudCredentialsFactory.java @@ -55,14 +55,12 @@ public class OwnCloudCredentialsFactory { } @Override - public void applyTo(OwnCloudClient client) { - // Clear previous basic credentials - HttpClient.deleteHeaderForAllRequests(HttpConstants.AUTHORIZATION_HEADER); - HttpClient.deleteHeaderForAllRequests(HttpConstants.COOKIE_HEADER); + public String getAuthToken() { + return ""; } @Override - public String getAuthToken() { + public String getHeaderAuth() { return ""; } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/HttpClient.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/HttpClient.java index 6c6784f1..f9939385 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/HttpClient.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/HttpClient.java @@ -26,9 +26,7 @@ package com.owncloud.android.lib.common.http; import android.content.Context; -import com.owncloud.android.lib.common.SingleSessionManager; 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 okhttp3.Cookie; @@ -137,33 +135,10 @@ public class HttpClient { private static HttpInterceptor getOkHttpInterceptor() { if (sOkHttpInterceptor == null) { sOkHttpInterceptor = new HttpInterceptor(); - addHeaderForAllRequests(HttpConstants.USER_AGENT_HEADER, SingleSessionManager.getUserAgent()); - addHeaderForAllRequests(HttpConstants.PARAM_SINGLE_COOKIE_HEADER, "true"); - addHeaderForAllRequests(HttpConstants.ACCEPT_ENCODING_HEADER, HttpConstants.ACCEPT_ENCODING_IDENTITY); } return sOkHttpInterceptor; } - /** - * Add header that will be included for all the requests from now on - * - * @param headerName - * @param headerValue - */ - public static void addHeaderForAllRequests(String headerName, String headerValue) { - HttpInterceptor httpInterceptor = getOkHttpInterceptor(); - - if (getOkHttpInterceptor() != null) { - httpInterceptor.addRequestInterceptor( - new RequestHeaderInterceptor(headerName, headerValue) - ); - } - } - - public static void deleteHeaderForAllRequests(String headerName) { - getOkHttpInterceptor().deleteRequestHeaderInterceptor(headerName); - } - public Context getContext() { return sContext; } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/HttpInterceptor.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/HttpInterceptor.java index b9965548..b7e6b6c9 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/HttpInterceptor.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/HttpInterceptor.java @@ -27,10 +27,10 @@ package com.owncloud.android.lib.common.http.interceptors; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; +import org.jetbrains.annotations.NotNull; +import timber.log.Timber; import java.io.IOException; -import java.util.ArrayList; -import java.util.ListIterator; /** * Http interceptor to use multiple interceptors in the same {@link okhttp3.OkHttpClient} instance @@ -39,78 +39,14 @@ import java.util.ListIterator; */ public class HttpInterceptor implements Interceptor { - private final ArrayList mRequestInterceptors = new ArrayList<>(); - private final ArrayList mResponseInterceptors = new ArrayList<>(); - + @NotNull @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); - ListIterator requestInterceptorIterator = mRequestInterceptors.listIterator(); + Timber.d("Executing in request headers %s", request.headers().toString()); - while (requestInterceptorIterator.hasNext()) { - RequestInterceptor currentRequestInterceptor = requestInterceptorIterator.next(); - request = currentRequestInterceptor.intercept(request); - } - - Response response = chain.proceed(request); - - ListIterator responseInterceptorIterator = mResponseInterceptors.listIterator(); - - while (responseInterceptorIterator.hasNext()) { - ResponseInterceptor currentResponseInterceptor = responseInterceptorIterator.next(); - response = currentResponseInterceptor.intercept(response); - } - - return response; + return chain.proceed(request); } - public HttpInterceptor addRequestInterceptor(RequestInterceptor requestInterceptor) { - mRequestInterceptors.listIterator().add(requestInterceptor); - return this; - } - - public HttpInterceptor addResponseInterceptor(ResponseInterceptor responseInterceptor) { - mResponseInterceptors.listIterator().add(responseInterceptor); - return this; - } - - public ArrayList getRequestInterceptors() { - return mRequestInterceptors; - } - - private ArrayList getRequestHeaderInterceptors() { - ArrayList requestHeaderInterceptors = new ArrayList<>(); - - for (RequestInterceptor requestInterceptor : mRequestInterceptors) { - if (requestInterceptor instanceof RequestHeaderInterceptor) { - requestHeaderInterceptors.add((RequestHeaderInterceptor) requestInterceptor); - } - } - - return requestHeaderInterceptors; - } - - public void deleteRequestHeaderInterceptor(String headerName) { - ListIterator requestInterceptorIterator = mRequestInterceptors.listIterator(); - while (requestInterceptorIterator.hasNext()) { - RequestInterceptor currentRequestInterceptor = requestInterceptorIterator.next(); - if (currentRequestInterceptor instanceof RequestHeaderInterceptor && - ((RequestHeaderInterceptor) currentRequestInterceptor).getHeaderName().equals(headerName)) { - requestInterceptorIterator.remove(); - } - } - } - - public ArrayList getResponseInterceptors() { - return mResponseInterceptors; - } - - public interface RequestInterceptor { - Request intercept(Request request) throws IOException; - } - - public interface ResponseInterceptor { - Response intercept(Response response) throws IOException; - } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/RequestHeaderInterceptor.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/RequestHeaderInterceptor.java deleted file mode 100644 index d7cb6dc4..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/interceptors/RequestHeaderInterceptor.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2020 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.http.interceptors; - -import okhttp3.Request; - -/** - * Intercept requests to update their headers - */ -public class RequestHeaderInterceptor implements HttpInterceptor.RequestInterceptor { - - private String mHeaderName; - private String mHeaderValue; - - public RequestHeaderInterceptor(String headerName, String headerValue) { - this.mHeaderName = headerName; - this.mHeaderValue = headerValue; - } - - @Override - public Request intercept(Request request) { - return request.newBuilder().addHeader(mHeaderName, mHeaderValue).build(); - } - - public String getHeaderName() { - return mHeaderName; - } - - public String getHeaderValue() { - return mHeaderValue; - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.java deleted file mode 100644 index 9dc8de97..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.java +++ /dev/null @@ -1,191 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2020 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.http.methods; - -import com.owncloud.android.lib.common.http.HttpClient; -import okhttp3.Call; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.concurrent.TimeUnit; - -/** - * Wrapper to perform http calls transparently by using: - * - OkHttp for non webdav methods - * - Dav4Android for webdav methods - * - * @author David González Verdugo - */ -public abstract class HttpBaseMethod { - protected OkHttpClient mOkHttpClient; - protected Request mRequest; - protected RequestBody mRequestBody; - protected Response mResponse; - protected String mResponseBodyString; - protected Call mCall; - - protected HttpBaseMethod(URL url) { - mOkHttpClient = HttpClient.getOkHttpClient(); - mRequest = new Request.Builder() - .url(HttpUrl.parse(url.toString())) - .build(); - } - - public int execute() throws Exception { - return onExecute(); - } - - public void abort() { - mCall.cancel(); - } - - public boolean isAborted() { - return mCall.isCanceled(); - } - - ////////////////////////////// - // For override - ////////////////////////////// - - protected abstract int onExecute() throws Exception; - - ////////////////////////////// - // Getter - ////////////////////////////// - - // Request - - public Headers getRequestHeaders() { - return mRequest.headers(); - } - - public String getRequestHeader(String name) { - return mRequest.header(name); - } - - // Response - - public int getStatusCode() { - return mResponse.code(); - } - - public String getStatusMessage() { - return mResponse.message(); - } - - public String getResponseBodyAsString() throws IOException { - if (mResponseBodyString == null && mResponse.body() != null) { - mResponseBodyString = mResponse.body().string(); - } - - return mResponseBodyString; - } - - public InputStream getResponseBodyAsStream() { - if (mResponse.body() != null) { - return mResponse.body().byteStream(); - } - return null; - } - - public Headers getResponseHeaders() { - return mResponse.headers(); - } - - public String getResponseHeader(String headerName) { - return mResponse.header(headerName); - } - - public boolean getRetryOnConnectionFailure() { - return mOkHttpClient.retryOnConnectionFailure(); - } - - ////////////////////////////// - // Setter - ////////////////////////////// - - // Connection parameters - - public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) { - mOkHttpClient = mOkHttpClient.newBuilder() - .retryOnConnectionFailure(retryOnConnectionFailure) - .build(); - } - - 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(); - } - - // Request - - public void addRequestHeader(String name, String value) { - mRequest = mRequest.newBuilder() - .addHeader(name, value) - .build(); - } - - /** - * Sets a header and replace it if already exists with that name - * - * @param name header name - * @param value header value - */ - 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(); - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt new file mode 100644 index 00000000..c71d065d --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt @@ -0,0 +1,163 @@ +package com.owncloud.android.lib.common.http.methods + +import com.owncloud.android.lib.common.http.HttpClient +import okhttp3.Call +import okhttp3.Headers +import okhttp3.HttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody +import okhttp3.Response +import java.io.InputStream +import java.net.MalformedURLException +import java.net.URL +import java.util.concurrent.TimeUnit + +abstract class HttpBaseMethod constructor(url: URL) { + var okHttpClient: OkHttpClient + var httpUrl: HttpUrl = HttpUrl.parse(url.toString()) ?: throw MalformedURLException() + var request: Request + var requestBody: RequestBody? = null + lateinit var response: Response + var responseBodyString: String? = null + + var call: Call? = null + + init { + okHttpClient = HttpClient.getOkHttpClient() + request = Request.Builder() + .url(httpUrl) + .build() + } + + @Throws(Exception::class) + open fun execute(): Int { + return onExecute() + } + + open fun setUrl(url: HttpUrl) { + request = request.newBuilder() + .url(url) + .build() + } + + /**************** + *** Requests *** + ****************/ + + // Headers + val requestHeaders: Headers + get() = request.headers() + + fun getRequestHeader(name: String): String? { + return request.header(name) + } + + fun getRequestHeadersAsHashMap(): HashMap { + val headers: HashMap = HashMap() + val superHeaders: Set = requestHeaders.names() + superHeaders.forEach { + headers[it] = getRequestHeader(it) + } + return headers + } + + open fun addRequestHeader(name: String, value: String) { + request = request.newBuilder() + .addHeader(name, value) + .build() + } + + /** + * Sets a header and replace it if already exists with that name + * + * @param name header name + * @param value header value + */ + open fun setRequestHeader(name: String, value: String) { + request = request.newBuilder() + .header(name, value) + .build() + } + + /**************** + *** Response *** + ****************/ + val statusCode: Int + get() = response.code() + + val statusMessage: String + get() = response.message() + + // Headers + open fun getResponseHeaders(): Headers? { + return response.headers() + } + + open fun getResponseHeader(headerName: String): String? { + return response.header(headerName) + } + + // Body + fun getResponseBodyAsString(): String? { + if (responseBodyString == null && response.body() != null) { + responseBodyString = response.body()?.string() + } + return responseBodyString + } + + open fun getResponseBodyAsStream(): InputStream? { + return response.body()?.byteStream() + } + + /************************* + *** Connection Params *** + *************************/ + + ////////////////////////////// + // Setter + ////////////////////////////// + // Connection parameters + open fun setRetryOnConnectionFailure(retryOnConnectionFailure: Boolean) { + okHttpClient = okHttpClient.newBuilder() + .retryOnConnectionFailure(retryOnConnectionFailure) + .build() + } + + open fun setReadTimeout(readTimeout: Long, timeUnit: TimeUnit) { + okHttpClient = okHttpClient.newBuilder() + .readTimeout(readTimeout, timeUnit) + .build() + } + + open fun setConnectionTimeout( + connectionTimeout: Long, + timeUnit: TimeUnit + ) { + okHttpClient = okHttpClient.newBuilder() + .readTimeout(connectionTimeout, timeUnit) + .build() + } + + open fun setFollowRedirects(followRedirects: Boolean) { + okHttpClient = okHttpClient.newBuilder() + .followRedirects(followRedirects) + .build() + } + + /************ + *** Call *** + ************/ + open fun abort() { + call?.cancel() + } + + open val isAborted: Boolean + get() = call?.isCanceled ?: false + + ////////////////////////////// + // For override + ////////////////////////////// + @Throws(Exception::class) + protected abstract fun onExecute(): Int +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/DeleteMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/DeleteMethod.kt index 6db4092f..51069bc2 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/DeleteMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/DeleteMethod.kt @@ -31,10 +31,10 @@ import java.net.URL * * @author David González Verdugo */ -class DeleteMethod(url: URL?) : HttpMethod(url) { +class DeleteMethod(url: URL) : HttpMethod(url) { @Throws(IOException::class) override fun onExecute(): Int { - mRequest = mRequest.newBuilder() + request = request.newBuilder() .delete() .build() return super.onExecute() diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/GetMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/GetMethod.kt index a73ffb9e..65bf40fc 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/GetMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/GetMethod.kt @@ -31,10 +31,10 @@ import java.net.URL * * @author David González Verdugo */ -class GetMethod(url: URL?) : HttpMethod(url) { +class GetMethod(url: URL) : HttpMethod(url) { @Throws(IOException::class) override fun onExecute(): Int { - mRequest = mRequest.newBuilder() + request = request.newBuilder() .get() .build() return super.onExecute() diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/HttpMethod.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/HttpMethod.kt similarity index 79% rename from owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/HttpMethod.java rename to owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/HttpMethod.kt index 971923b7..52c874cb 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/HttpMethod.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/HttpMethod.kt @@ -21,8 +21,7 @@ * THE SOFTWARE. * */ - -package com.owncloud.android.lib.common.http.methods.nonwebdav; +package com.owncloud.android.lib.common.http.methods.nonwebdav import com.owncloud.android.lib.common.http.methods.HttpBaseMethod; @@ -34,16 +33,11 @@ import java.net.URL; * * @author David González Verdugo */ -public abstract class HttpMethod extends HttpBaseMethod { - - public HttpMethod(URL url) { - super(url); +abstract class HttpMethod(url: URL) : HttpBaseMethod(url) { + @Throws(IOException::class) + public override fun onExecute(): Int { + call = okHttpClient.newCall(request) + call?.let { response = it.execute() } + return super.statusCode } - - @Override - public int onExecute() throws IOException { - mCall = mOkHttpClient.newCall(mRequest); - mResponse = mCall.execute(); - return super.getStatusCode(); - } -} \ No newline at end of file +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/PostMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/PostMethod.kt index fb564d3d..995b906e 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/PostMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/PostMethod.kt @@ -23,6 +23,7 @@ */ package com.owncloud.android.lib.common.http.methods.nonwebdav +import okhttp3.RequestBody import java.io.IOException import java.net.URL @@ -31,11 +32,12 @@ import java.net.URL * * @author David González Verdugo */ -class PostMethod(url: URL?) : HttpMethod(url) { +class PostMethod(url: URL, private val postRequestBody: RequestBody) : HttpMethod(url) { @Throws(IOException::class) override fun onExecute(): Int { - mRequest = mRequest.newBuilder() - .post(mRequestBody) + requestBody = postRequestBody + request = request.newBuilder() + .post(postRequestBody) .build() return super.onExecute() } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/PutMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/PutMethod.kt index 6842befb..524f06a6 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/PutMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/nonwebdav/PutMethod.kt @@ -23,6 +23,7 @@ */ package com.owncloud.android.lib.common.http.methods.nonwebdav +import okhttp3.RequestBody import java.io.IOException import java.net.URL @@ -31,11 +32,12 @@ import java.net.URL * * @author David González Verdugo */ -class PutMethod(url: URL?) : HttpMethod(url) { +class PutMethod(url: URL, private val putRequestBody: RequestBody) : HttpMethod(url) { @Throws(IOException::class) override fun onExecute(): Int { - mRequest = mRequest.newBuilder() - .put(mRequestBody) + requestBody = putRequestBody + request = request.newBuilder() + .put(putRequestBody) .build() return super.onExecute() } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/CopyMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/CopyMethod.kt index a49f7b6a..9da7c22e 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/CopyMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/CopyMethod.kt @@ -33,16 +33,19 @@ import java.net.URL * @author David González Verdugo */ class CopyMethod( - val url: URL?, + val url: URL, private val destinationUrl: String, private val forceOverride: Boolean ) : DavMethod(url) { @Throws(Exception::class) public override fun onExecute(): Int { - mDavResource.copy(destinationUrl, forceOverride) { response: Response -> - mResponse = response + mDavResource.copy( + destinationUrl, + forceOverride, + super.getRequestHeadersAsHashMap() + ) { callBackResponse: Response -> + response = callBackResponse } - return super.getStatusCode() + return super.statusCode } - } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.java deleted file mode 100644 index 1334e327..00000000 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.java +++ /dev/null @@ -1,162 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2020 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.http.methods.webdav; - -import at.bitfire.dav4jvm.Dav4jvm; -import at.bitfire.dav4jvm.DavOCResource; -import at.bitfire.dav4jvm.exception.HttpException; -import at.bitfire.dav4jvm.exception.RedirectException; -import com.owncloud.android.lib.common.http.HttpConstants; -import com.owncloud.android.lib.common.http.methods.HttpBaseMethod; -import okhttp3.HttpUrl; -import okhttp3.Protocol; -import okhttp3.Response; -import okhttp3.ResponseBody; - -import java.net.URL; -import java.util.concurrent.TimeUnit; - -/** - * Wrapper to perform WebDAV (dav4android) calls - * - * @author David González Verdugo - */ -public abstract class DavMethod extends HttpBaseMethod { - - protected DavOCResource mDavResource; - - protected DavMethod(URL url) { - super(url); - mDavResource = new DavOCResource( - mOkHttpClient, - HttpUrl.parse(url.toString()), - Dav4jvm.INSTANCE.getLog()); - } - - @Override - public void abort() { - mDavResource.cancelCall(); - } - - @Override - public int execute() throws Exception { - try { - return onExecute(); - } catch (HttpException httpException) { - // Modify responses with information gathered from exceptions - if (httpException instanceof RedirectException) { - mResponse = new Response.Builder() - .header( - HttpConstants.LOCATION_HEADER, ((RedirectException) httpException).getRedirectLocation() - ) - .code(httpException.getCode()) - .request(mRequest) - .message(httpException.getMessage()) - .protocol(Protocol.HTTP_1_1) - .build(); - - } else if (mResponse != null) { - // The check below should be included in okhttp library, method ResponseBody.create( - // TODO check most recent versions of okhttp to see if this is already fixed and try to update if so - if (mResponse.body().contentType() != null) { - ResponseBody responseBody = ResponseBody.create( - mResponse.body().contentType(), - httpException.getResponseBody() - ); - - mResponse = mResponse.newBuilder() - .body(responseBody) - .build(); - } - } - - return httpException.getCode(); - } - } - - ////////////////////////////// - // Setter - ////////////////////////////// - - // Connection parameters - @Override - public void setReadTimeout(long readTimeout, TimeUnit timeUnit) { - super.setReadTimeout(readTimeout, timeUnit); - mDavResource = new DavOCResource( - mOkHttpClient, - HttpUrl.parse(mRequest.url().toString()), - Dav4jvm.INSTANCE.getLog()); - } - - @Override - public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) { - super.setConnectionTimeout(connectionTimeout, timeUnit); - mDavResource = new DavOCResource( - mOkHttpClient, - HttpUrl.parse(mRequest.url().toString()), - Dav4jvm.INSTANCE.getLog()); - } - - @Override - public void setFollowRedirects(boolean followRedirects) { - super.setFollowRedirects(followRedirects); - mDavResource = new DavOCResource( - mOkHttpClient, - HttpUrl.parse(mRequest.url().toString()), - Dav4jvm.INSTANCE.getLog()); - } - - @Override - public void setUrl(HttpUrl url) { - super.setUrl(url); - mDavResource = new DavOCResource( - mOkHttpClient, - HttpUrl.parse(mRequest.url().toString()), - Dav4jvm.INSTANCE.getLog()); - } - - @Override - public boolean getRetryOnConnectionFailure() { - return false; //TODO: implement me - } - - ////////////////////////////// - // Getter - ////////////////////////////// - - @Override - public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) { - super.setRetryOnConnectionFailure(retryOnConnectionFailure); - mDavResource = new DavOCResource( - mOkHttpClient, - HttpUrl.parse(mRequest.url().toString()), - Dav4jvm.INSTANCE.getLog()); - } - - @Override - public boolean isAborted() { - return mDavResource.isCallAborted(); - } -} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt new file mode 100644 index 00000000..ce98bb4f --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt @@ -0,0 +1,164 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2020 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.http.methods.webdav + +import at.bitfire.dav4android.Constants.log +import at.bitfire.dav4android.exception.HttpException +import at.bitfire.dav4android.exception.RedirectException +import com.owncloud.android.lib.common.http.HttpConstants +import com.owncloud.android.lib.common.http.methods.HttpBaseMethod +import okhttp3.HttpUrl +import okhttp3.Protocol +import okhttp3.Response +import okhttp3.ResponseBody +import java.net.MalformedURLException +import java.net.URL +import java.util.concurrent.TimeUnit + +/** + * Wrapper to perform WebDAV (dav4android) calls + * + * @author David González Verdugo + */ +abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) { + protected var mDavResource: OCDavResource + + init { + val httpUrl = HttpUrl.parse(url.toString()) ?: throw MalformedURLException() + mDavResource = OCDavResource( + okHttpClient, + httpUrl, + log + ) + } + + override fun abort() { + mDavResource.cancelCall() + } + + @Throws(Exception::class) + override fun execute(): Int { + return try { + onExecute() + } catch (httpException: HttpException) { + // Modify responses with information gathered from exceptions + if (httpException is RedirectException) { + response = Response.Builder() + .header( + HttpConstants.LOCATION_HEADER, httpException.redirectLocation + ) + .code(httpException.code) + .request(request) + .message(httpException.message ?: "") + .protocol(Protocol.HTTP_1_1) + .build() + } else { + // The check below should be included in okhttp library, method ResponseBody.create( + // TODO check most recent versions of okhttp to see if this is already fixed and try to update if so + if (response.body()?.contentType() != null) { + val responseBody = ResponseBody.create( + response.body()?.contentType(), + httpException.responseBody?:"" + ) + response = response.newBuilder() + .body(responseBody) + .build() + } + } + httpException.code + } + } + + ////////////////////////////// + // Setter + ////////////////////////////// + // Connection parameters + override fun setReadTimeout(readTimeout: Long, timeUnit: TimeUnit) { + super.setReadTimeout(readTimeout, timeUnit) + mDavResource = OCDavResource( + okHttpClient, + httpUrl, + log + ) + } + + override fun setConnectionTimeout( + connectionTimeout: Long, + timeUnit: TimeUnit + ) { + super.setConnectionTimeout(connectionTimeout, timeUnit) + mDavResource = OCDavResource( + okHttpClient, + httpUrl, + log + ) + } + + override fun setFollowRedirects(followRedirects: Boolean) { + super.setFollowRedirects(followRedirects) + mDavResource = OCDavResource( + okHttpClient, + httpUrl, + log + ) + } + + override fun setUrl(url: HttpUrl) { + super.setUrl(url) + mDavResource = OCDavResource( + okHttpClient, + httpUrl, + log + ) + } + + override fun setRequestHeader(name: String, value: String) { + super.setRequestHeader(name, value) + mDavResource = OCDavResource( + okHttpClient, + httpUrl, + log + ) + } + + fun getRetryOnConnectionFailure(): Boolean { + return false //TODO: implement me + } + + ////////////////////////////// + // Getter + ////////////////////////////// + override fun setRetryOnConnectionFailure(retryOnConnectionFailure: Boolean) { + super.setRetryOnConnectionFailure(retryOnConnectionFailure) + mDavResource = OCDavResource( + okHttpClient, + httpUrl, + log + ) + } + + override val isAborted: Boolean + get() = mDavResource.isCallAborted() + +} \ No newline at end of file diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/MkColMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/MkColMethod.kt index ddcd85c2..088a2c6a 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/MkColMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/MkColMethod.kt @@ -32,12 +32,15 @@ import java.net.URL * @author Christian Schabesberger * @author David González Verdugo */ -class MkColMethod(url: URL?) : DavMethod(url) { +class MkColMethod(url: URL) : DavMethod(url) { @Throws(Exception::class) public override fun onExecute(): Int { - mDavResource.mkCol(null) { response: Response -> - mResponse = response + mDavResource.mkCol( + xmlBody = null, + listOfHeaders = super.getRequestHeadersAsHashMap() + ) { callBackResponse: Response -> + response = callBackResponse } - return super.getStatusCode() + return super.statusCode } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/MoveMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/MoveMethod.kt index d2c45cfa..9aaa5b20 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/MoveMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/MoveMethod.kt @@ -34,22 +34,20 @@ import java.net.URL * @author David González Verdugo */ class MoveMethod( - url: URL?, + url: URL, private val destinationUrl: String, private val forceOverride: Boolean -) : - DavMethod(url) { +) : DavMethod(url) { @Throws(Exception::class) public override fun onExecute(): Int { mDavResource.move( destinationUrl, forceOverride, - super.getRequestHeader(HttpConstants.OC_TOTAL_LENGTH_HEADER), - super.getRequestHeader(HttpConstants.OC_X_OC_MTIME_HEADER) - ) { response: Response -> - mResponse = response + super.getRequestHeadersAsHashMap() + ) { callBackResponse: Response -> + response = callBackResponse } - return super.getStatusCode() + return super.statusCode } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/OCDavResource.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/OCDavResource.kt new file mode 100644 index 00000000..037f65ed --- /dev/null +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/OCDavResource.kt @@ -0,0 +1,340 @@ +package com.owncloud.android.lib.common.http.methods.webdav + +import at.bitfire.dav4android.DavResource +import at.bitfire.dav4android.DavResponseCallback +import at.bitfire.dav4android.IF_MATCH_HEADER +import at.bitfire.dav4android.Property +import at.bitfire.dav4android.QuotedStringUtils +import at.bitfire.dav4android.XmlUtils +import at.bitfire.dav4android.exception.DavException +import at.bitfire.dav4android.exception.HttpException +import okhttp3.HttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody +import okhttp3.Response +import java.io.IOException +import java.io.StringWriter +import java.util.logging.Logger + +class OCDavResource( + httpClient: OkHttpClient, + location: HttpUrl, + log: Logger +) : DavResource(httpClient, location, log) { + + /** + * Sends a PUT request to the resource. + * @param body new resource body to upload + * @param ifMatchETag value of "If-Match" header to set, or null to omit + * @param ifNoneMatch indicates whether "If-None-Match: *" ("don't overwrite anything existing") header shall be sent + * @param contentType + * @param ocTotalLength total length of resource body + * @param ocXOcMtimeHeader modification time + * @return true if the request was redirected successfully, i.e. #{@link #location} and maybe resource name may have changed + * @throws IOException on I/O error + * @throws HttpException on HTTP error + */ + @Throws(IOException::class, HttpException::class) + fun put( + body: RequestBody, + ifMatchETag: String?, + listOfHeaders: HashMap?, + callback: (response: Response) -> Unit + ) { + val requestBuilder = Request.Builder() + .put(body) + + listOfHeaders?.forEach { (name, value) -> + value?.let { + requestBuilder.header(name, value) + } + } + + if (ifMatchETag != null) + // only overwrite specific version + requestBuilder.header(IF_MATCH_HEADER, QuotedStringUtils.asQuotedString(ifMatchETag)) +// if (contentType != null) { +// requestBuilder.header(CONTENT_TYPE_HEADER, contentType) +// } +// if (ocTotalLength != null) { +// requestBuilder.header(OC_TOTAL_LENGTH_HEADER, ocTotalLength) +// } +// if (ocXOcMtimeHeader != null) { +// requestBuilder.header(OC_X_OC_MTIME_HEADER, ocXOcMtimeHeader) +// } + + followRedirects { + requestBuilder + .url(location) + val call = httpClient.newCall(requestBuilder.build()) + + this.call = call + call.execute() + }.use { response -> + callback(response) + checkStatus(response) + } + } + + /** + * Sends a MOVE request to the resource + * @param ocTotalLength total length of resource body + * @param ocXOcMtimeHeader modification time + */ + @Throws(IOException::class, HttpException::class, DavException::class) + fun move( + destination: String, + forceOverride: Boolean, + listOfHeaders: HashMap?, + callback: (response: Response) -> Unit + ) { + val requestBuilder = Request.Builder() + .method("MOVE", null) + .header("Content-Length", "0") + .header("Destination", destination) + + if (forceOverride) + requestBuilder.header("Overwrite", "F") + + listOfHeaders?.forEach { (name, value) -> + value?.let { + requestBuilder.header(name, value) + } + } +// if (ocTotalLength != null) +// requestBuilder.header(OC_TOTAL_LENGTH_HEADER, ocTotalLength) +// if (ocXOcMtimeHeader != null) +// requestBuilder.header(OC_X_OC_MTIME_HEADER, ocXOcMtimeHeader) + + followRedirects { + requestBuilder.url(location) + val call = httpClient.newCall(requestBuilder.build()) + this.call = call + call.execute() + }.use { response -> + callback(response) + checkStatus(response) + } + } + + @Throws(IOException::class, HttpException::class, DavException::class) + fun copy( + destination: String, + forceOverride: Boolean, + listOfHeaders: HashMap?, + callback: (response: Response) -> Unit + ) { + val requestBuilder = Request.Builder() + .method("COPY", null) + .header("Content-Length", "0") + .header("Destination", destination) + if (forceOverride) + requestBuilder.header("Overwrite", "F") + + listOfHeaders?.forEach { (name, value) -> + value?.let { + requestBuilder.header(name, value) + } + } + + followRedirects { + requestBuilder.url(location) + val call = httpClient.newCall(requestBuilder.build()) + + this.call = call + call.execute() + }.use { response -> + callback(response) + checkStatus(response) + } + } + + /** + * Sends a MKCOL request to this resource. Follows up to [MAX_REDIRECTS] redirects. + * + * @throws IOException on I/O error + * @throws HttpException on HTTP error + */ + @Throws(IOException::class, HttpException::class) + fun mkCol( + xmlBody: String?, + listOfHeaders: HashMap?, + callback: (response: Response) -> Unit + ) { + val rqBody = if (xmlBody != null) RequestBody.create(MIME_XML, xmlBody) else null + val requestBuilder = Request.Builder() + .method("MKCOL", rqBody) + .url(location) + listOfHeaders?.forEach { (name, value) -> + value?.let { + requestBuilder.header(name, value) + } + } + followRedirects { + val call = httpClient.newCall( + requestBuilder.build() + ) + this.call = call + call.execute() + }.use { response -> + callback(response) + checkStatus(response) + } + } + + /** + * Sends a GET request to the resource. Sends `Accept-Encoding: identity` to disable + * compression, because compression might change the ETag. + * + * Follows up to [MAX_REDIRECTS] redirects. + * + * @param accept value of Accept header (must not be null, but may be */*) + * @param callback called with server response unless an exception is thrown + * + * @throws IOException on I/O error + * @throws HttpException on HTTP error + */ + @Throws(IOException::class, HttpException::class) + fun get( + accept: String, + listOfHeaders: HashMap?, + callback: (response: Response) -> Unit + ) { + val requestBuilder = Request.Builder() + .get() + .url(location) + .header("Accept", accept) + .header("Accept-Encoding", "identity") // disable compression because it can change the ETag + + listOfHeaders?.forEach { (name, value) -> + value?.let { + requestBuilder.header(name, value) + } + } + + followRedirects { + val call = httpClient.newCall( + requestBuilder + .build() + ) + this.call = call + call.execute() + }.use { response -> + callback(response) + checkStatus(response) + } + } + + /** + * Sends a DELETE request to the resource. Warning: Sending this request to a collection will + * delete the collection with all its contents! + * + * Follows up to [MAX_REDIRECTS] redirects. + * + * @param ifMatchETag value of `If-Match` header to set, or null to omit + * @param callback called with server response unless an exception is thrown + * + * @throws IOException on I/O error + * @throws HttpException on HTTP errors, or when 207 Multi-Status is returned + * (because then there was probably a problem with a member resource) + */ + @Throws(IOException::class, HttpException::class) + fun delete( + ifMatchETag: String?, + listOfHeaders: HashMap?, + callback: (Response) -> Unit + ) { + followRedirects { + val requestBuilder = Request.Builder() + .delete() + .url(location) + if (ifMatchETag != null) + requestBuilder.header("If-Match", QuotedStringUtils.asQuotedString(ifMatchETag)) + listOfHeaders?.forEach { (name, value) -> + value?.let { + requestBuilder.header(name, value) + } + } + + val call = httpClient.newCall(requestBuilder.build()) + + this.call = call + call.execute() + }.use { response -> + callback(response) + checkStatus(response) + if (response.code() == 207) + /* If an error occurs deleting a member resource (a resource other than + the resource identified in the Request-URI), then the response can be + a 207 (Multi-Status). […] (RFC 4918 9.6.1. DELETE for Collections) */ + throw HttpException(response) + } + } + + /** + * Sends a PROPFIND request to the resource. Expects and processes a 207 Multi-Status response. + * + * Follows up to [MAX_REDIRECTS] redirects. + * + * @param depth "Depth" header to send (-1 for `infinity`) + * @param reqProp properties to request + * @param callback called for every XML response element in the Multi-Status response + * + * @throws IOException on I/O error + * @throws HttpException on HTTP error + * @throws DavException on WebDAV error (like no 207 Multi-Status response) + */ + @Throws(IOException::class, HttpException::class, DavException::class) + fun propfind( + depth: Int, + vararg reqProp: + Property.Name, + listOfHeaders: HashMap?, + callback: DavResponseCallback, + rawCallback: (response: Response) -> Unit + ) { + // build XML request body + val serializer = XmlUtils.newSerializer() + val writer = StringWriter() + serializer.setOutput(writer) + serializer.setPrefix("", XmlUtils.NS_WEBDAV) + serializer.setPrefix("CAL", XmlUtils.NS_CALDAV) + serializer.setPrefix("CARD", XmlUtils.NS_CARDDAV) + serializer.setPrefix("SABRE", XmlUtils.NS_SABREDAV) + serializer.setPrefix("OC", XmlUtils.NS_OWNCLOUD) + serializer.startDocument("UTF-8", null) + serializer.startTag(XmlUtils.NS_WEBDAV, "propfind") + serializer.startTag(XmlUtils.NS_WEBDAV, "prop") + for (prop in reqProp) { + serializer.startTag(prop.namespace, prop.name) + serializer.endTag(prop.namespace, prop.name) + } + serializer.endTag(XmlUtils.NS_WEBDAV, "prop") + serializer.endTag(XmlUtils.NS_WEBDAV, "propfind") + serializer.endDocument() + + val requestBuilder = Request.Builder() + .url(location) + .method("PROPFIND", RequestBody.create(MIME_XML, writer.toString())) + .header("Depth", if (depth >= 0) depth.toString() else "infinity") + + listOfHeaders?.forEach { (name, value) -> + value?.let { + requestBuilder.header(name, value) + } + } + + followRedirects { + val call = httpClient.newCall( + requestBuilder.build() + ) + this.call = call + call.execute() + }.use { response -> + rawCallback(response) + processMultiStatus(response, callback) + } + } + +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PropfindMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PropfindMethod.kt index 2a2913c0..f99fd394 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PropfindMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PropfindMethod.kt @@ -37,7 +37,7 @@ import java.util.ArrayList * @author David González Verdugo */ class PropfindMethod( - url: URL?, + url: URL, // request val depth: Int, private val mPropertiesToRequest: Array @@ -53,6 +53,7 @@ class PropfindMethod( mDavResource.propfind( depth = depth, reqProp = *mPropertiesToRequest, + listOfHeaders = super.getRequestHeadersAsHashMap(), callback = { response: Response, hrefRelation: HrefRelation? -> when (hrefRelation) { HrefRelation.MEMBER -> mMembers.add(response) @@ -62,8 +63,8 @@ class PropfindMethod( else -> { } } - }, rawCallback = { response: okhttp3.Response -> - mResponse = response + }, rawCallback = { callBackResponse: okhttp3.Response -> + response = callBackResponse }) return statusCode } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PutMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PutMethod.kt index 55736a6e..c63b7327 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PutMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PutMethod.kt @@ -33,18 +33,18 @@ import java.net.URL * * @author David González Verdugo */ -class PutMethod(url: URL?) : DavMethod(url) { +class PutMethod( + url: URL +) : DavMethod(url) { @Throws(IOException::class, HttpException::class) public override fun onExecute(): Int { mDavResource.put( - mRequestBody, + requestBody!!, super.getRequestHeader(HttpConstants.IF_MATCH_HEADER), - super.getRequestHeader(HttpConstants.CONTENT_TYPE_HEADER), - super.getRequestHeader(HttpConstants.OC_TOTAL_LENGTH_HEADER), - super.getRequestHeader(HttpConstants.OC_X_OC_MTIME_HEADER) - ) { response: Response -> - mResponse = response + getRequestHeadersAsHashMap() + ) { callBackResponse -> + response = callBackResponse } - return super.getStatusCode() + return super.statusCode } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/WebdavUtils.java b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/WebdavUtils.java index 5647dec4..e86f89d7 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/WebdavUtils.java +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/WebdavUtils.java @@ -34,9 +34,6 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; -import static com.owncloud.android.lib.common.OwnCloudClient.WEBDAV_FILES_PATH_4_0; -import static com.owncloud.android.lib.common.OwnCloudClient.WEBDAV_PATH_4_0_AND_LATER; - public class WebdavUtils { private static final SimpleDateFormat[] DATETIME_FORMATS = { diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.kt index 5d5eeb39..e188f7a7 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/CreateRemoteShareOperation.kt @@ -116,9 +116,7 @@ class CreateRemoteShareOperation( val uriBuilder = requestUri.buildUpon() uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH) - val postMethod = PostMethod(URL(uriBuilder.build().toString())) - - postMethod.setRequestBody(formBodyBuilder.build()) + val postMethod = PostMethod(URL(uriBuilder.build().toString()), formBodyBuilder.build()) postMethod.setRequestHeader(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.CONTENT_TYPE_URLENCODED_UTF8) postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE) @@ -133,7 +131,7 @@ class CreateRemoteShareOperation( parser.oneOrMoreSharesRequired = true parser.ownCloudVersion = client.ownCloudVersion parser.serverBaseUri = client.baseUri - result = parser.parse(postMethod.responseBodyAsString) + result = parser.parse(postMethod.responseBodyString) if (result.isSuccess && retrieveShareDetails) { // retrieve more info - POST only returns the index of the new share @@ -145,7 +143,7 @@ class CreateRemoteShareOperation( } } else { - result = parser.parse(postMethod.responseBodyAsString) + result = parser.parse(postMethod.responseBodyString) } } catch (e: Exception) { diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.kt index 11449fb0..c1ec316e 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareesOperation.kt @@ -98,7 +98,7 @@ class GetRemoteShareesOperation getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE) val status = client.executeHttpMethod(getMethod) - val response = getMethod.responseBodyAsString + val response = getMethod.responseBodyString if (isSuccess(status)) { Timber.d("Successful response: $response") diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.kt index ae09166b..d58918e4 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteSharesForFileOperation.kt @@ -86,10 +86,10 @@ class GetRemoteSharesForFileOperation( ) parser.ownCloudVersion = client.ownCloudVersion parser.serverBaseUri = client.baseUri - result = parser.parse(getMethod.responseBodyAsString) + result = parser.parse(getMethod.responseBodyString) if (result.isSuccess) { - Timber.d("Got " + result.data.shares.size + " shares") + Timber.d("Got ${result.data.shares.size} shares") } } else { result = RemoteOperationResult(getMethod) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.kt index 034be286..0df2e332 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/RemoveRemoteShareOperation.kt @@ -73,9 +73,9 @@ class RemoveRemoteShareOperation(private val remoteShareId: Long) : RemoteOperat val parser = ShareToRemoteOperationResultParser( ShareXMLParser() ) - result = parser.parse(deleteMethod.responseBodyAsString) + result = parser.parse(deleteMethod.responseBodyString) - Timber.d("Unshare " + remoteShareId + ": " + result.logMessage) + Timber.d("Unshare $remoteShareId: ${result.logMessage}") } else { result = RemoteOperationResult(deleteMethod) @@ -83,7 +83,7 @@ class RemoveRemoteShareOperation(private val remoteShareId: Long) : RemoteOperat } catch (e: Exception) { result = RemoteOperationResult(e) - Timber.e(e, "Unshare Link Exception " + result.logMessage) + Timber.e(e, "Unshare Link Exception ${result.logMessage}") } return result diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.kt index 0b4a08e5..e2af8959 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/UpdateRemoteShareOperation.kt @@ -143,9 +143,7 @@ class UpdateRemoteShareOperation uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH) uriBuilder.appendEncodedPath(remoteId.toString()) - val putMethod = PutMethod(URL(uriBuilder.build().toString())) - - putMethod.setRequestBody(formBodyBuilder.build()) + val putMethod = PutMethod(URL(uriBuilder.build().toString()), formBodyBuilder.build()) putMethod.setRequestHeader(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.CONTENT_TYPE_URLENCODED_UTF8) putMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE) @@ -158,12 +156,12 @@ class UpdateRemoteShareOperation ) if (!isSuccess(status)) { - return parser.parse(putMethod.responseBodyAsString) + return parser.parse(putMethod.getResponseBodyAsString()) } parser.ownCloudVersion = client.ownCloudVersion parser.serverBaseUri = client.baseUri - result = parser.parse(putMethod.responseBodyAsString) + result = parser.parse(putMethod.getResponseBodyAsString()) if (result.isSuccess && retrieveShareDetails) { // retrieve more info - PUT only returns the index of the new share diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.kt index 256e03b6..f9f164eb 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteCapabilitiesOperation.kt @@ -65,7 +65,7 @@ class GetRemoteCapabilitiesOperation : RemoteOperation() { } val status = client.executeHttpMethod(getMethod) - val response = getMethod.responseBodyAsString + val response = getMethod.getResponseBodyAsString() if (status == HttpConstants.HTTP_OK) { Timber.d("Successful response $response") diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteStatusOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteStatusOperation.kt index b6fd1b39..f47544b1 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteStatusOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteStatusOperation.kt @@ -108,7 +108,7 @@ class GetRemoteStatusOperation : RemoteOperation() { } if (isSuccess(status)) { - val respJSON = JSONObject(getMethod.responseBodyAsString) + val respJSON = JSONObject(getMethod.getResponseBodyAsString()) if (!respJSON.getBoolean(NODE_INSTALLED)) { latestResult = RemoteOperationResult(ResultCode.INSTANCE_NOT_CONFIGURED) } else { diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/services/implementation/OCServerInfoService.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/services/implementation/OCServerInfoService.kt index 8efd9def..76f82a46 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/services/implementation/OCServerInfoService.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/services/implementation/OCServerInfoService.kt @@ -21,6 +21,7 @@ package com.owncloud.android.lib.resources.status.services.implementation import android.net.Uri import com.owncloud.android.lib.common.OwnCloudClient +import com.owncloud.android.lib.common.authentication.OwnCloudCredentialsFactory.getAnonymousCredentials import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.status.services.ServerInfoService import com.owncloud.android.lib.resources.files.CheckPathExistenceRemoteOperation @@ -38,6 +39,6 @@ class OCServerInfoService : ServerInfoService { GetRemoteStatusOperation().execute(createClientFromPath(path)) private fun createClientFromPath(path: String): OwnCloudClient { - return OwnCloudClient(Uri.parse(path)) + return OwnCloudClient(Uri.parse(path)).apply { credentials = getAnonymousCredentials() } } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserAvatarOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserAvatarOperation.kt index 0e998ebc..2efbacb6 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserAvatarOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserAvatarOperation.kt @@ -58,7 +58,7 @@ class GetRemoteUserAvatarOperation(private val avatarDimension: Int) : RemoteOpe if (isSuccess(status)) { // find out size of file to read - val contentLength = getMethod.getResponseHeader(HttpConstants.CONTENT_LENGTH_HEADER).toInt() + val contentLength = getMethod.getResponseHeader(HttpConstants.CONTENT_LENGTH_HEADER)?.toInt() // find out MIME-type! val mimeType = getMethod.getResponseHeader(HttpConstants.CONTENT_TYPE_HEADER) @@ -69,8 +69,8 @@ class GetRemoteUserAvatarOperation(private val avatarDimension: Int) : RemoteOpe } /// download will be performed to a buffer - inputStream = getMethod.responseBodyAsStream - val bytesArray = inputStream.readBytes() + inputStream = getMethod.getResponseBodyAsStream() + val bytesArray = inputStream?.readBytes()?: byteArrayOf() // TODO check total bytes transferred? Timber.d("Avatar size: Bytes received ${bytesArray.size} of $contentLength") @@ -87,7 +87,7 @@ class GetRemoteUserAvatarOperation(private val avatarDimension: Int) : RemoteOpe } else { result = RemoteOperationResult(getMethod) - client.exhaustResponse(getMethod.responseBodyAsStream) + client.exhaustResponse(getMethod.getResponseBodyAsStream()) } } catch (e: Exception) { diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserInfoOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserInfoOperation.kt index 7ea63c69..53600d29 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserInfoOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserInfoOperation.kt @@ -53,7 +53,7 @@ class GetRemoteUserInfoOperation : RemoteOperation() { try { val getMethod = GetMethod(URL(client.baseUri.toString() + OCS_ROUTE)) val status = client.executeHttpMethod(getMethod) - val response = getMethod.responseBodyAsString + val response = getMethod.getResponseBodyAsString() ?: "" if (status == HttpConstants.HTTP_OK) { Timber.d("Successful response $response")