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