eb828d4df139ecaa547d66c1490fda65f1ab5358
[pub/Android/ownCloud.git] / oc_framework / src / com / owncloud / android / oc_framework / network / webdav / WebdavClient.java
1 /* ownCloud Android Library is available under MIT license
2 * Copyright (C) 2014 ownCloud (http://www.owncloud.org/)
3 * Copyright (C) 2012 Bartek Przybylski
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 */
25
26 package com.owncloud.android.oc_framework.network.webdav;
27
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.util.ArrayList;
31 import java.util.List;
32
33 import org.apache.commons.httpclient.Credentials;
34 import org.apache.commons.httpclient.Header;
35 import org.apache.commons.httpclient.HttpClient;
36 import org.apache.commons.httpclient.HttpConnectionManager;
37 import org.apache.commons.httpclient.HttpException;
38 import org.apache.commons.httpclient.HttpMethod;
39 import org.apache.commons.httpclient.HttpMethodBase;
40 import org.apache.commons.httpclient.HttpVersion;
41 import org.apache.commons.httpclient.URI;
42 import org.apache.commons.httpclient.UsernamePasswordCredentials;
43 import org.apache.commons.httpclient.auth.AuthPolicy;
44 import org.apache.commons.httpclient.auth.AuthScope;
45 import org.apache.commons.httpclient.cookie.CookiePolicy;
46 import org.apache.commons.httpclient.methods.HeadMethod;
47 import org.apache.commons.httpclient.params.HttpMethodParams;
48 import org.apache.http.HttpStatus;
49 import org.apache.http.params.CoreProtocolPNames;
50
51 import com.owncloud.android.oc_framework.network.BearerAuthScheme;
52 import com.owncloud.android.oc_framework.network.BearerCredentials;
53
54 import android.net.Uri;
55 import android.util.Log;
56
57 public class WebdavClient extends HttpClient {
58 private static final int MAX_REDIRECTIONS_COUNT = 3;
59
60 private Uri mUri;
61 private Credentials mCredentials;
62 private boolean mFollowRedirects;
63 private String mSsoSessionCookie;
64 final private static String TAG = WebdavClient.class.getSimpleName();
65 public static final String USER_AGENT = "Android-ownCloud";
66
67 static private byte[] sExhaustBuffer = new byte[1024];
68
69 /**
70 * Constructor
71 */
72 public WebdavClient(HttpConnectionManager connectionMgr) {
73 super(connectionMgr);
74 Log.d(TAG, "Creating WebdavClient");
75 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
76 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
77 mFollowRedirects = true;
78 mSsoSessionCookie = null;
79 }
80
81 public void setBearerCredentials(String accessToken) {
82 AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class);
83
84 List<String> authPrefs = new ArrayList<String>(1);
85 authPrefs.add(BearerAuthScheme.AUTH_POLICY);
86 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
87
88 mCredentials = new BearerCredentials(accessToken);
89 getState().setCredentials(AuthScope.ANY, mCredentials);
90 mSsoSessionCookie = null;
91 }
92
93 public void setBasicCredentials(String username, String password) {
94 List<String> authPrefs = new ArrayList<String>(1);
95 authPrefs.add(AuthPolicy.BASIC);
96 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
97
98 getParams().setAuthenticationPreemptive(true);
99 mCredentials = new UsernamePasswordCredentials(username, password);
100 getState().setCredentials(AuthScope.ANY, mCredentials);
101 mSsoSessionCookie = null;
102 }
103
104 public void setSsoSessionCookie(String accessToken) {
105 getParams().setAuthenticationPreemptive(false);
106 getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
107 mSsoSessionCookie = accessToken;
108 mCredentials = null;
109 }
110
111
112 /**
113 * Check if a file exists in the OC server
114 *
115 * TODO replace with ExistenceOperation
116 *
117 * @return 'true' if the file exists; 'false' it doesn't exist
118 * @throws Exception When the existence could not be determined
119 */
120 public boolean existsFile(String path) throws IOException, HttpException {
121 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
122 try {
123 int status = executeMethod(head);
124 Log.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":""));
125 exhaustResponse(head.getResponseBodyAsStream());
126 return (status == HttpStatus.SC_OK);
127
128 } finally {
129 head.releaseConnection(); // let the connection available for other methods
130 }
131 }
132
133 /**
134 * Requests the received method with the received timeout (milliseconds).
135 *
136 * Executes the method through the inherited HttpClient.executedMethod(method).
137 *
138 * Sets the socket and connection timeouts only for the method received.
139 *
140 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
141 *
142 * @param method HTTP method request.
143 * @param readTimeout Timeout to set for data reception
144 * @param conntionTimout Timeout to set for connection establishment
145 */
146 public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException {
147 int oldSoTimeout = getParams().getSoTimeout();
148 int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
149 try {
150 if (readTimeout >= 0) {
151 method.getParams().setSoTimeout(readTimeout); // this should be enough...
152 getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS
153 }
154 if (connectionTimeout >= 0) {
155 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
156 }
157 return executeMethod(method);
158 } finally {
159 getParams().setSoTimeout(oldSoTimeout);
160 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
161 }
162 }
163
164
165 @Override
166 public int executeMethod(HttpMethod method) throws IOException, HttpException {
167 boolean customRedirectionNeeded = false;
168 try {
169 method.setFollowRedirects(mFollowRedirects);
170 } catch (Exception e) {
171 //if (mFollowRedirects) Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() + " method, custom redirection will be used if needed");
172 customRedirectionNeeded = mFollowRedirects;
173 }
174 if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
175 method.setRequestHeader("Cookie", mSsoSessionCookie);
176 }
177 int status = super.executeMethod(method);
178 int redirectionsCount = 0;
179 while (customRedirectionNeeded &&
180 redirectionsCount < MAX_REDIRECTIONS_COUNT &&
181 ( status == HttpStatus.SC_MOVED_PERMANENTLY ||
182 status == HttpStatus.SC_MOVED_TEMPORARILY ||
183 status == HttpStatus.SC_TEMPORARY_REDIRECT)
184 ) {
185
186 Header location = method.getResponseHeader("Location");
187 if (location != null) {
188 Log.d(TAG, "Location to redirect: " + location.getValue());
189 method.setURI(new URI(location.getValue(), true));
190 status = super.executeMethod(method);
191 redirectionsCount++;
192
193 } else {
194 Log.d(TAG, "No location to redirect!");
195 status = HttpStatus.SC_NOT_FOUND;
196 }
197 }
198
199 return status;
200 }
201
202
203 /**
204 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
205 *
206 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
207 */
208 public void exhaustResponse(InputStream responseBodyAsStream) {
209 if (responseBodyAsStream != null) {
210 try {
211 while (responseBodyAsStream.read(sExhaustBuffer) >= 0);
212 responseBodyAsStream.close();
213
214 } catch (IOException io) {
215 Log.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io);
216 }
217 }
218 }
219
220 /**
221 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
222 */
223 public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
224 getParams().setSoTimeout(defaultDataTimeout);
225 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
226 }
227
228 /**
229 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
230 * @param uri
231 */
232 public void setBaseUri(Uri uri) {
233 mUri = uri;
234 }
235
236 public Uri getBaseUri() {
237 return mUri;
238 }
239
240 public final Credentials getCredentials() {
241 return mCredentials;
242 }
243
244 public final String getSsoSessionCookie() {
245 return mSsoSessionCookie;
246 }
247
248 public void setFollowRedirects(boolean followRedirects) {
249 mFollowRedirects = followRedirects;
250 }
251
252 }