1 /* ownCloud Android Library is available under MIT license
2 * Copyright (C) 2014 ownCloud (http://www.owncloud.org/)
3 * Copyright (C) 2012 Bartek Przybylski
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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
26 package com
.owncloud
.android
.lib
.network
;
28 import java
.io
.IOException
;
29 import java
.io
.InputStream
;
30 import java
.util
.ArrayList
;
31 import java
.util
.List
;
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
;
51 import com
.owncloud
.android
.lib
.network
.webdav
.WebdavUtils
;
53 import android
.net
.Uri
;
54 import android
.util
.Log
;
56 public class OwnCloudClient
extends HttpClient
{
57 private static final int MAX_REDIRECTIONS_COUNT
= 3;
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";
66 static private byte[] sExhaustBuffer
= new byte[1024];
71 public OwnCloudClient(HttpConnectionManager 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
;
80 public void setBearerCredentials(String accessToken
) {
81 AuthPolicy
.registerAuthScheme(BearerAuthScheme
.AUTH_POLICY
, BearerAuthScheme
.class);
83 List
<String
> authPrefs
= new ArrayList
<String
>(1);
84 authPrefs
.add(BearerAuthScheme
.AUTH_POLICY
);
85 getParams().setParameter(AuthPolicy
.AUTH_SCHEME_PRIORITY
, authPrefs
);
87 mCredentials
= new BearerCredentials(accessToken
);
88 getState().setCredentials(AuthScope
.ANY
, mCredentials
);
89 mSsoSessionCookie
= null
;
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
);
97 getParams().setAuthenticationPreemptive(true
);
98 mCredentials
= new UsernamePasswordCredentials(username
, password
);
99 getState().setCredentials(AuthScope
.ANY
, mCredentials
);
100 mSsoSessionCookie
= null
;
103 public void setSsoSessionCookie(String accessToken
) {
104 getParams().setAuthenticationPreemptive(false
);
105 getParams().setCookiePolicy(CookiePolicy
.IGNORE_COOKIES
);
106 mSsoSessionCookie
= accessToken
;
112 * Check if a file exists in the OC server
114 * TODO replace with ExistenceOperation
116 * @return 'true' if the file exists; 'false' it doesn't exist
117 * @throws Exception When the existence could not be determined
119 public boolean existsFile(String path
) throws IOException
, HttpException
{
120 HeadMethod head
= new HeadMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
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
);
128 head
.releaseConnection(); // let the connection available for other methods
133 * Requests the received method with the received timeout (milliseconds).
135 * Executes the method through the inherited HttpClient.executedMethod(method).
137 * Sets the socket and connection timeouts only for the method received.
139 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
141 * @param method HTTP method request.
142 * @param readTimeout Timeout to set for data reception
143 * @param conntionTimout Timeout to set for connection establishment
145 public int executeMethod(HttpMethodBase method
, int readTimeout
, int connectionTimeout
) throws HttpException
, IOException
{
146 int oldSoTimeout
= getParams().getSoTimeout();
147 int oldConnectionTimeout
= getHttpConnectionManager().getParams().getConnectionTimeout();
149 if (readTimeout
>= 0) {
150 method
.getParams().setSoTimeout(readTimeout
); // this should be enough...
151 getParams().setSoTimeout(readTimeout
); // ... but this looks like necessary for HTTPS
153 if (connectionTimeout
>= 0) {
154 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout
);
156 return executeMethod(method
);
158 getParams().setSoTimeout(oldSoTimeout
);
159 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout
);
165 public int executeMethod(HttpMethod method
) throws IOException
, HttpException
{
166 boolean customRedirectionNeeded
= false
;
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
;
173 if (mSsoSessionCookie
!= null
&& mSsoSessionCookie
.length() > 0) {
174 method
.setRequestHeader("Cookie", mSsoSessionCookie
);
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
)
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
);
193 Log
.d(TAG
, "No location to redirect!");
194 status
= HttpStatus
.SC_NOT_FOUND
;
203 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
205 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
207 public void exhaustResponse(InputStream responseBodyAsStream
) {
208 if (responseBodyAsStream
!= null
) {
210 while (responseBodyAsStream
.read(sExhaustBuffer
) >= 0);
211 responseBodyAsStream
.close();
213 } catch (IOException io
) {
214 Log
.e(TAG
, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io
);
220 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
222 public void setDefaultTimeouts(int defaultDataTimeout
, int defaultConnectionTimeout
) {
223 getParams().setSoTimeout(defaultDataTimeout
);
224 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout
);
228 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
231 public void setBaseUri(Uri uri
) {
235 public Uri
getBaseUri() {
239 public final Credentials
getCredentials() {
243 public final String
getSsoSessionCookie() {
244 return mSsoSessionCookie
;
247 public void setFollowRedirects(boolean followRedirects
) {
248 mFollowRedirects
= followRedirects
;