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