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