9ec8867ffbd14322388daae898df56e807d6f8b4
[pub/Android/ownCloud.git] / oc_framework / src / com / owncloud / android / lib / network / OwnCloudClient.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.lib.network;
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.lib.network.webdav.WebdavUtils;
52
53 import android.net.Uri;
54 import android.util.Log;
55
56 public class OwnCloudClient extends HttpClient {
57 private static final int MAX_REDIRECTIONS_COUNT = 3;
58
59 private Uri mUri;
60 private Credentials mCredentials;
61 private boolean mFollowRedirects;
62 private String mSsoSessionCookie;
63 final private static String TAG = OwnCloudClient.class.getSimpleName();
64 public static final String USER_AGENT = "Android-ownCloud";
65
66 static private byte[] sExhaustBuffer = new byte[1024];
67
68 /**
69 * Constructor
70 */
71 public OwnCloudClient(HttpConnectionManager connectionMgr) {
72 super(connectionMgr);
73 Log.d(TAG, "Creating OwnCloudClient");
74 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
75 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
76 mFollowRedirects = true;
77 mSsoSessionCookie = null;
78 }
79
80 public void setBearerCredentials(String accessToken) {
81 AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class);
82
83 List<String> authPrefs = new ArrayList<String>(1);
84 authPrefs.add(BearerAuthScheme.AUTH_POLICY);
85 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
86
87 mCredentials = new BearerCredentials(accessToken);
88 getState().setCredentials(AuthScope.ANY, mCredentials);
89 mSsoSessionCookie = null;
90 }
91
92 public void setBasicCredentials(String username, String password) {
93 List<String> authPrefs = new ArrayList<String>(1);
94 authPrefs.add(AuthPolicy.BASIC);
95 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
96
97 getParams().setAuthenticationPreemptive(true);
98 mCredentials = new UsernamePasswordCredentials(username, password);
99 getState().setCredentials(AuthScope.ANY, mCredentials);
100 mSsoSessionCookie = null;
101 }
102
103 public void setSsoSessionCookie(String accessToken) {
104 getParams().setAuthenticationPreemptive(false);
105 getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
106 mSsoSessionCookie = accessToken;
107 mCredentials = null;
108 }
109
110
111 /**
112 * Check if a file exists in the OC server
113 *
114 * TODO replace with ExistenceOperation
115 *
116 * @return 'true' if the file exists; 'false' it doesn't exist
117 * @throws Exception When the existence could not be determined
118 */
119 public boolean existsFile(String path) throws IOException, HttpException {
120 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
121 try {
122 int status = executeMethod(head);
123 Log.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":""));
124 exhaustResponse(head.getResponseBodyAsStream());
125 return (status == HttpStatus.SC_OK);
126
127 } finally {
128 head.releaseConnection(); // let the connection available for other methods
129 }
130 }
131
132 /**
133 * Requests the received method with the received timeout (milliseconds).
134 *
135 * Executes the method through the inherited HttpClient.executedMethod(method).
136 *
137 * Sets the socket and connection timeouts only for the method received.
138 *
139 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
140 *
141 * @param method HTTP method request.
142 * @param readTimeout Timeout to set for data reception
143 * @param conntionTimout Timeout to set for connection establishment
144 */
145 public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException {
146 int oldSoTimeout = getParams().getSoTimeout();
147 int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
148 try {
149 if (readTimeout >= 0) {
150 method.getParams().setSoTimeout(readTimeout); // this should be enough...
151 getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS
152 }
153 if (connectionTimeout >= 0) {
154 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
155 }
156 return executeMethod(method);
157 } finally {
158 getParams().setSoTimeout(oldSoTimeout);
159 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
160 }
161 }
162
163
164 @Override
165 public int executeMethod(HttpMethod method) throws IOException, HttpException {
166 boolean customRedirectionNeeded = false;
167 try {
168 method.setFollowRedirects(mFollowRedirects);
169 } catch (Exception e) {
170 //if (mFollowRedirects) Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() + " method, custom redirection will be used if needed");
171 customRedirectionNeeded = mFollowRedirects;
172 }
173 if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
174 method.setRequestHeader("Cookie", mSsoSessionCookie);
175 }
176 int status = super.executeMethod(method);
177 int redirectionsCount = 0;
178 while (customRedirectionNeeded &&
179 redirectionsCount < MAX_REDIRECTIONS_COUNT &&
180 ( status == HttpStatus.SC_MOVED_PERMANENTLY ||
181 status == HttpStatus.SC_MOVED_TEMPORARILY ||
182 status == HttpStatus.SC_TEMPORARY_REDIRECT)
183 ) {
184
185 Header location = method.getResponseHeader("Location");
186 if (location != null) {
187 Log.d(TAG, "Location to redirect: " + location.getValue());
188 method.setURI(new URI(location.getValue(), true));
189 status = super.executeMethod(method);
190 redirectionsCount++;
191
192 } else {
193 Log.d(TAG, "No location to redirect!");
194 status = HttpStatus.SC_NOT_FOUND;
195 }
196 }
197
198 return status;
199 }
200
201
202 /**
203 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
204 *
205 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
206 */
207 public void exhaustResponse(InputStream responseBodyAsStream) {
208 if (responseBodyAsStream != null) {
209 try {
210 while (responseBodyAsStream.read(sExhaustBuffer) >= 0);
211 responseBodyAsStream.close();
212
213 } catch (IOException io) {
214 Log.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io);
215 }
216 }
217 }
218
219 /**
220 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
221 */
222 public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
223 getParams().setSoTimeout(defaultDataTimeout);
224 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
225 }
226
227 /**
228 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
229 * @param uri
230 */
231 public void setBaseUri(Uri uri) {
232 mUri = uri;
233 }
234
235 public Uri getBaseUri() {
236 return mUri;
237 }
238
239 public final Credentials getCredentials() {
240 return mCredentials;
241 }
242
243 public final String getSsoSessionCookie() {
244 return mSsoSessionCookie;
245 }
246
247 public void setFollowRedirects(boolean followRedirects) {
248 mFollowRedirects = followRedirects;
249 }
250
251 }