Преглед изворни кода

refactor the request creation to more general creation that can easy be overritten in subclasses

Sven Aßmann пре 13 година
родитељ
комит
b2dc291653

+ 20 - 13
src/eu/alefzero/owncloud/syncadapter/AbstractOwnCloudSyncAdapter.java

@@ -6,6 +6,7 @@ import java.util.Date;
 import java.util.LinkedList;
 
 import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
 import org.apache.http.HttpResponse;
 import org.apache.http.auth.AuthScope;
 import org.apache.http.auth.UsernamePasswordCredentials;
@@ -96,27 +97,32 @@ public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAd
 		};
 	}
 	
-	protected HttpPropFind getBasicQuery() throws OperationCanceledException, AuthenticatorException, IOException {
+	protected HttpPropFind getPropFindQuery() throws OperationCanceledException, AuthenticatorException, IOException {
 		HttpPropFind query = new HttpPropFind(getUri().toString());
 		query.setHeader("Content-type", "text/xml");
 		query.setHeader("User-Agent", "Android-ownCloud");
 		return query;
 	}
 	
-	protected TreeNode fireQuery(HttpPropFind query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {
-		BasicHttpContext httpContext = new BasicHttpContext();
-		BasicScheme basicAuth = new BasicScheme();
-		httpContext.setAttribute("preemptive-auth", basicAuth);
-		
-		HttpResponse response = getClient().execute(this.host, query, httpContext);
+	protected HttpResponse fireRawRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {
+	    BasicHttpContext httpContext = new BasicHttpContext();
+        BasicScheme basicAuth = new BasicScheme();
+        httpContext.setAttribute("preemptive-auth", basicAuth);
+        
+        HttpResponse response = getClient().execute(this.host, query, httpContext);
+        return response;
+	}
+	
+	protected TreeNode fireRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {
+		HttpResponse response = fireRawRequest(query);
 		
 		TreeNode root = new TreeNode();
 		root.setProperty(TreeNode.NodeProperty.NAME, "/");
-		this.parseResponse(response, getUri(), getClient(), this.host, httpContext, root.getChildList());
+		this.parseResponse(response, getUri(), getClient(), this.host, root.getChildList());
 		return root;
 	}
 	
-	private Uri getUri() {
+	protected Uri getUri() {
 		return Uri.parse(this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL));
 	}
 	
@@ -142,7 +148,7 @@ public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAd
 		return this.client;
 	}
 	
-	private void parseResponse(HttpResponse resp, Uri uri, DefaultHttpClient client, HttpHost targetHost, BasicHttpContext httpContext, LinkedList<TreeNode> insertList) throws IOException {
+	private void parseResponse(HttpResponse resp, Uri uri, DefaultHttpClient client, HttpHost targetHost, LinkedList<TreeNode> insertList) throws IOException, OperationCanceledException, AuthenticatorException {
 		boolean skipFirst = true;
 		for (TreeNode n :WebdavUtils.parseResponseToNodes(resp.getEntity().getContent())) {
 			String path = n.stripPathFromFilename(uri.getPath());
@@ -154,9 +160,10 @@ public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAd
 
 			if (!TextUtils.isEmpty(n.getProperty(NodeProperty.NAME)) &&
 					n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) {
-				HttpPropFind method = new HttpPropFind(uri.getPath() + path + n.getProperty(NodeProperty.NAME).replace(" ", "%20") + "/");
-				HttpResponse response = client.execute(targetHost, method, httpContext);
-				parseResponse(response, uri, client, targetHost, httpContext, n.getChildList());
+			    
+			    HttpPropFind method = new HttpPropFind(uri.getPath() + path + n.getProperty(NodeProperty.NAME).replace(" ", "%20") + "/");
+				HttpResponse response = fireRawRequest(method);
+				parseResponse(response, uri, client, targetHost, n.getChildList());
 			}
 		}
 	}

+ 116 - 77
src/eu/alefzero/owncloud/syncadapter/ContactSyncAdapter.java

@@ -4,7 +4,17 @@ import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 
+import android.accounts.AccountManager;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.entity.ByteArrayEntity;
+
+import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
+import eu.alefzero.webdav.HttpPropFind;
+
 import android.accounts.Account;
+import android.accounts.AuthenticatorException;
+import android.accounts.OperationCanceledException;
 import android.content.ContentProviderClient;
 import android.content.Context;
 import android.content.SyncResult;
@@ -17,82 +27,111 @@ import android.util.Log;
 
 public class ContactSyncAdapter extends AbstractOwnCloudSyncAdapter {
 
-	private static final String TAG = "ContactSyncAdapter";
-
-	public ContactSyncAdapter(Context context, boolean autoInitialize) {
-		super(context, autoInitialize);
-	}
-
-	@Override
-	public synchronized void onPerformSync(
-			Account account, 
-			Bundle extras, 
-			String authority, 
-			ContentProviderClient provider, 
-			SyncResult syncResult) {
-		
-		this.setAccount(account);
-		this.setContentProvider(provider);
-
-		// TODO find all contacts on ownCloud that not synced or the sync date is behind than the last sync date
-		Cursor cursor = getContacts();
-		if (cursor != null && cursor.getCount() > 0) {
-			while (cursor.moveToNext()) {
-				String id = cursor.getString(
-						cursor.getColumnIndex(ContactsContract.Contacts._ID));
-				String lookup = cursor.getString(
-						cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
-				Log.d(TAG, "Found Contact id: " + id + " with lookupkey: "+lookup);
-				
-				try {
-					FileInputStream fis = getContactVcard(lookup);
-					// TODO make a webdav request based on the stream
-					// TODO send request to the ownCloud server
-					// TODO mark the current contact as synced - where to store?
-					fis.close();
-				} catch (IOException e) {
-					// TODO Auto-generated catch block
-					e.printStackTrace();
-				}
-			}
-		}
-
-	}
-	
-	/**
-	 * Returns the vCard based on the LookupKey for Contact as Stream 
-	 * 
-	 * @param lookupKey
-	 * @return
-	 * @throws IOException
-	 */
-	private FileInputStream getContactVcard(String lookupKey) throws IOException {
-		Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
-		AssetFileDescriptor fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
-		return fd.createInputStream();
-	}
-
-	/**
-	 * Obtains the contact list.
-	 *
-	 * @return A cursor for for accessing the contact list.
-	 */
-	private Cursor getContacts()
-	{
-		// Run query
-		Uri uri = ContactsContract.Contacts.CONTENT_URI;
-		String[] projection = new String[] {
-				ContactsContract.Contacts._ID,
-				ContactsContract.Contacts.LOOKUP_KEY
-		};
-
-		boolean showInvisible = false;
-		String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + 
-				(showInvisible ? "0" : "1") + "'";
-		String[] selectionArgs = null;
-		String sortOrder = ContactsContract.Contacts._ID + " DESC";
-
-		return getContext().getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
-	}
+    private static final String TAG = "ContactSyncAdapter";
+
+    public ContactSyncAdapter(Context context, boolean autoInitialize) {
+        super(context, autoInitialize);
+    }
+
+    @Override
+    public synchronized void onPerformSync(
+            Account account, 
+            Bundle extras, 
+            String authority, 
+            ContentProviderClient provider, 
+            SyncResult syncResult) {
+
+        this.setAccount(account);
+        this.setContentProvider(provider);
+
+        // TODO find all contacts on ownCloud that not synced or the sync date is behind than the last sync date
+        Cursor cursor = getContacts();
+        if (cursor != null && cursor.getCount() > 0) {
+            while (cursor.moveToNext()) {
+                String id = cursor.getString(
+                        cursor.getColumnIndex(ContactsContract.Contacts._ID));
+                String lookup = cursor.getString(
+                        cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
+                Log.d(TAG, "Found Contact id: " + id + " with lookupkey: "+lookup);
+
+                try {
+                    FileInputStream fis = getContactVcard(lookup);
+                    
+                    HttpPut query = new HttpPut(
+                        getUri() + 
+                        "/addressbooks/"+
+                        getAccount().name.split("@")[0]+
+                        "/default/"+
+                        lookup+
+                        ".vcf"
+                    );
+                    
+                    byte[] b = new byte[fis.available()];
+                    fis.read(b);
+                    query.setEntity(new ByteArrayEntity(b));
+                    HttpResponse response = fireRawRequest(query);
+                    
+                    if(201 != response.getStatusLine().getStatusCode()) {
+                        syncResult.stats.numIoExceptions++;
+                    }
+                    // TODO make a webdav request based on the stream
+                    // TODO send request to the ownCloud server
+                    // TODO mark the current contact as synced - where to store?
+                    fis.close();
+                } catch (IOException e) {
+                    syncResult.stats.numIoExceptions++;
+                } catch (OperationCanceledException e) {
+                    //TODO maybe to a better break here
+                    return;
+                } catch (AuthenticatorException e) {
+                    syncResult.stats.numAuthExceptions++;
+                }
+            }
+        }
+
+    }
+
+    protected Uri getUri() {
+        Uri uri = Uri.parse(this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_CONTACT_URL));
+        return uri;
+    }
+
+   /**
+     * Returns the vCard based on the LookupKey for Contact as Stream 
+     * 
+     * @param lookupKey
+     * @return
+     * @throws IOException
+     */
+    private FileInputStream getContactVcard(String lookupKey) throws IOException {
+        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
+        AssetFileDescriptor fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
+        return fd.createInputStream();
+    }
+
+    /**
+     * Obtains the contact list.
+     *
+     * @return A cursor for for accessing the contact list.
+     */
+    private Cursor getContacts()
+    {
+        // Run query
+        Uri uri = ContactsContract.Contacts.CONTENT_URI;
+        String[] projection = new String[] {
+                ContactsContract.Contacts._ID,
+                ContactsContract.Contacts.LOOKUP_KEY
+        };
+
+        boolean showInvisible = false;
+        String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + 
+                (showInvisible ? "0" : "1") + "'";
+        String[] selectionArgs = null;
+        String sortOrder = ContactsContract.Contacts._ID + " DESC";
+
+        return getContext().getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
+    }
+
+
 
 }

+ 2 - 2
src/eu/alefzero/owncloud/syncadapter/FileSyncAdapter.java

@@ -63,9 +63,9 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
 			this.setAccount(account);
 			this.setContentProvider(provider);
 
-			HttpPropFind query = this.getBasicQuery();
+			HttpPropFind query = this.getPropFindQuery();
 			query.setEntity(new StringEntity(WebdavUtils.prepareXmlForPropFind()));
-			TreeNode root = this.fireQuery(query);
+			TreeNode root = this.fireRequest(query);
 
 			commitToDatabase(root, null);
 		} catch (OperationCanceledException e) {