Dataset Viewer
Auto-converted to Parquet Duplicate
size
int64
13
12M
filename
stringlengths
34
354
content
stringlengths
13
12M
8,792
apache/abdera/adapters/filesystem/src/main/java/org/apache/abdera/protocol/server/adapters/filesystem/FilesystemAdapter.java
package org.apache.abdera.protocol.server.adapters.filesystem; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.templates.Template; import org.apache.abdera.i18n.text.Normalizer; import org.apache.abdera.i18n.text.Sanitizer; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Link; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.Target; import org.apache.abdera.protocol.server.provider.managed.FeedConfiguration; import org.apache.abdera.protocol.server.provider.managed.ManagedCollectionAdapter; /** * Simple Filesystem Adapter that uses a local directory to store Atompub collection entries. As an extension of the * ManagedCollectionAdapter class, the Adapter is intended to be used with implementations of the ManagedProvider and * are configured using /abdera/adapter/*.properties files. The *.properties file MUST specify the fs.root property to * specify the root directory used by the Adapter. */ public class FilesystemAdapter extends ManagedCollectionAdapter { private final File root; private final static FileSorter sorter = new FileSorter(); private final static Template paging_template = new Template("?{-join|&|count,page}"); public FilesystemAdapter(Abdera abdera, FeedConfiguration config) { super(abdera, config); this.root = getRoot(); } private File getRoot() { try { String root = (String)config.getProperty("fs.root"); File file = new File(root); if (!file.exists()) file.mkdirs(); if (!file.isDirectory()) throw new RuntimeException("Root must be a directory"); return file; } catch (Exception e) { if (e instanceof RuntimeException) throw (RuntimeException)e; throw new RuntimeException(e); } } private Entry getEntry(File entryFile) { if (!entryFile.exists() || !entryFile.isFile()) throw new RuntimeException(); try { FileInputStream fis = new FileInputStream(entryFile); Document<Entry> doc = abdera.getParser().parse(fis); Entry entry = doc.getRoot(); return entry; } catch (Exception e) { throw new RuntimeException(e); } } private void addPagingLinks(RequestContext request, Feed feed, int currentpage, int count) { Map<String, Object> params = new HashMap<String, Object>(); params.put("count", count); params.put("page", currentpage + 1); String next = paging_template.expand(params); next = request.getResolvedUri().resolve(next).toString(); feed.addLink(next, "next"); if (currentpage > 0) { params.put("page", currentpage - 1); String prev = paging_template.expand(params); prev = request.getResolvedUri().resolve(prev).toString(); feed.addLink(prev, "previous"); } params.put("page", 0); String current = paging_template.expand(params); current = request.getResolvedUri().resolve(current).toString(); feed.addLink(current, "current"); } private void getEntries(RequestContext request, Feed feed, File root) { File[] files = root.listFiles(); Arrays.sort(files, sorter); int length = ProviderHelper.getPageSize(request, "count", 25); int offset = ProviderHelper.getOffset(request, "page", length); String _page = request.getParameter("page"); int page = (_page != null) ? Integer.parseInt(_page) : 0; addPagingLinks(request, feed, page, length); if (offset > files.length) return; for (int n = offset; n < offset + length && n < files.length; n++) { File file = files[n]; Entry entry = getEntry(file); feed.addEntry((Entry)entry.clone()); } } public ResponseContext getFeed(RequestContext request) { Feed feed = abdera.newFeed(); feed.setId(config.getServerConfiguration().getServerUri() + "/" + config.getFeedId()); feed.setTitle(config.getFeedTitle()); feed.addAuthor(config.getFeedAuthor()); feed.addLink(config.getFeedUri()); feed.addLink(config.getFeedUri(), "self"); feed.setUpdated(new Date()); getEntries(request, feed, root); return ProviderHelper.returnBase(feed.getDocument(), 200, null); } public ResponseContext deleteEntry(RequestContext request) { Target target = request.getTarget(); String key = target.getParameter("entry"); File file = getFile(key, false); if (file.exists()) file.delete(); return ProviderHelper.nocontent(); } public ResponseContext getEntry(RequestContext request) { Target target = request.getTarget(); String key = target.getParameter("entry"); File file = getFile(key, false); Entry entry = getEntry(file); if (entry != null) return ProviderHelper.returnBase(entry.getDocument(), 200, null); else return ProviderHelper.notfound(request); } public ResponseContext postEntry(RequestContext request) { if (request.isAtom()) { try { Entry entry = (Entry)request.getDocument().getRoot().clone(); String key = createKey(request); setEditDetail(request, entry, key); File file = getFile(key); FileOutputStream out = new FileOutputStream(file); entry.writeTo(out); String edit = entry.getEditLinkResolvedHref().toString(); return ProviderHelper.returnBase(entry.getDocument(), 201, null).setLocation(edit); } catch (Exception e) { return ProviderHelper.badrequest(request); } } else { return ProviderHelper.notsupported(request); } } private void setEditDetail(RequestContext request, Entry entry, String key) throws IOException { Target target = request.getTarget(); String feed = target.getParameter("feed"); String id = key; entry.setEdited(new Date()); Link link = entry.getEditLink(); Map<String, Object> params = new HashMap<String, Object>(); params.put("feed", feed); params.put("entry", id); String href = request.absoluteUrlFor("entry", params); if (link == null) { entry.addLink(href, "edit"); } else { link.setHref(href); } } private File getFile(String key) { return getFile(key, true); } private File getFile(String key, boolean post) { File file = new File(root, key); if (post && file.exists()) throw new RuntimeException("File exists"); return file; } private String createKey(RequestContext request) throws IOException { String slug = request.getSlug(); if (slug == null) { slug = ((Entry)request.getDocument().getRoot()).getTitle(); } return Sanitizer.sanitize(slug, "", true, Normalizer.Form.D); } public ResponseContext putEntry(RequestContext request) { if (request.isAtom()) { try { Entry entry = (Entry)request.getDocument().getRoot().clone(); String key = request.getTarget().getParameter("entry"); setEditDetail(request, entry, key); File file = getFile(key, false); FileOutputStream out = new FileOutputStream(file); entry.writeTo(out); String edit = entry.getEditLinkResolvedHref().toString(); return ProviderHelper.returnBase(entry.getDocument(), 200, null).setLocation(edit); } catch (Exception e) { return ProviderHelper.badrequest(request); } } else { return ProviderHelper.notsupported(request); } } private static class FileSorter implements Comparator<File> { public int compare(File o1, File o2) { return o1.lastModified() > o2.lastModified() ? -1 : o1.lastModified() < o2.lastModified() ? 1 : 0; } } }
6,724
apache/abdera/adapters/filesystem/src/test/java/org/apache/abdera/protocol/server/test/filesystem/FilesystemTest.java
package org.apache.abdera.protocol.server.test.filesystem; 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 java.util.Date; import org.apache.abdera.Abdera; import org.apache.abdera.model.Base; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Service; import org.apache.abdera.model.Workspace; import org.apache.abdera.protocol.Response.ResponseType; import org.apache.abdera.protocol.client.AbderaClient; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.client.RequestOptions; import org.apache.abdera.protocol.server.ServiceManager; import org.apache.abdera.protocol.server.provider.basic.BasicProvider; import org.apache.abdera.protocol.server.servlet.AbderaServlet; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.writer.Writer; import org.apache.abdera.writer.WriterFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; @Ignore public class FilesystemTest { private static Server server; private static Abdera abdera = Abdera.getInstance(); private static AbderaClient client = new AbderaClient(); @BeforeClass public static void setUp() throws Exception { if (server == null) { server = new Server(9002); Context context = new Context(server, "/", Context.SESSIONS); ServletHolder servletHolder = new ServletHolder(new AbderaServlet()); servletHolder.setInitParameter(ServiceManager.PROVIDER, BasicProvider.class.getName()); context.addServlet(servletHolder, "/*"); server.start(); } } @AfterClass public static void tearDown() throws Exception { 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() { ClientResponse resp = client.get("http://localhost:9002/"); assertNotNull(resp); assertEquals(ResponseType.SUCCESS, resp.getType()); assertTrue(MimeTypeHelper.isMatch(resp.getContentType().toString(), Constants.APP_MEDIA_TYPE)); Document<Service> doc = resp.getDocument(); Service service = doc.getRoot(); assertEquals(1, service.getWorkspaces().size()); Workspace workspace = service.getWorkspace("Abdera"); assertEquals(2, workspace.getCollections().size()); Collection collection = workspace.getCollection("Filesystem Feed"); assertNotNull(collection); assertTrue(collection.acceptsEntry()); assertEquals("http://localhost:9002/fs", collection.getResolvedHref().toString()); } @Test public void testGetFeed() { ClientResponse resp = client.get("http://localhost:9002/fs"); assertNotNull(resp); assertEquals(ResponseType.SUCCESS, resp.getType()); assertTrue(MimeTypeHelper.isMatch(resp.getContentType().toString(), Constants.ATOM_MEDIA_TYPE)); Document<Feed> doc = resp.getDocument(); Feed feed = doc.getRoot(); assertEquals("http://localhost:9002/fs", feed.getId().toString()); assertEquals("Filesystem Feed", feed.getTitle()); assertEquals("james", feed.getAuthor().getName()); assertEquals(0, feed.getEntries().size()); resp.release(); } @Test public void testPostEntry() { Entry entry = abdera.newEntry(); entry.setId("http://localhost:9002/fs/foo"); entry.setTitle("test entry"); entry.setContent("Test Content"); entry.addLink("http://example.org"); entry.setUpdated(new Date()); entry.addAuthor("James"); ClientResponse resp = client.post("http://localhost:9002/fs", entry); assertNotNull(resp); assertEquals(ResponseType.SUCCESS, resp.getType()); assertEquals(201, resp.getStatus()); assertEquals("http://localhost:9002/fs/test_entry", resp.getLocation().toString()); resp = client.get("http://localhost:9002/fs"); Document<Feed> feed_doc = resp.getDocument(); Feed feed = feed_doc.getRoot(); assertEquals(1, feed.getEntries().size()); resp.release(); } @Test public void testPostMedia() { ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04}); RequestOptions options = client.getDefaultRequestOptions(); options.setContentType("application/octet-stream"); ClientResponse resp = client.post("http://localhost:9002/fs", in, options); assertEquals(ResponseType.CLIENT_ERROR, resp.getType()); assertEquals(415, resp.getStatus()); resp.release(); } @Test public void testPutEntry() { ClientResponse resp = client.get("http://localhost:9002/fs/test_entry"); Document<Entry> doc = resp.getDocument(); Entry entry = (Entry)doc.getRoot().clone(); entry.setTitle("This is the modified title"); resp.release(); resp = client.put("http://localhost:9002/fs/test_entry", entry); assertEquals(ResponseType.SUCCESS, resp.getType()); assertEquals(200, resp.getStatus()); resp.release(); resp = client.get("http://localhost:9002/fs/test_entry"); doc = resp.getDocument(); entry = doc.getRoot(); assertEquals("This is the modified title", entry.getTitle()); resp.release(); resp = client.get("http://localhost:9002/fs"); Document<Feed> feed_doc = resp.getDocument(); Feed feed = feed_doc.getRoot(); assertEquals(1, feed.getEntries().size()); resp.release(); } @Test public void testDeleteEntry() { ClientResponse resp = client.delete("http://localhost:9002/fs/test_entry"); assertEquals(ResponseType.SUCCESS, resp.getType()); resp.release(); resp = client.get("http://localhost:9002/fs"); Document<Feed> feed_doc = resp.getDocument(); Feed feed = feed_doc.getRoot(); assertEquals(0, feed.getEntries().size()); resp.release(); } }
358
apache/abdera/adapters/filesystem/src/test/java/org/apache/abdera/protocol/server/test/filesystem/TestSuite.java
package org.apache.abdera.protocol.server.test.filesystem; import org.junit.internal.TextListener; import org.junit.runner.JUnitCore; public class TestSuite { public static void main(String[] args) { JUnitCore runner = new JUnitCore(); runner.addListener(new TextListener(System.out)); runner.run(FilesystemTest.class); } }
2,534
apache/abdera/adapters/hibernate/src/main/java/org/apache/abdera/protocol/server/adapters/hibernate/AtomEntryResultTransformer.java
package org.apache.abdera.protocol.server.adapters.hibernate; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.List; import org.apache.abdera.Abdera; import org.apache.abdera.ext.serializer.ConventionSerializationContext; import org.apache.abdera.ext.serializer.impl.EntrySerializer; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Link; import org.apache.abdera.parser.ParseException; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.writer.StreamWriter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.transform.ResultTransformer; /** * Converts Hibernate results into an Atom document using the Abdera Java Object Serializer */ public class AtomEntryResultTransformer implements ResultTransformer { private static Log logger = LogFactory.getLog(AtomEntryResultTransformer.class); private String feedId; private Abdera abdera; private Feed feed; public AtomEntryResultTransformer(String feedId, Abdera abdera, Feed feed) { this.feedId = feedId; this.abdera = abdera; this.feed = feed; } public List transformList(List collection) { return collection; } public Object transformTuple(Object[] tuple, String[] aliases) { try { if (tuple.length == 1) { StreamWriter sw = abdera.newStreamWriter(); ByteArrayOutputStream out = new ByteArrayOutputStream(); sw.setOutputStream(out).setAutoIndent(true); ConventionSerializationContext c = new ConventionSerializationContext(sw); c.setSerializer(tuple[0].getClass(), new EntrySerializer()); sw.startDocument(); c.serialize(tuple[0]); sw.endDocument(); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); if (ProviderHelper.getEditUriFromEntry(entry) == null) { entry.addLink(entry.getId().toString(), "edit"); } entry.setId(feedId + "/" + entry.getId().toString()); entry.getEditLink().setHref(entry.getId().toString()); if (feed != null) { feed.addEntry(entry); } return entry; } else { return tuple; } } catch (Exception ex) { logger.error("error creating an entry with the row data", ex); throw new ParseException(ex); } } }
8,344
apache/abdera/adapters/hibernate/src/main/java/org/apache/abdera/protocol/server/adapters/hibernate/HibernateCollectionAdapter.java
package org.apache.abdera.protocol.server.adapters.hibernate; import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_AUTHOR; import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_CONTENT; import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_ID; import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_TITLE; import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_UPDATED; import java.io.Serializable; import java.lang.reflect.Field; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.abdera.Abdera; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.protocol.server.provider.basic.BasicAdapter; import org.apache.abdera.protocol.server.provider.managed.FeedConfiguration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; /** * An adapter implementation that uses Hibernate and a backend database to store * Atompub collection entries. As an extension of the BasicAdapter, the adapter * is intended to be used with the BasicProvider and is configured using an * /abdera/adapter/*.properties file. */ public class HibernateCollectionAdapter extends BasicAdapter { private static Log logger = LogFactory.getLog(HibernateCollectionAdapter.class); protected static Configuration hibernateConfig; protected static SessionFactory sessionFactory; public static final String HIBERNATE_ANNOTATION_CONFIG = "hibernateAnnotationConfig"; public static final String HIBERNATE_CFG_PATH = "hibernateCfgPath"; public static final String ENTRY_MAPPING_CLASS_NAME = "entryMappingClassName"; public HibernateCollectionAdapter(Abdera abdera, FeedConfiguration config) { super(abdera, config); loadHibernateConfiguration(); } private void loadHibernateConfiguration() { if (hibernateConfig == null) { if (config.hasProperty(HIBERNATE_ANNOTATION_CONFIG) && config.getProperty(HIBERNATE_ANNOTATION_CONFIG) .toString().equalsIgnoreCase(Boolean.TRUE.toString())) { hibernateConfig = new AnnotationConfiguration(); } else { hibernateConfig = new Configuration(); } if (config.hasProperty(HIBERNATE_CFG_PATH)) { hibernateConfig.configure((String) config.getProperty(HIBERNATE_CFG_PATH)); } else { hibernateConfig.configure(); } rebuildSessionFactory(hibernateConfig); } } protected SessionFactory getSessionFactory() { String sfName = hibernateConfig.getProperty(Environment.SESSION_FACTORY_NAME); if ( sfName != null) { logger.debug("Looking up SessionFactory in JNDI"); try { return (SessionFactory) new InitialContext().lookup(sfName); } catch (NamingException ex) { throw new RuntimeException(ex); } } else if (sessionFactory == null) { rebuildSessionFactory(hibernateConfig); } return sessionFactory; } private void rebuildSessionFactory(Configuration cfg) { logger.debug("Rebuilding the SessionFactory from given Configuration"); if (sessionFactory != null && !sessionFactory.isClosed()) sessionFactory.close(); if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) { logger.debug("Managing SessionFactory in JNDI"); cfg.buildSessionFactory(); } else { logger.debug("Holding SessionFactory in static variable"); sessionFactory = cfg.buildSessionFactory(); } hibernateConfig = cfg; } @Override public Entry createEntry(Entry entry) throws Exception { Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); Serializable entryId = null; try { Object mapping = collectMappingObject(entry, null); entryId = session.save(mapping); tx.commit(); } catch (Exception ex) { tx.rollback(); logger.error("error creating a new entry", ex); } finally { session.close(); } return getEntry(entryId); } @Override public boolean deleteEntry(Object entryId) throws Exception { Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); boolean deleted = false; try { Object mapping = session.load( Class.forName((String) config.getProperty(ENTRY_MAPPING_CLASS_NAME)), (Serializable) entryId); if (mapping != null) { session.delete(mapping); tx.commit(); } deleted = true; } catch (HibernateException ex) { tx.rollback(); logger.error("error deleting the entry", ex); } finally { session.close(); } return deleted; } @Override public Entry getEntry(Object entryId) throws Exception { Session session = getSessionFactory().openSession(); Query query = session.getNamedQuery(config.getFeedId() + "-get-entry"); query.setParameter("id", entryId); query.setResultTransformer(new AtomEntryResultTransformer( config.getServerConfiguration().getServerUri() + "/" + config.getFeedId(), getAbdera(), null)); Entry entry = (Entry) query.uniqueResult(); session.close(); return entry; } @Override public Feed getFeed() throws Exception { Session session = getSessionFactory().openSession(); String queryName = config.getFeedId() + "-get-feed"; Query query = session.getNamedQuery(queryName); Feed feed = createFeed(); query.setResultTransformer(new AtomEntryResultTransformer( config.getServerConfiguration().getServerUri() + "/" + config.getFeedId(), this.getAbdera(), feed)); query.list(); session.close(); return feed; } @Override public Entry updateEntry(Object entryId, Entry entry) throws Exception { Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); try { Object forUpdate = session.load( Class.forName((String) config.getProperty(ENTRY_MAPPING_CLASS_NAME)), (Serializable) entryId); if (forUpdate != null) { forUpdate = collectMappingObject(entry, forUpdate); session.update(forUpdate); tx.commit(); } } catch (HibernateException ex) { tx.rollback(); logger.error("error deleting the entry", ex); } finally { session.close(); } return entry; } protected Object collectMappingObject(Entry entry, Object forUpdate) throws Exception { boolean create = false; Class clazz = Class.forName((String) config.getProperty(ENTRY_MAPPING_CLASS_NAME)); if (forUpdate == null) { forUpdate = clazz.newInstance(); create = true; } for (Field field : clazz.getDeclaredFields()) { if (create && field.getName().equals(ENTRY_ELEM_NAME_ID)) { collectField(field, clazz, forUpdate, entry.getId().toString()); } else if (field.getName().equals(ENTRY_ELEM_NAME_AUTHOR)){ collectField(field, clazz, forUpdate, entry.getAuthor().getName()); } else if (field.getName().equals(ENTRY_ELEM_NAME_TITLE)) { collectField(field, clazz, forUpdate, entry.getTitle()); } else if (field.getName().equals(ENTRY_ELEM_NAME_UPDATED)) { collectField(field, clazz, forUpdate, entry.getUpdated()); } else if (field.getName().equals(ENTRY_ELEM_NAME_CONTENT)) { collectField(field, clazz, forUpdate, entry.getContent()); } } return forUpdate; } protected void collectField(Field field, Class clazz, Object mappingObject, Object entryValue) throws Exception { clazz.getMethod(getSetter(field.getName()), new Class[]{field.getType()}) .invoke(mappingObject, new Object[]{entryValue}); } protected String getSetter(String fieldName) { return "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1); } }
818
apache/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters/hibernate/DummyData.java
package org.apache.abdera.protocol.server.adapters.hibernate; import java.util.Date; public class DummyData { public DummyData(){} private String id; private String author; private String title; private String content; private Date updated; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated; } }
4,269
apache/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters/hibernate/HibernateCollectionAdapterTest.java
package org.apache.abdera.protocol.server.adapters.hibernate; import java.util.Date; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.protocol.Response.ResponseType; import org.apache.abdera.protocol.client.AbderaClient; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.server.ServiceManager; import org.apache.abdera.protocol.server.provider.basic.BasicProvider; import org.apache.abdera.protocol.server.servlet.AbderaServlet; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import static org.junit.Assert.*; public class HibernateCollectionAdapterTest { private static Server server; private static Abdera abdera = Abdera.getInstance(); private static AbderaClient client = new AbderaClient(); @BeforeClass public static void setUp() throws Exception { if (server == null) { server = new Server(9002); Context context = new Context(server, "/", Context.SESSIONS); ServletHolder servletHolder = new ServletHolder(new AbderaServlet()); servletHolder.setInitParameter(ServiceManager.PROVIDER, BasicProvider.class.getName()); context.addServlet(servletHolder, "/*"); server.start(); } } @AfterClass public static void tearDown() throws Exception { server.stop(); } @Test public void testGetFeed() { ClientResponse resp = client.get("http://localhost:9002/hibernate"); assertNotNull(resp); assertEquals(ResponseType.SUCCESS, resp.getType()); assertTrue(MimeTypeHelper.isMatch(resp.getContentType().toString(), Constants.ATOM_MEDIA_TYPE)); Document<Feed> doc = resp.getDocument(); Feed feed = doc.getRoot(); assertEquals("http://localhost:9002/hibernate", feed.getId().toString()); assertEquals("david", feed.getAuthor().getName()); assertEquals(0, feed.getEntries().size()); resp.release(); } @Test public void testCreateEntry() { Entry entry = abdera.newEntry(); entry.setId("foo"); entry.setTitle("test entry"); entry.setContent("Test Content"); entry.addLink("http://example.org"); entry.setUpdated(new Date()); entry.addAuthor("david"); ClientResponse resp = client.post("http://localhost:9002/hibernate", entry); assertNotNull(resp); assertEquals(ResponseType.SUCCESS, resp.getType()); assertEquals(201, resp.getStatus()); assertEquals("http://localhost:9002/hibernate/foo", resp.getLocation().toString()); resp = client.get("http://localhost:9002/hibernate"); Document<Feed> feed_doc = resp.getDocument(); Feed feed = feed_doc.getRoot(); assertEquals(feed.getEntries().size(), 1); resp.release(); } @Test public void testUpdateEntry() { ClientResponse resp = client.get("http://localhost:9002/hibernate/foo"); Document<Entry> doc = resp.getDocument(); Entry entry = (Entry) doc.getRoot().clone(); entry.setTitle("This is the modified title"); resp.release(); resp = client.put("http://localhost:9002/hibernate/foo", entry); assertEquals(ResponseType.SUCCESS, resp.getType()); assertEquals(200, resp.getStatus()); resp.release(); resp = client.get("http://localhost:9002/hibernate/foo"); doc = resp.getDocument(); entry = doc.getRoot(); assertEquals("This is the modified title", entry.getTitle()); resp.release(); resp = client.get("http://localhost:9002/hibernate"); Document<Feed> feed_doc = resp.getDocument(); Feed feed = feed_doc.getRoot(); assertEquals(1, feed.getEntries().size()); resp.release(); } @Test public void testDeleteEntry() { ClientResponse resp = client.delete("http://localhost:9002/hibernate/foo"); assertEquals(ResponseType.SUCCESS, resp.getType()); resp.release(); resp = client.get("http://localhost:9002/hibernate"); Document<Feed> feed_doc = resp.getDocument(); Feed feed = feed_doc.getRoot(); assertEquals(0, feed.getEntries().size()); resp.release(); } }
372
apache/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters/hibernate/TestSuite.java
package org.apache.abdera.protocol.server.adapters.hibernate; import org.junit.internal.runners.TextListener; import org.junit.runner.JUnitCore; public class TestSuite { public static void main(String[] args) { JUnitCore runner = new JUnitCore(); runner.addListener(new TextListener(System.out)); runner.run(HibernateCollectionAdapterTest.class); } }
20,216
apache/abdera/adapters/jcr/src/main/java/org/apache/abdera/protocol/server/adapters/jcr/JcrCollectionAdapter.java
package org.apache.abdera.protocol.server.adapters.jcr; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.activation.MimeType; import javax.jcr.Credentials; import javax.jcr.ItemExistsException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.Workspace; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.text.Sanitizer; import org.apache.abdera.model.Content; import org.apache.abdera.model.Element; import org.apache.abdera.model.Person; import org.apache.abdera.model.Text; import org.apache.abdera.model.Content.Type; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.RequestContext.Scope; import org.apache.abdera.protocol.server.context.EmptyResponseContext; import org.apache.abdera.protocol.server.context.ResponseContextException; import org.apache.abdera.protocol.server.impl.AbstractEntityCollectionAdapter; import org.apache.abdera.protocol.util.PoolManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jackrabbit.api.JackrabbitNodeTypeManager; /** * Adapter implementation that uses a JCR Repository to store Atompub collection entries. The adapter is intended to be * used with the DefaultProvider implementation. */ public class JcrCollectionAdapter extends AbstractEntityCollectionAdapter<Node> { private final static Log log = LogFactory.getLog(JcrCollectionAdapter.class); private static final String TITLE = "title"; private static final String SUMMARY = "summary"; private static final String UPDATED = "updated"; private static final String AUTHOR = "author"; private static final String AUTHOR_EMAIL = "author.email"; private static final String AUTHOR_LANGUAGE = "author.language"; private static final String AUTHOR_NAME = "author.name"; private static final String CONTENT = "content"; private static final String SESSION_KEY = "jcrSession"; private static final String MEDIA = "media"; private static final String CONTENT_TYPE = "contentType"; private static final String NAMESPACE = "http://abdera.apache.org"; private String collectionNodePath; private String id; private String title; private String author; private String collectionNodeId; private Repository repository; private Credentials credentials; private int maxActiveSessions = 100; private PoolManager<Session> sessionPool; public void setCollectionNodePath(String collectionNodePath) { this.collectionNodePath = collectionNodePath; } public void setTitle(String title) { this.title = title; } public void setAuthor(String author) { this.author = author; } /** * Logs into the repository and posts a node for the collection if one does not exist. Also, this will set up the * session pool. * * @throws RepositoryException */ public void initialize() throws Exception { Session session = repository.login(credentials); Node collectionNode = null; try { collectionNode = session.getRootNode().getNode(collectionNodePath); } catch (PathNotFoundException e) { collectionNode = session.getRootNode().addNode(collectionNodePath); collectionNode.addMixin("mix:referenceable"); session.save(); } this.collectionNodeId = collectionNode.getUUID(); this.id = "urn:" + collectionNodeId; Workspace workspace = session.getWorkspace(); // Get the NodeTypeManager from the Workspace. // Note that it must be cast from the generic JCR NodeTypeManager to the // Jackrabbit-specific implementation. JackrabbitNodeTypeManager jntmgr = (JackrabbitNodeTypeManager)workspace.getNodeTypeManager(); if (!jntmgr.hasNodeType("abdera:entry")) { InputStream in = getClass().getResourceAsStream("/org/apache/abdera/jcr/nodeTypes.xml"); try { // register the node types and any referenced namespaces jntmgr.registerNodeTypes(in, JackrabbitNodeTypeManager.TEXT_XML); } finally { in.close(); } } session.logout(); sessionPool = new SessionPoolManager(maxActiveSessions, repository, credentials); } @Override public void start(RequestContext request) throws ResponseContextException { try { Session session = (Session)sessionPool.get(request); request.setAttribute(Scope.REQUEST, SESSION_KEY, session); } catch (Exception e) { throw new ResponseContextException(500, e); } } @Override public void end(RequestContext request, ResponseContext response) { // Logout of the JCR session Session session = getSession(request); if (session != null) { try { sessionPool.release(session); } catch (Exception e) { log.warn("Could not return Session to pool!", e); } } } @Override public String getContentType(Node entry) { try { return getStringOrNull(entry, CONTENT_TYPE); } catch (ResponseContextException e) { throw new UnsupportedOperationException(); } } @Override public boolean isMediaEntry(Node entry) throws ResponseContextException { try { return entry.hasProperty(MEDIA); } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } @Override public Node postMedia(MimeType mimeType, String slug, InputStream inputStream, RequestContext request) throws ResponseContextException { if (slug == null) { throw new ResponseContextException("A slug header must be supplied.", 500); } Node n = postEntry(slug, null, null, new Date(), null, null, request); try { n.setProperty(MEDIA, inputStream); n.setProperty(CONTENT_TYPE, mimeType.toString()); String summary = postSummaryForEntry(n); if (summary != null) { n.setProperty(SUMMARY, summary); } getSession(request).save(); return n; } catch (RepositoryException e) { try { getSession(request).refresh(false); } catch (Throwable t) { log.warn(t); } throw new ResponseContextException(500, e); } } /** * post a summary for an entry. Used when a media entry is postd so you have the chance to post a meaningful summary * for consumers of the feed. * * @param n * @return */ protected String postSummaryForEntry(Node n) { return null; } @Override public Node postEntry(String title, IRI id, String summary, Date updated, List<Person> authors, Content content, RequestContext request) throws ResponseContextException { Session session = getSession(request); try { Node collectionNode = session.getNodeByUUID(collectionNodeId); String resourceName = Sanitizer.sanitize(title, "-"); return postEntry(title, summary, updated, authors, content, session, collectionNode, resourceName, 0); } catch (RepositoryException e) { try { session.refresh(false); } catch (Throwable t) { log.warn(t); } throw new ResponseContextException(500, e); } } protected Node postEntry(String title, String summary, Date updated, List<Person> authors, Content content, Session session, Node collectionNode, String resourceName, int num) throws ResponseContextException, RepositoryException { try { String name = resourceName; if (num > 0) { name = name + "_" + num; } Node entry = collectionNode.addNode(name, "abdera:entry"); entry.addMixin("mix:referenceable"); mapEntryToNode(entry, title, summary, updated, authors, content, session); session.save(); return entry; } catch (ItemExistsException e) { return postEntry(title, summary, updated, authors, content, session, collectionNode, resourceName, ++num); } } protected Node mapEntryToNode(Node entry, String title, String summary, Date updated, List<Person> authors, Content content, Session session) throws ResponseContextException, RepositoryException { if (title == null) { EmptyResponseContext ctx = new EmptyResponseContext(500); ctx.setStatusText("Entry title cannot be empty."); throw new ResponseContextException(ctx); } entry.setProperty(TITLE, title); if (summary != null) { entry.setProperty(SUMMARY, summary); } Calendar upCal = Calendar.getInstance(); upCal.setTime(updated); entry.setProperty(UPDATED, upCal); if (authors != null) { for (Person p : authors) { Node addNode = entry.addNode(AUTHOR); addNode.setProperty(AUTHOR_EMAIL, p.getEmail()); addNode.setProperty(AUTHOR_LANGUAGE, p.getLanguage()); addNode.setProperty(AUTHOR_NAME, p.getName()); } } if (content != null) { switch (content.getContentType()) { case TEXT: entry.setProperty(CONTENT, content.getText()); entry.setProperty(CONTENT_TYPE, Type.TEXT.toString()); break; case XHTML: entry.setProperty(CONTENT, asString(content)); entry.setProperty(CONTENT_TYPE, Type.XHTML.toString()); break; default: throw new ResponseContextException("Invalid content element type.", 500); } } if (summary != null) { entry.setProperty(SUMMARY, summary); } return entry; } private String asString(Content content2) throws ResponseContextException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { content2.<Element> getFirstChild().writeTo(bos); } catch (IOException e) { throw new ResponseContextException(500, e); } return new String(bos.toByteArray()); } protected Session getSession(RequestContext request) { return (Session)request.getAttribute(Scope.REQUEST, SESSION_KEY); } @Override public void deleteEntry(String resourceName, RequestContext request) throws ResponseContextException { Session session = getSession(request); try { getNode(session, resourceName).remove(); session.save(); } catch (RepositoryException e) { try { session.refresh(false); } catch (Throwable t) { log.warn(t); } throw new ResponseContextException(500, e); } } private Node getNode(Session session, String resourceName) throws ResponseContextException, RepositoryException { try { return session.getNodeByUUID(collectionNodeId).getNode(resourceName); } catch (PathNotFoundException e) { throw new ResponseContextException(404); } } /** Recursively outputs the contents of the given node. */ public static void dump(Node node) throws RepositoryException { // First output the node path System.out.println(node.getPath()); // Skip the virtual (and large!) jcr:system subtree if (node.getName().equals("jcr:system")) { return; } // Then output the properties PropertyIterator properties = node.getProperties(); while (properties.hasNext()) { Property property = properties.nextProperty(); if (property.getDefinition().isMultiple()) { // A multi-valued property, print all values Value[] values = property.getValues(); for (int i = 0; i < values.length; i++) { System.out.println(property.getPath() + " = " + values[i].getString()); } } else { // A single-valued property System.out.println(property.getPath() + " = " + property.getString()); } } // Finally output all the child nodes recursively NodeIterator nodes = node.getNodes(); while (nodes.hasNext()) { dump(nodes.nextNode()); } } @Override public String getAuthor(RequestContext request) throws ResponseContextException { return author; } @Override public List<Person> getAuthors(Node entry, RequestContext request) throws ResponseContextException { try { ArrayList<Person> authors = new ArrayList<Person>(); for (NodeIterator nodes = entry.getNodes(); nodes.hasNext();) { Node n = nodes.nextNode(); if (n.getName().equals(AUTHOR)) { Person author = request.getAbdera().getFactory().newAuthor(); author.setName(getStringOrNull(entry, AUTHOR_NAME)); author.setEmail(getStringOrNull(entry, AUTHOR_EMAIL)); author.setLanguage(getStringOrNull(entry, AUTHOR_LANGUAGE)); authors.add(author); } } return authors; } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } @Override public Object getContent(Node entry, RequestContext request) throws ResponseContextException { String typeStr = getStringOrNull(entry, CONTENT_TYPE); Factory factory = Abdera.getInstance().getFactory(); String textContent = getStringOrNull(entry, CONTENT); Type type = Type.valueOf(typeStr); Content content = factory.newContent(type); switch (type) { case TEXT: content.setValue(textContent); return content; case XHTML: content.setWrappedValue(textContent); return content; default: } return null; } @Override public Iterable<Node> getEntries(RequestContext request) throws ResponseContextException { ArrayList<Node> entries = new ArrayList<Node>(); Session session = getSession(request); try { Node n = session.getNodeByUUID(collectionNodeId); for (NodeIterator nodes = n.getNodes(); nodes.hasNext();) { entries.add(nodes.nextNode()); } } catch (RepositoryException e) { throw new ResponseContextException(500, e); } return entries; } @Override public Node getEntry(String resourceName, RequestContext request) throws ResponseContextException { try { return getNode(getSession(request), resourceName); } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } @Override public String getId(RequestContext request) { return id; } @Override public String getId(Node entry) throws ResponseContextException { try { return "urn:" + entry.getUUID(); } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } public String getMediaName(Node entry) throws ResponseContextException { return getName(entry); } public InputStream getMediaStream(Node entry) throws ResponseContextException { try { Value value = getValueOrNull(entry, MEDIA); return (value != null) ? value.getStream() : null; } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } @Override public String getName(Node entry) throws ResponseContextException { try { return entry.getName(); } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } @Override public Text getSummary(Node entry, RequestContext request) throws ResponseContextException { Text summary = request.getAbdera().getFactory().newSummary(); summary.setText(getStringOrNull(entry, SUMMARY)); return summary; } public String getTitle(RequestContext request) { return title; } @Override public String getTitle(Node entry) throws ResponseContextException { return getStringOrNull(entry, TITLE); } @Override public Date getUpdated(Node entry) throws ResponseContextException { Calendar updated = getDateOrNull(entry, UPDATED); return (updated != null) ? updated.getTime() : null; } @Override public void putEntry(Node entry, String title, Date updated, List<Person> authors, String summary, Content content, RequestContext request) throws ResponseContextException { Session session = getSession(request); try { mapEntryToNode(entry, title, summary, updated, authors, content, session); } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } public static String getStringOrNull(Node node, String propName) throws ResponseContextException { try { Value v = getValueOrNull(node, propName); return (v != null) ? v.getString() : null; } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } public ResponseContext getCategories(RequestContext request) { return null; } public static Calendar getDateOrNull(Node node, String propName) throws ResponseContextException { try { Value v = getValueOrNull(node, propName); return (v != null) ? v.getDate() : null; } catch (RepositoryException e) { throw new ResponseContextException(500, e); } } public static Value getValueOrNull(Node node, String propName) throws RepositoryException { return node.hasProperty(propName) ? node.getProperty(propName).getValue() : null; } public void setRepository(Repository repository) { this.repository = repository; } public void setCredentials(Credentials credentials) { this.credentials = credentials; } public void setMaxActiveSessions(int maxActiveSessions) { this.maxActiveSessions = maxActiveSessions; } }
937
apache/abdera/adapters/jcr/src/main/java/org/apache/abdera/protocol/server/adapters/jcr/SessionPoolManager.java
package org.apache.abdera.protocol.server.adapters.jcr; import javax.jcr.Credentials; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.apache.abdera.protocol.Request; import org.apache.abdera.protocol.util.AbstractItemManager; public class SessionPoolManager extends AbstractItemManager<Session> { private Repository repository; private Credentials credentials; public SessionPoolManager(int maxSize, Repository repository, Credentials credentials) { super(maxSize); this.repository = repository; this.credentials = credentials; } @Override protected Session internalNewInstance() { try { return repository.login(credentials); } catch (RepositoryException e) { throw new RuntimeException(e); } } public Session get(Request request) { return getInstance(); } }
6,108
apache/abdera/adapters/jcr/src/test/java/org/apache/abdera/jcr/JcrCollectionAdapterTest.java
package org.apache.abdera.jcr; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.Date; import java.util.List; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.Repository; import javax.jcr.Session; import javax.jcr.SimpleCredentials; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Base; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Person; import org.apache.abdera.protocol.client.AbderaClient; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.client.RequestOptions; import org.apache.abdera.protocol.server.Provider; import org.apache.abdera.protocol.server.adapters.jcr.JcrCollectionAdapter; import org.apache.abdera.protocol.server.impl.DefaultProvider; import org.apache.abdera.protocol.server.impl.SimpleWorkspaceInfo; import org.apache.abdera.protocol.server.servlet.AbderaServlet; import org.apache.abdera.writer.Writer; import org.apache.axiom.testutils.PortAllocator; import org.apache.jackrabbit.core.TransientRepository; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; public class JcrCollectionAdapterTest { private int port; private Server server; private DefaultProvider jcrProvider; private Repository repository; @Before public void setUp() throws Exception { jcrProvider = new DefaultProvider(); repository = new TransientRepository(); JcrCollectionAdapter cp = new JcrCollectionAdapter(); cp.setTitle("My Entries"); cp.setAuthor("Apache Abdera"); cp.setCollectionNodePath("entries"); cp.setRepository(repository); cp.setCredentials(new SimpleCredentials("username", "pass".toCharArray())); cp.setHref("feed"); cp.initialize(); SimpleWorkspaceInfo wkspc = new SimpleWorkspaceInfo(); wkspc.setTitle("JCR Workspace"); wkspc.addCollection(cp); jcrProvider.addWorkspace(wkspc); initializeJetty(); } @Test public void testJCRAdapter() throws Exception { Abdera abdera = new Abdera(); Factory factory = abdera.getFactory(); AbderaClient client = new AbderaClient(abdera); String base = "http://localhost:" + port + "/"; // Testing of entry creation IRI colUri = new IRI(base).resolve("feed"); Entry entry = factory.newEntry(); entry.setTitle("Some Entry"); entry.setUpdated(new Date()); entry.addAuthor("Dan Diephouse"); entry.setId(factory.newUuidUri()); entry.setSummary("This is my entry."); entry.setContent("This is my entry. It's swell."); RequestOptions opts = new RequestOptions(); opts.setContentType("application/atom+xml;type=entry"); ClientResponse res = client.post(colUri.toString(), entry, opts); assertEquals(201, res.getStatus()); // prettyPrint(abdera, res.getDocument()); IRI location = res.getLocation(); assertEquals(base + "feed/Some_Entry", location.toString()); // GET the entry res = client.get(location.toString()); assertEquals(200, res.getStatus()); // prettyPrint(abdera, res.getDocument()); org.apache.abdera.model.Document<Entry> entry_doc = res.getDocument(); Entry entry2 = entry_doc.getRoot(); assertEquals(entry.getTitle(), entry2.getTitle()); assertEquals(entry.getSummary(), entry2.getSummary()); assertEquals(entry.getContent(), entry2.getContent()); List<Person> authors = entry2.getAuthors(); assertEquals(1, authors.size()); entry = entry2; entry.setSummary("New Summary"); entry.setContent("New Content"); res = client.put(location.toString(), entry, opts); assertEquals(204, res.getStatus()); res = client.get(colUri.toString()); org.apache.abdera.model.Document<Feed> feed_doc = res.getDocument(); Feed feed = feed_doc.getRoot(); assertEquals(1, feed.getEntries().size()); // prettyPrint(abdera, feed_doc); // test 404 not found res = client.get(location.toString() + "Invalid"); assertEquals(404, res.getStatus()); } protected void prettyPrint(Abdera abdera, Base doc) throws IOException { Writer writer = abdera.getWriterFactory().getWriter("prettyxml"); writer.writeTo(doc, System.out); System.out.println(); } private void clearJcrRepository() { try { Session session = repository.login(new SimpleCredentials("username", "password".toCharArray())); Node node = session.getRootNode(); for (NodeIterator itr = node.getNodes(); itr.hasNext();) { Node child = itr.nextNode(); if (!child.getName().equals("jcr:system")) { child.remove(); } } session.save(); session.logout(); } catch (PathNotFoundException t) { } catch (Throwable t) { t.printStackTrace(); } } private void initializeJetty() throws Exception { port = PortAllocator.allocatePort(); server = new Server(port); Context root = new Context(server, "/", Context.NO_SESSIONS); root.addServlet(new ServletHolder(new AbderaServlet() { @Override protected Provider createProvider() { jcrProvider.init(getAbdera(), getProperties(getServletConfig())); return jcrProvider; } }), "/*"); server.start(); } @After public void tearDown() throws Exception { clearJcrRepository(); if (server != null) server.stop(); } }
8,837
apache/abdera/adapters/jdbc/src/main/java/org/apache/abdera/protocol/server/adapters/ibatis/IBatisCollectionAdapter.java
package org.apache.abdera.protocol.server.adapters.ibatis; import java.io.ByteArrayInputStream; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.abdera.Abdera; import org.apache.abdera.model.Content; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.protocol.server.provider.basic.BasicAdapter; import org.apache.abdera.protocol.server.provider.managed.FeedConfiguration; import org.apache.abdera.protocol.server.provider.managed.ServerConfiguration; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; /** * Adapter that uses IBatis and a database to store Atompub collection entries. As an extension to BasicAdapter, the * adapter is intended to be used with BasicProvider and is configured using /abdera/adapter/*.properties files. */ public class IBatisCollectionAdapter extends BasicAdapter { // this class needs to be public - so that Adapter Manager can invoke it // to create an instance of this adapter public IBatisCollectionAdapter(Abdera abdera, FeedConfiguration config) { super(abdera, config); } protected Map<String, SqlMapClient> sqlMapClients = new HashMap<String, SqlMapClient>(); protected SqlMapClient getSqlMapClient() throws Exception { String dataSourceId = config.getFeedConfigLocation(); if (sqlMapClients.containsKey(dataSourceId)) { return sqlMapClients.get(dataSourceId); } else { SqlMapClient client = SqlMapClientBuilder.buildSqlMapClient(config.getAdapterConfiguration().getAdapterConfigAsReader()); sqlMapClients.put(dataSourceId, client); return client; } } @SuppressWarnings("unchecked") public Feed getFeed() throws Exception { SqlMapClient client = getSqlMapClient(); String queryId = config.getFeedId() + "-get-feed"; List<Map<String, Object>> rows = client.queryForList(queryId); Feed feed = createFeed(); ServerConfiguration serverConfig = config.getServerConfiguration(); if (serverConfig.getFeedNamespacePrefix() != null && serverConfig.getFeedNamespacePrefix().length() > 0) { feed.declareNS(serverConfig.getFeedNamespace(), serverConfig.getFeedNamespacePrefix()); } for (Map<String, Object> row : rows) createEntryFromRow(feed, row); return feed; } @SuppressWarnings("unchecked") public Entry getEntry(Object entryId) throws Exception { String queryId = config.getFeedId() + "-get-entry"; SqlMapClient client = getSqlMapClient(); Map<String, Object> row = (Map<String, Object>)client.queryForObject(queryId, entryId); if (row == null) { // didn't find the entry. return null; } return createEntryFromRow(null, row); } public Entry createEntry(Entry entry) throws Exception { SqlMapClient client = getSqlMapClient(); String queryId = config.getFeedId() + "-insert-entry"; Object newEntryId = client.insert(queryId, collectColumns(entry)); return getEntry(newEntryId); } public Entry updateEntry(Object entryId, Entry entry) throws Exception { SqlMapClient client = getSqlMapClient(); String queryId = config.getFeedId() + "-update-entry"; return client.update(queryId, collectColumns(entry)) > 0 ? getEntry(entryId) : null; } public boolean deleteEntry(Object entryId) throws Exception { String queryId = config.getFeedId() + "-delete-entry"; SqlMapClient client = getSqlMapClient(); return client.delete(queryId, entryId) > 0; } protected Entry createEntryFromRow(Feed feed, Map<String, Object> row) throws Exception { Entry entry = feed != null ? feed.addEntry() : abdera.newEntry(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element entity = doc.createElement("entity"); doc.appendChild(entity); for (String columnName : row.keySet()) { if (row.get(columnName) == null) { continue; } Object value = row.get(columnName); if (FeedConfiguration.ENTRY_ELEM_NAME_ID.equals(columnName)) { entry.setId(createEntryIdUri(value.toString())); } else if (FeedConfiguration.ENTRY_ELEM_NAME_TITLE.equals(columnName)) { entry.setTitle(value.toString()); } else if (FeedConfiguration.ENTRY_ELEM_NAME_AUTHOR.equals(columnName)) { entry.addAuthor(value.toString()); } else if (FeedConfiguration.ENTRY_ELEM_NAME_UPDATED.equals(columnName) && value instanceof java.util.Date) { entry.setUpdated((Date)value); } else if (FeedConfiguration.ENTRY_ELEM_NAME_LINK.equals(columnName)) { entry.addLink(value.toString()); } else { Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); entity.appendChild(node); } } if (entry.getUpdated() == null) { entry.setUpdated(new Date()); } if (entry.getAuthor() == null) { entry.addAuthor(config.getFeedAuthor()); } if (entry.getTitle() == null) { entry.setTitle((String)config.getProperty(FeedConfiguration.PROP_ENTRY_TITLE_NAME)); } entry.setContent(getDocumentAsXml(doc), "text/xml"); addEditLinkToEntry(entry); return entry; } public static String getDocumentAsXml(Document doc) throws TransformerConfigurationException, TransformerException { DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); java.io.StringWriter sw = new java.io.StringWriter(); StreamResult sr = new StreamResult(sw); transformer.transform(domSource, sr); String str = sw.toString(); logger.finest(str); return str; } protected Map<String, Object> collectColumns(Entry entry) throws Exception { Map<String, Object> columns = new HashMap<String, Object>(); if (entry.getId() != null) { columns.put(FeedConfiguration.ENTRY_ELEM_NAME_ID, entry.getId().toString()); } if (entry.getAuthor() != null) { columns.put(FeedConfiguration.ENTRY_ELEM_NAME_AUTHOR, entry.getAuthor().getText()); } if (entry.getTitle() != null) { columns.put(FeedConfiguration.ENTRY_ELEM_NAME_TITLE, entry.getTitle()); } if (entry.getUpdated() != null) { columns.put(FeedConfiguration.ENTRY_ELEM_NAME_UPDATED, entry.getUpdated()); } Content content = entry.getContentElement(); if (content != null) { String contentStr = content.getValue(); parseContent(contentStr, columns); } return columns; } static void parseContent(String str, Map<String, Object> columns) throws Exception { ByteArrayInputStream inStr = new ByteArrayInputStream(str.getBytes()); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader parser = factory.createXMLStreamReader(inStr); while (true) { int event = parser.next(); if (event == XMLStreamConstants.END_DOCUMENT) { parser.close(); break; } if (event == XMLStreamConstants.START_ELEMENT) { String name = parser.getLocalName(); int eventType = parser.next(); if (eventType == XMLStreamConstants.CHARACTERS) { String value = parser.getText(); columns.put(name, value); } } } } }
39,463
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/AbderaClient.java
package org.apache.abdera.protocol.client; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.net.ssl.TrustManager; import org.apache.abdera.Abdera; import org.apache.abdera.model.Base; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.protocol.EntityProvider; import org.apache.abdera.protocol.Response.ResponseType; import org.apache.abdera.protocol.client.cache.Cache; import org.apache.abdera.protocol.client.cache.CacheFactory; import org.apache.abdera.protocol.client.cache.CachedResponse; import org.apache.abdera.protocol.client.cache.LRUCache; import org.apache.abdera.protocol.client.cache.Cache.Disposition; import org.apache.abdera.protocol.client.util.BaseRequestEntity; import org.apache.abdera.protocol.client.util.EntityProviderRequestEntity; import org.apache.abdera.protocol.client.util.MethodHelper; import org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity; import org.apache.abdera.protocol.client.util.SimpleSSLProtocolSocketFactory; import org.apache.abdera.protocol.error.Error; import org.apache.abdera.protocol.error.ProtocolException; import org.apache.abdera.protocol.util.CacheControlUtil; import org.apache.abdera.util.EntityTag; import org.apache.abdera.util.Version; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.auth.AuthPolicy; import org.apache.commons.httpclient.auth.AuthScheme; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; /** * An Atom Publishing Protocol client. */ @SuppressWarnings( {"unchecked", "deprecation"}) public class AbderaClient { public static final String DEFAULT_USER_AGENT = Version.APP_NAME + "/" + Version.VERSION; public static int DEFAULT_MAX_REDIRECTS = 10; protected final Abdera abdera; protected final Cache cache; private final HttpClient client; public AbderaClient() { this(new Abdera(), DEFAULT_USER_AGENT); } /** * Create an AbderaClient instance using the specified useragent name * * @param useragent */ public AbderaClient(String useragent) { this(new Abdera(), useragent); } /** * Create an AbderaClient instance using the specified Abdera instance and useragent name * * @param abdera * @param useragent */ public AbderaClient(Abdera abdera, String useragent) { this(abdera, useragent, initCache(abdera)); } /** * Create an AbderaClient instance using the specified Abdera instance and useragent name * * @param abdera * @param useragent */ public AbderaClient(Abdera abdera, String useragent, Cache cache) { this.abdera = abdera; this.cache = cache; MultiThreadedHttpConnectionManager connManager = new MultiThreadedHttpConnectionManager(); client = new HttpClient(connManager); client.getParams().setParameter(HttpClientParams.USER_AGENT, useragent); client.getParams().setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, true); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); setAuthenticationSchemeDefaults(); setMaximumRedirects(DEFAULT_MAX_REDIRECTS); } /** * Create an Abdera using a preconfigured HttpClient object * * @param client An Apache HttpClient object */ public AbderaClient(HttpClient client) { this(new Abdera(), client); } /** * Create an Abdera using a preconfigured HttpClient object * * @param abdera * @param client An Apache HttpClient object */ public AbderaClient(Abdera abdera, HttpClient client) { this(abdera, client, initCache(abdera)); } /** * Create an Abdera using a preconfigured HttpClient object * * @param abdera * @param client An Apache HttpClient object */ public AbderaClient(Abdera abdera, HttpClient client, Cache cache) { this.abdera = abdera; this.cache = cache; this.client = client; setAuthenticationSchemeDefaults(); setMaximumRedirects(DEFAULT_MAX_REDIRECTS); } /** * Create an AbderaClient instance using the specified Abdera instance * * @param abdera */ public AbderaClient(Abdera abdera) { this(abdera, DEFAULT_USER_AGENT); } /** * Create an AbderaClient instance using the specified Abdera instance * * @param abdera */ public AbderaClient(Abdera abdera, Cache cache) { this(abdera, DEFAULT_USER_AGENT, cache); } /** * Returns the client HTTP cache instance */ public Cache getCache() { return cache; } /** * @deprecated The CacheFactory interface is no longer used. */ public Cache initCache(CacheFactory factory) { return initCache(abdera); } /** * Initializes the client HTTP cache */ public static Cache initCache(Abdera abdera) { return new LRUCache(abdera); } /** * Sends an HTTP HEAD request to the specified URI. * * @param uri The request URI * @param options The request options */ public ClientResponse head(String uri, RequestOptions options) { return execute("HEAD", uri, (RequestEntity)null, options); } /** * Sends an HTTP GET request to the specified URI. * * @param uri The request URI * @param options The request options */ public ClientResponse get(String uri, RequestOptions options) { return execute("GET", uri, (RequestEntity)null, options); } /** * Sends an HTTP POST request to the specified URI. * * @param uri The request URI * @param provider An EntityProvider implementation providing the payload of the request * @param options The request options */ public ClientResponse post(String uri, EntityProvider provider, RequestOptions options) { return post(uri, new EntityProviderRequestEntity(abdera, provider, options.isUseChunked()), options); } /** * Sends an HTTP POST request to the specified URI. * * @param uri The request URI * @param entity A RequestEntity object providing the payload of the request * @param options The request options */ public ClientResponse post(String uri, RequestEntity entity, RequestOptions options) { return execute("POST", uri, entity, options); } /** * Sends an HTTP POST request to the specified URI. * * @param uri The request URI * @param in An InputStream providing the payload of the request * @param options The request options */ public ClientResponse post(String uri, InputStream in, RequestOptions options) { return execute("POST", uri, new InputStreamRequestEntity(in), options); } /** * Sends an HTTP POST request to the specified URI. * * @param uri The request URI * @param base An Abdera FOM Document or Element object providing the payload of the request * @param options The request options */ public ClientResponse post(String uri, Base base, RequestOptions options) { if (base instanceof Document) { Document d = (Document)base; if (options.getSlug() == null && d.getSlug() != null) options.setSlug(d.getSlug()); } return execute("POST", uri, new BaseRequestEntity(base, options.isUseChunked()), options); } /** * Sends an HTTP POST request to the specified URI. It uses the media and entry parameters to create a * multipart/related object. If the contentType is not provided this method tries to get it from the type attribute * of the entry content. * * @param uri The request URI * @param entry The entry that will be sent as the first element of the multipart/related object * @param media The media object that will be sent as the second element of the multipart/related object */ public ClientResponse post(String uri, Entry entry, InputStream media) { return post(uri, entry, media, getDefaultRequestOptions()); } /** * Sends an HTTP POST request to the specified URI. It uses the media and entry parameters to create a * multipart/related object. If the contentType is not provided this method tries to get it from the type attribute * of the entry content. * * @param uri The request URI * @param entry The entry that will be sent as the first element of the multipart/related object * @param media The media object that will be sent as the second element of the multipart/related object * @param options The request options */ public ClientResponse post(String uri, Entry entry, InputStream media, RequestOptions options) { return post(uri, entry, media, null, options); } /** * Sends an HTTP POST request to the specified URI. It uses the media and entry parameters to create a * multipart/related object. * * @param uri The request URI * @param entry The entry that will be sent as the first element of the multipart/related object * @param media The media object that will be sent as the second element of the multipart/related object * @param contentType the content type of the media object * @param options The request options */ public ClientResponse post(String uri, Entry entry, InputStream media, String contentType, RequestOptions options) { return execute("POST", uri, new MultipartRelatedRequestEntity(entry, media, contentType), options); } /** * Sends an HTTP PUT request to the specified URI. * * @param uri The request URI * @param provider An EntityProvider implementation providing the payload of the request * @param options The request options */ public ClientResponse put(String uri, EntityProvider provider, RequestOptions options) { if (options == null) options = getDefaultRequestOptions(); if (options.isConditionalPut()) { EntityTag etag = provider.getEntityTag(); if (etag != null) options.setIfMatch(etag); else { Date lm = provider.getLastModified(); if (lm != null) options.setIfUnmodifiedSince(lm); } } return put(uri, new EntityProviderRequestEntity(abdera, provider, options.isUseChunked()), options); } /** * Sends an HTTP PUT request to the specified URI. * * @param uri The request URI * @param entity A RequestEntity object providing the payload of the request * @param options The request options */ public ClientResponse put(String uri, RequestEntity entity, RequestOptions options) { return execute("PUT", uri, entity, options); } /** * Sends an HTTP PUT request to the specified URI. * * @param uri The request URI * @param in An InputStream providing the payload of the request * @param options The request options */ public ClientResponse put(String uri, InputStream in, RequestOptions options) { return execute("PUT", uri, new InputStreamRequestEntity(in), options); } /** * Sends an HTTP PUT request to the specified URI. * * @param uri The request URI * @param base A FOM Document or Element providing the payload of the request * @param options The request options */ public ClientResponse put(String uri, Base base, RequestOptions options) { if (options == null) options = getDefaultRequestOptions(); if (base instanceof Document) { Document d = (Document)base; if (options.getSlug() == null && d.getSlug() != null) options.setSlug(d.getSlug()); if (options.isConditionalPut()) { if (d.getEntityTag() != null) options.setIfMatch(d.getEntityTag()); else if (d.getLastModified() != null) options.setIfUnmodifiedSince(d.getLastModified()); } } return execute("PUT", uri, new BaseRequestEntity(base, options.isUseChunked()), options); } /** * Sends an HTTP DELETE request to the specified URI. * * @param uri The request URI * @param options The request options */ public ClientResponse delete(String uri, RequestOptions options) { return execute("DELETE", uri, (RequestEntity)null, options); } /** * Sends an HTTP HEAD request to the specified URI using the default options * * @param uri The request URI */ public ClientResponse head(String uri) { return head(uri, getDefaultRequestOptions()); } /** * Sends an HTTP GET request to the specified URI using the default options * * @param uri The request URI */ public ClientResponse get(String uri) { return get(uri, getDefaultRequestOptions()); } /** * Sends an HTTP POST request to the specified URI using the default options * * @param uri The request URI * @param provider An EntityProvider implementation providing the payload the request */ public ClientResponse post(String uri, EntityProvider provider) { return post(uri, provider, getDefaultRequestOptions()); } /** * Sends an HTTP POST request to the specified URI using the default options * * @param uri The request URI * @param entity A RequestEntity object providing the payload of the request */ public ClientResponse post(String uri, RequestEntity entity) { return post(uri, entity, getDefaultRequestOptions()); } /** * Sends an HTTP POST request to the specified URI using the default options * * @param uri The request URI * @param in An InputStream providing the payload of the request */ public ClientResponse post(String uri, InputStream in) { return post(uri, in, getDefaultRequestOptions()); } /** * Sends an HTTP POST request to the specified URI using the default options * * @param uri The request URI * @param base A FOM Document or Element providing the payload of the request */ public ClientResponse post(String uri, Base base) { return post(uri, base, getDefaultRequestOptions()); } /** * Sends an HTTP PUT request to the specified URI using the default options * * @param uri The request URI * @param provider An EntityProvider implementation providing the payload of the request */ public ClientResponse put(String uri, EntityProvider provider) { return put(uri, provider, getDefaultRequestOptions()); } /** * Sends an HTTP PUT request to the specified URI using the default options * * @param uri The request URI * @param entity A RequestEntity object providing the payload of the request */ public ClientResponse put(String uri, RequestEntity entity) { return put(uri, entity, getDefaultRequestOptions()); } /** * Sends an HTTP PUT request to the specified URI using the default options * * @param uri The request URI * @param in An InputStream providing the payload of the request */ public ClientResponse put(String uri, InputStream in) { return put(uri, in, getDefaultRequestOptions()); } /** * Sends an HTTP PUT request to the specified URI using the default options * * @param uri The request URI * @param base A FOM Document or Element providing the payload of the request */ public ClientResponse put(String uri, Base base) { return put(uri, base, getDefaultRequestOptions()); } /** * Sends an HTTP DELETE request to the specified URI using the default options * * @param uri The request URI */ public ClientResponse delete(String uri) { return delete(uri, getDefaultRequestOptions()); } /** * Register a new authentication scheme. * * @param name * @param scheme */ public static void registerScheme(String name, Class<? extends AuthScheme> scheme) { AuthPolicy.registerAuthScheme(name, scheme); } /** * Unregister a specific authentication scheme * * @param name The name of the authentication scheme (e.g. "basic", "digest", etc) */ public static void unregisterScheme(String name) { AuthPolicy.unregisterAuthScheme(name); } /** * Unregister multiple HTTP authentication schemes */ public static void unregisterScheme(String... names) { for (String name : names) unregisterScheme(name); } /** * Register the specified TrustManager for SSL support on the default port (443) * * @param trustManager The TrustManager implementation */ public static void registerTrustManager(TrustManager trustManager) { registerTrustManager(trustManager, 443); } /** * Register the default TrustManager for SSL support on the default port (443) */ public static void registerTrustManager() { registerTrustManager(443); } /** * Register the specified TrustManager for SSL support on the specified port * * @param trustManager The TrustManager implementation * @param port The port */ public static void registerTrustManager(TrustManager trustManager, int port) { SimpleSSLProtocolSocketFactory f = new SimpleSSLProtocolSocketFactory(trustManager); registerFactory(f, port); } /** * Register the default trust manager on the specified port * * @param port The port */ public static void registerTrustManager(int port) { SimpleSSLProtocolSocketFactory f = new SimpleSSLProtocolSocketFactory(); registerFactory(f, port); } /** * Register the specified secure socket factory on the specified port */ public static void registerFactory(SecureProtocolSocketFactory factory, int port) { Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)factory, port)); } /** * Configure the client to use preemptive authentication (HTTP Basic Authentication only) */ public AbderaClient usePreemptiveAuthentication(boolean val) { client.getParams().setAuthenticationPreemptive(val); return this; } private boolean useCache(String method, RequestOptions options) { return (CacheControlUtil.isIdempotent(method)) && !options.isNoCache() && !options.isNoStore() && options.getUseLocalCache(); } private boolean mustRevalidate(RequestOptions options, CachedResponse response) { if (options.getRevalidateWithAuth()) { if (options.getAuthorization() != null) return true; if (client.getParams().getBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, false)) return true; if (response != null) { if (response.isPublic()) return false; } } return false; } /** * Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a * server (e.g. PATCH, LOCK, etc) * * @param method The HTTP method * @param uri The request URI * @param base A FOM Document and Element providing the payload for the request * @param options The Request Options */ public ClientResponse execute(String method, String uri, Base base, RequestOptions options) { return execute(method, uri, new BaseRequestEntity(base), options); } /** * Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a * server (e.g. PATCH, LOCK, etc) * * @param method The HTTP method * @param uri The request URI * @param provider An EntityProvider implementation providing the payload of the request * @param options The Request Options */ public ClientResponse execute(String method, String uri, EntityProvider provider, RequestOptions options) { if (options == null) options = getDefaultRequestOptions(); return execute(method, uri, new EntityProviderRequestEntity(abdera, provider, options.isUseChunked()), options); } /** * Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a * server (e.g. PATCH, LOCK, etc) * * @param method The HTTP method * @param uri The request URI * @param in An InputStream providing the payload of the request * @param options The Request Options */ public ClientResponse execute(String method, String uri, InputStream in, RequestOptions options) { RequestEntity re = null; try { if (options.getContentType() != null) { re = new InputStreamRequestEntity(in, options.getContentType().toString()); } else { re = new InputStreamRequestEntity(in); } } catch (Exception e) { re = new InputStreamRequestEntity(in); } return execute(method, uri, re, options); } private Disposition getCacheDisposition(boolean usecache, String uri, RequestOptions options, CachedResponse cached_response) { Disposition disp = (usecache) ? cache.disposition(uri, options) : Disposition.TRANSPARENT; disp = (!disp.equals(Disposition.TRANSPARENT) && mustRevalidate(options, cached_response)) ? Disposition.STALE : disp; return disp; } /** * Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a * server (e.g. PATCH, LOCK, etc) * * @param method The HTTP method * @param uri The request URI * @param entity A RequestEntity object providing the payload for the request * @param options The Request Options */ public ClientResponse execute(String method, String uri, RequestEntity entity, RequestOptions options) { boolean usecache = useCache(method, options); options = options != null ? options : getDefaultRequestOptions(); try { Cache cache = getCache(); CachedResponse cached_response = cache.get(uri); switch (getCacheDisposition(usecache, uri, options, cached_response)) { case FRESH: // CACHE HIT: FRESH if (cached_response != null) return checkRequestException(cached_response, options); case STALE: // CACHE HIT: STALE // revalidate the cached entry if (cached_response != null) { if (cached_response.getEntityTag() != null) options.setIfNoneMatch(cached_response.getEntityTag().toString()); else if (cached_response.getLastModified() != null) options.setIfModifiedSince(cached_response.getLastModified()); else options.setNoCache(true); } default: // CACHE MISS HttpMethod httpMethod = MethodHelper.createMethod(method, uri, entity, options); client.executeMethod(httpMethod); if (usecache && (httpMethod.getStatusCode() == 304 || httpMethod.getStatusCode() == 412) && cached_response != null) return cached_response; ClientResponse response = new CommonsResponse(abdera, httpMethod); response = options.getUseLocalCache() ? response = cache.update(uri, options, response, cached_response) : response; return checkRequestException(response, options); } } catch (RuntimeException r) { throw r; } catch (Throwable t) { throw new RuntimeException(t); } } private ClientResponse checkRequestException(ClientResponse response, RequestOptions options) { if (response == null) return response; ResponseType type = response.getType(); if ((type.equals(ResponseType.CLIENT_ERROR) && options.is4xxRequestException()) || (type .equals(ResponseType.SERVER_ERROR) && options.is5xxRequestException())) { try { Document<Element> doc = response.getDocument(); org.apache.abdera.protocol.error.Error error = null; if (doc != null) { Element root = doc.getRoot(); if (root instanceof Error) { error = (Error)root; } } if (error == null) error = org.apache.abdera.protocol.error.Error.create(abdera, response.getStatus(), response .getStatusText()); error.throwException(); } catch (ProtocolException pe) { throw pe; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } return response; } /** * Get a copy of the default request options */ public RequestOptions getDefaultRequestOptions() { return MethodHelper.createDefaultRequestOptions(); } /** * Add authentication credentials */ public AbderaClient addCredentials(String target, String realm, String scheme, Credentials credentials) throws URISyntaxException { String host = AuthScope.ANY_HOST; int port = AuthScope.ANY_PORT; if (target != null) { URI uri = new URI(target); host = uri.getHost(); port = uri.getPort(); } AuthScope scope = new AuthScope(host, port, (realm != null) ? realm : AuthScope.ANY_REALM, (scheme != null) ? scheme : AuthScope.ANY_SCHEME); client.getState().setCredentials(scope, credentials); return this; } /** * Configure the client to use the default authentication scheme settings */ public AbderaClient setAuthenticationSchemeDefaults() { List authPrefs = AuthPolicy.getDefaultAuthPrefs(); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); return this; } /** * When multiple authentication schemes are supported by a server, the client will automatically select a scheme * based on the configured priority. For instance, to tell the client to prefer "digest" over "basic", set the * priority by calling setAuthenticationSchemePriority("digest","basic") */ public AbderaClient setAuthenticationSchemePriority(String... scheme) { List authPrefs = java.util.Arrays.asList(scheme); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); return this; } /** * Returns the current listing of preferred authentication schemes, in order of preference * * @see setAuthenticationSchemePriority */ public String[] getAuthenticationSchemePriority() { List list = (List)client.getParams().getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY); return (String[])list.toArray(new String[list.size()]); } /** * <p> * Per http://jakarta.apache.org/commons/httpclient/performance.html * </p> * <blockquote> Generally it is recommended to have a single instance of HttpClient per communication component or * even per application. However, if the application makes use of HttpClient only very infrequently, and keeping an * idle instance of HttpClient in memory is not warranted, it is highly recommended to explicitly shut down the * multithreaded connection manager prior to disposing the HttpClient instance. This will ensure proper closure of * all HTTP connections in the connection pool. </blockquote> */ public AbderaClient teardown() { ((MultiThreadedHttpConnectionManager)client.getHttpConnectionManager()).shutdown(); return this; } /** * Set the maximum number of connections allowed for a single host */ public AbderaClient setMaxConnectionsPerHost(int max) { Map<HostConfiguration, Integer> m = new HashMap<HostConfiguration, Integer>(); m.put(HostConfiguration.ANY_HOST_CONFIGURATION, max); client.getHttpConnectionManager().getParams().setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, m); return this; } /** * Return the maximum number of connections allowed for a single host */ public int getMaxConnectionsPerHost() { Map<HostConfiguration, Integer> m = (Map<HostConfiguration, Integer>)client.getHttpConnectionManager().getParams() .getParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS); if (m == null) return MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS; Integer i = m.get(HostConfiguration.ANY_HOST_CONFIGURATION); return i != null ? i.intValue() : MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS; } /** * Return the maximum number of connections allowed for the client */ public AbderaClient setMaxConnectionsTotal(int max) { client.getHttpConnectionManager().getParams() .setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, max); return this; } /** * Return the maximum number of connections allowed for the client */ public int getMaxConnectionsTotal() { return client.getHttpConnectionManager().getParams() .getIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, MultiThreadedHttpConnectionManager.DEFAULT_MAX_TOTAL_CONNECTIONS); } /** * Configure the client to use the specified proxy */ public AbderaClient setProxy(String host, int port) { client.getHostConfiguration().setProxy(host, port); return this; } /** * Specify the auth credentials for the proxy server */ public AbderaClient setProxyCredentials(String host, int port, Credentials credentials) { setProxyCredentials(host, port, null, null, credentials); return this; } /** * Specify the auth credentials for the proxy server */ public AbderaClient setProxyCredentials(String host, int port, String realm, String scheme, Credentials credentials) { host = host != null ? host : AuthScope.ANY_HOST; port = port > -1 ? port : AuthScope.ANY_PORT; AuthScope scope = new AuthScope(host, port, realm != null ? realm : AuthScope.ANY_REALM, scheme != null ? scheme : AuthScope.ANY_SCHEME); client.getState().setProxyCredentials(scope, credentials); return this; } /** * Manually add cookies */ public AbderaClient addCookie(String domain, String name, String value) { Cookie cookie = new Cookie(domain, name, value); client.getState().addCookie(cookie); return this; } /** * Manually add cookies */ public AbderaClient addCookie(String domain, String name, String value, String path, Date expires, boolean secure) { Cookie cookie = new Cookie(domain, name, value, path, expires, secure); client.getState().addCookie(cookie); return this; } /** * Manually add cookies */ public AbderaClient addCookie(String domain, String name, String value, String path, int maxAge, boolean secure) { Cookie cookie = new Cookie(domain, name, value, path, maxAge, secure); client.getState().addCookie(cookie); return this; } /** * Manually add cookies */ public AbderaClient addCookies(Cookie cookie) { client.getState().addCookie(cookie); return this; } /** * Manually add cookies */ public AbderaClient addCookies(Cookie... cookies) { client.getState().addCookies(cookies); return this; } /** * Get all the cookies */ public Cookie[] getCookies() { return client.getState().getCookies(); } /** * Get the cookies for a specific domain and path */ public Cookie[] getCookies(String domain, String path) { Cookie[] cookies = getCookies(); List<Cookie> list = new ArrayList<Cookie>(); for (Cookie cookie : cookies) { String test = cookie.getDomain(); if (test.startsWith(".")) test = test.substring(1); if ((domain.endsWith(test) || test.endsWith(domain)) && (path == null || cookie.getPath().startsWith(path))) { list.add(cookie); } } return list.toArray(new Cookie[list.size()]); } /** * Get the cookies for a specific domain */ public Cookie[] getCookies(String domain) { return getCookies(domain, null); } /** * Clear the cookies */ public AbderaClient clearCookies() { client.getState().clearCookies(); return this; } /** * Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default * value is zero. */ public AbderaClient setConnectionTimeout(int timeout) { client.getHttpConnectionManager().getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, timeout); return this; } /** * Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout * value of zero is interpreted as an infinite timeout. */ public AbderaClient setSocketTimeout(int timeout) { client.getParams().setSoTimeout(timeout); return this; } /** * Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager. */ public void setConnectionManagerTimeout(long timeout) { client.getParams().setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, timeout); } /** * Return the timeout until a connection is etablished, in milliseconds. A value of zero means the timeout is not * used. The default value is zero. */ public int getConnectionTimeout() { return client.getHttpConnectionManager().getParams() .getIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 0); } /** * Return the socket timeout for the connection in milliseconds A timeout value of zero is interpreted as an * infinite timeout. */ public int getSocketTimeout() { return client.getParams().getSoTimeout(); } /** * Returns the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager. */ public long getConnectionManagerTimeout() { return client.getParams().getLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, 0); } /** * Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by * minimizing the number of segments that are sent. When applications wish to decrease network latency and increase * performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the * cost of an increase in bandwidth consumption. */ public void setTcpNoDelay(boolean enable) { client.getHttpConnectionManager().getParams().setBooleanParameter(HttpConnectionParams.TCP_NODELAY, enable); } /** * Tests if Nagle's algorithm is to be used. */ public boolean getTcpNoDelay() { return client.getHttpConnectionManager().getParams().getBooleanParameter(HttpConnectionParams.TCP_NODELAY, false); } /** * Return the HttpConnectionManagerParams object of the underlying HttpClient. This enables you to configure options * not explicitly exposed by the AbderaClient */ public HttpConnectionManagerParams getHttpConnectionManagerParams() { return client.getHttpConnectionManager().getParams(); } /** * Return the HttpClientParams object of the underlying HttpClient. This enables you to configure options not * explicitly exposed by the AbderaClient */ public HttpClientParams getHttpClientParams() { return client.getParams(); } /** * Set the maximum number of redirects */ public AbderaClient setMaximumRedirects(int redirects) { client.getParams().setIntParameter(HttpClientParams.MAX_REDIRECTS, redirects); return this; } /** * Get the maximum number of redirects */ public int getMaximumRedirects() { return client.getParams().getIntParameter(HttpClientParams.MAX_REDIRECTS, DEFAULT_MAX_REDIRECTS); } /** * Clear all credentials (including proxy credentials) */ public AbderaClient clearCredentials() { client.getState().clearCredentials(); clearProxyCredentials(); return this; } /** * Clear proxy credentials */ public AbderaClient clearProxyCredentials() { client.getState().clearProxyCredentials(); return this; } /** * Clear all state (cookies, credentials, etc) */ public AbderaClient clearState() { client.getState().clear(); return this; } }
6,078
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/AbstractClientResponse.java
package org.apache.abdera.protocol.client; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Date; import javax.activation.MimeType; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.protocol.util.AbstractResponse; import org.apache.abdera.protocol.util.CacheControlUtil; import org.apache.abdera.util.EntityTag; import org.apache.commons.httpclient.util.DateParseException; import org.apache.commons.httpclient.util.DateUtil; /** * Abstract base class for a ClientResponse */ public abstract class AbstractClientResponse extends AbstractResponse implements ClientResponse { protected final Abdera abdera; protected final Parser parser; protected final Date now = new Date(); protected InputStream in = null; protected Date response_date = null; protected AbstractClientResponse(Abdera abdera) { this.abdera = abdera; this.parser = abdera.getParser(); } protected Date initResponseDate() { Date date = getDateHeader("Date"); return (date != null) ? date : now; } protected synchronized Parser getParser() { return parser; } /** * Get the response payload as a parsed Abdera FOM Document */ public <T extends Element> Document<T> getDocument() throws ParseException { return getDocument(getParser()); } /** * Get the response payload as a parsed Abdera FOM Document using the specified parser options * * @param options The parser options */ public <T extends Element> Document<T> getDocument(ParserOptions options) throws ParseException { return getDocument(getParser(), options); } /** * Get the response payload as a parsed Abdera FOM Document using the specified parser * * @param parser The parser */ public <T extends Element> Document<T> getDocument(Parser parser) throws ParseException { return getDocument(parser, parser.getDefaultParserOptions()); } /** * Get the response payload as a parsed Abdera FOM Document using the specified parser and parser options * * @param parser The parser * @param options The parser options */ public <T extends Element> Document<T> getDocument(Parser parser, ParserOptions options) throws ParseException { try { if (options == null) options = parser.getDefaultParserOptions(); String charset = getCharacterEncoding(); if (charset != null) options.setCharset(charset); IRI cl = getContentLocation(); if (cl != null && !cl.isAbsolute()) { IRI r = new IRI(getUri()); cl = r.resolve(cl); } String base = (cl != null) ? cl.toASCIIString() : getUri(); Document<T> doc = parser.parse(getReader(), base, options); EntityTag etag = getEntityTag(); if (etag != null) doc.setEntityTag(etag); Date lm = getLastModified(); if (lm != null) doc.setLastModified(lm); MimeType mt = getContentType(); if (mt != null) doc.setContentType(mt.toString()); String language = getContentLanguage(); if (language != null) doc.setLanguage(language); String slug = getSlug(); if (slug != null) doc.setSlug(slug); return doc; } catch (Exception e) { throw new ParseException(e); } } /** * Get the response payload as an input stream */ public InputStream getInputStream() throws IOException { return in; } /** * Set the response input stream (used internally by Abdera) */ public void setInputStream(InputStream in) { this.in = in; } /** * Get the response payload as a reader (assumed UTF-8 charset) */ public Reader getReader() throws IOException { String charset = getCharacterEncoding(); return getReader(charset != null ? charset : "UTF-8"); } /** * Get the response payload as a reader using the specified charset * * @param charset The character set encoding */ public Reader getReader(String charset) throws IOException { if (charset == null) charset = "UTF-8"; return new InputStreamReader(getInputStream(), charset); } /** * Return the date returned by the server in the response */ public Date getServerDate() { if (response_date == null) response_date = initResponseDate(); return response_date; } protected void parse_cc() { String cc = getHeader("Cache-Control"); if (cc != null) CacheControlUtil.parseCacheControl(cc, this); } /** * Get the character set encoding specified by the server in the Content-Type header */ public String getCharacterEncoding() { String charset = null; try { MimeType mt = getContentType(); if (mt != null) charset = mt.getParameter("charset"); } catch (Exception e) { } return charset; } /** * Return the named HTTP header as a java.util.Date */ public Date getDateHeader(String header) { try { String value = getHeader(header); if (value != null) return DateUtil.parseDate(value); else return null; } catch (DateParseException e) { return null; // treat other invalid date formats, especially including the value "0", as in the past } } }
2,391
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/ClientResponse.java
package org.apache.abdera.protocol.client; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Date; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.protocol.Response; public interface ClientResponse extends Response { /** * Return the request method */ String getMethod(); /** * Return the request URI. The request was redirected, this will return the new URI */ String getUri(); /** * Release the resources associated with this response */ void release(); /** * Returns the inputstream used to read data from this response */ InputStream getInputStream() throws IOException; /** * Returns a reader used to read data from this response. Will use the character set declared in the Content-Type to * create the reader */ Reader getReader() throws IOException; /** * Returns a reader used to read data from this response. Will use the character set specified to create the reader */ Reader getReader(String charset) throws IOException; void setInputStream(InputStream in); /** * If the response contains an XML document, parse the document */ <T extends Element> Document<T> getDocument() throws ParseException; /** * If the response contains an XML document, parse the document using the specified ParserOptions */ <T extends Element> Document<T> getDocument(ParserOptions options) throws ParseException; /** * If the response contains an XML document, parse the document using the specified Parser */ <T extends Element> Document<T> getDocument(Parser parser) throws ParseException; /** * If the response contains an XML document, parse the document using the specified Parser and ParserOptions */ <T extends Element> Document<T> getDocument(Parser parser, ParserOptions options) throws ParseException; /** * Return the server-specified date returned in the response */ Date getServerDate(); /** * Return the character set encoding specified in the ContentType header, if any */ String getCharacterEncoding(); }
4,076
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/CommonsResponse.java
package org.apache.abdera.protocol.client; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.text.io.CompressionUtil; import org.apache.abdera.protocol.client.util.AutoReleasingInputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.URIException; public class CommonsResponse extends AbstractClientResponse implements ClientResponse { private final HttpMethod method; protected CommonsResponse(Abdera abdera, HttpMethod method) { super(abdera); if (method.isRequestSent()) this.method = method; else throw new IllegalStateException(); parse_cc(); getServerDate(); } public HttpMethod getHttpMethod() { return method; } /** * Return the request method */ public String getMethod() { return method.getName(); } /** * Return the status code of the response */ public int getStatus() { return method.getStatusCode(); } /** * Return the status text of the response */ public String getStatusText() { return method.getStatusText(); } /** * Release the resources associated with this response */ public void release() { method.releaseConnection(); } /** * Return the value of the named HTTP header */ public String getHeader(String header) { Header h = method.getResponseHeader(header); return h != null ? h.getValue() : null; } /** * Return the values of the named HTTP header */ public Object[] getHeaders(String header) { Header[] headers = method.getResponseHeaders(header); List<Object> values = new ArrayList<Object>(); for (Header h : headers) { values.add(h.getValue()); } return values.toArray(new Object[values.size()]); } /** * Return all of the HTTP headers */ public Map<String, Object[]> getHeaders() { Header[] headers = method.getResponseHeaders(); Map<String, Object[]> map = new HashMap<String, Object[]>(); for (Header header : headers) { Object[] values = map.get(header.getName()); List<Object> list = values == null ? new ArrayList<Object>() : Arrays.asList(values); list.add(header.getValue()); map.put(header.getName(), list.toArray(new Object[list.size()])); } return java.util.Collections.unmodifiableMap(map); } /** * Return a listing of HTTP header names */ public String[] getHeaderNames() { Header[] headers = method.getResponseHeaders(); List<String> list = new ArrayList<String>(); for (Header h : headers) { String name = h.getName(); if (!list.contains(name)) list.add(name); } return list.toArray(new String[list.size()]); } /** * Return the request URI */ public String getUri() { try { return method.getURI().toString(); } catch (URIException e) { } return null; // shouldn't happen } /** * Return the inputstream for reading the content of the response. The InputStream returned will automatically * decode Content-Encodings and will automatically release the response when the stream has been read fully. */ public InputStream getInputStream() throws IOException { if (in == null ) { String ce = getHeader("Content-Encoding"); in = method.getResponseBodyAsStream(); if (ce != null && in != null) { in = CompressionUtil.getDecodingInputStream(in, ce); } in = new AutoReleasingInputStream(method, in); } return in; } }
17,894
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/RequestOptions.java
package org.apache.abdera.protocol.client; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.activation.MimeType; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.i18n.text.Localizer; import org.apache.abdera.i18n.text.Rfc2047Helper; import org.apache.abdera.i18n.text.UrlEncoding; import org.apache.abdera.i18n.text.CharUtils.Profile; import org.apache.abdera.protocol.Request; import org.apache.abdera.protocol.util.AbstractRequest; import org.apache.abdera.protocol.util.CacheControlUtil; import org.apache.abdera.util.EntityTag; import org.apache.commons.httpclient.util.DateParseException; import org.apache.commons.httpclient.util.DateUtil; /** * The RequestOptions class allows a variety of options affecting the execution of the request to be modified. */ public class RequestOptions extends AbstractRequest implements Request { private boolean noLocalCache = false; private boolean revalidateAuth = false; private boolean useChunked = false; private boolean usePostOverride = false; private boolean requestException4xx = false; private boolean requestException5xx = false; private boolean useExpectContinue = true; private boolean useConditional = true; private boolean followRedirects = true; private final Map<String, String[]> headers = new HashMap<String, String[]>(); public RequestOptions() { } /** * Create the RequestOptions object with the specified If-Modified-Since header value * * @param ifModifiedSince */ public RequestOptions(Date ifModifiedSince) { this(); setIfModifiedSince(ifModifiedSince); } /** * Create the RequestOptions object with the specified If-None-Match header value * * @param IfNoneMatch */ public RequestOptions(String ifNoneMatch) { this(); setIfNoneMatch(ifNoneMatch); } /** * Create the RequestOptions object with the specified If-None-Match header value * * @param IfNoneMatch */ public RequestOptions(String... ifNoneMatch) { this(); setIfNoneMatch(ifNoneMatch); } /** * Create the RequestOptions object with the specified If-Modified-Since and If-None-Match header values * * @param ifModifiedSince * @param IfNoneMatch */ public RequestOptions(Date ifModifiedSince, String ifNoneMatch) { this(); setIfModifiedSince(ifModifiedSince); setIfNoneMatch(ifNoneMatch); } /** * Create the RequestOptions object with the specified If-Modified-Since and If-None-Match header values * * @param ifModifiedSince * @param IfNoneMatch */ public RequestOptions(Date ifModifiedSince, String... ifNoneMatch) { this(); setIfModifiedSince(ifModifiedSince); setIfNoneMatch(ifNoneMatch); } /** * Create the RequestOptions object * * @param no_cache True if the request will indicate that cached responses should not be returned */ public RequestOptions(boolean no_cache) { this(); setNoCache(no_cache); } private Map<String, String[]> getHeaders() { return headers; } private String combine(String... values) { StringBuilder v = new StringBuilder(); for (String val : values) { if (v.length() > 0) v.append(", "); v.append(val); } return v.toString(); } /** * The difference between this and getNoCache is that this only disables the local cache without affecting the * Cache-Control header. */ public boolean getUseLocalCache() { return !noLocalCache; } /** * True if the local client cache should be used */ public RequestOptions setUseLocalCache(boolean use_cache) { this.noLocalCache = !use_cache; return this; } /** * Set the value of the HTTP Content-Type header */ public RequestOptions setContentType(String value) { return setHeader("Content-Type", value); } public RequestOptions setContentLocation(String iri) { return setHeader("Content-Location", iri); } /** * Set the value of the HTTP Content-Type header */ public RequestOptions setContentType(MimeType value) { return setHeader("Content-Type", value.toString()); } /** * Set the value of the HTTP Authorization header */ public RequestOptions setAuthorization(String auth) { return setHeader("Authorization", auth); } /** * Set the value of a header using proper encoding of non-ascii characters */ public RequestOptions setEncodedHeader(String header, String charset, String value) { return setHeader(header, Rfc2047Helper.encode(value, charset)); } /** * Set the values of a header using proper encoding of non-ascii characters */ public RequestOptions setEncodedHeader(String header, String charset, String... values) { if (values != null && values.length > 0) { for (int n = 0; n < values.length; n++) { values[n] = Rfc2047Helper.encode(values[n], charset); } getHeaders().put(header, new String[] {combine(values)}); } else { removeHeaders(header); } return this; } /** * Set the value of the specified HTTP header */ public RequestOptions setHeader(String header, String value) { return value != null ? setHeader(header, new String[] {value}) : removeHeaders(header); } /** * Set the value of the specified HTTP header */ public RequestOptions setHeader(String header, String... values) { if (values != null && values.length > 0) { getHeaders().put(header, new String[] {combine(values)}); } else { removeHeaders(header); } return this; } /** * Set the date value of the specified HTTP header */ public RequestOptions setDateHeader(String header, Date value) { return value != null ? setHeader(header, DateUtil.formatDate(value)) : removeHeaders(header); } /** * Similar to setEncodedHeader, but allows for multiple instances of the specified header */ public RequestOptions addEncodedHeader(String header, String charset, String value) { return addHeader(header, Rfc2047Helper.encode(value, charset)); } /** * Similar to setEncodedHeader, but allows for multiple instances of the specified header */ public RequestOptions addEncodedHeader(String header, String charset, String... values) { if (values == null || values.length == 0) return this; for (int n = 0; n < values.length; n++) { values[n] = Rfc2047Helper.encode(values[n], charset); } List<String> list = Arrays.asList(getHeaders().get(header)); String value = combine(values); if (list != null) { if (!list.contains(value)) list.add(value); } else { setHeader(header, new String[] {value}); } return this; } /** * Similar to setHeader but allows for multiple instances of the specified header */ public RequestOptions addHeader(String header, String value) { if (value != null) addHeader(header, new String[] {value}); return this; } /** * Similar to setHeader but allows for multiple instances of the specified header */ public RequestOptions addHeader(String header, String... values) { if (values == null || values.length == 0) return this; String[] headers = getHeaders().get(header); List<String> list = headers != null ? Arrays.asList(headers) : new ArrayList<String>(); String value = combine(values); if (list != null) { if (!list.contains(value)) list.add(value); } else { setHeader(header, new String[] {value}); } return this; } /** * Similar to setDateHeader but allows for multiple instances of the specified header */ public RequestOptions addDateHeader(String header, Date value) { if (value == null) return this; return addHeader(header, DateUtil.formatDate(value)); } /** * Returns the text value of the specified header */ public String getHeader(String header) { String[] list = getHeaders().get(header); return (list != null && list.length > 0) ? list[0] : null; } /** * Return a listing of text values for the specified header */ public String[] getHeaders(String header) { return getHeaders().get(header); } /** * Returns the date value of the specified header */ public Date getDateHeader(String header) { String val = getHeader(header); try { return (val != null) ? DateUtil.parseDate(val) : null; } catch (DateParseException e) { throw new RuntimeException(e); } } /** * Returns a listing of header names */ public String[] getHeaderNames() { Set<String> names = getHeaders().keySet(); return names.toArray(new String[names.size()]); } /** * Sets the value of the HTTP If-Match header */ public RequestOptions setIfMatch(String entity_tag) { return setIfMatch(new EntityTag(entity_tag)); } /** * Sets the value of the HTTP If-Match header */ public RequestOptions setIfMatch(EntityTag entity_tag) { return setHeader("If-Match", entity_tag.toString()); } /** * Sets the value of the HTTP If-Match header */ public RequestOptions setIfMatch(EntityTag... entity_tags) { return setHeader("If-Match", EntityTag.toString(entity_tags)); } /** * Sets the value of the HTTP If-Match header */ public RequestOptions setIfMatch(String... entity_tags) { return setHeader("If-Match", EntityTag.toString(entity_tags)); } /** * Sets the value of the HTTP If-None-Match header */ public RequestOptions setIfNoneMatch(String entity_tag) { return setIfNoneMatch(new EntityTag(entity_tag)); } /** * Sets the value of the HTTP If-None-Match header */ public RequestOptions setIfNoneMatch(EntityTag entity_tag) { return setHeader("If-None-Match", entity_tag.toString()); } /** * Sets the value of the HTTP If-None-Match header */ public RequestOptions setIfNoneMatch(EntityTag... entity_tags) { return setHeader("If-None-Match", EntityTag.toString(entity_tags)); } /** * Sets the value of the HTTP If-None-Match header */ public RequestOptions setIfNoneMatch(String... entity_tags) { return setHeader("If-None-Match", EntityTag.toString(entity_tags)); } /** * Sets the value of the HTTP If-Modified-Since header */ public RequestOptions setIfModifiedSince(Date date) { return setDateHeader("If-Modified-Since", date); } /** * Sets the value of the HTTP If-Unmodified-Since header */ public RequestOptions setIfUnmodifiedSince(Date date) { return setDateHeader("If-Unmodified-Since", date); } /** * Sets the value of the HTTP Accept header */ public RequestOptions setAccept(String accept) { return setAccept(new String[] {accept}); } /** * Sets the value of the HTTP Accept header */ public RequestOptions setAccept(String... accept) { return setHeader("Accept", combine(accept)); } public RequestOptions setAcceptLanguage(Locale locale) { return setAcceptLanguage(Lang.fromLocale(locale)); } public RequestOptions setAcceptLanguage(Locale... locales) { String[] langs = new String[locales.length]; for (int n = 0; n < locales.length; n++) langs[n] = Lang.fromLocale(locales[n]); setAcceptLanguage(langs); return this; } /** * Sets the value of the HTTP Accept-Language header */ public RequestOptions setAcceptLanguage(String accept) { return setAcceptLanguage(new String[] {accept}); } /** * Sets the value of the HTTP Accept-Language header */ public RequestOptions setAcceptLanguage(String... accept) { return setHeader("Accept-Language", combine(accept)); } /** * Sets the value of the HTTP Accept-Charset header */ public RequestOptions setAcceptCharset(String accept) { return setAcceptCharset(new String[] {accept}); } /** * Sets the value of the HTTP Accept-Charset header */ public RequestOptions setAcceptCharset(String... accept) { return setHeader("Accept-Charset", combine(accept)); } /** * Sets the value of the HTTP Accept-Encoding header */ public RequestOptions setAcceptEncoding(String accept) { return setAcceptEncoding(new String[] {accept}); } /** * Sets the value of the HTTP Accept-Encoding header */ public RequestOptions setAcceptEncoding(String... accept) { return setHeader("Accept-Encoding", combine(accept)); } /** * Sets the value of the Atom Publishing Protocol Slug header */ public RequestOptions setSlug(String slug) { if (slug.indexOf((char)10) > -1 || slug.indexOf((char)13) > -1) throw new IllegalArgumentException(Localizer.get("SLUG.BAD.CHARACTERS")); return setHeader("Slug", UrlEncoding.encode(slug, Profile.ASCIISANSCRLF.filter())); } /** * Sets the value of the HTTP Cache-Control header */ public RequestOptions setCacheControl(String cc) { CacheControlUtil.parseCacheControl(cc, this); return this; } /** * Remove the specified HTTP header */ public RequestOptions removeHeaders(String name) { getHeaders().remove(name); return this; } /** * Return the value of the Cache-Control header */ public String getCacheControl() { return CacheControlUtil.buildCacheControl(this); } /** * Configure the AbderaClient Side cache to revalidate when using Authorization */ public boolean getRevalidateWithAuth() { return revalidateAuth; } /** * Configure the AbderaClient Side cache to revalidate when using Authorization */ public RequestOptions setRevalidateWithAuth(boolean revalidateAuth) { this.revalidateAuth = revalidateAuth; return this; } /** * Should the request use chunked encoding? */ public boolean isUseChunked() { return useChunked; } /** * Set whether the request should use chunked encoding. */ public RequestOptions setUseChunked(boolean useChunked) { this.useChunked = useChunked; return this; } /** * Set whether the request should use the X-HTTP-Method-Override option */ public RequestOptions setUsePostOverride(boolean useOverride) { this.usePostOverride = useOverride; return this; } /** * Return whether the request should use the X-HTTP-Method-Override option */ public boolean isUsePostOverride() { return this.usePostOverride; } /** * Set whether or not to throw a RequestExeption on 4xx responses */ public RequestOptions set4xxRequestException(boolean v) { this.requestException4xx = v; return this; } /** * Return true if a RequestException should be thrown on 4xx responses */ public boolean is4xxRequestException() { return this.requestException4xx; } /** * Set whether or not to throw a RequestExeption on 5xx responses */ public RequestOptions set5xxRequestException(boolean v) { this.requestException5xx = v; return this; } /** * Return true if a RequestException should be thrown on 5xx responses */ public boolean is5xxRequestException() { return this.requestException5xx; } /** * Set whether or not to use the HTTP Expect-Continue mechanism (enabled by default) */ public RequestOptions setUseExpectContinue(boolean useExpect) { this.useExpectContinue = useExpect; return this; } /** * Return true if Expect-Continue should be used */ public boolean isUseExpectContinue() { return this.useExpectContinue; } /** * True if HTTP Conditional Requests should be used automatically. This only has an effect when putting a Document * that has an ETag or Last-Modified date present */ public boolean isConditionalPut() { return this.useConditional; } /** * True if HTTP Conditinal Request should be used automatically. This only has an effect when putting a Document * that has an ETag or Last-Modified date present */ public RequestOptions setConditionalPut(boolean conditional) { this.useConditional = conditional; return this; } /** * True if the client should follow redirects automatically */ public boolean isFollowRedirects() { return followRedirects; } /** * True if the client should follow redirects automatically */ public RequestOptions setFollowRedirects(boolean followredirects) { this.followRedirects = followredirects; return this; } }
4,589
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/AbstractCache.java
package org.apache.abdera.protocol.client.cache; import java.io.IOException; import org.apache.abdera.Abdera; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.client.RequestOptions; import org.apache.abdera.protocol.util.CacheControlUtil; public abstract class AbstractCache implements Cache { protected final Abdera abdera; protected AbstractCache(Abdera abdera) { this.abdera = abdera; } public Disposition disposition(Object key, RequestOptions options) { CachedResponse response = get(key); if (response != null && options != null) { if (options.isNoCache()) return Disposition.TRANSPARENT; else if (response.isNoCache()) return Disposition.STALE; else if (options != null && options.isOnlyIfCached()) return Disposition.FRESH; else if (response.isMustRevalidate()) return Disposition.STALE; else if (response.getCachedTime() != -1) { if (response.isFresh()) { long maxAge = options.getMaxAge(); long currentAge = response.getCurrentAge(); long minFresh = options.getMinFresh(); if (maxAge != -1) return (maxAge > currentAge) ? Disposition.FRESH : Disposition.STALE; if (minFresh != -1) return response.getFreshnessLifetime() < currentAge + minFresh ? Disposition.TRANSPARENT : Disposition.FRESH; return Disposition.FRESH; } else { long maxStale = options.getMaxStale(); if (maxStale != -1) return maxStale < response.getHowStale() ? Disposition.STALE : Disposition.FRESH; return Disposition.STALE; } } } return Disposition.TRANSPARENT; } protected abstract void add(Object key, CachedResponse response); protected abstract CachedResponse createCachedResponse(ClientResponse response, Object key) throws IOException; private boolean shouldUpdateCache(ClientResponse response, boolean allowedByDefault) { if (allowedByDefault) { return !response.isNoCache() && !response.isNoStore() && response.getMaxAge() != 0; } else { return response.getExpires() != null || response.getMaxAge() > 0 || response.isMustRevalidate() || response.isPublic() || response.isPrivate(); } } public ClientResponse update(Object key, RequestOptions options, ClientResponse response, ClientResponse cached_response) { int status = response.getStatus(); String uri = response.getUri(); String method = response.getMethod(); // if the method changes state on the server, don't cache and // clear what we already have if (!CacheControlUtil.isIdempotent(method)) { remove(uri); return response; } // otherwise, base the decision on the response status code switch (status) { case 200: case 203: case 300: case 301: case 410: // rfc2616 says these are cacheable unless otherwise noted if (shouldUpdateCache(response, true)) return update(key, options, response); else remove(uri); break; case 304: case 412: // if not revalidated, fall through if (cached_response != null) return cached_response; default: // rfc2616 says are *not* cacheable unless otherwise noted if (shouldUpdateCache(response, false)) return update(key, options, response); else remove(uri); break; } return response; } private ClientResponse update(Object key, RequestOptions options, ClientResponse response) { try { CachedResponse cachedResponse = createCachedResponse(response, key); add(key, cachedResponse); return cachedResponse; } catch (IOException e) { throw new RuntimeException(e); } } }
852
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/Cache.java
package org.apache.abdera.protocol.client.cache; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.client.RequestOptions; public interface Cache extends Iterable<Object> { public static enum Disposition { STALE, FRESH, TRANSPARENT } /** * Get the disposition of a specific item */ Disposition disposition(Object key, RequestOptions options); /** * Get a specific item from the cache */ CachedResponse get(Object key); /** * Clear all items from the cache */ Cache clear(); /** * Remove a specific item from the cache */ Cache remove(Object key); /** * Update the cached item */ ClientResponse update(Object key, RequestOptions options, ClientResponse response, ClientResponse cached_response); }
193
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/CacheFactory.java
package org.apache.abdera.protocol.client.cache; import org.apache.abdera.Abdera; /** * @deprecated No longer used */ public interface CacheFactory { Cache getCache(Abdera abdera); }
405
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/CachedResponse.java
package org.apache.abdera.protocol.client.cache; import org.apache.abdera.protocol.client.ClientResponse; public interface CachedResponse extends ClientResponse { Object getKey(); Cache getCache(); long getCachedTime(); long getInitialAge(); long getResidentAge(); long getCurrentAge(); long getFreshnessLifetime(); long getHowStale(); boolean isFresh(); }
2,483
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/CachedResponseBase.java
package org.apache.abdera.protocol.client.cache; import java.util.Date; import org.apache.abdera.Abdera; import org.apache.abdera.protocol.client.AbstractClientResponse; public abstract class CachedResponseBase extends AbstractClientResponse implements CachedResponse { protected final Object key; protected final Cache cache; protected long initial_age; protected CachedResponseBase(Abdera abdera, Object key, Cache cache) { super(abdera); this.key = key; this.cache = cache; } private long calcInitialAge() { long age_value = getAge(); long now = (new Date()).getTime(); long cachedTime = getCachedTime(); long date_value = (cachedTime != -1) ? cachedTime : 0; long apparent_age = Math.max(0, now - date_value); long corrected_received_age = Math.max(apparent_age, age_value); return corrected_received_age / 1000; } public Object getKey() { return key; } public Cache getCache() { return cache; } public void release() { if (cache != null) { cache.remove(key); } } public long getInitialAge() { if (initial_age == -1) initial_age = calcInitialAge(); return initial_age; } public long getCachedTime() { return getServerDate().getTime(); } public long getResidentAge() { long now = (new Date()).getTime(); long init = getCachedTime(); return Math.max(0, (now - init)) / 1000; } public long getCurrentAge() { return getInitialAge() + getResidentAge(); } public long getFreshnessLifetime() { long lifetime = getMaxAge(); if (lifetime == -1) { Date expires_date = getExpires(); long expires = (expires_date != null) ? expires_date.getTime() : -1; long cachedTime = getCachedTime(); if (expires != -1) { lifetime = (expires > cachedTime) ? (expires - cachedTime) / 1000 : 0; } // else, expires is not set, return -1 for now. TODO: apply heuristics } return lifetime; } public long getHowStale() { return (!isFresh()) ? getCurrentAge() - getFreshnessLifetime() : 0; } public boolean isFresh() { long lifetime = getFreshnessLifetime(); long currentage = getCurrentAge(); return (lifetime != -1) ? lifetime > currentage : true; } }
1,128
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/InMemoryCache.java
package org.apache.abdera.protocol.client.cache; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.apache.abdera.Abdera; import org.apache.abdera.protocol.client.ClientResponse; public abstract class InMemoryCache extends AbstractCache { protected transient final Map<Object, CachedResponse> cache; protected InMemoryCache(Abdera abdera, Map<Object, CachedResponse> map) { super(abdera); this.cache = map; } @Override protected CachedResponse createCachedResponse(ClientResponse response, Object key) throws IOException { return new InMemoryCachedResponse(abdera, this, key, response); } public Cache clear() { cache.clear(); return this; } public CachedResponse get(Object key) { return cache.get(key); } public Cache remove(Object key) { cache.remove(key); return this; } protected void add(Object key, CachedResponse response) { cache.put(key, response); } public Iterator<Object> iterator() { return cache.keySet().iterator(); } }
2,839
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/InMemoryCachedResponse.java
package org.apache.abdera.protocol.client.cache; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.apache.abdera.Abdera; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.client.util.MethodHelper; import org.apache.abdera.protocol.util.CacheControlUtil; public class InMemoryCachedResponse extends CachedResponseBase implements CachedResponse { private final String method; private final int status; private final String status_text; private final String uri; private final Map<String, Object[]> headers; private final byte[] buf; public InMemoryCachedResponse(Abdera abdera, Cache cache, Object key, ClientResponse response) throws IOException { super(abdera, key, cache); this.method = response.getMethod(); this.status = response.getStatus(); this.status_text = response.getStatusText(); this.uri = response.getUri(); this.headers = MethodHelper.getCacheableHeaders(response); CacheControlUtil.parseCacheControl(this.getHeader("Cache-Control"), this); buf = cacheStream(response.getInputStream()); response.setInputStream(getInputStream()); } /** * This is terribly inefficient, but it is an in-memory cache that is being used by parsers that incrementally * consume InputStreams at different rates. There's really no other way to do it. */ private byte[] cacheStream(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] buf = new byte[1024]; int m = -1; while ((m = in.read(buf)) != -1) { out.write(buf, 0, m); } return out.toByteArray(); } public Map<String, Object[]> getHeaders() { return headers; } public String getMethod() { return method; } public String getHeader(String header) { Object[] values = getHeaders().get(header); return (values != null && values.length > 0) ? (String)values[0] : null; } public String[] getHeaderNames() { return getHeaders().keySet().toArray(new String[getHeaders().size()]); } public Object[] getHeaders(String header) { return getHeaders().get(header); } public int getStatus() { return status; } public String getStatusText() { return status_text; } public String getUri() { return uri; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(this.buf); } @Override public void setInputStream(InputStream in) { throw new UnsupportedOperationException(); } }
411
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/LRUCache.java
package org.apache.abdera.protocol.client.cache; import org.apache.abdera.Abdera; public class LRUCache extends InMemoryCache implements Cache { private final static int DEFAULT_SIZE = 10; public LRUCache(Abdera abdera) { this(abdera, DEFAULT_SIZE); } public LRUCache(Abdera abdera, final int size) { super(abdera, new LRUMap<Object, CachedResponse>(size, 0.75f)); } }
356
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/LRUCacheFactory.java
package org.apache.abdera.protocol.client.cache; import org.apache.abdera.Abdera; /** * @deprecated No longer used */ public class LRUCacheFactory implements CacheFactory { public LRUCacheFactory(Abdera abdera) { } public LRUCacheFactory() { } public Cache getCache(Abdera abdera) { return new LRUCache(abdera); } }
515
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/LRUMap.java
package org.apache.abdera.protocol.client.cache; import java.util.LinkedHashMap; import java.util.Map; public final class LRUMap<A, B> extends LinkedHashMap<A, B> { private static final long serialVersionUID = -8243948270889739367L; private final int size; public LRUMap(int initialSize, float loadFactor) { super(initialSize, loadFactor, true); this.size = initialSize; } protected boolean removeEldestEntry(Map.Entry<A, B> eldest) { return size() > size; } }
1,293
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/AutoReleasingInputStream.java
package org.apache.abdera.protocol.client.util; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.HttpMethod; public final class AutoReleasingInputStream extends FilterInputStream { private final HttpMethod method; public AutoReleasingInputStream(HttpMethod method, InputStream in) { super(in); this.method = method; } @Override public int read() throws IOException { if (this.in == null) return -1; try { int r = super.read(); if (r == -1) { method.releaseConnection(); } return r; } catch (IOException e) { if (method != null) method.releaseConnection(); throw e; } } @Override public int read(byte[] b, int off, int len) throws IOException { if (this.in == null) return -1; try { int r = super.read(b, off, len); if (r == -1) { method.releaseConnection(); } return r; } catch (IOException e) { if (method != null) method.releaseConnection(); throw e; } } }
2,156
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/BaseRequestEntity.java
package org.apache.abdera.protocol.client.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.abdera.model.Base; import org.apache.abdera.util.MimeTypeHelper; import org.apache.commons.httpclient.methods.RequestEntity; /** * Required for the Apache Commons HTTP AbderaClient. */ public class BaseRequestEntity implements RequestEntity { private final Base base; private byte[] buf = null; private boolean use_chunked = true; public BaseRequestEntity(Base base) { this.base = base; } public BaseRequestEntity(Base base, boolean use_chunked) { this(base); this.use_chunked = use_chunked; } public boolean isRepeatable() { return true; } public void writeRequest(OutputStream out) throws IOException { if (use_chunked) base.writeTo(out); else { // if we're not using chunked requests, the getContentLength method // has likely already been called and we want to just go ahead and // use the buffered output rather than reserialize if (buf == null) getContentLength(); // ensures that the content is buffered out.write(buf); out.flush(); } } public long getContentLength() { if (use_chunked) return -1; // chunk the response else { // this is ugly, but some proxies and server configurations (e.g. gdata) // require that requests contain the Content-Length header. The only // way to get that is to serialize the document into a byte array, which // we buffer into memory. if (buf == null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); base.writeTo(out); buf = out.toByteArray(); } catch (Exception e) { } } return buf.length; } } public String getContentType() { return MimeTypeHelper.getMimeType(base); } }
4,203
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/ClientAuthSSLProtocolSocketFactory.java
package org.apache.abdera.protocol.client.util; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import org.apache.abdera.i18n.text.Localizer; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; public class ClientAuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory { private static final String DEFAULT_PROTOCOL = "TLS"; private static final String DEFAULT_KMF_FACTORY = "ibmX509"; private final String protocol; private final String kmfFactory; private final TrustManager tm; private final String keyStorePass; private final KeyStore ks; public ClientAuthSSLProtocolSocketFactory(KeyStore ks, String keyStorePass) { this(ks, keyStorePass, DEFAULT_PROTOCOL, DEFAULT_KMF_FACTORY, null); } public ClientAuthSSLProtocolSocketFactory(KeyStore ks, String keyStorePass, String protocol, String kmfFactory, TrustManager tm) { if (ks == null) throw new IllegalArgumentException(Localizer.get("INVALID.KEYSTORE")); this.ks = ks; this.keyStorePass = keyStorePass; this.protocol = protocol != null ? protocol : DEFAULT_PROTOCOL; this.kmfFactory = kmfFactory != null ? kmfFactory : DEFAULT_KMF_FACTORY; this.tm = tm; } public ClientAuthSSLProtocolSocketFactory(String keyStore, String keyStoreType, String keyStorePass, String protocol, String kmfFactory, TrustManager tm) { this(initKeyStore(keyStore, keyStoreType, keyStorePass), keyStorePass, protocol, kmfFactory, tm); } private static KeyStore initKeyStore(String keyStore, String keyStoreType, String keyPass) { KeyStore ks = null; try { ks = KeyStore.getInstance(keyStoreType); ks.load(new FileInputStream(keyStore), keyPass.toCharArray()); } catch (Exception e) { } return ks; } public Socket createSocket(Socket socket, String host, int port, boolean close) throws IOException, UnknownHostException { return createSocket(host, port, null, 0, null); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return createSocket(host, port, null, 0, null); } public Socket createSocket(String host, int port, InetAddress chost, int cport) throws IOException, UnknownHostException { return createSocket(host, port, chost, cport, null); } public Socket createSocket(String host, int port, InetAddress chost, int cport, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { SSLContext context; SSLSocketFactory factory = null; SSLSocket socket = null; try { KeyManagerFactory kmf; context = SSLContext.getInstance(protocol); kmf = KeyManagerFactory.getInstance(kmfFactory); TrustManager tm = (this.tm != null) ? this.tm : new NonOpTrustManager(); kmf.init(ks, keyStorePass.toCharArray()); context.init(kmf.getKeyManagers(), new TrustManager[] {tm}, null); factory = context.getSocketFactory(); socket = (SSLSocket)factory.createSocket(host, port); return socket; } catch (Exception e) { throw new RuntimeException(e); } } }
1,118
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/DataSourceRequestEntity.java
package org.apache.abdera.protocol.client.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.activation.DataHandler; import javax.activation.DataSource; import org.apache.commons.httpclient.methods.RequestEntity; public class DataSourceRequestEntity implements RequestEntity { private final DataSource dataSource; public DataSourceRequestEntity(DataHandler dataHandler) { this(dataHandler.getDataSource()); } public DataSourceRequestEntity(DataSource dataSource) { this.dataSource = dataSource; } public long getContentLength() { return -1; } public String getContentType() { return dataSource.getContentType(); } public boolean isRepeatable() { return true; } public void writeRequest(OutputStream out) throws IOException { InputStream in = dataSource.getInputStream(); byte[] buf = new byte[1024]; int n = -1; while ((n = in.read(buf, 0, 1024)) != -1) { out.write(buf, 0, n); out.flush(); } } }
2,721
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/EntityProviderRequestEntity.java
package org.apache.abdera.protocol.client.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.abdera.Abdera; import org.apache.abdera.protocol.EntityProvider; import org.apache.commons.httpclient.methods.RequestEntity; public class EntityProviderRequestEntity implements RequestEntity { private final Abdera abdera; private final EntityProvider provider; private byte[] buf = null; private boolean use_chunked = true; private boolean auto_indent = false; private String encoding = "UTF-8"; public EntityProviderRequestEntity(Abdera abdera, EntityProvider provider, boolean use_chunked) { this.abdera = abdera; this.use_chunked = use_chunked; this.provider = provider; } private void write(OutputStream out) { provider.writeTo(abdera.newStreamWriter().setOutputStream(out, encoding).setAutoIndent(auto_indent)); } public long getContentLength() { if (use_chunked) return -1; // chunk the response else { // this is ugly, but some proxies and server configurations (e.g. gdata) // require that requests contain the Content-Length header. The only // way to get that is to serialize the document into a byte array, which // we buffer into memory. if (buf == null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); write(out); buf = out.toByteArray(); } catch (Exception e) { } } return buf.length; } } public String getContentType() { return provider.getContentType(); } public boolean isRepeatable() { return provider.isRepeatable(); } public void writeRequest(OutputStream out) throws IOException { if (use_chunked) write(out); else { // if we're not using chunked requests, the getContentLength method // has likely already been called and we want to just go ahead and // use the buffered output rather than reserialize if (buf == null) getContentLength(); // ensures that the content is buffered out.write(buf); out.flush(); } } public boolean isAutoIndent() { return auto_indent; } public void setAutoIndent(boolean auto_indent) { this.auto_indent = auto_indent; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } }
4,384
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/LocalizationHelper.java
package org.apache.abdera.protocol.client.util; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.i18n.rfc4646.Range; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Link; import org.apache.abdera.model.Source; public final class LocalizationHelper { private LocalizationHelper() { } public static Link[] selectAlternate(Source source) { return selectAlternate(source, Locale.getDefault()); } public static Link[] selectAlternate(Entry entry) { return selectAlternate(entry, Locale.getDefault()); } public static Link[] selectAlternate(Source source, Locale locale) { return selectAlternate(source, new Range(Lang.fromLocale(locale), true)); } public static Link[] selectAlternate(Entry entry, Locale locale) { return selectAlternate(entry, new Range(Lang.fromLocale(locale), true)); } public static Link[] selectAlternate(Entry entry, Locale... locales) { Range[] ranges = new Range[locales.length]; for (int n = 0; n < locales.length; n++) ranges[n] = new Range(Lang.fromLocale(locales[n]), true); return selectAlternate(entry, ranges); } public static Link[] selectAlternate(Entry entry, Range range) { return selectAlternate(entry, new Range[] {range}); } public static Link[] selectAlternate(Entry entry, Range... ranges) { return selectAlternate(entry.getLinks("alternate"), ranges); } public static Link[] selectAlternate(Entry entry, String range) { return selectAlternate(entry, new String[] {range}); } public static Link[] selectAlternate(Entry entry, String... ranges) { Range[] r = new Range[ranges.length]; for (int n = 0; n < ranges.length; n++) r[n] = new Range(ranges[n], true); return selectAlternate(entry, r); } public static Link[] selectAlternate(Source source, Locale... locales) { Range[] ranges = new Range[locales.length]; for (int n = 0; n < locales.length; n++) ranges[n] = new Range(Lang.fromLocale(locales[n]), true); return selectAlternate(source, ranges); } public static Link[] selectAlternate(Source source, Range range) { return selectAlternate(source, new Range[] {range}); } public static Link[] selectAlternate(Source source, Range... ranges) { return selectAlternate(source.getLinks("alternate"), ranges); } public static Link[] selectAlternate(Source source, String range) { return selectAlternate(source, new String[] {range}); } public static Link[] selectAlternate(Source source, String... ranges) { Range[] r = new Range[ranges.length]; for (int n = 0; n < ranges.length; n++) r[n] = new Range(ranges[n], true); return selectAlternate(source, r); } public static Link[] selectAlternate(List<Link> links, String range) { return selectAlternate(links, new Range(range, true)); } public static Link[] selectAlternate(List<Link> links, Range range) { return selectAlternate(links, new Range[] {range}); } public static Link[] selectAlternate(List<Link> links, Range... ranges) { List<Link> matching = new ArrayList<Link>(); for (Range range : ranges) { for (Link link : links) { String hreflang = link.getHrefLang(); if (hreflang != null) { Lang lang = new Lang(hreflang); Range basic = range.toBasicRange(); Lang blang = !basic.toString().equals("*") ? new Lang(basic.toString()) : null; if (range.matches(lang) || (blang != null && lang.isParentOf(blang))) matching.add(link); } } Collections.sort(matching, new Comparator<Link>() { public int compare(Link o1, Link o2) { Lang l1 = new Lang(o1.getHrefLang()); Lang l2 = new Lang(o2.getHrefLang()); return l1.compareTo(l2); } }); } return matching.toArray(new Link[matching.size()]); } }
7,099
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/MethodHelper.java
package org.apache.abdera.protocol.client.util; import java.util.HashMap; import java.util.Map; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.client.RequestOptions; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.EntityEnclosingMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.OptionsMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.TraceMethod; import org.apache.commons.httpclient.params.HttpMethodParams; public class MethodHelper { public static enum HopByHop { Connection, KeepAlive, ProxyAuthenticate, ProxyAuthorization, TE, Trailers, TransferEncoding, Upgrade; } public static enum Method { GET, POST, PUT, DELETE, OPTIONS, TRACE, HEAD, OTHER; public static Method fromString(String method) { try { return Method.valueOf(method.toUpperCase()); } catch (Exception e) { return OTHER; } } } public static Map<String, Object[]> getCacheableHeaders(ClientResponse response) { Map<String, Object[]> map = new HashMap<String, Object[]>(); String[] headers = response.getHeaderNames(); for (String header : headers) { if (MethodHelper.isCacheableHeader(header, response)) { Object[] list = response.getHeaders(header); map.put(header, list); } } return map; } public static boolean isCacheableHeader(String header, ClientResponse response) { return !isNoCacheOrPrivate(header, response) && !isHopByHop(header); } public static boolean isNoCacheOrPrivate(String header, ClientResponse response) { String[] no_cache_headers = response.getNoCacheHeaders(); String[] private_headers = response.getPrivateHeaders(); return contains(no_cache_headers, header) || contains(private_headers, header); } private static boolean contains(String[] headers, String header) { if (headers != null) { for (String h : headers) { if (h.equals(header)) return true; } } return false; } /** * We don't cache hop-by-hop headers TODO: There may actually be other hop-by-hop headers we need to filter out. * They'll be listed in the Connection header. see Section 14.10 of RFC2616 (last paragraph) */ public static boolean isHopByHop(String header) { try { HopByHop.valueOf(header.replaceAll("-", "")); return true; } catch (Exception e) { return false; } } private static EntityEnclosingMethod getMethod(EntityEnclosingMethod method, RequestEntity entity) { if (entity != null) method.setRequestEntity(entity); return method; } public static HttpMethod createMethod(String method, String uri, RequestEntity entity, RequestOptions options) { if (method == null) return null; Method m = Method.fromString(method); Method actual = null; HttpMethod httpMethod = null; if (options.isUsePostOverride()) { if (m.equals(Method.PUT)) { actual = m; } else if (m.equals(Method.DELETE)) { actual = m; } if (actual != null) m = Method.POST; } switch (m) { case GET: httpMethod = new GetMethod(uri); break; case POST: httpMethod = getMethod(new PostMethod(uri), entity); break; case PUT: httpMethod = getMethod(new PutMethod(uri), entity); break; case DELETE: httpMethod = new DeleteMethod(uri); break; case HEAD: httpMethod = new HeadMethod(uri); break; case OPTIONS: httpMethod = new OptionsMethod(uri); break; case TRACE: httpMethod = new TraceMethod(uri); break; default: httpMethod = getMethod(new ExtensionMethod(method, uri), entity); } if (actual != null) { httpMethod.addRequestHeader("X-HTTP-Method-Override", actual.name()); } initHeaders(options, httpMethod); // by default use expect-continue is enabled on the client // only disable if explicitly disabled if (!options.isUseExpectContinue()) httpMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); // should we follow redirects, default is true if (!(httpMethod instanceof EntityEnclosingMethod)) httpMethod.setFollowRedirects(options.isFollowRedirects()); return httpMethod; } private static void initHeaders(RequestOptions options, HttpMethod method) { String[] headers = options.getHeaderNames(); for (String header : headers) { Object[] values = options.getHeaders(header); for (Object value : values) { method.addRequestHeader(header, value.toString()); } } String cc = options.getCacheControl(); if (cc != null && cc.length() != 0) method.setRequestHeader("Cache-Control", cc); if (options.getAuthorization() != null) method.setDoAuthentication(false); } public static final class ExtensionMethod extends EntityEnclosingMethod { private String method = null; public ExtensionMethod(String method, String uri) { super(method); try { this.setURI(new URI(uri, false)); } catch (Exception e) { } this.method = method; } @Override public String getName() { return method; } } public static RequestOptions createDefaultRequestOptions() { RequestOptions options = new RequestOptions(); options.setAcceptEncoding("gzip", "deflate"); options.setAccept("application/atom+xml;type=entry", "application/atom+xml;type=feed", "application/atom+xml", "application/atomsvc+xml", "application/atomcat+xml", "application/xml;q=0.5", "text/xml;q=0.5", "*/*;q=0.01"); options.setAcceptCharset("utf-8", "*;q=0.5"); return options; } }
2,982
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/MultipartRelatedRequestEntity.java
package org.apache.abdera.protocol.client.util; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.abdera.model.Entry; import org.apache.abdera.util.MimeTypeHelper; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.methods.RequestEntity; public class MultipartRelatedRequestEntity implements RequestEntity { static final int BUFF_SIZE = 1024; static final byte[] buffer = new byte[BUFF_SIZE]; private final Entry entry; private final InputStream input; private final String contentType; private String boundary; public MultipartRelatedRequestEntity(Entry entry, InputStream input) { this(entry, input, null); } public MultipartRelatedRequestEntity(Entry entry, InputStream input, String contentType) { this(entry, input, contentType, null); } public MultipartRelatedRequestEntity(Entry entry, InputStream input, String contentType, String boundary) { this.input = input; this.entry = entry; this.contentType = contentType != null ? contentType : entry.getContentMimeType().toString(); this.boundary = boundary != null ? boundary : String.valueOf(System.currentTimeMillis()); } public void writeRequest(OutputStream arg0) throws IOException { DataOutputStream out = new DataOutputStream(arg0); out.writeBytes("--" + boundary + "\r\n"); writeEntry(out); writeInput(out); } private void writeEntry(DataOutputStream out) throws IOException { out.writeBytes("content-type: " + MimeTypeHelper.getMimeType(entry) + "\r\n\r\n"); entry.writeTo(out); out.writeBytes("--" + boundary + "\r\n"); } private void writeInput(DataOutputStream out) throws IOException { if (contentType == null) { throw new NullPointerException("media content type can't be null"); } out.writeBytes("content-type: " + contentType + "\r\n"); String contentId = entry.getContentSrc().toString(); if (!contentId.matches("cid:.+")) { throw new IllegalArgumentException("entry content source is not a correct content-ID"); } out.writeBytes("content-id: <" + contentId.substring(4) + ">\r\n\r\n"); ByteArrayOutputStream output = new ByteArrayOutputStream(); while (input.read(buffer) != -1) { output.write(buffer); } Base64 base64 = new Base64(); out.write(base64.encode(output.toByteArray())); out.writeBytes("\r\n" + "--" + boundary + "--"); } public long getContentLength() { return -1; } public String getContentType() { return "Multipart/Related; boundary=\"" + boundary + "\";type=\"" + MimeTypeHelper.getMimeType(entry) + "\""; } public boolean isRepeatable() { return true; } }
543
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/NonOpTrustManager.java
package org.apache.abdera.protocol.client.util; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; public class NonOpTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }
1,907
apache/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/SimpleSSLProtocolSocketFactory.java
package org.apache.abdera.protocol.client.util; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; public class SimpleSSLProtocolSocketFactory implements SecureProtocolSocketFactory { private SSLContext context = null; public SimpleSSLProtocolSocketFactory(TrustManager trustManager) { init(trustManager); } public SimpleSSLProtocolSocketFactory() { this(new NonOpTrustManager()); } private void init(TrustManager trustManager) { try { context = SSLContext.getInstance("SSL"); context.init(null, new TrustManager[] {trustManager}, null); } catch (Exception e) { } } public Socket createSocket(Socket socket, String host, int port, boolean close) throws IOException, UnknownHostException { return context.getSocketFactory().createSocket(socket, host, port, close); } public Socket createSocket(String host, int port, InetAddress chost, int cport) throws IOException, UnknownHostException { return context.getSocketFactory().createSocket(host, port, chost, cport); } public Socket createSocket(String host, int port, InetAddress chost, int cport, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { return context.getSocketFactory().createSocket(host, port, chost, cport); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return context.getSocketFactory().createSocket(host, port); } }
1,678
apache/abdera/client/src/test/java/org/apache/abdera/test/client/JettyUtil.java
package org.apache.abdera.test.client; import org.apache.axiom.testutils.PortAllocator; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.servlet.ServletHandler; public class JettyUtil { private static final String PORT_PROP = "abdera.test.client.port"; private static int PORT = PortAllocator.allocatePort(); private static Server server = null; private static ServletHandler handler = null; public static int getPort() { if (System.getProperty(PORT_PROP) != null) { PORT = Integer.parseInt(System.getProperty(PORT_PROP)); } return PORT; } private static void initServer() throws Exception { server = new Server(); Connector connector = new SocketConnector(); connector.setPort(getPort()); server.setConnectors(new Connector[] {connector}); handler = new ServletHandler(); server.setHandler(handler); } public static void addServlet(String _class, String path) { try { if (server == null) initServer(); } catch (Exception e) { } handler.addServletWithMapping(_class, path); } public static void start() throws Exception { if (server == null) initServer(); if (server.isRunning()) return; server.start(); } public static void stop() throws Exception { if (server == null) return; server.stop(); server = null; } public static boolean isRunning() { return (server != null); } }
571
apache/abdera/client/src/test/java/org/apache/abdera/test/client/TestSuite.java
package org.apache.abdera.test.client; import org.apache.abdera.test.client.app.AppTest; import org.apache.abdera.test.client.cache.CacheTest; import org.apache.abdera.test.client.util.MultipartRelatedRequestEntityTest; import org.junit.internal.TextListener; import org.junit.runner.JUnitCore; public class TestSuite { public static void main(String[] args) { JUnitCore runner = new JUnitCore(); runner.addListener(new TextListener(System.out)); runner.run(CacheTest.class, AppTest.class, MultipartRelatedRequestEntityTest.class); } }
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
23