abdera-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jmsn...@apache.org
Subject svn commit: r1173209 [42/49] - in /abdera/abdera2: ./ .settings/ activities/ activities/src/ activities/src/main/ activities/src/main/java/ activities/src/main/java/org/ activities/src/main/java/org/apache/ activities/src/main/java/org/apache/abdera2/ ...
Date Tue, 20 Sep 2011 15:57:20 GMT
Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/AsyncBasicTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/AsyncBasicTest.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/AsyncBasicTest.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/AsyncBasicTest.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,129 @@
+package org.apache.abdera2.test.activities.server;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.Date;
+
+import org.apache.abdera2.activities.client.ActivityEntity;
+import org.apache.abdera2.activities.model.ASObject;
+import org.apache.abdera2.activities.model.Activity;
+import org.apache.abdera2.activities.model.Collection;
+import org.apache.abdera2.activities.model.IO;
+import org.apache.abdera2.activities.model.Verb;
+import org.apache.abdera2.activities.model.objects.NoteObject;
+import org.apache.abdera2.activities.model.objects.PersonObject;
+import org.apache.abdera2.activities.protocol.ActivitiesServiceManager;
+import org.apache.abdera2.activities.protocol.basic.BasicProvider;
+import org.apache.abdera2.common.http.ResponseType;
+import org.apache.abdera2.protocol.client.BasicClient;
+import org.apache.abdera2.protocol.client.ClientResponse;
+import org.apache.abdera2.protocol.client.Client;
+import org.apache.abdera2.protocol.client.Session;
+import org.apache.abdera2.test.server.JettyServer;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class AsyncBasicTest {
+
+    private static JettyServer server;
+    private static Client client = new BasicClient();
+    private static IO io = IO.get();
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+        if (server == null) {
+            server = new JettyServer();
+            server.startAsync(
+              ActivitiesServiceManager.class, 
+              BasicProvider.class,
+              new TestChannelServlet());
+        }
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+      try {
+         Thread.sleep(20 * 1000);
+      } catch (Throwable t) {}
+        client.shutdown();
+        server.stop();
+    }
+
+    @Test
+    public void testGetFeed() throws IOException {
+        Session session = client.newSession();
+        ClientResponse resp = session.get("http://localhost:9002/sample");
+        Collection<ASObject> coll = io.readCollection(resp.getReader());
+        assertEquals("http://localhost:9002/sample", coll.getProperty("id").toString());
+        assertEquals("title for any sample feed", coll.getProperty("title"));
+        PersonObject person = coll.getProperty("author");
+        assertNotNull(person);
+        assertEquals("rayc", person.getDisplayName());
+        resp.release();
+    }
+ 
+    @Test
+    public void testPostEntry() throws IOException {
+      
+      
+        try {
+          Thread.sleep(20 * 1000);
+        } catch (Throwable t) {}
+      
+      
+        Activity activity = new Activity();
+        activity.setId("http://localhost:9002/sample/foo");
+        activity.setTitle("test entry");
+        activity.setVerb(Verb.POST);
+        activity.setPublished(new Date());
+        PersonObject person = new PersonObject();
+        person.setDisplayName("James");
+        activity.setActor(person);
+        NoteObject note = new NoteObject();
+        note.setContent("Test Content");
+        activity.setObject(note);
+        Session session = client.newSession();
+        ActivityEntity ae = new ActivityEntity(activity);
+        ClientResponse resp = session.post("http://localhost:9002/sample", ae);
+        assertNotNull(resp);
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        assertEquals(201, resp.getStatus());
+        assertEquals("http://localhost:9002/sample/foo", resp.getLocation().toString());
+        resp.release();
+        resp = session.get("http://localhost:9002/sample");
+        Collection<ASObject> coll = io.readCollection(resp.getReader());
+        Iterable<ASObject> items = coll.getItems();
+        int n = 0;
+        for (ASObject obj : items) {
+          assertTrue(obj instanceof Activity);
+          activity = (Activity) obj;
+          assertEquals(Verb.POST, activity.getVerb());
+          n++;
+        }
+        assertEquals(1, n);
+        resp.release();
+    }
+
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/AsyncBasicTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/BasicTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/BasicTest.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/BasicTest.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/BasicTest.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,199 @@
+package org.apache.abdera2.test.activities.server;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.Date;
+
+import org.apache.abdera2.activities.client.ActivityEntity;
+import org.apache.abdera2.activities.model.ASObject;
+import org.apache.abdera2.activities.model.Activity;
+import org.apache.abdera2.activities.model.Collection;
+import org.apache.abdera2.activities.model.IO;
+import org.apache.abdera2.activities.model.Verb;
+import org.apache.abdera2.activities.model.objects.NoteObject;
+import org.apache.abdera2.activities.model.objects.PersonObject;
+import org.apache.abdera2.activities.protocol.ActivitiesServiceManager;
+import org.apache.abdera2.activities.protocol.basic.BasicProvider;
+import org.apache.abdera2.protocol.client.BasicClient;
+import org.apache.abdera2.protocol.client.ClientResponse;
+import org.apache.abdera2.protocol.client.Client;
+import org.apache.abdera2.protocol.client.Session;
+import org.apache.abdera2.test.server.JettyServer;
+import org.apache.abdera2.common.Constants;
+import org.apache.abdera2.common.http.ResponseType;
+import org.apache.abdera2.common.mediatype.MimeTypeHelper;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class BasicTest {
+
+    private static JettyServer server;
+    private static Client client = new BasicClient();
+    private static IO io = IO.get();
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+        if (server == null) {
+            server = new JettyServer();
+            server.start(ActivitiesServiceManager.class, BasicProvider.class);
+        }
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        client.shutdown();
+        server.stop();
+    }
+
+    @Test
+    public void testGetFeed() throws IOException {
+        Session session = client.newSession();
+        ClientResponse resp = session.get("http://localhost:9002/sample");
+        Collection<ASObject> coll = io.readCollection(resp.getReader());
+        assertEquals("http://localhost:9002/sample", coll.getProperty("id").toString());
+        assertEquals("title for any sample feed", coll.getProperty("title"));
+        PersonObject person = coll.getProperty("author");
+        assertNotNull(person);
+        assertEquals("rayc", person.getDisplayName());
+        resp.release();
+    }
+
+    @Test
+    public void testPostEntry() throws IOException {
+        Activity activity = new Activity();
+        activity.setId("http://localhost:9002/sample/foo");
+        activity.setTitle("test entry");
+        activity.setVerb(Verb.POST);
+        activity.setPublished(new Date());
+        PersonObject person = new PersonObject();
+        person.setDisplayName("James");
+        activity.setActor(person);
+        NoteObject note = new NoteObject();
+        note.setContent("Test Content");
+        activity.setObject(note);
+        Session session = client.newSession();
+        ActivityEntity ae = new ActivityEntity(activity);
+        ClientResponse resp = session.post("http://localhost:9002/sample", ae);
+        assertNotNull(resp);
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        assertEquals(201, resp.getStatus());
+        assertEquals("http://localhost:9002/sample/foo", resp.getLocation().toString());
+        resp.release();
+        resp = session.get("http://localhost:9002/sample");
+        Collection<ASObject> coll = io.readCollection(resp.getReader());
+        Iterable<ASObject> items = coll.getItems();
+        int n = 0;
+        for (ASObject obj : items) {
+          assertTrue(obj instanceof Activity);
+          activity = (Activity) obj;
+          assertEquals(Verb.POST, activity.getVerb());
+          assertEquals("test entry", activity.getTitle());
+          n++;
+        }
+        assertEquals(1, n);
+        resp.release();
+    }
+
+    @Test
+    public void testPutEntry()  throws IOException {
+        Session session = client.newSession();
+        ClientResponse resp = session.get("http://localhost:9002/sample/foo");
+        assertTrue(MimeTypeHelper.isMatch(resp.getContentType().toString(), Constants.JSON_MEDIA_TYPE));
+        ASObject object = io.readObject(resp.getReader());
+        resp.release();
+        assertTrue(object instanceof Activity);
+        Activity activity = (Activity) object;
+        activity.setTitle("This is the modified title");
+        ActivityEntity ae = new ActivityEntity(activity);
+        resp = session.put("http://localhost:9002/sample/foo", ae);
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        assertEquals(200, resp.getStatus());
+        resp.release();
+        resp = session.get("http://localhost:9002/sample/foo");
+        object = io.readObject(resp.getReader());
+        resp.release();
+        assertTrue(object instanceof Activity);
+        activity = (Activity) object;
+        assertEquals("This is the modified title", activity.getTitle());
+        resp = session.get("http://localhost:9002/sample");
+        Collection<ASObject> coll = io.readCollection(resp.getReader());
+        Iterable<ASObject> items = coll.getItems();
+        int n = 0;
+        for (ASObject obj : items) {
+          assertTrue(obj instanceof Activity);
+          activity = (Activity) obj;
+          assertEquals(Verb.POST, activity.getVerb());
+          n++;
+        }
+        assertEquals(1, n);
+        resp.release();
+    }
+
+    @Test
+    public void testDeleteEntry() throws IOException {
+      Session session = client.newSession();
+        ClientResponse resp = session.delete("http://localhost:9002/sample/foo");
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        resp.release();
+        resp = session.get("http://localhost:9002/sample");
+        Collection<ASObject> coll = io.readCollection(resp.getReader());
+        coll.getItems();
+        resp.release();
+    }
+    
+    @SuppressWarnings("unused")
+    @Test
+    public void testMultiPostEntry() throws IOException {
+        Collection<Activity> collection = new Collection<Activity>();
+        for (int n = 0; n < 10; n++) {
+          Activity activity = new Activity();
+          activity.setId("http://localhost:9002/sample/foo" + n);
+          activity.setTitle("test entry " + n);
+          activity.setVerb(Verb.POST);
+          activity.setPublished(new Date());
+          PersonObject person = new PersonObject();
+          person.setDisplayName("James");
+          activity.setActor(person);
+          NoteObject note = new NoteObject();
+          note.setContent("Test Content " + n);
+          activity.setObject(note);
+          collection.addItem(activity);
+        }
+        Session session = client.newSession();
+        ActivityEntity ae = new ActivityEntity(collection);
+        ClientResponse resp = session.post("http://localhost:9002/sample", ae);
+        assertNotNull(resp);
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        assertEquals(201, resp.getStatus());
+        resp.release();
+        resp = session.get("http://localhost:9002/sample");
+        Collection<ASObject> coll = io.readCollection(resp.getReader());
+        Iterable<ASObject> items = coll.getItems();
+        int n = 0;
+        for (ASObject obj : items) n++;
+        assertEquals(10, n);
+        resp.release();
+    }
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/BasicTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/SampleBasicAdapter.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/SampleBasicAdapter.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/SampleBasicAdapter.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/SampleBasicAdapter.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,165 @@
+package org.apache.abdera2.test.activities.server;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+
+
+import java.util.Date;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.logging.Logger;
+
+import org.apache.abdera2.activities.model.ASObject;
+import org.apache.abdera2.activities.model.Collection;
+import org.apache.abdera2.activities.protocol.basic.BasicAdapter;
+import org.apache.abdera2.activities.protocol.managed.FeedConfiguration;
+import org.apache.abdera2.common.protocol.RequestContext;
+import org.apache.abdera2.common.protocol.ResponseContextException;
+
+public class SampleBasicAdapter extends BasicAdapter {
+
+    private static final String ERROR_INVALID_ENTRY = "No Such Entry in the Feed";
+
+    public static Logger logger = Logger.getLogger(SampleBasicAdapter.class.getName());
+    protected List<Item> entries = new LinkedList<Item>();
+
+    private static class Item {
+      private final String key;
+      private ASObject value;
+      Item(String key, ASObject value) {
+        this.key = key;
+        this.value = value;
+      }
+      String getKey() {
+        return key;
+      }
+      ASObject getValue() {
+        return value;
+      }
+      void setValue(ASObject value) {
+        this.value = value;
+      }
+    }
+    
+    public SampleBasicAdapter(FeedConfiguration config) {
+        super(config);
+    }
+
+    @Override
+    public Collection<ASObject> getCollection() throws Exception {
+        Collection<ASObject> col = createCollection();
+        
+        for (Item item : entries)
+          col.addItem(item.getValue());
+        return col;
+    }
+
+    @Override
+    public ASObject getItem(Object entryId) throws Exception {
+      ASObject ret = null;
+      for (Item item : entries)
+        if (item.getKey().equals(entryId.toString())) {
+          ret = item.getValue();
+          break;
+        }
+      return ret;
+    }
+
+    @Override
+    public ASObject createItem(ASObject object) throws Exception {
+        return createItem(object,-1);
+    }
+    
+    @Override
+    public ASObject createItem(ASObject object, int c) throws Exception {
+        setObjectIdIfNull(object);
+        logger.info("assigning id to Object: " + object.getId().toString());
+        String entryId = getObjectIdFromUri(object.getId().toString());
+        if (c != -1) entryId += c;
+        if (object.getUpdated() == null) {
+            object.setUpdated(new Date());
+        }
+        addEditLinkToObject(object);
+        storeObject(entryId, object);
+        logger.finest("returning this object from sampleadapter.createItem: " + object.toString());
+        return object;
+    }
+
+    @Override
+    public ASObject updateItem(Object entryId, ASObject object) throws Exception {
+        if (!deleteItem(entryId))
+            throw new Exception(ERROR_INVALID_ENTRY);
+        
+        if (object.getUpdated() == null) {
+            object.setUpdated(new Date());
+        }
+        addEditLinkToObject(object);
+        storeObject((String)entryId, object);
+        logger.finest("returning this entry from sampleadapter.updateEntry: " + object.toString());
+        return object;
+    }
+
+    @Override
+    public boolean deleteItem(Object entryId) throws Exception {
+      Item item = null;
+      for (Item i : entries) {
+        if (i.getKey().equals(entryId.toString())) {
+          item = i;
+          break;
+        }
+      }
+      if (item != null) {
+        entries.remove(item);
+        return true;
+      } else return false;
+    }
+
+    protected String getObjectIdFromUri(String uri) {
+        String[] segments = uri.split("/");
+        return segments[segments.length - 1];
+    }
+
+    protected void storeObject(String entryId, ASObject object) throws Exception {
+      Item item = null;
+      for (Item i : entries) {
+        if (i.getKey().equals(entryId)) {
+          item = i;
+          break;
+        }
+      }
+      if (item == null) { 
+        entries.add(0,new Item(entryId,object));
+      } else {
+        item.setValue(object);
+      }
+    }
+
+    @Override
+    public String getAuthor(RequestContext request) throws ResponseContextException {
+        return config.getFeedAuthor();
+    }
+
+    @Override
+    public String getId(RequestContext request) {
+        return config.getFeedId();
+    }
+
+    @Override
+    public String getTitle(RequestContext request) {
+        return config.getFeedTitle();
+    }
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/SampleBasicAdapter.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/TestChannelServlet.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/TestChannelServlet.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/TestChannelServlet.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/TestChannelServlet.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,66 @@
+package org.apache.abdera2.test.activities.server;
+
+import java.io.IOException;
+import java.io.Writer;
+
+import javax.servlet.AsyncContext;
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.abdera2.activities.model.ASObject;
+import org.apache.abdera2.activities.model.IO;
+import org.apache.abdera2.common.protocol.servlet.async.AbderaChannelServlet;
+
+public class TestChannelServlet 
+  extends AbderaChannelServlet {
+
+  private static final long serialVersionUID = 4020428773015858214L;
+
+  protected String getChannel(AsyncContext context) {
+    HttpServletRequest req = (HttpServletRequest) context.getRequest();
+    String pi = req.getPathInfo();
+    return pi.substring(pi.lastIndexOf('/')+1);
+  }
+
+  @Override
+  protected AsyncListener<ASObject> createListener(final AsyncContext context) {
+    return new AsyncListener<ASObject>(context) {
+
+      public void beforeItems() {
+        try {
+          HttpServletResponse response = 
+            (HttpServletResponse) context.getResponse();
+          Writer writer = response.getWriter();
+          writer.write("{\"items\":[");
+          response.flushBuffer();
+        } catch (IOException e) {}
+      }
+      public void onItem(ASObject t) {
+        try {
+          HttpServletResponse response = 
+            (HttpServletResponse) context.getResponse();
+          Writer writer = response.getWriter();
+          IO.get().write(t,writer);
+          response.flushBuffer();
+        } catch (Throwable e) {}
+      }
+      protected void finish() {
+        try {
+          HttpServletResponse response = 
+            (HttpServletResponse) context.getResponse();
+          Writer writer = response.getWriter();
+          writer.write("]}");
+          response.flushBuffer();
+        } catch (IOException e) {}
+      }
+    };
+  }
+
+  @Override
+  protected long getTimeout(ServletConfig config, ServletContext context) {
+    return 60 * 1000;
+  }
+
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/activities/server/TestChannelServlet.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/AppTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/AppTest.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/AppTest.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/AppTest.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,727 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+package org.apache.abdera2.test.client;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.activation.MimeType;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.abdera2.Abdera;
+import org.apache.abdera2.factory.Factory;
+import org.apache.abdera2.common.iri.IRI;
+import org.apache.abdera2.model.Collection;
+import org.apache.abdera2.model.Document;
+import org.apache.abdera2.model.Entry;
+import org.apache.abdera2.model.Feed;
+import org.apache.abdera2.model.Service;
+import org.apache.abdera2.model.Workspace;
+import org.apache.abdera2.parser.Parser;
+import org.apache.abdera2.parser.ParserOptions;
+import org.apache.abdera2.protocol.client.AbderaClient;
+import org.apache.abdera2.protocol.client.AbderaClientResponse;
+import org.apache.abdera2.protocol.client.AbderaSession;
+import org.apache.abdera2.protocol.client.BasicClient;
+import org.apache.abdera2.protocol.client.Client;
+import org.apache.abdera2.protocol.client.RequestOptions;
+import org.apache.abdera2.protocol.client.Session;
+import org.apache.abdera2.common.http.CacheControl;
+import org.apache.abdera2.common.http.EntityTag;
+import org.apache.abdera2.common.mediatype.MimeTypeHelper;
+import org.apache.abdera2.test.JettyUtil;
+import org.apache.abdera2.writer.WriterOptions;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Test to make sure that we can operate as a simple APP client
+ */
+@SuppressWarnings("serial")
+public class AppTest {
+
+    protected static void getServletHandler(String... servletMappings) {
+        for (int n = 0; n < servletMappings.length; n = n + 2) {
+            String name = servletMappings[n];
+            String root = servletMappings[n + 1];
+            JettyUtil.addServlet(name, root);
+        }
+    }
+
+    protected String getBase() {
+        return "http://localhost:" + JettyUtil.getPort();
+    }
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+        getServletHandler();
+        JettyUtil.start();
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        JettyUtil.stop();
+    }
+
+    private static Abdera abdera = Abdera.getInstance();
+
+    private static Factory getFactory() {
+        return abdera.getFactory();
+    }
+
+    private static Parser getParser() {
+        return abdera.getParser();
+    }
+
+    private static AppTest INSTANCE = null;
+
+    private static Document<Service> init_service_document(String base) {
+        try {
+            Service service = getFactory().newService();
+            Workspace workspace = service.addWorkspace("Test");
+            workspace.addCollection("Entries", base + "/collections/entries").setAcceptsEntry();
+            workspace.addCollection("Other", base + "/collections/other").setAccept("text/plain");
+            Document<Service> doc = service.getDocument();
+            return doc;
+        } catch (Exception e) {
+        }
+        return null;
+    }
+
+    private static Document<Feed> init_entries_document(String base) {
+        try {
+            Feed feed = getFactory().newFeed();
+            feed.setId(base + "/collections/entries");
+            feed.setTitle("Entries");
+            feed.setUpdated(new Date());
+            feed.addLink(base + "/collections/entries");
+            feed.addLink(base + "/collections/entries", "self");
+            feed.addAuthor("James");
+            Document<Feed> doc = feed.getDocument();
+            return doc;
+        } catch (Exception e) {
+        }
+        return null;
+    }
+
+    public static class ServiceDocumentServlet extends HttpServlet {
+        private Document<Service> service = init_service_document(AppTest.INSTANCE.getBase());
+
+        @Override
+        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+
+            response.setStatus(HttpServletResponse.SC_OK);
+            response.setContentType("application/atomsvc+xml; charset=utf-8");
+            WriterOptions options = service.getDefaultWriterOptions();
+            options.setCharset("UTF-8");
+            service.writeTo(response.getOutputStream(), options);
+        }
+    }
+
+    /**
+     * this implements a very simple (and quite buggy) APP server. It's just enough for us to test the client behaviors.
+     * I'm sure it could be greatly improved.
+     */
+    public static class CollectionServlet extends HttpServlet {
+        protected Document<Feed> feed = init_entries_document(AppTest.INSTANCE.getBase());
+        protected Map<String, String> media = new HashMap<String, String>();
+
+        private String[] tokens = null;
+        private final static int COLLECTION = 0;
+        private final static int ENTRY = 1;
+        private final static int MEDIA = 2;
+
+        private int getTargetType(HttpServletRequest request) {
+            tokens = request.getRequestURI().split("/");
+            if (tokens[2].equals("entries") && tokens.length == 3)
+                return COLLECTION;
+            if (tokens[2].equals("entries") && tokens.length == 4)
+                return ENTRY;
+            if (tokens[2].equals("media") && tokens.length == 4)
+                return MEDIA;
+            return -1;
+        }
+
+        private int getTarget() {
+            return (tokens.length != 4) ? -1 : Integer.parseInt(tokens[3]);
+        }
+
+        @Override
+        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+            int t = getTargetType(request);
+            switch (t) {
+                case COLLECTION:
+                    response.setStatus(HttpServletResponse.SC_OK);
+                    response.setContentType("application/atom+xml; charset=utf-8");
+                    WriterOptions options = feed.getDefaultWriterOptions();
+                    options.setCharset("UTF-8");
+                    feed.writeTo(response.getOutputStream(), options);
+                    break;
+                case ENTRY:
+                    try {
+                        Entry entry = feed.getRoot().getEntries().get(getTarget());
+                        response.setStatus(HttpServletResponse.SC_OK);
+                        response.setContentType("application/atom+xml; charset=utf-8");
+                        options = entry.getDefaultWriterOptions();
+                        options.setCharset("UTF-8");
+                        entry.writeTo(response.getOutputStream(), options);
+                    } catch (Exception e) {
+                        response.sendError(HttpServletResponse.SC_NOT_FOUND);
+                        break;
+                    }
+                    break;
+                case MEDIA:
+                    try {
+                        String m = media.get(AppTest.INSTANCE.getBase() + "/collections/entries/" + getTarget());
+                        if (m != null) {
+                            response.setStatus(HttpServletResponse.SC_OK);
+                            response.setContentType("text/plain");
+                            response.getWriter().write(m);
+                            break;
+                        } else {
+                            response.sendError(HttpServletResponse.SC_NOT_FOUND);
+                        }
+                    } catch (Exception e) {
+                        response.sendError(HttpServletResponse.SC_NOT_FOUND);
+                    }
+            }
+        }
+
+        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+            int t = getTargetType(request);
+            switch (t) {
+                case COLLECTION:
+                    try {
+                        if (MimeTypeHelper.isMatch(request.getContentType(), "application/atom+xml;type=entry")) {
+                            MimeType type = new MimeType(request.getContentType());
+                            String charset = type.getParameter("charset");
+                            String uri = AppTest.INSTANCE.getBase() + "/collections/entries";
+                            ParserOptions options = getParser().getDefaultParserOptions();
+                            options.setCharset(charset);
+                            Document<?> doc = getParser().parse(request.getInputStream(), uri, options);
+                            if (doc.getRoot() instanceof Entry) {
+                                Entry entry = (Entry)doc.getRoot().clone();
+                                String newID =
+                                    AppTest.INSTANCE.getBase() + "/collections/entries/"
+                                        + feed.getRoot().getEntries().size();
+                                entry.setId(newID);
+                                entry.setUpdated(new Date());
+                                entry.addLink(entry.getId().toString(), "edit");
+                                entry.addLink(entry.getId().toString(), "self");
+                                feed.getRoot().insertEntry(entry);
+                                response.setStatus(HttpServletResponse.SC_CREATED);
+                                response.setHeader("Location", entry.getId().toString());
+                                response.setHeader("Content-Location", entry.getId().toString());
+                                WriterOptions woptions = entry.getDefaultWriterOptions();
+                                woptions.setCharset("UTF-8");
+                                entry.writeTo(response.getOutputStream(), woptions);
+                                return;
+                            }
+                        }
+                        if (MimeTypeHelper.isMatch(request.getContentType(), "text/plain")) {
+                            int n = feed.getRoot().getEntries().size();
+                            String media = read(request.getInputStream());
+                            Entry entry = getFactory().newEntry();
+                            String newID = AppTest.INSTANCE.getBase() + "/collections/entries/" + n;
+                            String slug = request.getHeader("Slug");
+                            entry.setId(newID);
+                            entry.setTitle(slug);
+                            entry.setUpdated(new Date());
+                            entry.setSummary(slug);
+                            entry.addLink(entry.getId().toString(), "edit");
+                            entry.addLink(AppTest.INSTANCE.getBase() + "/collections/media/" + n, "edit-media")
+                                .setMimeType("text/plain");
+                            entry.addLink(entry.getId().toString(), "self");
+                            entry.setContent(new IRI(AppTest.INSTANCE.getBase() + "/collections/media/" + n),
+                                             "text/plain");
+                            feed.getRoot().insertEntry(entry);
+                            this.media.put(entry.getId().toString(), media);
+                            response.setStatus(HttpServletResponse.SC_CREATED);
+                            response.setHeader("Location", entry.getId().toString());
+                            response.setHeader("Content-Location", entry.getId().toString());
+                            WriterOptions woptions = entry.getDefaultWriterOptions();
+                            woptions.setCharset("UTF-8");
+                            entry.writeTo(response.getOutputStream(), woptions);
+                            return;
+                        }
+                        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
+                    } catch (Exception e) {
+                    }
+                    break;
+                default:
+                    response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
+            }
+        }
+
+        protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+            int t = getTargetType(request);
+            int target = getTarget();
+            switch (t) {
+                case ENTRY:
+                    try {
+                        if (MimeTypeHelper.isMatch(request.getContentType(), "application/atom+xml;type=entry")) {
+                            Entry entry = feed.getRoot().getEntries().get(target);
+                            MimeType type = new MimeType(request.getContentType());
+                            String charset = type.getParameter("charset");
+                            String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target;
+                            ParserOptions options = getParser().getDefaultParserOptions();
+                            options.setCharset(charset);
+                            Document<?> doc = getParser().parse(request.getInputStream(), uri, options);
+                            if (doc.getRoot() instanceof Entry) {
+                                Entry newentry = (Entry)doc.getRoot().clone();
+                                if (newentry.getId().equals(entry.getId())) {
+                                    newentry.setUpdated(new Date());
+                                    entry.discard();
+                                    feed.getRoot().insertEntry(newentry);
+                                    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+                                    return;
+                                } else {
+                                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot change atom:id");
+                                    return;
+                                }
+                            }
+                        }
+                        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
+                    } catch (Exception e) {
+                    }
+                    break;
+                case MEDIA:
+                    if (MimeTypeHelper.isMatch(request.getContentType(), "text/plain")) {
+                        String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target;
+                        String media = read(request.getInputStream());
+                        this.media.put(uri, media);
+                        Entry entry = feed.getRoot().getEntries().get(target);
+                        entry.setUpdated(new Date());
+                        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+                        return;
+                    }
+                    response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
+                    break;
+                default:
+                    response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
+            }
+        }
+
+        protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+            int t = getTargetType(request);
+            int target = getTarget();
+            switch (t) {
+                case ENTRY:
+                case MEDIA:
+                    String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target;
+                    Entry entry = feed.getRoot().getEntries().get(target);
+                    entry.discard();
+                    media.remove(uri);
+                    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
+                    return;
+                default:
+                    response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
+            }
+        }
+    }
+
+    private static String read(InputStream in) throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        int m = -1;
+        while ((m = in.read()) != -1) {
+            out.write(m);
+        }
+        String resp = new String(out.toByteArray());
+        return resp.trim();
+    }
+
+    public AppTest() {
+        AppTest.INSTANCE = this;
+    }
+
+    protected static void getServletHandler() {
+        getServletHandler(ServiceDocumentServlet.class.getName(),
+                          "/service",
+                          CollectionServlet.class.getName(),
+                          "/collections/*");
+    }
+
+    @Test
+    public void testRequestOptions() throws Exception {
+        Client abderaClient = new BasicClient();
+        Session session = abderaClient.newSession();
+        RequestOptions options = session.getDefaultRequestOptions();
+        options.setIfModifiedSince(new Date());
+        assertNotNull(options.getIfModifiedSince());
+
+        options.set4xxRequestException(true);
+        assertTrue(options.is4xxRequestException());
+
+        options.set5xxRequestException(true);
+        assertTrue(options.is5xxRequestException());
+
+        options.setAccept("text/plain");
+        assertEquals("text/plain", options.getAccept());
+
+        options.setAcceptCharset("UTF-8");
+        assertEquals("UTF-8", options.getAcceptCharset());
+
+        options.setAcceptEncoding("gzip");
+        assertEquals("gzip", options.getAcceptEncoding());
+
+        options.setAcceptLanguage("en-US");
+        assertEquals("en-US", options.getAcceptLanguage());
+
+//        options.setAuthorization("auth");
+//        assertEquals("auth", options.getAuthorization());
+
+        options.setCacheControl("no-cache");
+        CacheControl cc = options.getCacheControl();
+        assertTrue(cc.isNoCache());
+
+        options.setContentType("text/plain");
+        assertTrue(MimeTypeHelper.isMatch(options.getContentType(), new MimeType("text/plain")));
+
+        options.setEncodedHeader("foo", "UTF-8", "bar");
+        assertEquals("bar", options.getDecodedHeader("foo"));
+
+        options.setHeader("foo", "bar");
+        assertEquals("bar", options.getHeader("foo"));
+
+        options.setIfMatch("testing");
+        assertTrue(EntityTag.matchesAny(new EntityTag("testing"), options.getIfMatch()));
+
+        options.setIfNoneMatch("testing");
+        assertTrue(EntityTag.matchesAny(new EntityTag("testing"), options.getIfNoneMatch()));
+
+        options.setSlug("This is the slug");
+        assertEquals("This is the slug", options.getSlug());
+
+        options.setUsePostOverride(true);
+        assertTrue(options.isUsePostOverride());
+        
+        abderaClient.shutdown();
+    }
+
+    @Test
+    public void testAppClient() throws Exception {
+        AbderaClient abderaClient = new AbderaClient();
+        AbderaSession session = (AbderaSession) abderaClient.newSession();
+        Entry entry = getFactory().newEntry();
+        RequestOptions options = session.getDefaultRequestOptions();
+        options.setHeader("Connection", "close");
+        options.setUseExpectContinue(false);
+
+        // do the introspection step
+        AbderaClientResponse response = 
+          (AbderaClientResponse) session.get(
+            "http://localhost:" + JettyUtil.getPort() + "/service", options);
+        String col_uri;
+
+        try {
+            assertEquals(200, response.getStatus());
+
+            Document<Service> service_doc = response.getDocument();
+            assertNotNull(service_doc);
+            assertEquals(1, service_doc.getRoot().getWorkspaces().size());
+
+            Workspace workspace = service_doc.getRoot().getWorkspace("Test");
+            assertNotNull(workspace);
+
+            for (Collection c : workspace.getCollections()) {
+                assertNotNull(c.getTitle());
+                assertNotNull(c.getHref());
+            }
+
+            col_uri = getBase() + "/collections/entries";
+        } finally {
+            response.release();
+        }
+
+        // post a new entry
+        response = (AbderaClientResponse) session.post(col_uri, entry, options);
+
+        String self_uri;
+
+        try {
+            assertEquals(201, response.getStatus());
+            assertNotNull(response.getLocation());
+            assertNotNull(response.getContentLocation());
+
+            self_uri = response.getLocation().toString();
+        } finally {
+            response.release();
+        }
+
+        // get the collection to see if our entry is there
+        response = (AbderaClientResponse) session.get(col_uri, options);
+
+        try {
+            assertEquals(200, response.getStatus());
+            Document<Feed> feed_doc = response.getDocument();
+            assertEquals(1, feed_doc.getRoot().getEntries().size());
+        } finally {
+            response.release();
+        }
+
+        // get the entry to see if we can get it
+        response = (AbderaClientResponse) session.get(self_uri, options);
+
+        String edit_uri;
+
+        try {
+            assertEquals(200, response.getStatus());
+            Document<Entry> entry_doc = response.getDocument();
+
+            // this isn't always true, but for our tests they are the same
+            assertEquals(self_uri, entry_doc.getRoot().getId().toString());
+
+            // get the edit uri from the entry
+            edit_uri = entry_doc.getRoot().getEditLink().getHref().toString();
+
+            // change the entry
+            Document<Entry> doc = response.getDocument();
+            entry = (Entry)doc.getRoot().clone();
+            entry.setTitle("New title");
+        } finally {
+            response.release();
+        }
+
+        // submit the changed entry back to the server
+        response = (AbderaClientResponse) session.put(edit_uri, entry, options);
+
+        try {
+            assertEquals(204, response.getStatus());
+        } finally {
+            response.release();
+        }
+
+        // check to see if the entry was modified properly
+        response = (AbderaClientResponse) session.get(self_uri, options);
+
+        try {
+            assertEquals(200, response.getStatus());
+
+            Document<Entry> entry_doc = response.getDocument();
+            assertEquals("New title", entry_doc.getRoot().getTitle());
+        } finally {
+            response.release();
+        }
+
+        // delete the entry
+        response = (AbderaClientResponse) session.delete(edit_uri, options);
+
+        try {
+            assertEquals(204, response.getStatus());
+        } finally {
+            response.release();
+        }
+
+        // is it gone?
+        response = (AbderaClientResponse) session.get(self_uri, options);
+
+        try {
+            assertEquals(404, response.getStatus());
+        } finally {
+            response.release();
+        }
+
+        // YAY! We're a working APP client
+
+        // Now let's try to do a media post
+
+        // Post the media resource
+        options = session.getDefaultRequestOptions();
+        options.setContentType("text/plain");
+        options.setHeader("Connection", "close");
+        options.setUseExpectContinue(false);
+
+        response = (AbderaClientResponse) session.post(col_uri, new ByteArrayInputStream("test".getBytes()), options);
+
+        try {
+            assertEquals(201, response.getStatus());
+            assertNotNull(response.getLocation());
+            assertNotNull(response.getContentLocation());
+
+            self_uri = response.getLocation().toString();
+        } finally {
+            response.release();
+        }
+
+        // was an entry created?
+        options = session.getDefaultRequestOptions();
+        options.setHeader("Connection", "close");
+        response = (AbderaClientResponse) session.get(self_uri, options);
+
+        String edit_media, media;
+
+        try {
+            assertEquals(200, response.getStatus());
+            Document<Entry> entry_doc = response.getDocument();
+
+            // this isn't always true, but for our tests they are the same
+            assertEquals(self_uri, entry_doc.getRoot().getId().toString());
+
+            // get the right links from the entry
+            edit_uri = entry_doc.getRoot().getEditLink().getHref().toString();
+            edit_media = entry_doc.getRoot().getLink("edit-media").getHref().toString();
+            media = entry_doc.getRoot().getContentElement().getSrc().toString();
+
+            // edit the entry
+            Document<Entry> doc = response.getDocument();
+            entry = (Entry)doc.getRoot().clone();
+            entry.setTitle("New title");
+        } finally {
+            response.release();
+        }
+
+        // submit the changes
+        options = session.getDefaultRequestOptions();
+        options.setContentType("application/atom+xml;type=entry");
+        options.setHeader("Connection", "close");
+        options.setUseExpectContinue(false);
+
+        response = (AbderaClientResponse) session.put(edit_uri, entry, options);
+
+        try {
+            assertEquals(204, response.getStatus());
+        } finally {
+            response.release();
+        }
+
+        // get the media resource
+        response = (AbderaClientResponse) session.get(media);
+
+        try {
+            assertEquals(200, response.getStatus());
+
+            String mediavalue = read(response.getInputStream());
+            assertEquals("test", mediavalue);
+        } finally {
+            response.release();
+        }
+
+        // edit the media resource
+        options = session.getDefaultRequestOptions();
+        options.setHeader("Connection", "close");
+        options.setContentType("text/plain");
+        options.setUseExpectContinue(false);
+
+        response = (AbderaClientResponse) session.put(edit_media, new ByteArrayInputStream("TEST".getBytes()), options);
+
+        try {
+            assertEquals(204, response.getStatus());
+        } finally {
+            response.release();
+        }
+
+        // was the resource changed?
+        response = (AbderaClientResponse) session.get(media, options);
+
+        try {
+            assertEquals(200, response.getStatus());
+
+            String mediavalue = read(response.getInputStream());
+            assertEquals("TEST", mediavalue);
+        } finally {
+            response.release();
+        }
+
+        // delete the entry
+        response = (AbderaClientResponse) session.delete(edit_uri, options);
+
+        try {
+            assertEquals(204, response.getStatus());
+        } finally {
+            response.release();
+        }
+
+        // is the entry gone?
+        response = (AbderaClientResponse) session.get(self_uri, options);
+
+        try {
+            assertEquals(404, response.getStatus());
+        } finally {
+            response.release();
+        }
+
+        // is the media resource gone?
+        options.setCacheControl(CacheControl.NOCACHE());
+
+        response = (AbderaClientResponse) session.get(media, options);
+
+        try {
+            assertEquals(404, response.getStatus());
+        } finally {
+            response.release();
+        }
+
+        // YAY! We can handle media link entries
+        abderaClient.shutdown();
+    }
+
+    private Iterable<EntityTag> i(EntityTag... tags) {
+      List<EntityTag> l = new ArrayList<EntityTag>();
+      for (EntityTag tag : tags)
+        l.add(tag);
+      return l;
+    }
+    
+    @Test
+    public void testEntityTag() throws Exception {
+        EntityTag tag1 = new EntityTag("tag");
+        EntityTag tag2 = new EntityTag("tag", true); // weak;
+        assertFalse(tag1.isWeak());
+        assertTrue(tag2.isWeak());
+        assertFalse(EntityTag.matches(tag1, tag2));
+        assertFalse(EntityTag.matchesAny(tag1, i(tag2)));
+        assertEquals("\"tag\"", tag1.toString());
+        assertEquals("W/\"tag\"", tag2.toString());
+        tag1 = EntityTag.parse("\"tag\"");
+        assertFalse(tag1.isWeak());
+        assertEquals("tag", tag1.getTag());
+        tag2 = EntityTag.parse("W/\"tag\"");
+        assertTrue(tag2.isWeak());
+        assertEquals("tag", tag2.getTag());
+        Iterable<EntityTag> tags = EntityTag.parseTags("\"tag1\", W/\"tag2\"");
+        Iterator<EntityTag> i = tags.iterator();
+        EntityTag tag = i.next();
+        assertFalse(tag.isWeak());
+        assertEquals("tag1", tag.getTag());
+        tag = i.next();
+        assertTrue(tag.isWeak());
+        assertEquals("tag2", tag.getTag());
+    }
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/AppTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,480 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+package org.apache.abdera2.test.client;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.abdera2.common.http.CacheControl;
+import org.apache.abdera2.protocol.client.BasicCachingClient;
+import org.apache.abdera2.protocol.client.ClientResponse;
+import org.apache.abdera2.protocol.client.Client;
+import org.apache.abdera2.protocol.client.RequestOptions;
+import org.apache.abdera2.protocol.client.Session;
+import org.apache.abdera2.test.JettyUtil;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * These cache tests were originally based on Mark Nottingham's javascript cache tests, available at:
+ * http://www.mnot.net/javascript/xmlhttprequest/cache.html They have since been modified to use an embedded Jetty
+ * server instead of going off over the internet to hit Mark's server, since there are too many things that can get in
+ * the way of those sort things (proxies, intermediate caches, etc) if you try to talk to a remote server.
+ */
+@SuppressWarnings("serial")
+public class CacheTest {
+
+    private static String CHECK_CACHE_INVALIDATE;
+    private static String CHECK_NO_CACHE;
+    // private static String CHECK_AUTH;
+    private static String CHECK_MUST_REVALIDATE;
+
+    public CacheTest() {
+        String base = getBase();
+        CHECK_CACHE_INVALIDATE = base + "/check_cache_invalidate";
+        CHECK_NO_CACHE = base + "/no_cache";
+        // CHECK_AUTH = base + "/auth";
+        CHECK_MUST_REVALIDATE = base + "/must_revalidate";
+    }
+
+    protected static void getServletHandler(String... servletMappings) {
+        for (int n = 0; n < servletMappings.length; n = n + 2) {
+            String name = servletMappings[n];
+            String root = servletMappings[n + 1];
+            JettyUtil.addServlet(name, root);
+        }
+    }
+
+    protected String getBase() {
+        return "http://localhost:" + JettyUtil.getPort();
+    }
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+        getServletHandler();
+        JettyUtil.start();
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        JettyUtil.stop();
+    }
+
+    protected static void getServletHandler() {
+        getServletHandler("org.apache.abdera2.test.client.CacheTest$CheckCacheInvalidateServlet",
+                          "/check_cache_invalidate",
+                          "org.apache.abdera2.test.client.CacheTest$NoCacheServlet",
+                          "/no_cache",
+                          "org.apache.abdera2.test.client.CacheTest$AuthServlet",
+                          "/auth",
+                          "org.apache.abdera2.test.client.CacheTest$CheckMustRevalidateServlet",
+                          "/must_revalidate");
+    }
+
+    public static class CheckMustRevalidateServlet extends HttpServlet {
+        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+            String reqnum = request.getHeader("X-Reqnum");
+            int req = Integer.parseInt(reqnum);
+            if (req == 1) {
+                response.setStatus(HttpServletResponse.SC_OK);
+                response.setContentType("text/plain");
+                response.setHeader("Cache-Control", "must-revalidate");
+                response.setDateHeader("Date", System.currentTimeMillis());
+                response.getWriter().println(reqnum);
+                response.getWriter().close();
+            } else if (req == 2) {
+                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
+                response.setContentType("text/plain");
+                response.setDateHeader("Date", System.currentTimeMillis());
+                return;
+            } else if (req == 3) {
+                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+                response.setDateHeader("Date", System.currentTimeMillis());
+                return;
+            }
+        }
+    }
+
+    public static class CheckCacheInvalidateServlet extends HttpServlet {
+        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+            String reqnum = request.getHeader("X-Reqnum");
+            response.setStatus(HttpServletResponse.SC_OK);
+            response.setDateHeader("Date", System.currentTimeMillis());
+            response.setContentType("text/plain");
+            response.setHeader("Cache-Control", "max-age=60");
+            response.getWriter().println(reqnum);
+            response.getWriter().close();
+        }
+
+        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+        }
+
+        protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+        }
+
+        protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+        }
+    }
+
+    public static class NoCacheServlet extends HttpServlet {
+        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+            String reqnum = request.getHeader("X-Reqnum");
+            int reqtest = Integer.parseInt(request.getHeader("X-Reqtest"));
+
+            response.setContentType("text/plain");
+            response.setStatus(HttpServletResponse.SC_OK);
+            switch (reqtest) {
+                case NOCACHE:
+                    response.setHeader("Cache-Control", "no-cache");
+                    break;
+                case NOSTORE:
+                    response.setHeader("Cache-Control", "no-store");
+                    break;
+                case MAXAGE0:
+                    response.setHeader("Cache-Control", "max-age=0");
+                    break;
+            }
+            response.setDateHeader("Date", System.currentTimeMillis());
+
+            response.getWriter().println(reqnum);
+            response.getWriter().close();
+        }
+    }
+
+    public static class AuthServlet extends HttpServlet {
+        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+            IOException {
+            String reqnum = request.getHeader("X-Reqnum");
+            int num = Integer.parseInt(reqnum);
+            switch (num) {
+                case 1:
+                    response.setStatus(HttpServletResponse.SC_OK);
+                    break;
+                case 2:
+                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+                    break;
+                default:
+                    response.setStatus(HttpServletResponse.SC_OK);
+                    break;
+            }
+            response.setDateHeader("Date", System.currentTimeMillis());
+            response.setContentType("text/plain");
+            response.getWriter().println(reqnum);
+            response.getWriter().close();
+        }
+    }
+
+    private static final int NOCACHE = 0;
+    private static final int NOSTORE = 1;
+    private static final int MAXAGE0 = 2;
+    private static final int POST = 3;
+    private static final int DELETE = 4;
+    private static final int PUT = 5;
+
+    @Test
+    public void testRequestNoStore() throws Exception {
+        _requestCacheInvalidation(NOSTORE);
+    }
+
+    @Test
+    public void testRequestNoCache() throws Exception {
+        _requestCacheInvalidation(NOCACHE);
+    }
+
+    @Test
+    public void testRequestMaxAge0() throws Exception {
+        _requestCacheInvalidation(MAXAGE0);
+    }
+
+    @Test
+    public void testResponseNoStore() throws Exception {
+        _responseNoCache(NOSTORE);
+    }
+
+    @Test
+    public void testResponseNoCache() throws Exception {
+        _responseNoCache(NOCACHE);
+    }
+
+    @Test
+    public void testResponseMaxAge0() throws Exception {
+        _responseNoCache(MAXAGE0);
+    }
+
+    @Test
+    public void testPostInvalidates() throws Exception {
+        _methodInvalidates(POST);
+    }
+
+    @Test
+    public void testPutInvalidates() throws Exception {
+        _methodInvalidates(PUT);
+    }
+
+    @Test
+    public void testDeleteInvalidates() throws Exception {
+        _methodInvalidates(DELETE);
+    }
+
+    @Test
+    public void testAuthForcesRevalidation() throws Exception {
+
+        // TODO: Actually need to rethink this. Responses to authenticated requests
+        // should never be cached unless the resource is explicitly marked as
+        // being cacheable (e.g. using Cache-Control: public). So this test
+        // was testing incorrect behavior.
+
+        // AbderaClient client = new CommonsClient();
+        // client.usePreemptiveAuthentication(true);
+        // client.addCredentials(CHECK_AUTH, null, null, new UsernamePasswordCredentials("james","snell"));
+        // RequestOptions options = client.getDefaultRequestOptions();
+        // options.setHeader("Connection", "close");
+        // options.setRevalidateWithAuth(true);
+        // options.setHeader("x-reqnum", "1");
+        // Response response = client.get(CHECK_AUTH, options);
+        //  
+        // // first request works as expected. fills the cache
+        // String resp1 = getResponse(response);
+        // assertEquals(resp1, "1");
+        //
+        // // second request uses authentication, should force revalidation of the cache
+        // options.setHeader("x-reqnum", "2");
+        // response = client.get(CHECK_AUTH, options);
+        //  
+        // resp1 = getResponse(response);
+        // assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED);
+        // assertEquals(resp1, "2");
+        //
+        // // third request does not use authentication, but since the previous request
+        // // resulted in an "unauthorized" response, the cache needs to be refilled
+        // options.setHeader("x-reqnum", "3");
+        // client.usePreemptiveAuthentication(false);
+        // response = client.get(CHECK_AUTH, options);
+        //  
+        // resp1 = getResponse(response);
+        // assertEquals(response.getStatus(), HttpServletResponse.SC_OK);
+        // assertEquals(resp1, "3");
+        //
+        // // fourth request does not use authentication, will pull from the cache
+        // options = client.getDefaultRequestOptions();
+        // options.setHeader("x-reqnum", "4");
+        // client.usePreemptiveAuthentication(false);
+        // response = client.get(CHECK_AUTH, options);
+        //  
+        // resp1 = getResponse(response);
+        // assertEquals(response.getStatus(), HttpServletResponse.SC_OK);
+        // assertEquals(resp1, "3");
+        //    
+        // // fifth request uses authentication, will force revalidation
+        // options.setAuthorization("Basic amFtZXM6c25lbGw=");
+        // options.setHeader("x-reqnum", "5");
+        // response = client.get(CHECK_AUTH, options);
+        //    
+        // resp1 = getResponse(response);
+        // assertEquals(response.getStatus(), HttpServletResponse.SC_OK);
+        // assertEquals(resp1, "5");
+    }
+
+    @Test
+    public void testResponseMustRevalidate() throws Exception {
+        Client abderaClient = new BasicCachingClient();
+        Session session = abderaClient.newSession();
+        RequestOptions options = session.getDefaultRequestOptions();
+        options.setHeader("Connection", "close");
+        options.setHeader("x-reqnum", "1");
+        ClientResponse response = session.get(CHECK_MUST_REVALIDATE, options);
+
+        String resp1 = getResponse(response);
+        assertEquals("1", resp1);
+
+        // Should be revalidated and use the cache
+        options.setHeader("x-reqnum", "2");
+        response = session.get(CHECK_MUST_REVALIDATE, options);
+
+        assertEquals(304, response.getStatus());
+
+        // Should be revalidated and return a 404
+        options.setHeader("x-reqnum", "3");
+        response = session.get(CHECK_MUST_REVALIDATE, options);
+        assertEquals(404, response.getStatus());
+        response.release();
+
+        abderaClient.shutdown();
+    }
+
+    private RequestOptions getRequestOptions(Session session, int num) {
+        RequestOptions options = session.getDefaultRequestOptions();
+        options.setHeader("Connection", "close");
+        options.setHeader("x-reqnum", String.valueOf(num));
+        options.setUseExpectContinue(false);
+        return options;
+    }
+
+    private void _methodInvalidates(int type) throws Exception {
+
+        Client abderaClient = new BasicCachingClient();
+        Session session = abderaClient.newSession();
+        RequestOptions options = getRequestOptions(session, 1);
+        ClientResponse response = session.get(CHECK_CACHE_INVALIDATE, options);
+
+        String resp1 = getResponse(response);
+
+        response.release();
+        assertEquals("1", resp1);
+
+        // calling a method that could change state on the server should invalidate the cache
+        options = getRequestOptions(session, 2);
+        switch (type) {
+            case POST:
+                response = session.post(CHECK_CACHE_INVALIDATE, new ByteArrayInputStream("".getBytes()), options);
+                break;
+            case PUT:
+                response = session.put(CHECK_CACHE_INVALIDATE, new ByteArrayInputStream("".getBytes()), options);
+                break;
+            case DELETE:
+                response = session.delete(CHECK_CACHE_INVALIDATE, options);
+                break;
+        }
+        response.release();
+
+        options = getRequestOptions(session, 3);
+        response = session.get(CHECK_CACHE_INVALIDATE, options);
+
+        resp1 = getResponse(response);
+        response.release();
+        assertEquals("3", resp1);
+        
+        abderaClient.shutdown();
+    }
+
+    private void _requestCacheInvalidation(int type) throws Exception {
+
+        BasicCachingClient abderaClient = new BasicCachingClient();
+        Session session = abderaClient.newSession();
+        RequestOptions options = getRequestOptions(session, 1);
+        ClientResponse response = session.get(CHECK_CACHE_INVALIDATE, options);
+        String resp1 = getResponse(response);
+        assertEquals("1", resp1);
+
+        // Should use the cache
+        options = getRequestOptions(session, 3);
+        switch (type) {
+            case NOCACHE:
+                options.setCacheControl(CacheControl.NOCACHE().setNoCache(false));
+                break;
+            case NOSTORE:
+              options.setCacheControl(CacheControl.NOSTORE().setNoStore(false));
+                break;
+            case MAXAGE0:
+              options.setCacheControl(CacheControl.MAXAGE(60));
+              try {
+                // sleep for a few seconds to let the cache age;
+                Thread.sleep(5*1000);
+              } catch (Throwable t) {}
+                break;
+        }
+        response = session.get(CHECK_CACHE_INVALIDATE, options);
+        String resp3 = getResponse(response);
+        assertEquals("1", resp3);
+        
+        // Should not use the cache
+        options = getRequestOptions(session, 2);
+        switch (type) {
+            case NOCACHE:
+                options.setCacheControl(CacheControl.NOCACHE());
+                break;
+            case NOSTORE:
+                options.setCacheControl(CacheControl.NOSTORE());
+                break;
+            case MAXAGE0:
+                options.setCacheControl(CacheControl.MAXAGE(0));
+                try {
+                  // sleep for a few seconds to let the cache age;
+                  Thread.sleep(5*1000);
+                } catch (Throwable t) {}
+                break;
+        }
+        response = session.get(CHECK_CACHE_INVALIDATE, options);
+
+        String resp2 = getResponse(response);
+        assertEquals("2", resp2);
+       
+        abderaClient.shutdown();
+    }
+
+    private void _responseNoCache(int type) throws Exception {
+
+        Client abderaClient = new BasicCachingClient();
+        Session session = abderaClient.newSession();
+        RequestOptions options = getRequestOptions(session, 1);
+        options.setHeader("x-reqtest", String.valueOf(type));
+        ClientResponse response = session.get(CHECK_NO_CACHE, options);
+
+        String resp1 = getResponse(response);
+        assertEquals("1", resp1);
+
+        // Should not use the cache
+
+        options = getRequestOptions(session, 2);
+        options.setHeader("x-reqtest", String.valueOf(type));
+        response = session.get(CHECK_NO_CACHE, options);
+
+        String resp2 = getResponse(response);
+        assertEquals("2", resp2);
+
+        // Should use the cache
+        options = getRequestOptions(session, 3);
+        options.setHeader("x-reqtest", String.valueOf(type));
+        response = session.get(CHECK_NO_CACHE, options);
+
+        String resp3 = getResponse(response);
+        assertEquals("3", resp3);
+        
+        abderaClient.shutdown();
+    }
+
+    private static String getResponse(ClientResponse response) throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        int m = -1;
+        InputStream in = response.getInputStream();
+        if (in == null) return null;
+        while ((m = in.read()) != -1) {
+            out.write(m);
+        }
+        in.close();
+        String resp = new String(out.toByteArray());
+        return resp.trim();
+    }
+
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+package org.apache.abdera2.test.client;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+
+import javax.activation.MimeType;
+
+import org.apache.abdera2.common.iri.IRI;
+import org.apache.abdera2.model.Entry;
+import org.apache.abdera2.parser.axiom.FOMEntry;
+import org.apache.abdera2.protocol.client.MultipartRelatedEntity;
+import org.apache.abdera2.common.mediatype.MimeTypeHelper;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.entity.mime.content.InputStreamBody;
+import org.eclipse.jetty.io.WriterOutputStream;
+import org.junit.Test;
+
+public class MultipartRelatedEntityTest {
+
+    @Test
+    public void testMultipartFormat() throws IOException {
+        Entry entry = new FOMEntry();
+        entry.setTitle("my image");
+        entry.addAuthor("david");
+        entry.setId("tag:apache.org,2008:234534344");
+        entry.setSummary("multipart test");
+        entry.setContent(new IRI("cid:234234@example.com"), "image/jpg");
+        MultipartRelatedEntity request =
+            new MultipartRelatedEntity(
+              entry, 
+              new InputStreamBody(this.getClass().getResourceAsStream("/info.png"),"image/jpg",null),
+              "image/jpg",
+              "asdfasdfasdf");
+        StringWriter sw = new StringWriter();
+        WriterOutputStream os = new WriterOutputStream(sw);
+        request.writeTo(os);
+
+        String multipart = sw.toString();
+        // System.out.println(sw.toString());
+
+        assertTrue(multipart.contains("Content-ID: <234234@example.com>"));
+        assertTrue(multipart.contains("Content-Type: image/jpg"));
+    }
+
+    @Test
+    public void testMultimediaRelatedContentType() throws Exception {
+        MimeType type = new MimeType("Multipart/Related;boundary=\"35245352345sdfg\"");
+        assertTrue(MimeTypeHelper.isMatch("Multipart/Related", type.toString()));
+        assertEquals("35245352345sdfg", type.getParameter("boundary"));
+    }
+
+    // @Test
+    public void testMultipartEncoding() throws Exception {
+        InputStream input = this.getClass().getResourceAsStream("info.png");
+        int BUFF_SIZE = 1024;
+
+        byte[] line = new byte[BUFF_SIZE];
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        while (input.read(line) != -1) {
+            output.write(line);
+        }
+
+        Base64 base64 = new Base64();
+        byte[] encoded = base64.encode(output.toByteArray());
+        ByteArrayInputStream bi = new ByteArrayInputStream(base64.decode(encoded));
+
+        File f = new File("info-out.png");
+        if (f.exists())
+            f.delete();
+        f.createNewFile();
+        FileOutputStream fo = new FileOutputStream(f);
+
+        int end;
+        while ((end = bi.read(line)) != -1) {
+            fo.write(line, 0, end);
+        }
+
+        fo.flush();
+        fo.close();
+    }
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/anno/AnnoUtilTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/anno/AnnoUtilTest.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/anno/AnnoUtilTest.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/anno/AnnoUtilTest.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,78 @@
+package org.apache.abdera2.test.common.anno;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Set;
+
+import org.apache.abdera2.common.anno.AnnoUtil;
+import org.apache.abdera2.common.anno.DefaultImplementation;
+import org.apache.abdera2.common.anno.Name;
+import org.apache.abdera2.common.anno.Namespace;
+import org.apache.abdera2.common.anno.QName;
+import org.apache.abdera2.common.anno.Version;
+import org.apache.abdera2.protocol.client.BasicClient;
+import org.junit.Test;
+
+@DefaultImplementation("FooBarBaz")
+@Version(value="A",name="B",uri="C")
+@Name("AnnoUtilTest")
+@Namespace("Foo")
+@QName(value="A",ns="B",pfx="C")
+public class AnnoUtilTest {
+
+  @Test
+  public void getDefaultImplementationTest() {
+    String di = AnnoUtil.getDefaultImplementation(AnnoUtilTest.class);
+    assertEquals("FooBarBaz", di);
+  }
+  
+  @Test
+  public void getDefaultUserAgentTest() {
+    String ua = BasicClient.getDefaultUserAgent();
+    assertEquals("Abdera/v2.0-SNAPSHOT",ua);
+  }
+  
+  @Test
+  public void getVersionTest() {
+    Version version = AnnoUtil.getVersion(AnnoUtilTest.class);
+    assertEquals("A",version.value());
+    assertEquals("B",version.name());
+    assertEquals("C",version.uri());
+  }
+  
+  @Test
+  public void getNameTest() {
+    String name = AnnoUtil.getName(AnnoUtilTest.class);
+    assertEquals("AnnoUtilTest",name);
+  }
+  
+  @Test
+  public void getNamespacesTest() {
+    Set<String> set = AnnoUtil.getNamespaces(AnnoUtilTest.class);
+    assertTrue(set.contains("Foo"));
+  }
+  
+  @Test
+  public void handlesNamespaceTest() {
+    assertTrue(AnnoUtil.handlesNamespace("Foo", AnnoUtilTest.class));
+  }
+  
+  @Test
+  public void getQNameTest() {
+    javax.xml.namespace.QName qname = AnnoUtil.getQName(AnnoUtilTest.class);
+    assertEquals("A",qname.getLocalPart());
+    assertEquals("B",qname.getNamespaceURI());
+    assertEquals("C",qname.getPrefix());
+  }
+  
+  @Test
+  public void qNameFromAnnoTest() {
+    Class<?> _class = AnnoUtilTest.class;
+    QName qname = _class.getAnnotation(QName.class);
+    javax.xml.namespace.QName q = AnnoUtil.qNameFromAnno(qname);
+    assertEquals("A",q.getLocalPart());
+    assertEquals("B",q.getNamespaceURI());
+    assertEquals("C",q.getPrefix());
+  }
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/anno/AnnoUtilTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/date/DateTimeTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/date/DateTimeTest.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/date/DateTimeTest.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/date/DateTimeTest.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,89 @@
+package org.apache.abdera2.test.common.date;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+
+import java.util.Calendar;
+import java.util.Date;
+
+import org.apache.abdera2.common.date.DateTime;
+import org.junit.Test;
+
+public class DateTimeTest {
+
+    @Test
+    public void testHashCode() {
+        long time = System.currentTimeMillis();
+        DateTime ad1 = new DateTime(time);
+        assertTrue(ad1.hashCode() == ad1.hashCode());
+        DateTime ad2 = new DateTime(time + 10);
+        assertFalse(ad1.hashCode() == ad2.hashCode());
+    }
+
+    @Test
+    public void testDateTimeDate() {
+        Date now = new Date();
+        DateTime adNow = new DateTime(now);
+        assertEquals(now, adNow.getDate());
+        // mutate 'now', to assert DateTime cloned value
+        now.setTime(now.getTime() + 10);
+        assertFalse(now.getTime() == adNow.getTime());
+    }
+
+    @Test
+    public void testGetDate() {
+        Date now = new Date();
+        DateTime adNow = new DateTime(now);
+        assertEquals(now, adNow.getDate());
+
+        // getDate, then mutate to assert it was cloned
+        Date now2 = adNow.getDate();
+        now2.setTime(now2.getTime() + 10);
+        assertFalse(now2.equals(adNow.getDate()));
+    }
+
+    @Test
+    public void testClone() {
+        DateTime ad = new DateTime();
+        DateTime adClone = (DateTime)ad.clone();
+        assertEquals(ad, adClone);
+        assertNotSame(ad, adClone);
+    }
+
+    @Test
+    public void testDateTime() {
+        Date now = new Date();
+        DateTime atomNow = DateTime.valueOf(now);
+        String rfc3339 = atomNow.getValue();
+        atomNow = DateTime.valueOf(rfc3339);
+        Date parsed = atomNow.getDate();
+        assertEquals(now, parsed);
+    }
+
+    @Test
+    public void testDateTime2() {
+        String date = "2007-12-13T14:15:16.123Z";
+        DateTime DateTime = new DateTime(date);
+        Calendar calendar = DateTime.getCalendar();
+        DateTime = new DateTime(calendar);
+        assertEquals(date, DateTime.toString());
+    }
+
+    @Test
+    public void testDateTime3() {
+        long date = System.currentTimeMillis();
+        DateTime DateTime = new DateTime(date);
+        Calendar calendar = DateTime.getCalendar();
+        DateTime = new DateTime(calendar);
+        assertEquals(date, DateTime.getTime());
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testIllegalDateFormat() {
+        String date = "";
+        new DateTime(date);
+    }
+
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/date/DateTimeTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/geo/GeoTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/geo/GeoTest.java?rev=1173209&view=auto
==============================================================================
--- abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/geo/GeoTest.java (added)
+++ abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/geo/GeoTest.java Tue Sep 20 15:56:46 2011
@@ -0,0 +1,97 @@
+package org.apache.abdera2.test.common.geo;
+
+import org.apache.abdera2.common.geo.Box;
+import org.apache.abdera2.common.geo.Coordinate;
+import org.apache.abdera2.common.geo.Coordinates;
+import org.apache.abdera2.common.geo.IsoPosition;
+import org.apache.abdera2.common.geo.Line;
+import org.apache.abdera2.common.geo.Multiple;
+import org.apache.abdera2.common.geo.Point;
+import org.apache.abdera2.common.geo.Polygon;
+import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class GeoTest {
+
+  @Test
+  public void isoPositionTest() {
+    IsoPosition iso = IsoPosition.parse("+12.1234567+123.1234567+123.1234567");
+    assertEquals(12.1234567,iso.getLatitude(),0);
+    assertEquals(123.1234567,iso.getLongitude(),0);
+    assertEquals(123.1234567,iso.getAltitude(),0);
+    assertEquals("+12.123457+123.123457+123.123457/", iso.toString());
+  }
+  
+  @Test
+  public void boxTest() {
+    Coordinate c1 = new Coordinate(1.0,2.0);
+    Coordinate c2 = new Coordinate(3.0,4.0);
+    Box box = new Box(c1,c2);
+    assertEquals(c1,box.getLowerCorner());
+    assertEquals(c2,box.getUpperCorner());
+  }
+  
+  @Test
+  public void coordinateTest() {
+    Coordinate c1 = new Coordinate(1.0,2.0);
+    assertEquals(1.0,c1.getLatitude(),0);
+    assertEquals(2.0,c1.getLongitude(),0);
+  }
+  
+  @Test
+  public void coordinatesTest() {
+    Coordinates cs = new Coordinates();
+    cs.add(new Coordinate(1.0,2.0));
+    cs.add(new Coordinate(3.0,4.0));
+    cs.add(new Coordinate(5.0,6.0));
+    assertEquals(3,cs.size());
+    assertTrue(cs.contains(3.0,4.0));
+    cs.remove(1.0,2.0);
+    assertFalse(cs.contains(1.0,2.0));
+    assertEquals(2,cs.size());
+  }
+  
+  @Test
+  public void lineTest() {
+    Coordinates cs = new Coordinates();
+    cs.add(new Coordinate(1.0,2.0));
+    cs.add(new Coordinate(3.0,4.0));
+    cs.add(new Coordinate(5.0,6.0));
+    Line line = new Line(cs);
+    line.verify();
+  }
+  
+  @SuppressWarnings("unused")
+  @Test
+  public void multipleTest() {
+    Coordinates cs = new Coordinates();
+    cs.add(new Coordinate(1.0,2.0));
+    cs.add(new Coordinate(3.0,4.0));
+    cs.add(new Coordinate(5.0,6.0));
+    Multiple mult = new Multiple(cs) {
+      private static final long serialVersionUID = 2214118656567387273L;};
+    int n = 0;
+    for (Coordinate c : mult) n++;
+    assertEquals(3,n);
+  }
+  
+  @Test
+  public void pointTest() {
+    Coordinate c = new Coordinate(1.0,2.0);
+    Point point = new Point(c);
+    assertEquals(1.0,point.getCoordinate().getLatitude(),0);
+  }
+  
+  @Test
+  public void polygonTest() {
+    Coordinates cs = new Coordinates();
+    cs.add(new Coordinate(1.0,2.0));
+    cs.add(new Coordinate(3.0,4.0));
+    cs.add(new Coordinate(5.0,6.0));
+    Polygon poly = new Polygon(cs);
+    poly.verify();
+  }
+  
+}

Propchange: abdera/abdera2/test/src/main/java/org/apache/abdera2/test/common/geo/GeoTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain



Mime
View raw message