abdera-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jmsn...@apache.org
Subject svn commit: r1239237 [10/12] - in /abdera/abdera2-server: ./ .settings/ etc/ examples/ examples/src/ examples/src/main/ examples/src/main/java/ examples/src/main/java/org/ examples/src/main/java/org/apache/ examples/src/main/java/org/apache/abdera2/ ex...
Date Wed, 01 Feb 2012 17:55:02 GMT
Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,503 @@
+/*
+ * 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.Client;
+import org.apache.abdera2.protocol.client.ClientResponse;
+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();
+        ClientResponse response = 
+          session.get(
+            CHECK_MUST_REVALIDATE, 
+            session.getDefaultRequestOptions()
+              .header("Connection", "close")
+              .header("x-reqnum", "1")
+              .get());
+
+        String resp1 = getResponse(response);
+        assertEquals("1", resp1);
+
+        response = session.get(
+          CHECK_MUST_REVALIDATE, 
+          session.getDefaultRequestOptions()
+            .header("Connection", "close")
+            .header("x-reqnum", "2")
+            .get());
+
+        assertEquals(304, response.getStatus());
+
+        response = session.get(
+          CHECK_MUST_REVALIDATE, 
+          session.getDefaultRequestOptions()
+            .header("Connection", "close")
+            .header("x-reqnum", "3")
+            .get());
+        assertEquals(404, response.getStatus());
+        response.release();
+
+        abderaClient.shutdown();
+    }
+
+    private RequestOptions.Builder getRequestOptions(Session session, int num) {
+        return session.getDefaultRequestOptions()
+          .header("Connection", "close")
+          .header("x-reqnum", String.valueOf(num))
+          .doNotUseExpectContinue();
+    }
+
+    private void _methodInvalidates(int type) throws Exception {
+
+        Client abderaClient = new BasicCachingClient();
+        Session session = abderaClient.newSession();
+        ClientResponse response = session.get(
+          CHECK_CACHE_INVALIDATE, 
+          getRequestOptions(session, 1).get());
+
+        String resp1 = getResponse(response);
+
+        response.release();
+        assertEquals("1", resp1);
+
+        switch (type) {
+            case POST:
+                response = session.post(
+                  CHECK_CACHE_INVALIDATE, 
+                  new ByteArrayInputStream("".getBytes()), 
+                  getRequestOptions(session, 2).get());
+                break;
+            case PUT:
+                response = session.put(
+                  CHECK_CACHE_INVALIDATE, 
+                  new ByteArrayInputStream("".getBytes()), 
+                  getRequestOptions(session, 2).get());
+                break;
+            case DELETE:
+                response = session.delete(
+                  CHECK_CACHE_INVALIDATE, 
+                  getRequestOptions(session, 2).get());
+                break;
+        }
+        response.release();
+        
+        response = session.get(
+          CHECK_CACHE_INVALIDATE, 
+          getRequestOptions(session, 3).get());
+
+        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();
+        ClientResponse response = session.get(
+          CHECK_CACHE_INVALIDATE, 
+          getRequestOptions(session, 1).get());
+        String resp1 = getResponse(response);
+        assertEquals("1", resp1);
+
+        // Should use the cache
+        RequestOptions.Builder builder = getRequestOptions(session, 3);
+        switch (type) {
+          case NOCACHE:
+            builder.cacheControl(CacheControl.NONNOCACHE());
+            break;
+          case NOSTORE:
+            builder.cacheControl(CacheControl.NONNOSTORE());
+            break;
+          case MAXAGE0:
+            builder.cacheControl(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, builder.get());
+        String resp3 = getResponse(response);
+        assertEquals("1", resp3);
+        
+        // Should not use the cache
+        builder = getRequestOptions(session, 2);
+        switch (type) {
+          case NOCACHE:
+            builder.cacheControl(CacheControl.NOCACHE());
+            break;
+          case NOSTORE:
+            builder.cacheControl(CacheControl.NOSTORE());
+            break;
+          case MAXAGE0:
+            builder.cacheControl(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, builder.get());
+
+        String resp2 = getResponse(response);
+        assertEquals("2", resp2);
+       
+        abderaClient.shutdown();
+    }
+
+    private void _responseNoCache(int type) throws Exception {
+
+        Client abderaClient = new BasicCachingClient();
+        Session session = abderaClient.newSession();
+        ClientResponse response = 
+          session.get(
+            CHECK_NO_CACHE, 
+            getRequestOptions(session, 1)
+              .header("x-reqtest", String.valueOf(type))
+              .get());
+
+        String resp1 = getResponse(response);
+        assertEquals("1", resp1);
+
+        // Should not use the cache
+        response = session.get(
+          CHECK_NO_CACHE, 
+          getRequestOptions(session, 2)
+            .header("x-reqtest", String.valueOf(type))
+            .get());
+
+        String resp2 = getResponse(response);
+        assertEquals("2", resp2);
+
+        // Should use the cache
+        response = session.get(
+          CHECK_NO_CACHE, 
+          getRequestOptions(session, 3)
+            .header("x-reqtest", String.valueOf(type))
+            .get());
+
+        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-server/test/src/main/java/org/apache/abdera2/test/client/CacheTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/ClientTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/ClientTest.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/ClientTest.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/ClientTest.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,157 @@
+package org.apache.abdera2.test.client;
+/*
+ * 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 java.io.IOException;
+import java.io.Reader;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.abdera2.common.misc.MoreExecutors2;
+import org.apache.abdera2.protocol.client.BasicClient;
+import org.apache.abdera2.protocol.client.Client;
+import org.apache.abdera2.protocol.client.ClientResponse;
+import org.apache.abdera2.protocol.client.Session;
+import org.apache.abdera2.protocol.client.Session.Listener;
+import org.apache.abdera2.test.JettyUtil;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.AbstractFuture;
+import static com.google.common.base.Preconditions.checkState;
+
+public class ClientTest {
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+      JettyUtil.addServlet(TestServlet.class.getName(), "/");
+      JettyUtil.start();
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+      JettyUtil.stop();
+    }
+
+    public static class TestServlet extends HttpServlet {
+      private static final long serialVersionUID = -1725406584245400456L;
+      protected void doGet(
+        HttpServletRequest request, 
+        HttpServletResponse response)
+          throws ServletException, IOException {
+        Cookie cookie = 
+          new Cookie(
+            "x-test", 
+            "x-test");
+        response.addCookie(
+          cookie);
+        
+        String val = "Foo";
+        Cookie[] cookies = request.getCookies();
+        if (cookies.length > 0)
+          for (Cookie c : cookies)
+            if (c.getName().equalsIgnoreCase("x-test"))
+              val = c.getValue();
+        response.getWriter().write(val);
+      }
+    }
+    
+    String read(Reader reader) throws IOException {
+      StringBuilder sb = new StringBuilder();
+      char[] buf = new char[100];
+      int r = -1;
+      while ((r = reader.read(buf)) > -1) 
+        sb.append(buf,0,r);
+      return sb.toString();
+    }
+    
+    @Test
+    public void testClient() throws Exception {
+      Client client = new BasicClient();
+      
+      Session session = client.newSession();
+      
+      // Test Blocking Request
+      ClientResponse resp = session.get("http://localhost:9002/");
+      assertEquals(200,resp.getStatus());
+      assertEquals("Foo",read(resp.getReader()));
+      resp.release();
+      
+      // Test Non-Blocking Request using a listener.. test cookies while we're at it
+      ExecutorService exec =
+        MoreExecutors2.getExitingExecutor();
+      
+      final FutureMap<String,Object> future =
+        new FutureMap<String,Object>();
+      session.get(
+        "http://localhost:9002/", 
+        exec,
+        new Listener<ClientResponse>() {
+          public void onResponse(ClientResponse resp) {
+            try {
+              future
+                .put("status", resp.getStatus())
+                .put("data", read(resp.getReader()));
+            } catch (Throwable t) {
+              future.put("error", t);
+            } finally {
+              future.complete();
+              //resp.release(); session will auto-release the response
+            }
+          }
+        }
+      );
+      Map<String,Object> map = future.get();
+      assertEquals(Integer.valueOf(200),map.get("status"));
+      assertEquals("x-test",map.get("data"));
+      
+      // Test Non-Blocking Request using a Future
+      Future<ClientResponse> respFuture = 
+        session.get("http://localhost:9002/", exec);
+      resp = respFuture.get();
+      assertEquals(200,resp.getStatus());
+      assertEquals("x-test",read(resp.getReader()));
+      resp.release();
+      
+      client.shutdown();
+    }
+    
+    static class FutureMap<X,Y> extends AbstractFuture<Map<X,Y>> {
+      private ImmutableMap.Builder<X,Y> builder = ImmutableMap.builder();
+      FutureMap<X,Y> put(X key, Y value) {
+        checkState(!isDone());
+        builder.put(key,value);
+        return this;
+      }
+      void complete() {
+        checkState(!isDone());
+        this.set(builder.build());
+      }
+    }
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,105 @@
+/*
+ * 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);
+        input.close();
+
+        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();
+        if (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-server/test/src/main/java/org/apache/abdera2/test/client/MultipartRelatedEntityTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/DigitalSignatureTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/DigitalSignatureTest.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/DigitalSignatureTest.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/DigitalSignatureTest.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,114 @@
+/*
+ * 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.security;
+
+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.InputStream;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+
+import javax.xml.namespace.QName;
+
+import org.apache.abdera2.Abdera;
+import org.apache.abdera2.factory.Factory;
+import org.apache.abdera2.model.Document;
+import org.apache.abdera2.model.Entry;
+import org.apache.abdera2.security.Security;
+import org.apache.abdera2.security.Signature;
+import org.apache.abdera2.security.SignatureOptions;
+import org.joda.time.DateTime;
+import org.junit.Test;
+
+public class DigitalSignatureTest {
+
+    private static final String keystoreFile = "/key.jks";
+    private static final String keystoreType = "JKS";
+    private static final String keystorePass = "testing";
+    private static final String privateKeyAlias = "James";
+    private static final String privateKeyPass = "testing";
+    private static final String certificateAlias = "James";
+
+    @Test
+    public void testSignEntry() throws Exception {
+
+        // Initialize the keystore
+        KeyStore ks = KeyStore.getInstance(keystoreType);
+        assertNotNull(ks);
+
+        InputStream in = DigitalSignatureTest.class.getResourceAsStream(keystoreFile);
+        assertNotNull(in);
+
+        ks.load(in, keystorePass.toCharArray());
+        PrivateKey signingKey = (PrivateKey)ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
+        X509Certificate cert = (X509Certificate)ks.getCertificate(certificateAlias);
+        assertNotNull(signingKey);
+        assertNotNull(cert);
+
+        // Create the entry to sign
+        Abdera abdera = Abdera.getInstance();
+        Security absec = new Security(abdera);
+        Factory factory = abdera.getFactory();
+
+        Entry entry = factory.newEntry();
+        entry.setId("http://example.org/foo/entry");
+        entry.setUpdated(DateTime.now());
+        entry.setTitle("This is an entry");
+        entry.setContentAsXhtml("This <b>is</b> <i>markup</i>");
+        entry.addAuthor("James");
+        entry.addLink("http://www.example.org");
+
+        // Prepare the digital signature options
+        Signature sig = absec.getSignature();
+        SignatureOptions options = 
+          sig.getDefaultSignatureOptions()
+            .certificate(cert)
+            .signingKey(signingKey)
+            .get();
+
+        // Sign the entry
+        entry = sig.sign(entry, options);
+        assertNotNull(entry.getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature")));
+
+        X509Certificate[] certs = sig.getValidSignatureCertificates(entry, options);
+        assertNotNull(certs);
+        assertEquals(1, certs.length);
+        assertEquals("CN=James M Snell, OU=WebAhead, O=IBM, L=Hanford, ST=California, C=US", certs[0].getSubjectDN()
+            .getName());
+
+        // Check the round trip
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        entry.writeTo(out); // do not use the pretty writer, it will break the signature
+        ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray());
+        Document<Entry> entry_doc = abdera.getParser().parse(bais);
+        entry = entry_doc.getRoot();
+        assertTrue(sig.verify(entry, null)); // the signature better still be valid
+
+        entry.setTitle("Change the title");
+
+        assertFalse(sig.verify(entry, null)); // the signature better be invalid
+
+    }
+
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/EncryptionTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/EncryptionTest.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/EncryptionTest.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/EncryptionTest.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,98 @@
+/*
+ * 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.security;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.security.Provider;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.xml.namespace.QName;
+
+import org.apache.abdera2.Abdera;
+import org.apache.abdera2.factory.Factory;
+import org.apache.abdera2.model.Document;
+import org.apache.abdera2.model.Entry;
+import org.apache.abdera2.security.Security;
+import org.apache.abdera2.security.Encryption;
+import org.apache.abdera2.security.EncryptionOptions;
+import org.joda.time.DateTime;
+import org.junit.Test;
+
+public class EncryptionTest {
+
+    /**
+     * The bouncy castle JCE provider is required to run this test
+     */
+    @Test
+    public void testEncryption() throws Exception {
+
+        Abdera abdera = Abdera.getInstance();
+
+        try {
+            String jce =
+                abdera.getConfiguration().getConfigurationOption("jce.provider",
+                                                                 "org.bouncycastle.jce.provider.BouncyCastleProvider");
+            Class<?> provider = Class.forName(jce);
+            Provider p = (Provider)provider.newInstance();
+            java.security.Security.addProvider(p);
+        } catch (Exception e) {
+            // the configured jce provider is not available, try to proceed anyway
+        }
+
+        // Generate Encryption Key
+        String jceAlgorithmName = "AES";
+        KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName);
+        keyGenerator.init(128);
+        SecretKey key = keyGenerator.generateKey();
+
+        // Create the entry to encrypt
+        Security absec = new Security(abdera);
+        Factory factory = abdera.getFactory();
+
+        Entry entry = factory.newEntry();
+        entry.setId("http://example.org/foo/entry");
+        entry.setUpdated(DateTime.now());
+        entry.setTitle("This is an entry");
+        entry.setContentAsXhtml("This <b>is</b> <i>markup</i>");
+        entry.addAuthor("James");
+        entry.addLink("http://www.example.org");
+
+        // Prepare the encryption options
+        Encryption enc = absec.getEncryption();
+        EncryptionOptions options = 
+          enc.getDefaultEncryptionOptions()
+            .dataEncryptionKey(key).get();
+
+        // Encrypt the document using the generated key
+        Document<?> enc_doc = enc.encrypt(entry.getDocument(), options);
+
+        assertEquals(new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), enc_doc.getRoot().getQName());
+
+        // Decrypt the document using the generated key
+        Document<Entry> entry_doc = enc.decrypt(enc_doc, options);
+
+        assertTrue(entry_doc.getRoot() instanceof Entry);
+
+        assertEquals("http://example.org/foo/entry", entry_doc.getRoot().getId().toString());
+
+    }
+
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/CustomAtompubServiceManager.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/CustomAtompubServiceManager.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/CustomAtompubServiceManager.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/CustomAtompubServiceManager.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,18 @@
+package org.apache.abdera2.test.security.filter;
+
+import java.util.Map;
+
+import org.apache.abdera2.common.protocol.Provider;
+import org.apache.abdera2.protocol.server.AtompubServiceManager;
+
+public class CustomAtompubServiceManager extends AtompubServiceManager {
+
+  @SuppressWarnings("unchecked")
+  @Override
+  public <P extends Provider> P newProvider(Map<String, Object> properties) {
+    CustomProvider cp = new CustomProvider("/");
+    cp.init(properties);
+    return (P)cp;
+  }
+
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/CustomProvider.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/CustomProvider.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/CustomProvider.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/CustomProvider.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,72 @@
+/*
+ * 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.security.filter;
+
+import org.apache.abdera2.common.protocol.CollectionAdapter;
+import org.apache.abdera2.common.protocol.RequestContext;
+import org.apache.abdera2.common.protocol.RouteManager;
+import org.apache.abdera2.common.protocol.TargetType;
+import org.apache.abdera2.protocol.server.impl.AbstractAtompubWorkspaceProvider;
+import org.apache.abdera2.protocol.server.impl.SimpleWorkspaceInfo;
+import org.apache.abdera2.security.util.filters.SignedRequestFilter;
+import org.apache.abdera2.security.util.filters.SignedResponseFilter;
+
+public class CustomProvider 
+  extends AbstractAtompubWorkspaceProvider {
+
+    private final SimpleAdapter adapter;
+
+    private static final String keystoreFile = "/key.jks";
+    private static final String keystorePass = "testing";
+    private static final String privateKeyAlias = "James";
+    private static final String privateKeyPass = "testing";
+    private static final String certificateAlias = "James";
+
+    @SuppressWarnings("unchecked")
+    public CustomProvider(String href) {
+        this.adapter = new SimpleAdapter(href);
+        RouteManager<TargetType,RequestContext,String> rm =
+          RouteManager.<TargetType,RequestContext,String>make()
+            .with("service", "/", TargetType.TYPE_SERVICE)
+            .with("collection","/:collection",TargetType.TYPE_COLLECTION)
+            .with("entry", "/:collection/:entry", TargetType.TYPE_ENTRY)
+            .get();
+        setTargetBuilder(rm);
+        setTargetResolver(rm);
+        addWorkspace(
+          SimpleWorkspaceInfo
+            .make()
+            .title("A Simple Workspace")
+            .collection(adapter)
+            .get());
+        addFilter(
+          new SignedRequestFilter());
+        addFilter(new SignedResponseFilter(
+              keystoreFile, 
+              keystorePass, 
+              privateKeyAlias,
+              privateKeyPass, 
+              certificateAlias, 
+              null));
+    }
+
+    public CollectionAdapter getCollectionAdapter(RequestContext request) {
+        return adapter;
+    }
+
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/JettyServer.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/JettyServer.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/JettyServer.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/JettyServer.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,62 @@
+/*
+ * 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.security.filter;
+
+import org.apache.abdera2.common.protocol.Provider;
+import org.apache.abdera2.common.protocol.ServiceManager;
+import org.apache.abdera2.common.protocol.servlet.AbderaServlet;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+
+
+public class JettyServer {
+
+    public static final int DEFAULT_PORT = 9002;
+
+    private final int port;
+    private Server server;
+
+    public JettyServer() {
+        this(DEFAULT_PORT);
+    }
+
+    public JettyServer(int port) {
+        this.port = port;
+    }
+
+    public void start(Class<? extends ServiceManager> _class) throws Exception {
+        server = new Server(port);
+        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
+        context.setContextPath("/");
+        server.setHandler(context);
+        ServletHolder servletHolder = new ServletHolder(new AbderaServlet());
+        servletHolder.setInitParameter(ServiceManager.class.getName(), _class.getName());
+        context.addServlet(servletHolder, "/*");
+        server.start();
+    }
+
+    public void stop() throws Exception {
+        server.stop();
+    }
+
+    public void join() throws Exception {
+        server.join();
+    }
+
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/SecurityFilterTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/SecurityFilterTest.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/SecurityFilterTest.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/SecurityFilterTest.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,127 @@
+/*
+ * 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.security.filter;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+
+import org.apache.abdera2.Abdera;
+import org.apache.abdera2.common.http.ResponseType;
+import org.apache.abdera2.model.Document;
+import org.apache.abdera2.model.Element;
+import org.apache.abdera2.model.Entry;
+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.security.Security;
+import org.apache.abdera2.security.Signature;
+import org.apache.abdera2.security.SignatureOptions;
+import org.apache.abdera2.test.security.DigitalSignatureTest;
+import org.joda.time.DateTime;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class SecurityFilterTest {
+
+    private static JettyServer server;
+    private static Abdera abdera = Abdera.getInstance();
+    private static AbderaClient client = new AbderaClient(abdera);
+    
+    @BeforeClass
+    public static void setUp() throws Exception {
+        try {
+
+            server = new JettyServer();
+            server.start(CustomAtompubServiceManager.class);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        server.stop();
+    }
+
+    @Test
+    public void testSignedResponseFilter() throws Exception {
+        Document<Element> doc = client.get("http://localhost:9002/");
+        Element root = doc.getRoot();
+        Security security = new Security(abdera);
+        Signature sig = security.getSignature();
+        assertTrue(sig.isSigned(root));
+        assertTrue(sig.verify(root, sig.getDefaultSignatureOptions().get()));
+    }
+
+    private static final String keystoreFile = "/key.jks";
+    private static final String keystoreType = "JKS";
+    private static final String keystorePass = "testing";
+    private static final String privateKeyAlias = "James";
+    private static final String privateKeyPass = "testing";
+    private static final String certificateAlias = "James";
+
+    @Test
+    public void testSignedRequestFilter() throws Exception {
+        Entry entry = abdera.newEntry();
+        entry.setId("http://localhost:9002/feed/entries/1");
+        entry.setTitle("test entry");
+        entry.setContent("Test Content");
+        entry.addLink("http://example.org");
+        entry.setUpdated(DateTime.now());
+        entry.addAuthor("James");
+        AbderaSession session = (AbderaSession) client.newSession();
+        AbderaClientResponse resp = (AbderaClientResponse) session.post("http://localhost:9002/feed", entry);
+        assertNotNull(resp);
+        assertEquals(ResponseType.CLIENT_ERROR, resp.getType());
+
+        // Initialize the keystore
+        Security security = new Security(abdera);
+        KeyStore ks = KeyStore.getInstance(keystoreType);
+        assertNotNull(ks);
+
+        InputStream in = DigitalSignatureTest.class.getResourceAsStream(keystoreFile);
+        assertNotNull(in);
+
+        ks.load(in, keystorePass.toCharArray());
+        PrivateKey signingKey = (PrivateKey)ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
+        X509Certificate cert = (X509Certificate)ks.getCertificate(certificateAlias);
+        assertNotNull(signingKey);
+        assertNotNull(cert);
+
+        Signature sig = security.getSignature();
+        SignatureOptions options = 
+          sig.getDefaultSignatureOptions()
+            .certificate(cert)
+            .signingKey(signingKey)
+            .get();
+
+        // Sign the entry
+        entry = sig.sign(entry, options);
+        resp = (AbderaClientResponse) session.post("http://localhost:9002/feed", entry);
+        assertNotNull(resp);
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        client.shutdown();
+    }
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/SimpleAdapter.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/SimpleAdapter.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/SimpleAdapter.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/security/filter/SimpleAdapter.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,259 @@
+/*
+ * 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.security.filter;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.abdera2.Abdera;
+import org.apache.abdera2.common.Constants;
+import org.apache.abdera2.common.protocol.RequestContext;
+import org.apache.abdera2.common.protocol.RequestContext.Scope;
+import org.apache.abdera2.common.protocol.ResponseContext;
+import org.apache.abdera2.common.protocol.ProviderHelper;
+import org.apache.abdera2.common.protocol.ResponseContextException;
+import org.apache.abdera2.common.protocol.TargetType;
+import org.apache.abdera2.common.text.UrlEncoding;
+import org.apache.abdera2.model.Document;
+import org.apache.abdera2.model.Entry;
+import org.apache.abdera2.model.Feed;
+import org.apache.abdera2.parser.ParseException;
+import org.apache.abdera2.protocol.server.context.FOMResponseContext;
+import org.apache.abdera2.protocol.server.context.StreamWriterResponseContext;
+import org.apache.abdera2.protocol.server.impl.AbstractAtompubCollectionAdapter;
+import org.apache.abdera2.protocol.server.impl.AbstractAtompubProvider;
+import org.apache.abdera2.util.MorePredicates;
+import org.apache.abdera2.writer.StreamWriter;
+import org.joda.time.DateTime;
+
+import com.google.common.base.Function;
+
+@SuppressWarnings("unchecked")
+public class SimpleAdapter extends AbstractAtompubCollectionAdapter {
+
+  public SimpleAdapter(String href) {
+    super(href);
+    putHandler(TargetType.TYPE_COLLECTION,"GET",getItemList());
+    putHandler(TargetType.TYPE_COLLECTION,"HEAD",getItemList());
+    putHandler(TargetType.TYPE_COLLECTION,"POST",postItem());
+    putHandler(TargetType.TYPE_ENTRY,"DELETE",deleteItem());
+    putHandler(TargetType.TYPE_ENTRY,"GET",getItem());
+    putHandler(TargetType.TYPE_ENTRY,"HEAD",getItem());
+    putHandler(TargetType.TYPE_ENTRY,"PUT",putItem());
+    putHandler(TargetType.TYPE_CATEGORIES,"GET",getCategories());
+    putHandler(TargetType.TYPE_CATEGORIES,"HEAD",getCategories());
+  }
+
+  @Override
+  public String getAuthor(RequestContext request) throws ResponseContextException {
+      return "Simple McGee";
+  }
+
+  @Override
+  public String getId(RequestContext request) {
+      return "tag:example.org,2008:feed";
+  }
+
+  public String getHref(RequestContext request) {
+      Map<String, Object> params = new HashMap<String, Object>();
+      params.put("collection", "feed");
+      return request.urlFor(TargetType.TYPE_COLLECTION, params);
+  }
+
+  public String getTitle(RequestContext request) {
+      return "A simple feed";
+  }
+
+  private Document<Feed> getFeedDocument(RequestContext context) throws ResponseContextException {
+      Feed feed = (Feed)context.getAttribute(Scope.SESSION, "feed");
+      if (feed == null) {
+          feed = createFeedBase(context);
+          feed.setBaseUri(getHref(context));
+          context.setAttribute(Scope.SESSION, "feed", feed);
+      }
+      return feed.getDocument();
+  }
+
+  private Function<RequestContext,ResponseContext> getItemList() {
+    return new Function<RequestContext,ResponseContext>() {
+      public ResponseContext apply(RequestContext input) {
+        Document<Feed> feed;
+        try {
+            feed = getFeedDocument(input);
+        } catch (ResponseContextException e) {
+            return e.getResponseContext();
+        }
+        return AbstractAtompubProvider
+          .returnBase(feed, 200, feed.getRoot().getUpdated())
+          .setEntityTag(
+            AbstractAtompubProvider
+              .calculateEntityTag(feed.getRoot()));
+      }
+    };
+  }
+
+  public Function<RequestContext,ResponseContext> deleteItem() {
+    return new Function<RequestContext,ResponseContext>() {
+      public ResponseContext apply(RequestContext input) {
+        Entry entry = getAbderaEntry(input);
+        if (entry != null)
+            entry.discard();
+        return ProviderHelper.nocontent();
+      }
+    };
+  }
+
+  private Function<RequestContext,ResponseContext> getItem() {
+    return new Function<RequestContext,ResponseContext>() {
+      public ResponseContext apply(RequestContext input) {
+        Entry entry = (Entry)getAbderaEntry(input);
+        if (entry != null) {
+            Feed feed = entry.getParentElement();
+            entry = (Entry)entry.clone();
+            entry.setSource(feed.getAsSource());
+            Document<Entry> entry_doc = entry.getDocument();
+            return AbstractAtompubProvider
+              .returnBase(entry_doc, 200, entry.getEdited())
+              .setEntityTag(AbstractAtompubProvider
+                .calculateEntityTag(entry));
+        } else {
+            return ProviderHelper.notfound(input);
+        }
+      }
+    };
+  }
+  
+  private Function<RequestContext,ResponseContext> postItem() {
+    return new Function<RequestContext,ResponseContext>() {
+      public ResponseContext apply(RequestContext request) {
+        try {
+            Document<Entry> entry_doc = (Document<Entry>)AbstractAtompubProvider.getDocument(request).clone();
+            if (entry_doc != null) {
+                Entry entry = entry_doc.getRoot();
+                if (!MorePredicates.VALID_ENTRY.apply(entry))
+                    return ProviderHelper.badrequest(request);
+                setEntryDetails(request, entry, Abdera.getInstance().getFactory().newUuidUri());
+                Feed feed = getFeedDocument(request).getRoot();
+                feed.insertEntry(entry);
+                feed.setUpdated(DateTime.now());
+                FOMResponseContext<?> rc =
+                    (FOMResponseContext<?>)AbstractAtompubProvider.returnBase(entry_doc, 201, entry.getEdited());
+                return rc
+                  .setLocation(
+                    ProviderHelper
+                      .resolveBase(request)
+                      .resolve(entry.getEditLinkResolvedHref()))
+                  .setContentLocation(
+                    rc.getLocation()
+                      .toString())
+                  .setEntityTag(
+                    AbstractAtompubProvider
+                      .calculateEntityTag(entry));
+            } else {
+                return ProviderHelper.badrequest(request);
+            }
+        } catch (ParseException pe) {
+            return ProviderHelper.notsupported(request);
+        } catch (ClassCastException cce) {
+            return ProviderHelper.notsupported(request);
+        } catch (Exception e) {
+            return ProviderHelper.badrequest(request);
+        }
+      }
+    };
+  }
+  
+  private void setEntryDetails(RequestContext request, Entry entry, String id) {
+      entry.setUpdated(DateTime.now());
+      entry.setEdited(entry.getUpdated());
+      entry.getIdElement().setValue(id);
+      entry.addLink(getEntryLink(request, entry.getId().toASCIIString()), "edit");
+  }
+
+  private String getEntryLink(RequestContext request, String entryid) {
+      Map<String, String> params = new HashMap<String, String>();
+      params.put("collection", request.getTarget().getParameter("collection"));
+      params.put("entry", entryid);
+      return request.urlFor("entry",params);
+  }
+
+  private Function<RequestContext,ResponseContext> putItem() {
+    return new Function<RequestContext,ResponseContext>() {
+      public ResponseContext apply(RequestContext request) {
+        Entry orig_entry = getAbderaEntry(request);
+        if (orig_entry != null) {
+            try {
+                Document<Entry> entry_doc = (Document<Entry>)AbstractAtompubProvider.getDocument(request).clone();
+                if (entry_doc != null) {
+                    Entry entry = entry_doc.getRoot();
+                    if (!entry.getId().equals(orig_entry.getId()))
+                        return ProviderHelper.conflict(request);
+                    if (!MorePredicates.VALID_ENTRY.apply(entry))
+                        return ProviderHelper.badrequest(request);
+                    setEntryDetails(request, entry, orig_entry.getId().toString());
+                    orig_entry.discard();
+                    Feed feed = getFeedDocument(request).getRoot();
+                    feed.insertEntry(entry);
+                    feed.setUpdated(DateTime.now());
+                    return ProviderHelper.nocontent();
+                } else {
+                    return ProviderHelper.badrequest(request);
+                }
+            } catch (ParseException pe) {
+                return ProviderHelper.notsupported(request);
+            } catch (ClassCastException cce) {
+                return ProviderHelper.notsupported(request);
+            } catch (Exception e) {
+                return ProviderHelper.badrequest(request);
+            }
+        } else {
+            return ProviderHelper.notfound(request);
+        }
+      }
+    };
+  }
+  
+  private Entry getAbderaEntry(RequestContext request) {
+      try {
+          return getFeedDocument(request).getRoot().getEntry(getResourceName(request));
+      } catch (Exception e) {
+      }
+      return null;
+  }
+
+  public String getResourceName(RequestContext request) {
+      if (request.getTarget().getType() != TargetType.TYPE_ENTRY)
+          return null;
+      String[] segments = request.getUri().toString().split("/");
+      return UrlEncoding.decode(segments[segments.length - 1]);
+  }
+
+  private Function<RequestContext,ResponseContext> getCategories() {
+    return new Function<RequestContext,ResponseContext>() {
+      public ResponseContext apply(RequestContext request) {
+        return new StreamWriterResponseContext(Abdera.getInstance()) {
+            protected void writeTo(StreamWriter sw) throws IOException {
+                sw.startDocument().startCategories(false).writeCategory("foo").writeCategory("bar")
+                    .writeCategory("baz").endCategories().endDocument();
+            }
+        }.setStatus(200).setContentType(Constants.CAT_MEDIA_TYPE);
+      }
+    };
+  }
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/JettyServer.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/JettyServer.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/JettyServer.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/JettyServer.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,74 @@
+/*
+ * 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.server;
+
+import java.util.EventListener;
+
+import org.apache.abdera2.common.protocol.Provider;
+import org.apache.abdera2.common.protocol.ServiceManager;
+import org.apache.abdera2.common.protocol.servlet.AbderaServlet;
+import org.apache.abdera2.common.protocol.servlet.async.AbderaAsyncService;
+import org.apache.abdera2.common.protocol.servlet.async.AbderaChannelServlet;
+import org.apache.abdera2.common.protocol.servlet.async.AsyncAbderaServlet;
+import org.apache.abdera2.test.JettyUtil;
+import org.eclipse.jetty.servlet.ServletHolder;
+
+public class JettyServer {
+
+    public void start(
+        Class<? extends ServiceManager> _smclass) throws Exception {
+      
+      ServletHolder servletHolder = new ServletHolder(new AbderaServlet());
+      servletHolder.setInitParameter(ServiceManager.class.getName(), _smclass.getName());
+      JettyUtil.addServlet(servletHolder, "/*");
+      JettyUtil.start();
+    }
+    
+    public void startAsync(
+        Class<? extends ServiceManager> _smclass, 
+        AbderaChannelServlet acs) throws Exception {
+
+      JettyUtil.initServer();
+      JettyUtil.getSch().setInitParameter("AbderaAtompubService", "true");
+      JettyUtil.getSch().setInitParameter("AbderaChannelService", "true");
+      JettyUtil.getSch().setInitParameter(ServiceManager.class.getName(), _smclass.getName());
+      
+      ServletHolder servletHolder = 
+        new ServletHolder(
+          new AsyncAbderaServlet());
+      JettyUtil.addServlet(servletHolder, "/*");
+      
+      if (acs != null) {
+        servletHolder = new ServletHolder(acs);
+        JettyUtil.addServlet(servletHolder, "/stream/*");
+      }
+      
+      EventListener[] listeners = 
+        new EventListener[] {
+          new AbderaAsyncService()
+      };
+      JettyUtil.getSch().setEventListeners(listeners);
+      JettyUtil.start();
+    }
+
+    public void stop() throws Exception {
+       // server.stop();
+      JettyUtil.stop();
+    }
+
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/BasicAtompubServiceManager.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/BasicAtompubServiceManager.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/BasicAtompubServiceManager.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/BasicAtompubServiceManager.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,23 @@
+package org.apache.abdera2.test.server.basic;
+
+import java.util.Map;
+
+import org.apache.abdera2.common.protocol.Provider;
+import org.apache.abdera2.protocol.server.AtompubServiceManager;
+import org.apache.abdera2.protocol.server.provider.basic.BasicProvider;
+
+public class BasicAtompubServiceManager 
+  extends AtompubServiceManager {
+
+  public BasicAtompubServiceManager() {}
+  
+  @SuppressWarnings("unchecked")
+  @Override
+  public <P extends Provider> P newProvider(
+    Map<String, Object> properties) {
+      BasicProvider bp = new BasicProvider();
+      bp.init(properties);
+      return (P)bp;
+  }
+  
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/BasicTest.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/BasicTest.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/BasicTest.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/BasicTest.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,174 @@
+/*
+ * 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.server.basic;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+
+import org.apache.abdera2.Abdera;
+import org.apache.abdera2.model.Base;
+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.protocol.client.AbderaClient;
+import org.apache.abdera2.protocol.client.AbderaClientResponse;
+import org.apache.abdera2.protocol.client.AbderaSession;
+import org.apache.abdera2.protocol.client.ClientResponse;
+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.apache.abdera2.writer.Writer;
+import org.apache.abdera2.writer.WriterFactory;
+import org.joda.time.DateTime;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class BasicTest {
+
+    private static JettyServer server;
+    private static Abdera abdera = Abdera.getInstance();
+    private static AbderaClient client = new AbderaClient(abdera);
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+        if (server == null) {
+            server = new JettyServer();
+            server.start(BasicAtompubServiceManager.class);
+        }
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        client.shutdown();
+        server.stop();
+    }
+
+    protected void prettyPrint(Base doc) throws IOException {
+        WriterFactory factory = abdera.getWriterFactory();
+        Writer writer = factory.getWriter("prettyxml");
+        writer.writeTo(doc, System.out);
+        System.out.println();
+    }
+
+    @Test
+    public void testGetService() throws IOException {
+        Document<Service> doc = client.get("http://localhost:9002/");
+        Service service = doc.getRoot();
+        assertEquals(1, service.getWorkspaces().size());
+        Workspace workspace = service.getWorkspace("Abdera");
+        assertEquals(1, workspace.getCollections().size());
+        Collection collection = workspace.getCollection("title for any sample feed");
+        assertNotNull(collection);
+        assertTrue(collection.acceptsEntry());
+        assertEquals("http://localhost:9002/sample", collection.getResolvedHref().toString());
+    }
+
+    @Test
+    public void testGetFeed() throws IOException {
+        Document<Feed> doc = client.get("http://localhost:9002/sample");
+        Feed feed = doc.getRoot();
+        assertEquals("http://localhost:9002/sample", feed.getId().toString());
+        assertEquals("title for any sample feed", feed.getTitle());
+        assertEquals("rayc", feed.getAuthor().getName());
+        assertEquals(0, feed.getEntries().size());
+    }
+
+    @Test
+    public void testPostEntry() {
+        Entry entry = abdera.newEntry();
+        entry.setId("http://localhost:9002/sample/foo");
+        entry.setTitle("test entry");
+        entry.setContent("Test Content");
+        entry.addLink("http://example.org");
+        entry.setUpdated(DateTime.now());
+        entry.addAuthor("James");
+        AbderaSession session = (AbderaSession) client.newSession();
+        AbderaClientResponse resp = (AbderaClientResponse) session.post("http://localhost:9002/sample", entry);
+        assertNotNull(resp);
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        assertEquals(201, resp.getStatus());
+        assertEquals("http://localhost:9002/sample/foo", resp.getLocation().toString());
+        resp.release();
+        resp = (AbderaClientResponse) session.get("http://localhost:9002/sample");
+        Document<Feed> feed_doc = resp.getDocument();
+        Feed feed = feed_doc.getRoot();
+        assertEquals(1, feed.getEntries().size());
+        resp.release();
+    }
+
+    @Test
+    public void testPostMedia() {
+        Session session = client.newSession();
+        ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04});
+        ClientResponse resp = session.post(
+          "http://localhost:9002/sample", 
+          in, session.getDefaultRequestOptions()
+            .contentType("application/octet-stream").get());
+        assertEquals(ResponseType.CLIENT_ERROR, resp.getType());
+        assertEquals(405, resp.getStatus());
+        resp.release();
+    }
+
+    @Test
+    public void testPutEntry() {
+      AbderaSession session = (AbderaSession) client.newSession();
+        AbderaClientResponse resp = (AbderaClientResponse) session.get("http://localhost:9002/sample/foo");
+        assertTrue(MimeTypeHelper.isMatch(resp.getContentType().toString(), Constants.ENTRY_MEDIA_TYPE));
+        Document<Entry> doc = resp.getDocument();
+        Entry entry = doc.getRoot();
+        entry.setTitle("This is the modified title");
+        resp.release();
+        resp = (AbderaClientResponse) session.put("http://localhost:9002/sample/foo", entry);
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        assertEquals(200, resp.getStatus());
+        resp.release();
+        resp = (AbderaClientResponse) session.get("http://localhost:9002/sample/foo");
+        doc = resp.getDocument();
+        entry = doc.getRoot();
+        assertEquals("This is the modified title", entry.getTitle());
+        resp.release();
+        resp = (AbderaClientResponse) session.get("http://localhost:9002/sample");
+        Document<Feed> feed_doc = resp.getDocument();
+        Feed feed = feed_doc.getRoot();
+        assertEquals(1, feed.getEntries().size());
+        resp.release();
+    }
+
+    @Test
+    public void testDeleteEntry() {
+      AbderaSession session = (AbderaSession) client.newSession();
+        AbderaClientResponse resp = (AbderaClientResponse) session.delete("http://localhost:9002/sample/foo");
+        assertEquals(ResponseType.SUCCESSFUL, resp.getType());
+        resp.release();
+        resp = (AbderaClientResponse) session.get("http://localhost:9002/sample");
+        Document<Feed> feed_doc = resp.getDocument();
+        Feed feed = feed_doc.getRoot();
+        assertEquals(0, feed.getEntries().size());
+        resp.release();
+    }
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/SampleBasicAdapter.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/SampleBasicAdapter.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/SampleBasicAdapter.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/basic/SampleBasicAdapter.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,152 @@
+/*
+ * 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.server.basic;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.HashMap;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import org.apache.abdera2.Abdera;
+import org.apache.abdera2.common.protocol.RequestContext;
+import org.apache.abdera2.common.protocol.ResponseContextException;
+import org.apache.abdera2.model.Document;
+import org.apache.abdera2.model.Element;
+import org.apache.abdera2.model.Entry;
+import org.apache.abdera2.model.Feed;
+import org.apache.abdera2.protocol.server.provider.basic.BasicAdapter;
+import org.apache.abdera2.protocol.server.provider.managed.FeedConfiguration;
+import org.joda.time.DateTime;
+
+public class SampleBasicAdapter extends BasicAdapter {
+
+    private static final String ERROR_DUP_ENTRY = "Entry Already Exists";
+    private static final String ERROR_INVALID_ENTRY = "No Such Entry in the Feed";
+
+    public final static Logger logger = Logger.getLogger(SampleBasicAdapter.class.getName());
+    protected HashMap<String, byte[]> entries = new HashMap<String, byte[]>();
+
+    public SampleBasicAdapter(Abdera abdera, FeedConfiguration config) {
+        super(abdera, config);
+    }
+
+    public Feed getFeed() throws Exception {
+        Feed feed = createFeed();
+
+        // get all keys in the feed - with keys in descending order of
+        // lastUpdatedDate
+        Set<String> keys = entries.keySet();
+        for (String s : keys) {
+            Entry entry = getEntry(s);
+            // TODO: why clone this? Abdera seems to mess up the object
+            // if we pass the reference to this object
+            feed.addEntry((Entry)entry.clone());
+        }
+        return feed;
+    }
+
+    public Entry getEntry(Object entryId) throws Exception {
+        return retrieveEntry((String)entryId);
+    }
+
+    public Entry createEntry(Entry entry) throws Exception {
+        // entryId may be null. if it is, assign one
+        setEntryIdIfNull(entry);
+        logger.info("assigning id to Entry: " + entry.getId().toString());
+        String entryId = getEntryIdFromUri(entry.getId().toString());
+
+        if (entries.containsKey(entryId)) {
+            throw new Exception(ERROR_DUP_ENTRY);
+        }
+        // add an "updated" element if one was not provided
+        if (entry.getUpdated() == null) {
+            entry.setUpdated(DateTime.now());
+        }
+        addEditLinkToEntry(entry);
+        storeEntry(entryId, entry);
+        logger.finest("returning this entry from sampleadapter.createEntry: " + entry.toString());
+        return entry;
+    }
+
+    public Entry updateEntry(Object entryId, Entry entry) throws Exception {
+        if (!entries.containsKey(entryId)) {
+            throw new Exception(ERROR_INVALID_ENTRY);
+        }
+        entries.remove(entryId);
+        // add an "updated" element if one was not provided
+        if (entry.getUpdated() == null) {
+            entry.setUpdated(DateTime.now());
+        }
+        addEditLinkToEntry(entry);
+        storeEntry((String)entryId, entry);
+        logger.finest("returning this entry from sampleadapter.updateEntry: " + entry.toString());
+        return entry;
+    }
+
+    public boolean deleteEntry(Object entryId) throws Exception {
+        if (!entries.containsKey(entryId)) {
+            return false;
+        }
+        entries.remove(entryId);
+        return true;
+    }
+
+    protected String getEntryIdFromUri(String uri) {
+        String[] segments = uri.split("/");
+        return segments[segments.length - 1];
+    }
+
+    protected void storeEntry(String entryId, Entry entry) throws Exception {
+        Document<Element> entryDoc = entry.getDocument();
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        entryDoc.writeTo(bos);
+
+        // Get the bytes of the serialized object and store in hashmap
+        byte[] buf = bos.toByteArray();
+        bos.close();
+        entries.put(entryId, buf);
+    }
+
+    protected Entry retrieveEntry(String entryId) throws Exception {
+        // Deserialize from a byte array
+        byte[] bytes = entries.get(entryId);
+        if (bytes == null) {
+            // entry not found
+            return null;
+        }
+        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
+        Document<Entry> entryDoc = abdera.getParser().parse(in);
+        Entry entry = entryDoc.getRoot();
+        return entry;
+    }
+
+    @Override
+    public String getAuthor(RequestContext request) throws ResponseContextException {
+        return config.getFeedAuthor();
+    }
+
+    @Override
+    public String getId(RequestContext request) {
+        return config.getFeedId();
+    }
+
+    public String getTitle(RequestContext request) {
+        return config.getFeedTitle();
+    }
+}

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

Added: abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/custom/CustomAtompubServiceManager.java
URL: http://svn.apache.org/viewvc/abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/custom/CustomAtompubServiceManager.java?rev=1239237&view=auto
==============================================================================
--- abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/custom/CustomAtompubServiceManager.java (added)
+++ abdera/abdera2-server/test/src/main/java/org/apache/abdera2/test/server/custom/CustomAtompubServiceManager.java Wed Feb  1 17:54:54 2012
@@ -0,0 +1,18 @@
+package org.apache.abdera2.test.server.custom;
+
+import java.util.Map;
+
+import org.apache.abdera2.common.protocol.Provider;
+import org.apache.abdera2.protocol.server.AtompubServiceManager;
+
+public class CustomAtompubServiceManager extends AtompubServiceManager {
+
+  @SuppressWarnings("unchecked")
+  @Override
+  public <P extends Provider> P newProvider(Map<String, Object> properties) {
+    CustomProvider cp = new CustomProvider("/");
+    cp.init(properties);
+    return (P)cp;
+  }
+
+}

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



Mime
View raw message