1f196292513b7d7cb72a913c9e366309b94787af
[pub/Android/ownCloud.git] / src / eu / alefzero / webdav / WebdavClient.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
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 package eu.alefzero.webdav;
19
20 import java.io.BufferedInputStream;
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24
25 import org.apache.commons.httpclient.Credentials;
26 import org.apache.commons.httpclient.HttpClient;
27 import org.apache.commons.httpclient.HttpMethod;
28 import org.apache.commons.httpclient.UsernamePasswordCredentials;
29 import org.apache.commons.httpclient.auth.AuthScope;
30 import org.apache.commons.httpclient.methods.HeadMethod;
31 import org.apache.http.HttpHost;
32 import org.apache.http.HttpResponse;
33 import org.apache.http.HttpStatus;
34 import org.apache.http.HttpVersion;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.client.methods.HttpHead;
37 import org.apache.http.client.methods.HttpPut;
38 import org.apache.http.conn.ClientConnectionManager;
39 import org.apache.http.conn.params.ConnManagerPNames;
40 import org.apache.http.conn.params.ConnPerRouteBean;
41 import org.apache.http.conn.scheme.PlainSocketFactory;
42 import org.apache.http.conn.scheme.Scheme;
43 import org.apache.http.conn.scheme.SchemeRegistry;
44 import org.apache.http.conn.ssl.SSLSocketFactory;
45 import org.apache.http.entity.FileEntity;
46 import org.apache.http.impl.auth.BasicScheme;
47 import org.apache.http.impl.client.DefaultHttpClient;
48 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
49 import org.apache.http.params.BasicHttpParams;
50 import org.apache.http.params.HttpParams;
51 import org.apache.http.params.HttpProtocolParams;
52 import org.apache.http.protocol.BasicHttpContext;
53
54 import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory;
55 import eu.alefzero.webdav.HttpMkCol;
56
57 import android.net.Uri;
58 import android.util.Log;
59
60 public class WebdavClient extends HttpClient {
61 private DefaultHttpClient mHttpClient;
62 private BasicHttpContext mHttpContext;
63 private HttpHost mTargetHost;
64 private SchemeRegistry mSchemeRegistry;
65 private Uri mUri;
66 private Credentials mCredentials;
67 final private static String TAG = "WebdavClient";
68
69 public DefaultHttpClient getHttpClient() {
70 return mHttpClient;
71 }
72 public HttpHost getTargetHost() {
73 return mTargetHost;
74 }
75
76 public WebdavClient(Uri uri) {
77 mUri = uri;
78 mSchemeRegistry = new SchemeRegistry();
79 setupHttpClient();
80 }
81
82 public void setCredentials(String username, String password) {
83 // determine default port for http or https
84 int targetPort = mTargetHost.getPort() == -1 ?
85 ( mUri.getScheme().equals("https") ? 443 : 80)
86 : mUri.getPort();
87
88 getParams().setAuthenticationPreemptive(true);
89 getState().setCredentials(AuthScope.ANY, getCredentials(username, password));
90 }
91
92 private Credentials getCredentials(String username, String password) {
93 if (mCredentials == null)
94 mCredentials = new UsernamePasswordCredentials(username, password);
95 return mCredentials;
96 }
97 public void allowUnsignedCertificates() {
98 // https
99 mSchemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
100 }
101
102 public boolean downloadFile(String filepath, File targetPath) {
103 HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ", "%20"));
104 get.setHeader("Host", mUri.getHost());
105 get.setHeader("User-Agent", "Android-ownCloud");
106
107 try {
108 HttpResponse response = mHttpClient.execute(mTargetHost, get, mHttpContext);
109 if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
110 return false;
111 }
112 BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
113 FileOutputStream fos = new FileOutputStream(targetPath);
114
115 byte[] bytes = new byte[512];
116 int readResult;
117 while ((readResult = bis.read(bytes)) != -1) fos.write(bytes, 0, readResult);
118
119 } catch (IOException e) {
120 e.printStackTrace();
121 return false;
122 }
123 return true;
124 }
125
126 public boolean putFile(String localFile,
127 String remoteTarget,
128 String contentType) {
129 boolean result = true;
130 HttpPut method = new HttpPut(mUri.toString() + remoteTarget.replace(" ", "%20"));
131 method.setHeader("Content-type", contentType);
132 method.setHeader("Host", mUri.getHost());
133 method.setHeader("User-Agent", "Android-ownCloud");
134
135 try {
136 final FileEntity fileEntity = new FileEntity(new File(localFile), contentType);
137
138 method.setEntity(fileEntity);
139 Log.i(TAG, "executing:" + method.getRequestLine().toString());
140
141 mHttpClient.execute(mTargetHost, method, mHttpContext);
142 /*mHandler.post(new Runnable() {
143 public void run() {
144 Uploader.this.PartialupdateUpload(c.getString(c.getColumnIndex(Media.DATA)),
145 c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),
146 mUploadPath + (mUploadPath.equals("/")?"":"/"),
147 fileEntity.getContentType().getValue(),
148 fileEntity.getContentLength()+"");
149 }
150 });
151 Log.i(TAG, "Uploading, done");
152 */
153 Log.i(TAG, "Uploading, done");
154 } catch (final Exception e) {
155 Log.i(TAG, ""+e.getMessage());
156 result = false;
157 }
158
159 return result;
160 }
161
162 public int tryToLogin() {
163 int r = 0;
164 HeadMethod head = new HeadMethod(mUri.toString());
165 try {
166 r = executeMethod(head);
167 } catch (Exception e) {
168 Log.e(TAG, "Error: " + e.getMessage());
169 }
170 return r;
171 }
172
173 public boolean createDirectory(String path) {
174 HttpMkCol method = new HttpMkCol(mUri.toString() + path + "/");
175 method.setHeader("User-Agent", "Android-ownCloud");
176
177 try {
178 mHttpClient.execute(mTargetHost, method, mHttpContext);
179 Log.i(TAG, "Creating dir completed");
180 } catch (final Exception e) {
181 e.printStackTrace();
182 return false;
183 }
184 return true;
185 }
186
187 private void setupHttpClient() {
188 // http scheme
189 mSchemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
190 mSchemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
191
192 HttpParams params = new BasicHttpParams();
193 params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
194 params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
195 params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
196 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
197
198 mHttpContext = new BasicHttpContext();
199 ClientConnectionManager cm = new ThreadSafeClientConnManager(params, mSchemeRegistry);
200
201 int port = mUri.getPort() == -1 ?
202 mUri.getScheme().equals("https") ? 443 : 80
203 : mUri.getPort();
204
205 mTargetHost = new HttpHost(mUri.getHost(), port, mUri.getScheme());
206
207 mHttpClient = new DefaultHttpClient(cm, params);
208 }
209 }