Merge branch 'develop' into file_browsing_refactoring
[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 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 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.Log_OC;
51
52 import com.owncloud.android.network.BearerAuthScheme;
53 import com.owncloud.android.network.BearerCredentials;
54
55 import android.net.Uri;
56
57 public class WebdavClient extends HttpClient {
58 private Uri mUri;
59 private Credentials mCredentials;
60 final private static String TAG = "WebdavClient";
61 private static final String USER_AGENT = "Android-ownCloud";
62
63 private OnDatatransferProgressListener mDataTransferListener;
64 static private byte[] sExhaustBuffer = new byte[1024];
65
66 /**
67 * Constructor
68 */
69 public WebdavClient(HttpConnectionManager connectionMgr) {
70 super(connectionMgr);
71 Log_OC.d(TAG, "Creating WebdavClient");
72 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
73 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
74 }
75
76 public void setBearerCredentials(String accessToken) {
77 AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class);
78
79 List<String> authPrefs = new ArrayList<String>(1);
80 authPrefs.add(BearerAuthScheme.AUTH_POLICY);
81 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
82
83 mCredentials = new BearerCredentials(accessToken);
84 getState().setCredentials(AuthScope.ANY, mCredentials);
85 }
86
87 public void setBasicCredentials(String username, String password) {
88 List<String> authPrefs = new ArrayList<String>(1);
89 authPrefs.add(AuthPolicy.BASIC);
90 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
91
92 getParams().setAuthenticationPreemptive(true);
93 mCredentials = new UsernamePasswordCredentials(username, password);
94 getState().setCredentials(AuthScope.ANY, mCredentials);
95 }
96
97 /**
98 * Check if a file exists in the OC server
99 *
100 * TODO replace with ExistenceOperation
101 *
102 * @return 'true' if the file exists; 'false' it doesn't exist
103 * @throws Exception When the existence could not be determined
104 */
105 public boolean existsFile(String path) throws IOException, HttpException {
106 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
107 try {
108 int status = executeMethod(head);
109 Log_OC.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":""));
110 exhaustResponse(head.getResponseBodyAsStream());
111 return (status == HttpStatus.SC_OK);
112
113 } finally {
114 head.releaseConnection(); // let the connection available for other methods
115 }
116 }
117
118 /**
119 * Requests the received method with the received timeout (milliseconds).
120 *
121 * Executes the method through the inherited HttpClient.executedMethod(method).
122 *
123 * Sets the socket and connection timeouts only for the method received.
124 *
125 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
126 *
127 * @param method HTTP method request.
128 * @param readTimeout Timeout to set for data reception
129 * @param conntionTimout Timeout to set for connection establishment
130 */
131 public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException {
132 int oldSoTimeout = getParams().getSoTimeout();
133 int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
134 try {
135 if (readTimeout >= 0) {
136 method.getParams().setSoTimeout(readTimeout); // this should be enough...
137 getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS
138 }
139 if (connectionTimeout >= 0) {
140 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
141 }
142 return executeMethod(method);
143 } finally {
144 getParams().setSoTimeout(oldSoTimeout);
145 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
146 }
147 }
148
149 /**
150 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
151 *
152 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
153 */
154 public void exhaustResponse(InputStream responseBodyAsStream) {
155 if (responseBodyAsStream != null) {
156 try {
157 while (responseBodyAsStream.read(sExhaustBuffer) >= 0);
158 responseBodyAsStream.close();
159
160 } catch (IOException io) {
161 Log_OC.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io);
162 }
163 }
164 }
165
166 /**
167 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
168 */
169 public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
170 getParams().setSoTimeout(defaultDataTimeout);
171 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
172 }
173
174 /**
175 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
176 * @param uri
177 */
178 public void setBaseUri(Uri uri) {
179 mUri = uri;
180 }
181
182 public Uri getBaseUri() {
183 return mUri;
184 }
185
186 public final Credentials getCredentials() {
187 return mCredentials;
188 }
189
190 }