Make the OAuth authorization available or not depending upon a variable in oauth.xml
[pub/Android/ownCloud.git] / src / eu / alefzero / 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 as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19 package eu.alefzero.webdav;
20
21 import java.io.BufferedInputStream;
22 import java.io.File;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.commons.httpclient.Credentials;
30 import org.apache.commons.httpclient.HostConfiguration;
31 import org.apache.commons.httpclient.HttpClient;
32 import org.apache.commons.httpclient.HttpConnectionManager;
33 import org.apache.commons.httpclient.HttpException;
34 import org.apache.commons.httpclient.HttpMethod;
35 import org.apache.commons.httpclient.HttpMethodBase;
36 import org.apache.commons.httpclient.HttpState;
37 import org.apache.commons.httpclient.HttpVersion;
38 import org.apache.commons.httpclient.UsernamePasswordCredentials;
39 import org.apache.commons.httpclient.auth.AuthPolicy;
40 import org.apache.commons.httpclient.auth.AuthScope;
41 import org.apache.commons.httpclient.methods.GetMethod;
42 import org.apache.commons.httpclient.methods.HeadMethod;
43 import org.apache.commons.httpclient.methods.PutMethod;
44 import org.apache.commons.httpclient.params.HttpMethodParams;
45 import org.apache.http.HttpStatus;
46 import org.apache.http.params.CoreProtocolPNames;
47 import org.apache.jackrabbit.webdav.client.methods.DavMethod;
48 import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
49
50 import com.owncloud.android.network.BearerAuthScheme;
51 import com.owncloud.android.network.BearerCredentials;
52
53 import android.net.Uri;
54 import android.util.Log;
55
56 public class WebdavClient extends HttpClient {
57 private Uri mUri;
58 private Credentials mCredentials;
59 final private static String TAG = "WebdavClient";
60 private static final String USER_AGENT = "Android-ownCloud";
61
62 private OnDatatransferProgressListener mDataTransferListener;
63 static private byte[] sExhaustBuffer = new byte[1024];
64
65 /**
66 * Constructor
67 */
68 public WebdavClient(HttpConnectionManager connectionMgr) {
69 super(connectionMgr);
70 Log.d(TAG, "Creating WebdavClient");
71 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
72 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
73 }
74
75 public void setBearerCredentials(String accessToken) {
76 AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class);
77
78 List<String> authPrefs = new ArrayList<String>(1);
79 authPrefs.add(BearerAuthScheme.AUTH_POLICY);
80 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
81
82 mCredentials = new BearerCredentials(accessToken);
83 getState().setCredentials(AuthScope.ANY, mCredentials);
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 }
95
96
97 /**
98 * Downloads a file in remoteFilepath to the local targetPath.
99 *
100 * @param remoteFilepath Path to the file in the remote server, URL DECODED.
101 * @param targetFile Local path to save the downloaded file.
102 * @return 'True' when the file is successfully downloaded.
103 */
104 public boolean downloadFile(String remoteFilePath, File targetFile) {
105 boolean ret = false;
106 GetMethod get = new GetMethod(mUri.toString() + WebdavUtils.encodePath(remoteFilePath));
107
108 try {
109 int status = executeMethod(get);
110 if (status == HttpStatus.SC_OK) {
111 targetFile.createNewFile();
112 BufferedInputStream bis = new BufferedInputStream(
113 get.getResponseBodyAsStream());
114 FileOutputStream fos = new FileOutputStream(targetFile);
115
116 byte[] bytes = new byte[4096];
117 int readResult;
118 while ((readResult = bis.read(bytes)) != -1) {
119 if (mDataTransferListener != null)
120 mDataTransferListener.onTransferProgress(readResult);
121 fos.write(bytes, 0, readResult);
122 }
123 fos.close();
124 ret = true;
125 } else {
126 exhaustResponse(get.getResponseBodyAsStream());
127 }
128 Log.e(TAG, "Download of " + remoteFilePath + " to " + targetFile + " finished with HTTP status " + status + (!ret?"(FAIL)":""));
129 } catch (Exception e) {
130 logException(e, "dowloading " + remoteFilePath);
131
132 } finally {
133 if (!ret && targetFile.exists()) {
134 targetFile.delete();
135 }
136 get.releaseConnection(); // let the connection available for other methods
137 }
138 return ret;
139 }
140
141 /**
142 * Deletes a remote file via webdav
143 * @param remoteFilePath Remote file path of the file to delete, in URL DECODED format.
144 * @return
145 */
146 public boolean deleteFile(String remoteFilePath) {
147 boolean ret = false;
148 DavMethod delete = new DeleteMethod(mUri.toString() + WebdavUtils.encodePath(remoteFilePath));
149 try {
150 int status = executeMethod(delete);
151 ret = (status == HttpStatus.SC_OK || status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_NO_CONTENT);
152 exhaustResponse(delete.getResponseBodyAsStream());
153
154 Log.e(TAG, "DELETE of " + remoteFilePath + " finished with HTTP status " + status + (!ret?"(FAIL)":""));
155
156 } catch (Exception e) {
157 logException(e, "deleting " + remoteFilePath);
158
159 } finally {
160 delete.releaseConnection(); // let the connection available for other methods
161 }
162 return ret;
163 }
164
165
166 public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
167 mDataTransferListener = listener;
168 }
169
170 /**
171 * Creates or update a file in the remote server with the contents of a local file.
172 *
173 * @param localFile Path to the local file to upload.
174 * @param remoteTarget Remote path to the file to create or update, URL DECODED
175 * @param contentType MIME type of the file.
176 * @return Status HTTP code returned by the server.
177 * @throws IOException When a transport error that could not be recovered occurred while uploading the file to the server.
178 * @throws HttpException When a violation of the HTTP protocol occurred.
179 */
180 public int putFile(String localFile, String remoteTarget, String contentType) throws HttpException, IOException {
181 int status = -1;
182 PutMethod put = new PutMethod(mUri.toString() + WebdavUtils.encodePath(remoteTarget));
183
184 try {
185 File f = new File(localFile);
186 FileRequestEntity entity = new FileRequestEntity(f, contentType);
187 entity.addOnDatatransferProgressListener(mDataTransferListener);
188 put.setRequestEntity(entity);
189 status = executeMethod(put);
190
191 exhaustResponse(put.getResponseBodyAsStream());
192
193 } finally {
194 put.releaseConnection(); // let the connection available for other methods
195 }
196 return status;
197 }
198
199 /**
200 * Tries to log in to the current URI, with the current credentials
201 *
202 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
203 */
204 public int tryToLogin() {
205 int status = 0;
206 HeadMethod head = new HeadMethod(mUri.toString());
207 try {
208 status = executeMethod(head);
209 boolean result = status == HttpStatus.SC_OK;
210 Log.d(TAG, "HEAD for " + mUri + " finished with HTTP status " + status + (!result?"(FAIL)":""));
211 exhaustResponse(head.getResponseBodyAsStream());
212
213 } catch (Exception e) {
214 logException(e, "trying to login at " + mUri.toString());
215
216 } finally {
217 head.releaseConnection();
218 }
219 return status;
220 }
221
222
223 /**
224 * Check if a file exists in the OC server
225 *
226 * @return 'true' if the file exists; 'false' it doesn't exist
227 * @throws Exception When the existence could not be determined
228 */
229 public boolean existsFile(String path) throws IOException, HttpException {
230 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
231 try {
232 int status = executeMethod(head);
233 Log.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":""));
234 exhaustResponse(head.getResponseBodyAsStream());
235 return (status == HttpStatus.SC_OK);
236
237 } finally {
238 head.releaseConnection(); // let the connection available for other methods
239 }
240 }
241
242
243 /**
244 * Requests the received method with the received timeout (milliseconds).
245 *
246 * Executes the method through the inherited HttpClient.executedMethod(method).
247 *
248 * Sets the socket and connection timeouts only for the method received.
249 *
250 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
251 *
252 * @param method HTTP method request.
253 * @param readTimeout Timeout to set for data reception
254 * @param conntionTimout Timeout to set for connection establishment
255 */
256 public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException {
257 int oldSoTimeout = getParams().getSoTimeout();
258 int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
259 try {
260 if (readTimeout >= 0) {
261 method.getParams().setSoTimeout(readTimeout); // this should be enough...
262 getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS
263 }
264 if (connectionTimeout >= 0) {
265 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
266 }
267 return executeMethod(method);
268 } finally {
269 getParams().setSoTimeout(oldSoTimeout);
270 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
271 }
272 }
273
274 /**
275 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
276 *
277 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
278 */
279 public void exhaustResponse(InputStream responseBodyAsStream) {
280 if (responseBodyAsStream != null) {
281 try {
282 while (responseBodyAsStream.read(sExhaustBuffer) >= 0);
283 responseBodyAsStream.close();
284
285 } catch (IOException io) {
286 Log.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io);
287 }
288 }
289 }
290
291
292 /**
293 * Logs an exception triggered in a HTTP request.
294 *
295 * @param e Caught exception.
296 * @param doing Suffix to add at the end of the logged message.
297 */
298 private void logException(Exception e, String doing) {
299 if (e instanceof HttpException) {
300 Log.e(TAG, "HTTP violation while " + doing, e);
301
302 } else if (e instanceof IOException) {
303 Log.e(TAG, "Unrecovered transport exception while " + doing, e);
304
305 } else {
306 Log.e(TAG, "Unexpected exception while " + doing, e);
307 }
308 }
309
310
311 /**
312 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
313 */
314 public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
315 getParams().setSoTimeout(defaultDataTimeout);
316 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
317 }
318
319 /**
320 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
321 * @param uri
322 */
323 public void setBaseUri(Uri uri) {
324 mUri = uri;
325 }
326
327 public Uri getBaseUri() {
328 return mUri;
329 }
330
331
332 @Override
333 public int executeMethod(HostConfiguration hostconfig, final HttpMethod method, final HttpState state) throws IOException, HttpException {
334 if (mCredentials instanceof BearerCredentials) {
335 method.getHostAuthState().setAuthScheme(AuthPolicy.getAuthScheme(BearerAuthScheme.AUTH_POLICY));
336 method.getHostAuthState().setAuthAttempted(true);
337 }
338 return super.executeMethod(hostconfig, method, state);
339 }
340
341
342 public final Credentials getCredentials() {
343 return mCredentials;
344 }
345
346 }