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); } }
27,135
apache/abdera/client/src/test/java/org/apache/abdera/test/client/app/AppTest.java
package org.apache.abdera.test.client.app; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.activation.MimeType; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; 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.parser.Parser; import org.apache.abdera.parser.ParserOptions; 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.test.client.JettyUtil; import org.apache.abdera.util.EntityTag; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.writer.WriterOptions; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * Test to make sure that we can operate as a simple APP client */ @SuppressWarnings("serial") public class AppTest { protected static void getServletHandler(String... servletMappings) { for (int n = 0; n < servletMappings.length; n = n + 2) { String name = servletMappings[n]; String root = servletMappings[n + 1]; JettyUtil.addServlet(name, root); } } protected String getBase() { return "http://localhost:" + JettyUtil.getPort(); } @BeforeClass public static void setUp() throws Exception { getServletHandler(); JettyUtil.start(); } @AfterClass public static void tearDown() throws Exception { JettyUtil.stop(); } private static Abdera abdera = new Abdera(); private static Factory getFactory() { return abdera.getFactory(); } private static Parser getParser() { return abdera.getParser(); } private static AppTest INSTANCE = null; private static Document<Service> init_service_document(String base) { try { Service service = getFactory().newService(); Workspace workspace = service.addWorkspace("Test"); workspace.addCollection("Entries", base + "/collections/entries").setAcceptsEntry(); workspace.addCollection("Other", base + "/collections/other").setAccept("text/plain"); Document<Service> doc = service.getDocument(); return doc; } catch (Exception e) { } return null; } private static Document<Feed> init_entries_document(String base) { try { Feed feed = getFactory().newFeed(); feed.setId(base + "/collections/entries"); feed.setTitle("Entries"); feed.setUpdated(new Date()); feed.addLink(base + "/collections/entries"); feed.addLink(base + "/collections/entries", "self"); feed.addAuthor("James"); Document<Feed> doc = feed.getDocument(); return doc; } catch (Exception e) { } return null; } public static class ServiceDocumentServlet extends HttpServlet { private Document<Service> service = init_service_document(AppTest.INSTANCE.getBase()); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/atomsvc+xml; charset=utf-8"); WriterOptions options = service.getDefaultWriterOptions(); options.setCharset("UTF-8"); service.writeTo(response.getOutputStream(), options); } } /** * this implements a very simple (and quite buggy) APP server. It's just enough for us to test the client behaviors. * I'm sure it could be greatly improved. */ public static class CollectionServlet extends HttpServlet { protected Document<Feed> feed = init_entries_document(AppTest.INSTANCE.getBase()); protected Map<String, String> media = new HashMap<String, String>(); private String[] tokens = null; private final static int COLLECTION = 0; private final static int ENTRY = 1; private final static int MEDIA = 2; private int getTargetType(HttpServletRequest request) { tokens = request.getRequestURI().split("/"); if (tokens[2].equals("entries") && tokens.length == 3) return COLLECTION; if (tokens[2].equals("entries") && tokens.length == 4) return ENTRY; if (tokens[2].equals("media") && tokens.length == 4) return MEDIA; return -1; } private int getTarget() { return (tokens.length != 4) ? -1 : Integer.parseInt(tokens[3]); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int t = getTargetType(request); switch (t) { case COLLECTION: response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/atom+xml; charset=utf-8"); WriterOptions options = feed.getDefaultWriterOptions(); options.setCharset("UTF-8"); feed.writeTo(response.getOutputStream(), options); break; case ENTRY: try { Entry entry = feed.getRoot().getEntries().get(getTarget()); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/atom+xml; charset=utf-8"); options = entry.getDefaultWriterOptions(); options.setCharset("UTF-8"); entry.writeTo(response.getOutputStream(), options); } catch (Exception e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); break; } break; case MEDIA: try { String m = media.get(AppTest.INSTANCE.getBase() + "/collections/entries/" + getTarget()); if (m != null) { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/plain"); response.getWriter().write(m); break; } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (Exception e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int t = getTargetType(request); switch (t) { case COLLECTION: try { if (MimeTypeHelper.isMatch(request.getContentType(), "application/atom+xml;type=entry")) { MimeType type = new MimeType(request.getContentType()); String charset = type.getParameter("charset"); String uri = AppTest.INSTANCE.getBase() + "/collections/entries"; ParserOptions options = getParser().getDefaultParserOptions(); options.setCharset(charset); Document<?> doc = getParser().parse(request.getInputStream(), uri, options); if (doc.getRoot() instanceof Entry) { Entry entry = (Entry)doc.getRoot().clone(); String newID = AppTest.INSTANCE.getBase() + "/collections/entries/" + feed.getRoot().getEntries().size(); entry.setId(newID); entry.setUpdated(new Date()); entry.addLink(entry.getId().toString(), "edit"); entry.addLink(entry.getId().toString(), "self"); feed.getRoot().insertEntry(entry); response.setStatus(HttpServletResponse.SC_CREATED); response.setHeader("Location", entry.getId().toString()); response.setHeader("Content-Location", entry.getId().toString()); WriterOptions woptions = entry.getDefaultWriterOptions(); woptions.setCharset("UTF-8"); entry.writeTo(response.getOutputStream(), woptions); return; } } if (MimeTypeHelper.isMatch(request.getContentType(), "text/plain")) { int n = feed.getRoot().getEntries().size(); String media = read(request.getInputStream()); Entry entry = getFactory().newEntry(); String newID = AppTest.INSTANCE.getBase() + "/collections/entries/" + n; String slug = request.getHeader("Slug"); entry.setId(newID); entry.setTitle(slug); entry.setUpdated(new Date()); entry.setSummary(slug); entry.addLink(entry.getId().toString(), "edit"); entry.addLink(AppTest.INSTANCE.getBase() + "/collections/media/" + n, "edit-media") .setMimeType("text/plain"); entry.addLink(entry.getId().toString(), "self"); entry.setContent(new IRI(AppTest.INSTANCE.getBase() + "/collections/media/" + n), "text/plain"); feed.getRoot().insertEntry(entry); this.media.put(entry.getId().toString(), media); response.setStatus(HttpServletResponse.SC_CREATED); response.setHeader("Location", entry.getId().toString()); response.setHeader("Content-Location", entry.getId().toString()); WriterOptions woptions = entry.getDefaultWriterOptions(); woptions.setCharset("UTF-8"); entry.writeTo(response.getOutputStream(), woptions); return; } response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } catch (Exception e) { } break; default: response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int t = getTargetType(request); int target = getTarget(); switch (t) { case ENTRY: try { if (MimeTypeHelper.isMatch(request.getContentType(), "application/atom+xml;type=entry")) { Entry entry = feed.getRoot().getEntries().get(target); MimeType type = new MimeType(request.getContentType()); String charset = type.getParameter("charset"); String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target; ParserOptions options = getParser().getDefaultParserOptions(); options.setCharset(charset); Document<?> doc = getParser().parse(request.getInputStream(), uri, options); if (doc.getRoot() instanceof Entry) { Entry newentry = (Entry)doc.getRoot().clone(); if (newentry.getId().equals(entry.getId())) { newentry.setUpdated(new Date()); entry.discard(); feed.getRoot().insertEntry(newentry); response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot change atom:id"); return; } } } response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } catch (Exception e) { } break; case MEDIA: if (MimeTypeHelper.isMatch(request.getContentType(), "text/plain")) { String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target; String media = read(request.getInputStream()); this.media.put(uri, media); Entry entry = feed.getRoot().getEntries().get(target); entry.setUpdated(new Date()); response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); break; default: response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int t = getTargetType(request); int target = getTarget(); switch (t) { case ENTRY: case MEDIA: String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target; Entry entry = feed.getRoot().getEntries().get(target); entry.discard(); media.remove(uri); response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; default: response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } } private static String read(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int m = -1; while ((m = in.read()) != -1) { out.write(m); } String resp = new String(out.toByteArray()); return resp.trim(); } public AppTest() { AppTest.INSTANCE = this; } protected static void getServletHandler() { getServletHandler(ServiceDocumentServlet.class.getName(), "/service", CollectionServlet.class.getName(), "/collections/*"); } @Test public void testRequestOptions() throws Exception { AbderaClient abderaClient = new AbderaClient(); RequestOptions options = abderaClient.getDefaultRequestOptions(); options.setIfModifiedSince(new Date()); assertNotNull(options.getIfModifiedSince()); options.set4xxRequestException(true); assertTrue(options.is4xxRequestException()); options.set5xxRequestException(true); assertTrue(options.is5xxRequestException()); options.setAccept("text/plain"); assertEquals("text/plain", options.getAccept()); options.setAcceptCharset("UTF-8"); assertEquals("UTF-8", options.getAcceptCharset()); options.setAcceptEncoding("gzip"); assertEquals("gzip", options.getAcceptEncoding()); options.setAcceptLanguage("en-US"); assertEquals("en-US", options.getAcceptLanguage()); options.setAuthorization("auth"); assertEquals("auth", options.getAuthorization()); options.setCacheControl("no-cache"); assertEquals("no-cache", options.getCacheControl()); options.setContentType("text/plain"); assertTrue(MimeTypeHelper.isMatch(options.getContentType(), new MimeType("text/plain"))); options.setEncodedHeader("foo", "UTF-8", "bar"); assertEquals("bar", options.getDecodedHeader("foo")); options.setHeader("foo", "bar"); assertEquals("bar", options.getHeader("foo")); options.setIfMatch("testing"); assertTrue(EntityTag.matchesAny(new EntityTag("testing"), options.getIfMatch())); options.setIfNoneMatch("testing"); assertTrue(EntityTag.matchesAny(new EntityTag("testing"), options.getIfNoneMatch())); options.setSlug("This is the slug"); assertEquals("This is the slug", options.getSlug()); options.setUsePostOverride(true); assertTrue(options.isUsePostOverride()); } @Test public void testAppClient() throws Exception { AbderaClient abderaClient = new AbderaClient(); Entry entry = getFactory().newEntry(); RequestOptions options = abderaClient.getDefaultRequestOptions(); options.setHeader("Connection", "close"); options.setUseExpectContinue(false); // do the introspection step ClientResponse response = abderaClient.get("http://localhost:" + JettyUtil.getPort() + "/service", options); String col_uri; try { assertEquals(200, response.getStatus()); Document<Service> service_doc = response.getDocument(); assertNotNull(service_doc); assertEquals(1, service_doc.getRoot().getWorkspaces().size()); Workspace workspace = service_doc.getRoot().getWorkspace("Test"); assertNotNull(workspace); for (Collection c : workspace.getCollections()) { assertNotNull(c.getTitle()); assertNotNull(c.getHref()); } col_uri = getBase() + "/collections/entries"; } finally { response.release(); } // post a new entry response = abderaClient.post(col_uri, entry, options); String self_uri; try { assertEquals(201, response.getStatus()); assertNotNull(response.getLocation()); assertNotNull(response.getContentLocation()); self_uri = response.getLocation().toString(); } finally { response.release(); } // get the collection to see if our entry is there response = abderaClient.get(col_uri, options); try { assertEquals(200, response.getStatus()); Document<Feed> feed_doc = response.getDocument(); assertEquals(1, feed_doc.getRoot().getEntries().size()); } finally { response.release(); } // get the entry to see if we can get it response = abderaClient.get(self_uri, options); String edit_uri; try { assertEquals(200, response.getStatus()); Document<Entry> entry_doc = response.getDocument(); // this isn't always true, but for our tests they are the same assertEquals(self_uri, entry_doc.getRoot().getId().toString()); // get the edit uri from the entry edit_uri = entry_doc.getRoot().getEditLink().getHref().toString(); // change the entry Document<Entry> doc = response.getDocument(); entry = (Entry)doc.getRoot().clone(); entry.setTitle("New title"); } finally { response.release(); } // submit the changed entry back to the server response = abderaClient.put(edit_uri, entry, options); try { assertEquals(204, response.getStatus()); } finally { response.release(); } // check to see if the entry was modified properly response = abderaClient.get(self_uri, options); try { assertEquals(200, response.getStatus()); Document<Entry> entry_doc = response.getDocument(); assertEquals("New title", entry_doc.getRoot().getTitle()); } finally { response.release(); } // delete the entry response = abderaClient.delete(edit_uri, options); try { assertEquals(204, response.getStatus()); } finally { response.release(); } // is it gone? response = abderaClient.get(self_uri, options); try { assertEquals(404, response.getStatus()); } finally { response.release(); } // YAY! We're a working APP client // Now let's try to do a media post // Post the media resource options = abderaClient.getDefaultRequestOptions(); options.setContentType("text/plain"); options.setHeader("Connection", "close"); options.setUseExpectContinue(false); response = abderaClient.post(col_uri, new ByteArrayInputStream("test".getBytes()), options); try { assertEquals(201, response.getStatus()); assertNotNull(response.getLocation()); assertNotNull(response.getContentLocation()); self_uri = response.getLocation().toString(); } finally { response.release(); } // was an entry created? options = abderaClient.getDefaultRequestOptions(); options.setHeader("Connection", "close"); response = abderaClient.get(self_uri, options); String edit_media, media; try { assertEquals(200, response.getStatus()); Document<Entry> entry_doc = response.getDocument(); // this isn't always true, but for our tests they are the same assertEquals(self_uri, entry_doc.getRoot().getId().toString()); // get the right links from the entry edit_uri = entry_doc.getRoot().getEditLink().getHref().toString(); edit_media = entry_doc.getRoot().getLink("edit-media").getHref().toString(); media = entry_doc.getRoot().getContentElement().getSrc().toString(); // edit the entry Document<Entry> doc = response.getDocument(); entry = (Entry)doc.getRoot().clone(); entry.setTitle("New title"); } finally { response.release(); } // submit the changes options = abderaClient.getDefaultRequestOptions(); options.setContentType("application/atom+xml;type=entry"); options.setHeader("Connection", "close"); options.setUseExpectContinue(false); response = abderaClient.put(edit_uri, entry, options); try { assertEquals(204, response.getStatus()); } finally { response.release(); } // get the media resource response = abderaClient.get(media); try { assertEquals(200, response.getStatus()); String mediavalue = read(response.getInputStream()); assertEquals("test", mediavalue); } finally { response.release(); } // edit the media resource options = abderaClient.getDefaultRequestOptions(); options.setHeader("Connection", "close"); options.setContentType("text/plain"); options.setUseExpectContinue(false); response = abderaClient.put(edit_media, new ByteArrayInputStream("TEST".getBytes()), options); try { assertEquals(204, response.getStatus()); } finally { response.release(); } // was the resource changed? response = abderaClient.get(media, options); try { assertEquals(200, response.getStatus()); String mediavalue = read(response.getInputStream()); assertEquals("TEST", mediavalue); } finally { response.release(); } // delete the entry response = abderaClient.delete(edit_uri, options); try { assertEquals(204, response.getStatus()); } finally { response.release(); } // is the entry gone? response = abderaClient.get(self_uri, options); try { assertEquals(404, response.getStatus()); } finally { response.release(); } // is the media resource gone? options.setNoCache(true); // need to force revalidation to check response = abderaClient.get(media, options); try { assertEquals(404, response.getStatus()); } finally { response.release(); } // YAY! We can handle media link entries } @Test public void testEntityTag() throws Exception { EntityTag tag1 = new EntityTag("tag"); EntityTag tag2 = new EntityTag("tag", true); // weak; assertFalse(tag1.isWeak()); assertTrue(tag2.isWeak()); assertFalse(EntityTag.matches(tag1, tag2)); assertFalse(EntityTag.matchesAny(tag1, new EntityTag[] {tag2})); assertEquals("\"tag\"", tag1.toString()); assertEquals("W/\"tag\"", tag2.toString()); tag1 = EntityTag.parse("\"tag\""); assertFalse(tag1.isWeak()); assertEquals("tag", tag1.getTag()); tag2 = EntityTag.parse("W/\"tag\""); assertTrue(tag2.isWeak()); assertEquals("tag", tag2.getTag()); EntityTag[] tags = EntityTag.parseTags("\"tag1\", W/\"tag2\""); assertFalse(tags[0].isWeak()); assertEquals("tag1", tags[0].getTag()); assertTrue(tags[1].isWeak()); assertEquals("tag2", tags[1].getTag()); } }
17,059
apache/abdera/client/src/test/java/org/apache/abdera/test/client/cache/CacheTest.java
package org.apache.abdera.test.client.cache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import junit.framework.Assert; 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.client.cache.CachedResponse; import org.apache.abdera.test.client.JettyUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * These cache tests were originally based on Mark Nottingham's javascript cache tests, available at: * http://www.mnot.net/javascript/xmlhttprequest/cache.html They have since been modified to use an embedded Jetty * server instead of going off over the internet to hit Mark's server, since there are too many things that can get in * the way of those sort things (proxies, intermediate caches, etc) if you try to talk to a remote server. */ @SuppressWarnings("serial") public class CacheTest { private static String CHECK_CACHE_INVALIDATE; private static String CHECK_NO_CACHE; // private static String CHECK_AUTH; private static String CHECK_MUST_REVALIDATE; public CacheTest() { String base = getBase(); CHECK_CACHE_INVALIDATE = base + "/check_cache_invalidate"; CHECK_NO_CACHE = base + "/no_cache"; // CHECK_AUTH = base + "/auth"; CHECK_MUST_REVALIDATE = base + "/must_revalidate"; } protected static void getServletHandler(String... servletMappings) { for (int n = 0; n < servletMappings.length; n = n + 2) { String name = servletMappings[n]; String root = servletMappings[n + 1]; JettyUtil.addServlet(name, root); } } protected String getBase() { return "http://localhost:" + JettyUtil.getPort(); } @BeforeClass public static void setUp() throws Exception { getServletHandler(); JettyUtil.start(); } @AfterClass public static void tearDown() throws Exception { JettyUtil.stop(); } protected static void getServletHandler() { getServletHandler("org.apache.abdera.test.client.cache.CacheTest$CheckCacheInvalidateServlet", "/check_cache_invalidate", "org.apache.abdera.test.client.cache.CacheTest$NoCacheServlet", "/no_cache", "org.apache.abdera.test.client.cache.CacheTest$AuthServlet", "/auth", "org.apache.abdera.test.client.cache.CacheTest$CheckMustRevalidateServlet", "/must_revalidate"); } public static class CheckMustRevalidateServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String reqnum = request.getHeader("X-Reqnum"); int req = Integer.parseInt(reqnum); if (req == 1) { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/plain"); response.setHeader("Cache-Control", "must-revalidate"); response.setDateHeader("Date", System.currentTimeMillis()); response.getWriter().println(reqnum); response.getWriter().close(); } else if (req == 2) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setContentType("text/plain"); response.setDateHeader("Date", System.currentTimeMillis()); return; } else if (req == 3) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setDateHeader("Date", System.currentTimeMillis()); return; } } } public static class CheckCacheInvalidateServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String reqnum = request.getHeader("X-Reqnum"); response.setStatus(HttpServletResponse.SC_OK); response.setDateHeader("Date", System.currentTimeMillis()); response.setContentType("text/plain"); response.setHeader("Cache-Control", "max-age=60"); response.getWriter().println(reqnum); response.getWriter().close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } public static class NoCacheServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String reqnum = request.getHeader("X-Reqnum"); int reqtest = Integer.parseInt(request.getHeader("X-Reqtest")); response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); switch (reqtest) { case NOCACHE: response.setHeader("Cache-Control", "no-cache"); break; case NOSTORE: response.setHeader("Cache-Control", "no-store"); break; case MAXAGE0: response.setHeader("Cache-Control", "max-age=0"); break; } response.setDateHeader("Date", System.currentTimeMillis()); response.getWriter().println(reqnum); response.getWriter().close(); } } public static class AuthServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String reqnum = request.getHeader("X-Reqnum"); int num = Integer.parseInt(reqnum); switch (num) { case 1: response.setStatus(HttpServletResponse.SC_OK); break; case 2: response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); break; default: response.setStatus(HttpServletResponse.SC_OK); break; } response.setDateHeader("Date", System.currentTimeMillis()); response.setContentType("text/plain"); response.getWriter().println(reqnum); response.getWriter().close(); } } private static final int NOCACHE = 0; private static final int NOSTORE = 1; private static final int MAXAGE0 = 2; private static final int POST = 3; private static final int DELETE = 4; private static final int PUT = 5; @Test public void testRequestNoStore() throws Exception { _requestCacheInvalidation(NOSTORE); } @Test public void testRequestNoCache() throws Exception { _requestCacheInvalidation(NOCACHE); } @Test public void testRequestMaxAge0() throws Exception { _requestCacheInvalidation(MAXAGE0); } @Test public void testResponseNoStore() throws Exception { _responseNoCache(NOSTORE); } @Test public void testResponseNoCache() throws Exception { _responseNoCache(NOCACHE); } @Test public void testResponseMaxAge0() throws Exception { _responseNoCache(MAXAGE0); } @Test public void testPostInvalidates() throws Exception { _methodInvalidates(POST); } @Test public void testPutInvalidates() throws Exception { _methodInvalidates(PUT); } @Test public void testDeleteInvalidates() throws Exception { _methodInvalidates(DELETE); } @Test public void testAuthForcesRevalidation() throws Exception { // TODO: Actually need to rethink this. Responses to authenticated requests // should never be cached unless the resource is explicitly marked as // being cacheable (e.g. using Cache-Control: public). So this test // was testing incorrect behavior. // AbderaClient client = new CommonsClient(); // client.usePreemptiveAuthentication(true); // client.addCredentials(CHECK_AUTH, null, null, new UsernamePasswordCredentials("james","snell")); // RequestOptions options = client.getDefaultRequestOptions(); // options.setHeader("Connection", "close"); // options.setRevalidateWithAuth(true); // options.setHeader("x-reqnum", "1"); // Response response = client.get(CHECK_AUTH, options); // // // first request works as expected. fills the cache // String resp1 = getResponse(response); // assertEquals(resp1, "1"); // // // second request uses authentication, should force revalidation of the cache // options.setHeader("x-reqnum", "2"); // response = client.get(CHECK_AUTH, options); // // resp1 = getResponse(response); // assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED); // assertEquals(resp1, "2"); // // // third request does not use authentication, but since the previous request // // resulted in an "unauthorized" response, the cache needs to be refilled // options.setHeader("x-reqnum", "3"); // client.usePreemptiveAuthentication(false); // response = client.get(CHECK_AUTH, options); // // resp1 = getResponse(response); // assertEquals(response.getStatus(), HttpServletResponse.SC_OK); // assertEquals(resp1, "3"); // // // fourth request does not use authentication, will pull from the cache // options = client.getDefaultRequestOptions(); // options.setHeader("x-reqnum", "4"); // client.usePreemptiveAuthentication(false); // response = client.get(CHECK_AUTH, options); // // resp1 = getResponse(response); // assertEquals(response.getStatus(), HttpServletResponse.SC_OK); // assertEquals(resp1, "3"); // // // fifth request uses authentication, will force revalidation // options.setAuthorization("Basic amFtZXM6c25lbGw="); // options.setHeader("x-reqnum", "5"); // response = client.get(CHECK_AUTH, options); // // resp1 = getResponse(response); // assertEquals(response.getStatus(), HttpServletResponse.SC_OK); // assertEquals(resp1, "5"); } @Test public void testResponseMustRevalidate() throws Exception { AbderaClient abderaClient = new AbderaClient(); RequestOptions options = abderaClient.getDefaultRequestOptions(); options.setHeader("Connection", "close"); options.setHeader("x-reqnum", "1"); ClientResponse response = abderaClient.get(CHECK_MUST_REVALIDATE, options); String resp1 = getResponse(response); assertEquals("1", resp1); // Should be revalidated and use the cache options.setHeader("x-reqnum", "2"); response = abderaClient.get(CHECK_MUST_REVALIDATE, options); assertTrue(response instanceof CachedResponse); String resp2 = getResponse(response); assertEquals("1", resp2); // Should be revalidated and return a 404 options.setHeader("x-reqnum", "3"); response = abderaClient.get(CHECK_MUST_REVALIDATE, options); assertEquals(404, response.getStatus()); response.release(); } private RequestOptions getRequestOptions(AbderaClient client, int num) { RequestOptions options = client.getDefaultRequestOptions(); options.setHeader("Connection", "close"); options.setHeader("x-reqnum", String.valueOf(num)); options.setUseExpectContinue(false); return options; } private void _methodInvalidates(int type) throws Exception { AbderaClient abderaClient = new AbderaClient(); RequestOptions options = getRequestOptions(abderaClient, 1); ClientResponse response = abderaClient.get(CHECK_CACHE_INVALIDATE, options); String resp1 = getResponse(response); response.release(); assertEquals("1", resp1); // calling a method that could change state on the server should invalidate the cache options = getRequestOptions(abderaClient, 2); switch (type) { case POST: response = abderaClient.post(CHECK_CACHE_INVALIDATE, new ByteArrayInputStream("".getBytes()), options); break; case PUT: response = abderaClient.put(CHECK_CACHE_INVALIDATE, new ByteArrayInputStream("".getBytes()), options); break; case DELETE: response = abderaClient.delete(CHECK_CACHE_INVALIDATE, options); break; } response.release(); options = getRequestOptions(abderaClient, 3); response = abderaClient.get(CHECK_CACHE_INVALIDATE, options); resp1 = getResponse(response); response.release(); assertEquals("3", resp1); } private void _requestCacheInvalidation(int type) throws Exception { AbderaClient abderaClient = new AbderaClient(); RequestOptions options = getRequestOptions(abderaClient, 1); ClientResponse response = abderaClient.get(CHECK_CACHE_INVALIDATE, options); String resp1 = getResponse(response); assertEquals("1", resp1); // Should not use the cache options = getRequestOptions(abderaClient, 2); switch (type) { case NOCACHE: options.setNoCache(true); break; case NOSTORE: options.setNoStore(true); break; case MAXAGE0: options.setMaxAge(0); break; } response = abderaClient.get(CHECK_CACHE_INVALIDATE, options); String resp2 = getResponse(response); assertEquals("2", resp2); // Should use the cache options = getRequestOptions(abderaClient, 3); switch (type) { case NOCACHE: options.setNoCache(false); break; case NOSTORE: options.setNoStore(false); break; case MAXAGE0: options.setMaxAge(60); break; } response = abderaClient.get(CHECK_CACHE_INVALIDATE, options); String resp3 = getResponse(response); assertEquals("2", resp3); } private void _responseNoCache(int type) throws Exception { AbderaClient abderaClient = new AbderaClient(); RequestOptions options = getRequestOptions(abderaClient, 1); options.setHeader("x-reqtest", String.valueOf(type)); ClientResponse response = abderaClient.get(CHECK_NO_CACHE, options); String resp1 = getResponse(response); assertEquals("1", resp1); // Should not use the cache options = getRequestOptions(abderaClient, 2); options.setHeader("x-reqtest", String.valueOf(type)); response = abderaClient.get(CHECK_NO_CACHE, options); String resp2 = getResponse(response); assertEquals("2", resp2); // Should use the cache options = getRequestOptions(abderaClient, 3); options.setHeader("x-reqtest", String.valueOf(type)); response = abderaClient.get(CHECK_NO_CACHE, options); String resp3 = getResponse(response); assertEquals("3", resp3); } private static String getResponse(ClientResponse response) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int m = -1; InputStream in = response.getInputStream(); while ((m = in.read()) != -1) { out.write(m); } in.close(); String resp = new String(out.toByteArray()); return resp.trim(); } @Test public void testInitCache() { AbderaClient client = new AbderaClient(); assertNotNull(client.getCache()); } }
3,018
apache/abdera/client/src/test/java/org/apache/abdera/test/client/util/MultipartRelatedRequestEntityTest.java
package org.apache.abdera.test.client.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import javax.activation.MimeType; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Entry; import org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity; import org.apache.abdera.util.MimeTypeHelper; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.methods.RequestEntity; import org.junit.Test; import org.mortbay.io.WriterOutputStream; public class MultipartRelatedRequestEntityTest { @Test public void testMultipartFormat() throws IOException { Entry entry = Abdera.getInstance().newEntry(); entry.setTitle("my image"); entry.addAuthor("david"); entry.setId("tag:apache.org,2008:234534344"); entry.setSummary("multipart test"); entry.setContent(new IRI("cid:234234@example.com"), "image/jpg"); RequestEntity request = new MultipartRelatedRequestEntity(entry, this.getClass().getResourceAsStream("info.png"), "image/jpg", "asdfasdfasdf"); StringWriter sw = new StringWriter(); WriterOutputStream os = new WriterOutputStream(sw); request.writeRequest(os); String multipart = sw.toString(); // System.out.println(sw.toString()); assertTrue(multipart.contains("content-id: <234234@example.com>")); assertTrue(multipart.contains("content-type: image/jpg")); } @Test public void testMultimediaRelatedContentType() throws Exception { MimeType type = new MimeType("Multipart/Related;boundary=\"35245352345sdfg\""); assertTrue(MimeTypeHelper.isMatch("Multipart/Related", type.toString())); assertEquals("35245352345sdfg", type.getParameter("boundary")); } // @Test public void testMultipartEncoding() throws Exception { InputStream input = this.getClass().getResourceAsStream("info.png"); int BUFF_SIZE = 1024; byte[] line = new byte[BUFF_SIZE]; ByteArrayOutputStream output = new ByteArrayOutputStream(); while (input.read(line) != -1) { output.write(line); } Base64 base64 = new Base64(); byte[] encoded = base64.encode(output.toByteArray()); ByteArrayInputStream bi = new ByteArrayInputStream(base64.decode(encoded)); File f = new File("info-out.png"); if (f.exists()) f.delete(); f.createNewFile(); FileOutputStream fo = new FileOutputStream(f); int end; while ((end = bi.read(line)) != -1) { fo.write(line, 0, end); } fo.flush(); fo.close(); } }
9,374
apache/abdera/core/src/main/java/org/apache/abdera/Abdera.java
package org.apache.abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Categories; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Service; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserFactory; import org.apache.abdera.util.AbderaConfiguration; import org.apache.abdera.util.Configuration; import org.apache.abdera.writer.StreamWriter; import org.apache.abdera.writer.Writer; import org.apache.abdera.writer.WriterFactory; import org.apache.abdera.xpath.XPath; /** * The top level entry point for Abdera that provides access to various subcomponents. Upon creation, this class will * attempt to create singleton instances of each of the various subcomponents components. These instances may be * retrieved using the appropriate get___ methods. Alternatively, new instances may be created using the appropriate * new___ methods. Instances of the Abdera object, and it's direct children (Parser, Factory, XPath, etc) are * Threadsafe. Because of the dynamic configuration model Abdera uses, creating a new instance of the Abdera object can * be time consuming. It is, therefore, a good idea for applications to create only a single static instance of the * Abdera object (see the Abdera.getInstance() method). Abdera's configuration model depends heavily on the context * classloader. Extension Factories, custom writers, custom parsers, etc are all discovered automatically by searching * the classpath. This means that care needs to be taken when using Abdera in environments that utilize multiple * classloaders (such as Web application servers). */ public class Abdera { /** A static instance of Abdera **/ private static Abdera instance; /** * Get a static instance of the Abdera object. */ public static synchronized Abdera getInstance() { if (instance == null) instance = new Abdera(); return instance; } private final Configuration config; private Factory factory; private Parser parser; private XPath xpath; private ParserFactory parserFactory; private WriterFactory writerFactory; private Writer writer; /** * Initialize using the default Abdera Configuration */ public Abdera() { this(AbderaConfiguration.getDefault()); } /** * Initialize using the specified Abdera Configuration * * @param config The Abdera Configuration to use */ public Abdera(Configuration config) { this.config = config; IRI.preinit(); // initializes the IRI stuff to improve performance later } /** * Create a new Feed instance. This is a convenience shortcut for <code>abdera.getFactory().newFeed()</code> * * @return A newly created feed element */ public Feed newFeed() { return getFactory().newFeed(); } /** * Create a new Entry instance. This is a convenience shortcut for <code>abdera.getFactory().newEntry()</code> * * @return A newly created entry element */ public Entry newEntry() { return getFactory().newEntry(); } /** * Create a new Service instance. This is a convenience shortcut for <code>abdera.getFactory().newService()</code> * * @return A newly created service element */ public Service newService() { return getFactory().newService(); } /** * Create a new Categories instance. This is a convenience shortcut for * <code>abdera.getFactory().newCategories()</code> * * @return A newly created categories element */ public Categories newCategories() { return getFactory().newCategories(); } /** * Return the Abdera Configuration used to initialize this instance * * @return The Abdera configuration */ public Configuration getConfiguration() { return config; } /** * Return the singleton instance of org.apache.abdera.factory.Factory * * @return The factory instance */ public synchronized Factory getFactory() { if (factory == null) factory = newFactory(); return factory; } /** * Return the singleton instance of org.apache.abdera.parser.Parser * * @return The parser instance */ public synchronized Parser getParser() { if (parser == null) parser = newParser(); return parser; } /** * Return the singleton instance of org.apache.abdera.xpath.XPath * * @return The XPath instance */ public synchronized XPath getXPath() { if (xpath == null) xpath = newXPath(); return xpath; } /** * Return the singleton instance of org.apache.abdera.parser.ParserFactory. The Parser Factory is used to acquire * alternative parser implementation instances. * * @return The ParserFactory instance */ public synchronized ParserFactory getParserFactory() { if (parserFactory == null) parserFactory = newParserFactory(); return parserFactory; } /** * Return the singleton instance of org.apache.abdera.writer.WriterFactory. The Writer Factory is used to acquire * alternative writer implementation instances. * * @return The WriterFactory instance */ public synchronized WriterFactory getWriterFactory() { if (writerFactory == null) writerFactory = newWriterFactory(); return writerFactory; } /** * Return the singleton instance of the default org.apache.abdera.writer.Writer implementation. * * @return The default writer implementation */ public synchronized Writer getWriter() { if (writer == null) writer = newWriter(); return writer; } /** * Return a new instance of org.apache.abdera.factory.Factory * * @return A new factory instance */ private Factory newFactory() { return config.newFactoryInstance(this); } /** * Return a new instance of org.apache.abdera.parser.Parser * * @return A new parser instance */ private Parser newParser() { return config.newParserInstance(this); } /** * Return a new instance of org.apache.abdera.xpath.XPath * * @return A new XPath instance */ private XPath newXPath() { return config.newXPathInstance(this); } /** * Return a new instance of org.apache.abdera.parser.ParserFactory * * @return A new ParserFactory instance */ private ParserFactory newParserFactory() { return config.newParserFactoryInstance(this); } /** * Return a new instance of org.apache.abdera.writer.WriterFactory * * @return A new WriterFactory instance */ private WriterFactory newWriterFactory() { return config.newWriterFactoryInstance(this); } /** * Return a new instance of the default org.apache.abdera.writer.Writer * * @return A new default writer implementation instance */ private Writer newWriter() { return config.newWriterInstance(this); } /** * Return a new instance of the default org.apache.abdera.writer.Writer * * @return A new default writer implementation instance */ public StreamWriter newStreamWriter() { return config.newStreamWriterInstance(this); } // Static convenience methods // /** * Return a new Factory instance using a non-shared Abdera object * * @return A new factory instance */ public static Factory getNewFactory() { return (new Abdera()).newFactory(); } /** * Return a new Parser instance using a non-shared Abdera object * * @return A new parser instance */ public static Parser getNewParser() { return (new Abdera()).newParser(); } /** * Return a new XPath instance using a non-shared Abdera object * * @return A new XPath instance */ public static XPath getNewXPath() { return (new Abdera()).newXPath(); } /** * Return a new ParserFactory instance using a non-shared Abdera object * * @return A new ParserFactory instance */ public static ParserFactory getNewParserFactory() { return (new Abdera()).newParserFactory(); } /** * Return a new WriterFactory instance using a non-shared Abdera object * * @return A new WriterFactory instance */ public static WriterFactory getNewWriterFactory() { return (new Abdera()).newWriterFactory(); } /** * Return a new instance of the default Writer using a non-shared Abdera object * * @return A new default writer implementation instance */ public static Writer getNewWriter() { return (new Abdera()).newWriter(); } /** * Return a new instance of the default StreamWriter using a non-shared Abdera object * * @return A new default stream writer implementation instance */ public static StreamWriter getNewStreamWriter() { return (new Abdera()).newStreamWriter(); } }
2,191
apache/abdera/core/src/main/java/org/apache/abdera/factory/ExtensionFactory.java
package org.apache.abdera.factory; import org.apache.abdera.model.Base; import org.apache.abdera.model.Element; /** * <p> * Extension Factories are used to provide a means of dynamically resolving builders for namespaced extension elements * </p> * <p> * There are four ways of supporting extension elements. * </p> * <ol> * <li>Implement your own Factory (hard)</li> * <li>Subclass the default Axiom-based Factory (also somewhat difficult)</li> * <li>Implement and register an ExtensionFactory (wonderfully simple)</li> * <li>Use the Feed Object Model's dynamic support for extensions (also very simple)</li> * </ol> * <p> * Registering an Extension Factory requires generally nothing more than implementing ExtensionFactory and then creating * a file called META-INF/services/org.apache.abdera.factory.ExtensionFactory and listing the class names of each * ExtensionFactory you wish to register. * </p> * <p> * ExtensionFactory implementations are assumed to be threadsafe * </p> */ public interface ExtensionFactory { /** * Returns true if this extension factory handles the specified namespace * * @param namespace The XML namespace of the extension * @return True if the namespace is supported by the ExtensionFactory */ boolean handlesNamespace(String namespace); /** * Returns the Namespace URIs handled by this Extension Factory * * @return A List of Namespace URIs Supported by this Extension */ String[] getNamespaces(); /** * Abdera's support for static extensions is based on a simple delegation model. Static extension interfaces wrap * the dynamic extension API. ExtensionFactory's are handed the internal dynamic element instance and are expected * to hand back an object wrapper. * * @param internal The Abdera element that needs to be wrapped * @return The wrapper element */ <T extends Element> T getElementWrapper(Element internal); /** * Retrieve the mime type for the element * * @param base An Abdera object * @return A MIME media type for the object */ <T extends Base> String getMimeType(T base); }
3,048
apache/abdera/core/src/main/java/org/apache/abdera/factory/ExtensionFactoryMap.java
package org.apache.abdera.factory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.abdera.model.Base; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; /** * A utility implementation of ExtensionFactory used internally by Abdera. It maintains the collection ExtensionFactory * instances discovered on the classpath and a cache of Internal-Wrapper mappings. */ public class ExtensionFactoryMap implements ExtensionFactory { private final List<ExtensionFactory> factories; public ExtensionFactoryMap(List<ExtensionFactory> factories) { this.factories = Collections.synchronizedList(factories); } @SuppressWarnings("unchecked") public <T extends Element> T getElementWrapper(Element internal) { if (internal == null) return null; T t = null; synchronized (factories) { for (ExtensionFactory factory : factories) { t = (T)factory.getElementWrapper(internal); if (t != null && t != internal) { return t; } } } return (t != null) ? t : (T)internal; } public String[] getNamespaces() { List<String> ns = new ArrayList<String>(); synchronized (factories) { for (ExtensionFactory factory : factories) { String[] namespaces = factory.getNamespaces(); for (String uri : namespaces) { if (!ns.contains(uri)) ns.add(uri); } } } return ns.toArray(new String[ns.size()]); } public boolean handlesNamespace(String namespace) { synchronized (factories) { for (ExtensionFactory factory : factories) { if (factory.handlesNamespace(namespace)) return true; } } return false; } public ExtensionFactoryMap addFactory(ExtensionFactory factory) { if (!factories.contains(factory)) factories.add(factory); return this; } public <T extends Base> String getMimeType(T base) { Element element = base instanceof Element ? (Element)base : ((Document<?>)base).getRoot(); String namespace = element.getQName().getNamespaceURI(); synchronized (factories) { for (ExtensionFactory factory : factories) { if (factory.handlesNamespace(namespace)) return factory.getMimeType(base); } } return null; } public String[] listExtensionFactories() { List<String> names = new ArrayList<String>(); synchronized (factories) { for (ExtensionFactory factory : factories) { String name = factory.getClass().getName(); if (!names.contains(name)) names.add(name); } } return names.toArray(new String[names.size()]); } }
23,130
apache/abdera/core/src/main/java/org/apache/abdera/factory/Factory.java
package org.apache.abdera.factory; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.model.Base; import org.apache.abdera.model.Categories; import org.apache.abdera.model.Category; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Content; import org.apache.abdera.model.Control; import org.apache.abdera.model.DateTime; import org.apache.abdera.model.Div; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Generator; import org.apache.abdera.model.IRIElement; import org.apache.abdera.model.Link; import org.apache.abdera.model.Person; import org.apache.abdera.model.Service; import org.apache.abdera.model.Source; import org.apache.abdera.model.Text; import org.apache.abdera.model.Workspace; import org.apache.abdera.parser.Parser; /** * The Factory interface is the primary means by which Feed Object Model instances are built. Factories are specific to * parser implementations. Users will generally not have to know anything about the Factory implementation, which will * be automatically selected based on the Abdera configuration options. */ public interface Factory { /** * Create a new Parser instance. * * @return A new instance of the Parser associated with this Factory */ Parser newParser(); /** * Create a new Document instance with a root Element of type T. * * @return A new instance of a Document */ <T extends Element> Document<T> newDocument(); /** * Create a new Service element. * * @return A newly created Service element */ Service newService(); /** * Create a new Service element as a child of the given Base. * * @param parent The element or document to which the new Service should be added as a child * @return A newly created Service element */ Service newService(Base parent); /** * Create a new Workspace element. * * @return A newly created Workspace element */ Workspace newWorkspace(); /** * Create a new Workspace element as a child of the given Element. * * @param parent The element to which the new Workspace should be added as a child * @return A newly created Workspace element */ Workspace newWorkspace(Element parent); /** * Create a new Collection element. * * @return A newly created Collection element */ Collection newCollection(); /** * Create a new Collection element as a child of the given Element. * * @param parent The element to which the new Collection should be added as a child * @return A newly created Collection element */ Collection newCollection(Element parent); /** * Create a new Feed element. A new Document containing the Feed will be created automatically * * @return A newly created Feed element. */ Feed newFeed(); /** * Create a new Feed element as a child of the given Base. * * @param parent The element or document to which the new Feed should be added as a child * @return A newly created Feed element */ Feed newFeed(Base parent); /** * Create a new Entry element. A new Document containing the Entry will be created automatically * * @return A newly created Entry element */ Entry newEntry(); /** * Create a new Entry element as a child of the given Base. * * @param parent The element or document to which the new Entry should be added as a child * @return A newly created Entry element */ Entry newEntry(Base parent); /** * Create a new Category element. * * @return A newly created Category element */ Category newCategory(); /** * Create a new Category element as a child of the given Element. * * @param parent The element to which the new Category should be added as a child * @return A newly created Category element */ Category newCategory(Element parent); /** * Create a new Content element. * * @return A newly created Content element with type="text" */ Content newContent(); /** * Create a new Content element of the given Content.Type. * * @param type The Content.Type for the newly created Content element. * @return A newly created Content element using the specified type */ Content newContent(Content.Type type); /** * Create a new Content element of the given Content.Type as a child of the given Element. * * @param type The Content.Type for the newly created Content element. * @param parent The element to which the new Content should be added as a child * @return A newly created Content element using the specified type */ Content newContent(Content.Type type, Element parent); /** * Create a new Content element of the given MediaType. * * @param mediaType The MIME media type to be specified by the type attribute * @return A newly created Content element using the specified MIME type */ Content newContent(MimeType mediaType); /** * Create a new Content element of the given MediaType as a child of the given Element. * * @param mediaType The MIME media type to be specified by the type attribute * @param parent The element to which the new Content should be added as a child * @return A newly created Content element using the specified mediatype. */ Content newContent(MimeType mediaType, Element parent); /** * Create a new published element. * * @return A newly created atom:published element */ DateTime newPublished(); /** * Create a new published element as a child of the given Element. * * @param parent The element to which the new Published element should be added as a child * @return A newly created atom:published element */ DateTime newPublished(Element parent); /** * Create a new updated element. * * @return A newly created atom:updated element */ DateTime newUpdated(); /** * create a new updated element as a child of the given Element. * * @param parent The element to which the new Updated element should be added as a child * @return A newly created atom:updated element */ DateTime newUpdated(Element parent); /** * Create a new app:edited element. The app:edited element is defined by the Atom Publishing Protocol specification * for use in atom:entry elements created and edited using that protocol. The element should only ever appear as a * child of atom:entry. * * @return A newly created app:edited element */ DateTime newEdited(); /** * Create a new app:edited element. The app:edited element is defined by the Atom Publishing Protocol specification * for use in atom:entry elements created and edited using that protocol. The element should only ever appear as a * child of atom:entry. * * @param parent The element to which the new Edited element should be added as a child * @return A newly created app:edited element */ DateTime newEdited(Element parent); /** * Create a new DateTime element with the given QName as a child of the given Element. RFC4287 provides the abstract * Atom Date Construct as a reusable component. Any extension element whose value is a Date/Time SHOULD reuse this * construct to maintain consistency with the base specification. * * @param qname The XML QName of the Atom Date element to create * @param parent The element to which the new Atom Date element should be added as a child * @return The newly created Atom Date Construct element */ DateTime newDateTime(QName qname, Element parent); /** * Create a new Generator with Abdera's default name and version. * * @return A newly created and pre-populated atom:generator element */ Generator newDefaultGenerator(); /** * Create a new Generator using Abdera's default name and version as a child of the given Element. * * @param parent The element to which the new Generator element should be added as a child * @return A newly created and pre-populated atom:generator element */ Generator newDefaultGenerator(Element parent); /** * Create a new Generator element. * * @return A newly created atom:generator element */ Generator newGenerator(); /** * Create a new Generator element as a child of the given Element. * * @param parent The element to which the new Generator element should be added as a child * @return A newly creatd atom:generator element */ Generator newGenerator(Element parent); /** * Create a new id element. * * @return A newly created atom:id element */ IRIElement newID(); /** * Create a new id element as a child of the given Element. * * @param parent The element to which the new ID element should be added as a child * @return A newly created atom:id element */ IRIElement newID(Element parent); /** * Create a new icon element. * * @return A newly created atom:icon element */ IRIElement newIcon(); /** * Create a new icon element as a child of the given Element. * * @param parent The element to which the new Icon element should be added as a child * @return A newly created atom:icon element */ IRIElement newIcon(Element parent); /** * Create a new logo element. * * @return A newly created atom:logo element */ IRIElement newLogo(); /** * Create a new logo element as a child of the given Element. * * @param parent The element to which the new Logo element should be added as a child * @return A newly created atom:logo element */ IRIElement newLogo(Element parent); /** * Create a new uri element. * * @return A newly created atom:uri element */ IRIElement newUri(); /** * Create a new uri element as a child of the given Element. * * @param parent The element to which the new URI element should be added as a child * @return A newly created atom:uri element */ IRIElement newUri(Element parent); /** * Create a new IRI element with the given QName as a child of the given Element. * * @param qname The XML QName of the new IRI element * @param parent The element to which the new generic IRI element should be added as a child * @return A newly created element whose text value can be an IRI */ IRIElement newIRIElement(QName qname, Element parent); /** * Create a new Link element. * * @return A newly created atom:link element */ Link newLink(); /** * Create a new Link element as a child of the given Element. * * @param parent The element to which the new Link element should be added as a child * @return A newly created atom:uri element */ Link newLink(Element parent); /** * Create a new author element. * * @return A newly created atom:author element */ Person newAuthor(); /** * Create a new author element as a child of the given Element. * * @param parent The element to which the new Author element should be added as a child * @return A newly created atom:author element */ Person newAuthor(Element parent); /** * Create a new contributor element. * * @return A newly created atom:contributor element */ Person newContributor(); /** * Create a new contributor element as a child of the given Element. * * @param parent The element to which the new Contributor element should be added as a child * @return A newly created atom:contributor element */ Person newContributor(Element parent); /** * Create a new Person element with the given QName as a child of the given Element. RFC4287 provides the abstract * Atom Person Construct to represent people and other entities within an Atom Document. Extensions that wish to * represent people SHOULD reuse this construct. * * @param qname The XML QName of the newly created Person element * @param parent The element to which the new Person element should be added as a child * @return A newly created Atom Person Construct element */ Person newPerson(QName qname, Element parent); /** * Create a new Source element. * * @return A newly created atom:source element */ Source newSource(); /** * Create a new Source element as a child of the given Element. * * @param parent The element to which the new Source element should be added as a child * @return A newly created atom:source element */ Source newSource(Element parent); /** * Create a new Text element with the given QName and Text.Type. RFC4287 provides the abstract Text Construct to * represent simple Text, HTML or XHTML within a document. This construct is used by Atom core elements like * atom:title, atom:summary, atom:rights, atom:subtitle, etc and SHOULD be reused by extensions that need a way of * embedding text in a document. * * @param qname The XML QName of the Text element to create * @param type The type of text (plain text, HTML or XHTML) * @return A newly created Atom Text Construct element */ Text newText(QName qname, Text.Type type); /** * Create a new Text element with the given QName and Text.Type as a child of the given Element. * * @param qname The XML QName of the Text element to create * @param type The type of text (plain text, HTML or XHTML) * @param parent The element to which the new Updated element should be added as a child * @return A newly created Atom Text Construct element */ Text newText(QName qname, Text.Type type, Element parent); /** * Create a new title element. * * @return A newly created atom:title element */ Text newTitle(); /** * Create a new title element as a child of the given Element. * * @param parent The element to which the new Title element should be added as a child * @return A newly created atom:title element */ Text newTitle(Element parent); /** * Create a new title element with the given Text.Type. * * @param type The type of text used in the title (plain text, HTML, XHTML) * @return A newly created atom:title element */ Text newTitle(Text.Type type); /** * Create a new title element with the given Text.Type as a child of the given Element. * * @param type The type of text used in the title (plain text, HTML, XHTML) * @param parent The element to which the new Updated element should be added as a child * @return A newly created atom:title element */ Text newTitle(Text.Type type, Element parent); /** * Create a new subtitle element. * * @return A newly created atom:subtitle element */ Text newSubtitle(); /** * Create a new subtitle element as a child of the given Element. * * @param parent The element to which the new Subtitle element should be added as a child * @return A newly created atom:subtitle element */ Text newSubtitle(Element parent); /** * Create a new subtitle element with the given Text.Type. * * @param type The type of text used in the subtitle (plain text, HTML, XHTML) * @return A newly created atom:subtitle element */ Text newSubtitle(Text.Type type); /** * Create a new subtitle element with the given Text.Type as a child of the given Element. * * @param type The type of text used i the subtitle (plain text, HTML, XHTML) * @param parent The element to which the new Subtitle element should be added as a child * @return A newly created atom:subtitle element */ Text newSubtitle(Text.Type type, Element parent); /** * Create a new summary element. * * @return A newly created atom:summary element */ Text newSummary(); /** * Create a new summary element as a child of the given Element. * * @param parent The element to which the new Summary element should be added as a child * @return A newly created atom:summary element */ Text newSummary(Element parent); /** * Create a new summary element with the given Text.Type. * * @param type The type of text used in the summary (plain text, HTML, XHTML) * @return A newly created atom:summary element */ Text newSummary(Text.Type type); /** * Create a new summary element with the given Text.Type as a child of the given Element. * * @param type The type of text used in the summary (plain text, HTML, XHTML) * @param parent The element to which the new Summary element should be added as a child * @return A newly created atom:summary element */ Text newSummary(Text.Type type, Element parent); /** * Create a new rights element. * * @return A newly created atom:rights element */ Text newRights(); /** * Create a new rights element as a child of the given Element. * * @param parent The element to which the new Rights element should be added as a child * @return A newly created atom:rights element */ Text newRights(Element parent); /** * Create a new rights element with the given Text.Type. * * @param type The type of text used in the Rights (plain text, HTML, XHTML) * @return A newly created atom:rights element */ Text newRights(Text.Type type); /** * Create a new rights element with the given Text.Type as a child of the given Element. * * @param type The type of text used in the Rights (plain text, HTML, XHTML) * @param parent The element to which the new Rights element should be added as a child * @return A newly created atom:rights element */ Text newRights(Text.Type type, Element parent); /** * Create a new name element. * * @return A newly created atom:name element */ Element newName(); /** * Create a new name element as a child of the given Element. * * @param parent The element to which the new Name element should be added as a child * @return A newly created atom:summary element */ Element newName(Element parent); /** * Create a new email element. * * @return A newly created atom:email element */ Element newEmail(); /** * Create a new email element as a child of the given Element. * * @param parent The element to which the new Email element should be added as a child * @return A newly created atom:email element */ Element newEmail(Element parent); /** * Create a new Element with the given QName. * * @return A newly created element */ <T extends Element> T newElement(QName qname); /** * Create a new Element with the given QName as a child of the given Base. * * @param qname The XML QName of the element to create * @param parent The element or document to which the new element should be added as a child * @return A newly created element */ <T extends Element> T newElement(QName qname, Base parent); /** * Create a new extension element with the given QName. * * @param qname The XML QName of the element to create * @return A newly created element */ <T extends Element> T newExtensionElement(QName qname); /** * Create a new extension element with the given QName as a child of the given Base. * * @param qname The XML QName of the element to create * @param parent The element or document to which the new element should be added as a child * @return A newly created element */ <T extends Element> T newExtensionElement(QName qname, Base parent); /** * Create a new Control element. The app:control element is introduced by the Atom Publishing Protocol as a means of * allowing publishing clients to provide metadata to a server affecting the way an entry is published. The control * element SHOULD only ever appear as a child of the atom:entry and MUST only ever appear once. * * @return A newly app:control element */ Control newControl(); /** * Create a new Control element as a child of the given Element. * * @param parent The element to which the new Control element should be added as a child * @return A newly app:control element */ Control newControl(Element parent); /** * Create a new Div element. * * @return A newly xhtml:div element */ Div newDiv(); /** * Create a new Div element as a child of the given Base. * * @param parent The element or document to which the new XHTML div element should be added as a child * @return A newly xhtml:div element */ Div newDiv(Base parent); /** * Registers an extension factory for this Factory instance only * * @param extensionFactory An ExtensionFactory instance */ Factory registerExtension(ExtensionFactory extensionFactory); /** * Create a new Categories element. The app:categories element is introduced by the Atom Publishing Protocol as a * means of providing a listing of atom:category's that can be used by entries in a collection. * * @return A newly app:categories element */ Categories newCategories(); /** * Create a new Categories element. The app:categories element is introduced by the Atom Publishing Protocol as a * means of providing a listing of atom:category's that can be used by entries in a collection. * * @param parent The element or document to which the new Categories element should be added as a child * @return A newly app:categories element */ Categories newCategories(Base parent); /** * Generate a new random UUID URI */ String newUuidUri(); /** * Get the Abdera instance for this factory */ Abdera getAbdera(); /** * Get the mime type for the specified extension element / document */ <T extends Base> String getMimeType(T base); /** * Returns a listing of extension factories registered */ String[] listExtensionFactories(); }
26,749
apache/abdera/core/src/main/java/org/apache/abdera/factory/StreamBuilder.java
package org.apache.abdera.factory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.nio.channels.WritableByteChannel; import java.util.Date; import java.util.Locale; import javax.activation.DataHandler; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.model.Base; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Content.Type; import org.apache.abdera.util.AbstractStreamWriter; /** * StreamBuilder is a special implementation of the StreamWriter interface that can be used to create Feed Object Model * instances using the StreamWriter interface. StreamBuilder provides an additional method (getBase) for returning the * FOM Base element that was built. The StreamWriter methods indent(), flush(), close(), setWriter(), setInputStream, * setAutoclose(), setAutoflush(), setAutoIndent(), and setChannel() have no effect on this StreamWriter implementation * * <pre> * StreamBuilder sw = new StreamBuilder(); * Entry entry = * sw.startElement(Constants.ENTRY).writeBase(&quot;http://example.org&quot;).writeLanguage(&quot;en-US&quot;) * .writeId(&quot;http://example.org&quot;).writeTitle(&quot;testing&quot;).writeUpdated(new Date()).endElement().getBase(); * entry.writeTo(System.out); * </pre> */ @SuppressWarnings("unchecked") public class StreamBuilder extends AbstractStreamWriter { private final Abdera abdera; private Base root = null; private Base current = null; public StreamBuilder() { this(Abdera.getInstance()); } public StreamBuilder(Abdera abdera) { super(abdera, "fom"); this.abdera = abdera; } public <T extends Base> T getBase() { return (T)root; } public StreamBuilder startDocument(String xmlversion, String charset) { if (root != null) throw new IllegalStateException("Document already started"); root = abdera.getFactory().newDocument(); ((Document)root).setCharset(charset); current = root; return this; } public StreamBuilder startDocument(String xmlversion) { return startDocument(xmlversion, "UTF-8"); } private static QName getQName(String name, String namespace, String prefix) { if (prefix != null) return new QName(namespace, name, prefix); else if (namespace != null) return new QName(namespace, name); else return new QName(name); } public StreamBuilder startElement(String name, String namespace, String prefix) { current = abdera.getFactory().newElement(getQName(name, namespace, prefix), current); if (root == null) root = current; return this; } public StreamBuilder endElement() { current = current instanceof Element ? ((Element)current).getParentElement() : null; return this; } public StreamBuilder writeAttribute(String name, String namespace, String prefix, String value) { if (!(current instanceof Element)) throw new IllegalStateException("Not currently an element"); ((Element)current).setAttributeValue(getQName(name, namespace, prefix), value); return this; } public StreamBuilder writeComment(String value) { current.addComment(value); return this; } public StreamBuilder writeElementText(String value) { if (!(current instanceof Element)) throw new IllegalStateException("Not currently an element"); Element element = (Element)current; String text = element.getText(); element.setText(text + value); return this; } public StreamBuilder writeId() { return writeId(abdera.getFactory().newUuidUri()); } public StreamBuilder writePI(String value) { return writePI(value, null); } public StreamBuilder writePI(String value, String target) { if (!(current instanceof Document)) throw new IllegalStateException("Not currently a document"); ((Document)current).addProcessingInstruction(target != null ? target : "", value); return this; } public void close() throws IOException { } public StreamBuilder flush() { // non-op return this; } public StreamBuilder indent() { // non-op return this; } public StreamBuilder setOutputStream(OutputStream out) { // non-op return this; } public StreamBuilder setOutputStream(OutputStream out, String charset) { // non-op return this; } public StreamBuilder setWriter(Writer writer) { // non-op return this; } public StreamBuilder endAuthor() { return (StreamBuilder)super.endAuthor(); } public StreamBuilder endCategories() { return (StreamBuilder)super.endCategories(); } public StreamBuilder endCategory() { return (StreamBuilder)super.endCategory(); } public StreamBuilder endCollection() { return (StreamBuilder)super.endCollection(); } public StreamBuilder endContent() { return (StreamBuilder)super.endContent(); } public StreamBuilder endContributor() { return (StreamBuilder)super.endContributor(); } public StreamBuilder endControl() { return (StreamBuilder)super.endControl(); } public StreamBuilder endDocument() { return (StreamBuilder)super.endDocument(); } public StreamBuilder endEntry() { return (StreamBuilder)super.endEntry(); } public StreamBuilder endFeed() { return (StreamBuilder)super.endFeed(); } public StreamBuilder endGenerator() { return (StreamBuilder)super.endGenerator(); } public StreamBuilder endLink() { return (StreamBuilder)super.endLink(); } public StreamBuilder endPerson() { return (StreamBuilder)super.endPerson(); } public StreamBuilder endService() { return (StreamBuilder)super.endService(); } public StreamBuilder endSource() { return (StreamBuilder)super.endSource(); } public StreamBuilder endText() { return (StreamBuilder)super.endText(); } public StreamBuilder endWorkspace() { return (StreamBuilder)super.endWorkspace(); } public StreamBuilder setAutoclose(boolean auto) { return (StreamBuilder)super.setAutoclose(auto); } public StreamBuilder setAutoflush(boolean auto) { return (StreamBuilder)super.setAutoflush(auto); } public StreamBuilder setAutoIndent(boolean indent) { return (StreamBuilder)super.setAutoIndent(indent); } public StreamBuilder setChannel(WritableByteChannel channel, String charset) { return (StreamBuilder)super.setChannel(channel, charset); } public StreamBuilder setChannel(WritableByteChannel channel) { return (StreamBuilder)super.setChannel(channel); } public StreamBuilder startAuthor() { return (StreamBuilder)super.startAuthor(); } public StreamBuilder startCategories() { return (StreamBuilder)super.startCategories(); } public StreamBuilder startCategories(boolean fixed, String scheme) { return (StreamBuilder)super.startCategories(fixed, scheme); } public StreamBuilder startCategories(boolean fixed) { return (StreamBuilder)super.startCategories(fixed); } public StreamBuilder startCategory(String term, String scheme, String label) { return (StreamBuilder)super.startCategory(term, scheme, label); } public StreamBuilder startCategory(String term, String scheme) { return (StreamBuilder)super.startCategory(term, scheme); } public StreamBuilder startCategory(String term) { return (StreamBuilder)super.startCategory(term); } public StreamBuilder startCollection(String href) { return (StreamBuilder)super.startCollection(href); } public StreamBuilder startContent(String type, String src) { return (StreamBuilder)super.startContent(type, src); } public StreamBuilder startContent(String type) { return (StreamBuilder)super.startContent(type); } public StreamBuilder startContent(Type type, String src) { return (StreamBuilder)super.startContent(type, src); } public StreamBuilder startContent(Type type) { return (StreamBuilder)super.startContent(type); } public StreamBuilder startContributor() { return (StreamBuilder)super.startContributor(); } public StreamBuilder startControl() { return (StreamBuilder)super.startControl(); } public StreamBuilder startDocument() { return (StreamBuilder)super.startDocument(); } public StreamBuilder startElement(QName qname) { return (StreamBuilder)super.startElement(qname); } public StreamBuilder startElement(String name, String namespace) { return (StreamBuilder)super.startElement(name, namespace); } public StreamBuilder startElement(String name) { return (StreamBuilder)super.startElement(name); } public StreamBuilder startEntry() { return (StreamBuilder)super.startEntry(); } public StreamBuilder startFeed() { return (StreamBuilder)super.startFeed(); } public StreamBuilder startGenerator(String version, String uri) { return (StreamBuilder)super.startGenerator(version, uri); } public StreamBuilder startLink(String iri, String rel, String type, String title, String hreflang, long length) { return (StreamBuilder)super.startLink(iri, rel, type, title, hreflang, length); } public StreamBuilder startLink(String iri, String rel, String type) { return (StreamBuilder)super.startLink(iri, rel, type); } public StreamBuilder startLink(String iri, String rel) { return (StreamBuilder)super.startLink(iri, rel); } public StreamBuilder startLink(String iri) { return (StreamBuilder)super.startLink(iri); } public StreamBuilder startPerson(QName qname) { return (StreamBuilder)super.startPerson(qname); } public StreamBuilder startPerson(String name, String namespace, String prefix) { return (StreamBuilder)super.startPerson(name, namespace, prefix); } public StreamBuilder startPerson(String name, String namespace) { return (StreamBuilder)super.startPerson(name, namespace); } public StreamBuilder startPerson(String name) { return (StreamBuilder)super.startPerson(name); } public StreamBuilder startService() { return (StreamBuilder)super.startService(); } public StreamBuilder startSource() { return (StreamBuilder)super.startSource(); } public StreamBuilder startText(QName qname, org.apache.abdera.model.Text.Type type) { return (StreamBuilder)super.startText(qname, type); } public StreamBuilder startText(String name, String namespace, String prefix, org.apache.abdera.model.Text.Type type) { return (StreamBuilder)super.startText(name, namespace, prefix, type); } public StreamBuilder startText(String name, String namespace, org.apache.abdera.model.Text.Type type) { return (StreamBuilder)super.startText(name, namespace, type); } public StreamBuilder startText(String name, org.apache.abdera.model.Text.Type type) { return (StreamBuilder)super.startText(name, type); } public StreamBuilder startWorkspace() { return (StreamBuilder)super.startWorkspace(); } public StreamBuilder writeAccepts(String... accepts) { return (StreamBuilder)super.writeAccepts(accepts); } public StreamBuilder writeAcceptsEntry() { return (StreamBuilder)super.writeAcceptsEntry(); } public StreamBuilder writeAcceptsNothing() { return (StreamBuilder)super.writeAcceptsNothing(); } public StreamBuilder writeAttribute(QName qname, Date value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(QName qname, double value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(QName qname, int value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(QName qname, long value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(QName qname, String value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(String name, Date value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAttribute(String name, double value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAttribute(String name, int value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAttribute(String name, long value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAttribute(String name, String namespace, Date value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String namespace, double value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String namespace, int value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String namespace, long value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String namespace, String prefix, Date value) { return (StreamBuilder)super.writeAttribute(name, namespace, prefix, value); } public StreamBuilder writeAttribute(String name, String namespace, String prefix, double value) { return (StreamBuilder)super.writeAttribute(name, namespace, prefix, value); } public StreamBuilder writeAttribute(String name, String namespace, String prefix, int value) { return (StreamBuilder)super.writeAttribute(name, namespace, prefix, value); } public StreamBuilder writeAttribute(String name, String namespace, String prefix, long value) { return (StreamBuilder)super.writeAttribute(name, namespace, prefix, value); } public StreamBuilder writeAttribute(String name, String namespace, String value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAuthor(String name, String email, String uri) { return (StreamBuilder)super.writeAuthor(name, email, uri); } public StreamBuilder writeAuthor(String name) { return (StreamBuilder)super.writeAuthor(name); } public StreamBuilder writeBase(IRI iri) { return (StreamBuilder)super.writeBase(iri); } public StreamBuilder writeBase(String iri) { return (StreamBuilder)super.writeBase(iri); } public StreamBuilder writeCategory(String term, String scheme, String label) { return (StreamBuilder)super.writeCategory(term, scheme, label); } public StreamBuilder writeCategory(String term, String scheme) { return (StreamBuilder)super.writeCategory(term, scheme); } public StreamBuilder writeCategory(String term) { return (StreamBuilder)super.writeCategory(term); } public StreamBuilder writeContent(String type, String value) { return (StreamBuilder)super.writeContent(type, value); } public StreamBuilder writeContent(Type type, DataHandler value) throws IOException { return (StreamBuilder)super.writeContent(type, value); } public StreamBuilder writeContent(Type type, InputStream value) throws IOException { return (StreamBuilder)super.writeContent(type, value); } public StreamBuilder writeContent(Type type, String value) { return (StreamBuilder)super.writeContent(type, value); } public StreamBuilder writeContributor(String name, String email, String uri) { return (StreamBuilder)super.writeContributor(name, email, uri); } public StreamBuilder writeContributor(String name) { return (StreamBuilder)super.writeContributor(name); } public StreamBuilder writeDate(QName qname, Date date) { return (StreamBuilder)super.writeDate(qname, date); } public StreamBuilder writeDate(QName qname, String date) { return (StreamBuilder)super.writeDate(qname, date); } public StreamBuilder writeDate(String name, Date date) { return (StreamBuilder)super.writeDate(name, date); } public StreamBuilder writeDate(String name, String namespace, Date date) { return (StreamBuilder)super.writeDate(name, namespace, date); } public StreamBuilder writeDate(String name, String namespace, String prefix, Date date) { return (StreamBuilder)super.writeDate(name, namespace, prefix, date); } public StreamBuilder writeDate(String name, String namespace, String prefix, String date) { return (StreamBuilder)super.writeDate(name, namespace, prefix, date); } public StreamBuilder writeDate(String name, String namespace, String date) { return (StreamBuilder)super.writeDate(name, namespace, date); } public StreamBuilder writeDate(String name, String date) { return (StreamBuilder)super.writeDate(name, date); } public StreamBuilder writeDraft(boolean draft) { return (StreamBuilder)super.writeDraft(draft); } public StreamBuilder writeEdited(Date date) { return (StreamBuilder)super.writeEdited(date); } public StreamBuilder writeEdited(String date) { return (StreamBuilder)super.writeEdited(date); } public StreamBuilder writeElementText(DataHandler value) throws IOException { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(Date value) { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(double value) { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(InputStream value) throws IOException { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(int value) { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(long value) { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(String format, Object... args) { return (StreamBuilder)super.writeElementText(format, args); } public StreamBuilder writeGenerator(String version, String uri, String value) { return (StreamBuilder)super.writeGenerator(version, uri, value); } public StreamBuilder writeIcon(IRI iri) { return (StreamBuilder)super.writeIcon(iri); } public StreamBuilder writeIcon(String iri) { return (StreamBuilder)super.writeIcon(iri); } public StreamBuilder writeId(IRI iri) { return (StreamBuilder)super.writeId(iri); } public StreamBuilder writeId(String iri) { return (StreamBuilder)super.writeId(iri); } public StreamBuilder writeIRIElement(QName qname, IRI iri) { return (StreamBuilder)super.writeIRIElement(qname, iri); } public StreamBuilder writeIRIElement(QName qname, String iri) { return (StreamBuilder)super.writeIRIElement(qname, iri); } public StreamBuilder writeIRIElement(String name, IRI iri) { return (StreamBuilder)super.writeIRIElement(name, iri); } public StreamBuilder writeIRIElement(String name, String namespace, IRI iri) { return (StreamBuilder)super.writeIRIElement(name, namespace, iri); } public StreamBuilder writeIRIElement(String name, String namespace, String prefix, IRI iri) { return (StreamBuilder)super.writeIRIElement(name, namespace, prefix, iri); } public StreamBuilder writeIRIElement(String name, String namespace, String prefix, String iri) { return (StreamBuilder)super.writeIRIElement(name, namespace, prefix, iri); } public StreamBuilder writeIRIElement(String name, String namespace, String iri) { return (StreamBuilder)super.writeIRIElement(name, namespace, iri); } public StreamBuilder writeIRIElement(String name, String iri) { return (StreamBuilder)super.writeIRIElement(name, iri); } public StreamBuilder writeLanguage(Lang lang) { return (StreamBuilder)super.writeLanguage(lang); } public StreamBuilder writeLanguage(Locale locale) { return (StreamBuilder)super.writeLanguage(locale); } public StreamBuilder writeLanguage(String lang) { return (StreamBuilder)super.writeLanguage(lang); } public StreamBuilder writeLink(String iri, String rel, String type, String title, String hreflang, long length) { return (StreamBuilder)super.writeLink(iri, rel, type, title, hreflang, length); } public StreamBuilder writeLink(String iri, String rel, String type) { return (StreamBuilder)super.writeLink(iri, rel, type); } public StreamBuilder writeLink(String iri, String rel) { return (StreamBuilder)super.writeLink(iri, rel); } public StreamBuilder writeLink(String iri) { return (StreamBuilder)super.writeLink(iri); } public StreamBuilder writeLogo(IRI iri) { return (StreamBuilder)super.writeLogo(iri); } public StreamBuilder writeLogo(String iri) { return (StreamBuilder)super.writeLogo(iri); } public StreamBuilder writePerson(QName qname, String name, String email, String uri) { return (StreamBuilder)super.writePerson(qname, name, email, uri); } public StreamBuilder writePerson(String localname, String namespace, String prefix, String name, String email, String uri) { return (StreamBuilder)super.writePerson(localname, namespace, prefix, name, email, uri); } public StreamBuilder writePerson(String localname, String namespace, String name, String email, String uri) { return (StreamBuilder)super.writePerson(localname, namespace, name, email, uri); } public StreamBuilder writePerson(String localname, String name, String email, String uri) { return (StreamBuilder)super.writePerson(localname, name, email, uri); } public StreamBuilder writePersonEmail(String email) { return (StreamBuilder)super.writePersonEmail(email); } public StreamBuilder writePersonName(String name) { return (StreamBuilder)super.writePersonName(name); } public StreamBuilder writePersonUri(String uri) { return (StreamBuilder)super.writePersonUri(uri); } public StreamBuilder writePublished(Date date) { return (StreamBuilder)super.writePublished(date); } public StreamBuilder writePublished(String date) { return (StreamBuilder)super.writePublished(date); } public StreamBuilder writeRights(String value) { return (StreamBuilder)super.writeRights(value); } public StreamBuilder writeRights(org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeRights(type, value); } public StreamBuilder writeSubtitle(String value) { return (StreamBuilder)super.writeSubtitle(value); } public StreamBuilder writeSubtitle(org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeSubtitle(type, value); } public StreamBuilder writeSummary(String value) { return (StreamBuilder)super.writeSummary(value); } public StreamBuilder writeSummary(org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeSummary(type, value); } public StreamBuilder writeText(QName qname, org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeText(qname, type, value); } public StreamBuilder writeText(String name, String namespace, String prefix, org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeText(name, namespace, prefix, type, value); } public StreamBuilder writeText(String name, String namespace, org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeText(name, namespace, type, value); } public StreamBuilder writeText(String name, org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeText(name, type, value); } public StreamBuilder writeTitle(String value) { return (StreamBuilder)super.writeTitle(value); } public StreamBuilder writeTitle(org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeTitle(type, value); } public StreamBuilder writeUpdated(Date date) { return (StreamBuilder)super.writeUpdated(date); } public StreamBuilder writeUpdated(String date) { return (StreamBuilder)super.writeUpdated(date); } public StreamBuilder setPrefix(String prefix, String uri) { if (!(current instanceof Element)) throw new IllegalStateException("Not currently an element"); ((Element)current).declareNS(uri, prefix); return this; } public StreamBuilder writeNamespace(String prefix, String uri) { return setPrefix(prefix, uri); } }
687
apache/abdera/core/src/main/java/org/apache/abdera/filter/ListParseFilter.java
package org.apache.abdera.filter; import javax.xml.namespace.QName; /** * A ParseFilter that is based on an internal collection of QName's. */ public interface ListParseFilter extends ParseFilter { /** * Add an element QName to the parse filter */ ListParseFilter add(QName qname); /** * Returns true if the given qname has been added to the filter */ boolean contains(QName qname); /** * Adds an attribute to the parse filter */ ListParseFilter add(QName parent, QName attribute); /** * Returns true if the given attribute has been added to the filter */ boolean contains(QName qname, QName attribute); }
1,502
apache/abdera/core/src/main/java/org/apache/abdera/filter/ParseFilter.java
package org.apache.abdera.filter; import java.io.Serializable; import javax.xml.namespace.QName; /** * ParseFilter's determine which elements and attributes are acceptable within a parsed document. They are set via the * ParserOptions.setParseFilter method. */ public interface ParseFilter extends Cloneable, Serializable { /** * Clone this ParseFilter */ Object clone() throws CloneNotSupportedException; /** * Returns true if elements with the given QName are acceptable */ boolean acceptable(QName qname); /** * Returns true if attributes with the given qname appearing on elements with the given qname are acceptable */ boolean acceptable(QName qname, QName attribute); /** * Return true if the parser should ignore comments */ boolean getIgnoreComments(); /** * Return true if the parser should ignore insignificant whitespace */ boolean getIgnoreWhitespace(); /** * Return true if the parser should ignore processing instructions */ boolean getIgnoreProcessingInstructions(); /** * True if the parser should ignore comments */ ParseFilter setIgnoreComments(boolean ignore); /** * True if the parser should ignore insignificant whitespace */ ParseFilter setIgnoreWhitespace(boolean ignore); /** * True if the parser should ignore processing instructions */ ParseFilter setIgnoreProcessingInstructions(boolean ignore); }
10,401
apache/abdera/core/src/main/java/org/apache/abdera/model/AtomDate.java
package org.apache.abdera.model; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * Provides an implementation of the Atom Date Construct, which is itself a specialization of the RFC3339 date-time. * </p> * <p> * Accessors on this class are not synchronized. * </p> * <p> * Per RFC4287: * </p> * * <pre> * 3.3. Date Constructs * * A Date construct is an element whose content MUST conform to the * "date-time" production in [RFC3339]. In addition, an uppercase "T" * character MUST be used to separate date and time, and an uppercase * "Z" character MUST be present in the absence of a numeric time zone * offset. * * atomDateConstruct = * atomCommonAttributes, * xsd:dateTime * * Such date values happen to be compatible with the following * specifications: [ISO.8601.1988], [W3C.NOTE-datetime-19980827], and * [W3C.REC-xmlschema-2-20041028]. * * Example Date constructs: * * &lt;updated>2003-12-13T18:30:02Z&lt;/updated> * &lt;updated>2003-12-13T18:30:02.25Z&lt;/updated> * &lt;updated>2003-12-13T18:30:02+01:00&lt;/updated> * &lt;updated>2003-12-13T18:30:02.25+01:00&lt;/updated> * * Date values SHOULD be as accurate as possible. For example, it would * be generally inappropriate for a publishing system to apply the same * timestamp to several entries that were published during the course of * a single day. * </pre> */ public final class AtomDate implements Cloneable, Serializable { private static final long serialVersionUID = -7062139688635877771L; private Date value; /** * Create an AtomDate using the current date and time */ public AtomDate() { this(new Date()); } /** * Create an AtomDate using the serialized string format (e.g. 2003-12-13T18:30:02Z). * * @param value The serialized RFC3339 date/time value */ public AtomDate(String value) { this(parse(value)); } /** * Create an AtomDate using a java.util.Date * * @param value The java.util.Date value * @throws NullPointerException if {@code date} is {@code null} */ public AtomDate(Date value) { this.value = (Date)value.clone(); } /** * Create an AtomDate using a java.util.Calendar. * * @param value The java.util.Calendar value * @throws NullPointerException if {@code value} is {@code null} */ public AtomDate(Calendar value) { this(value.getTime()); } /** * Create an AtomDate using the number of milliseconds since January 1, 1970, 00:00:00 GMT * * @param value The number of milliseconds since January 1, 1970, 00:00:00 GMT */ public AtomDate(long value) { this(new Date(value)); } /** * Return the serialized string form of the Atom date * * @return the serialized string form of the date as specified by RFC4287 */ public String getValue() { return format(value); } /** * Sets the value of the Atom date using the serialized string form * * @param value The serialized string form of the date */ public AtomDate setValue(String value) { this.value = parse(value); return this; } /** * Sets the value of the Atom date using java.util.Date * * @param date A java.util.Date * @throws NullPointerException if {@code date} is {@code null} */ public AtomDate setValue(Date date) { this.value = (Date)date.clone(); return this; } /** * Sets the value of the Atom date using java.util.Calendar * * @param calendar a java.util.Calendar */ public AtomDate setValue(Calendar calendar) { this.value = calendar.getTime(); return this; } /** * Sets the value of the Atom date using the number of milliseconds since January 1, 1970, 00:00:00 GMT * * @param timestamp The number of milliseconds since January 1, 1970, 00:00:00 GMT */ public AtomDate setValue(long timestamp) { this.value = new Date(timestamp); return this; } /** * Returns the value of this Atom Date * * @return A java.util.Date representing this Atom Date */ public Date getDate() { return (Date)value.clone(); } /** * Returns the value of this Atom Date as a java.util.Calendar * * @return A java.util.Calendar representing this Atom Date */ public Calendar getCalendar() { Calendar cal = Calendar.getInstance(); cal.setTime(value); return cal; } /** * Returns the value of this Atom Date as the number of milliseconds since January 1, 1970, 00:00:00 GMT * * @return The number of milliseconds since January 1, 1970, 00:00:00 GMT */ public long getTime() { return value.getTime(); } @Override public String toString() { return getValue(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + value.hashCode(); return result; } @Override public boolean equals(Object obj) { boolean answer = false; if (obj instanceof Date) { Date d = (Date)obj; answer = (this.value.equals(d)); } else if (obj instanceof String) { Date d = parse((String)obj); answer = (this.value.equals(d)); } else if (obj instanceof Calendar) { Calendar c = (Calendar)obj; answer = (this.value.equals(c.getTime())); } else if (obj instanceof AtomDate) { Date d = ((AtomDate)obj).value; answer = (this.value.equals(d)); } return answer; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } private static final Pattern PATTERN = Pattern .compile("(\\d{4})(?:-(\\d{2}))?(?:-(\\d{2}))?(?:([Tt])?(?:(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(?:\\.(\\d{3}))?)?([Zz])?(?:([+-])(\\d{2}):(\\d{2}))?"); /** * Parse the serialized string form into a java.util.Date * * @param date The serialized string form of the date * @return The created java.util.Date */ public static Date parse(String date) { Matcher m = PATTERN.matcher(date); if (m.find()) { if (m.group(4) == null) throw new IllegalArgumentException("Invalid Date Format"); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); int hoff = 0, moff = 0, doff = -1; if (m.group(10) != null) { doff = m.group(10).equals("-") ? 1 : -1; hoff = doff * (m.group(11) != null ? Integer.parseInt(m.group(11)) : 0); moff = doff * (m.group(12) != null ? Integer.parseInt(m.group(12)) : 0); } c.set(Calendar.YEAR, Integer.parseInt(m.group(1))); c.set(Calendar.MONTH, m.group(2) != null ? Integer.parseInt(m.group(2)) - 1 : 0); c.set(Calendar.DATE, m.group(3) != null ? Integer.parseInt(m.group(3)) : 1); c.set(Calendar.HOUR_OF_DAY, m.group(5) != null ? Integer.parseInt(m.group(5)) + hoff : 0); c.set(Calendar.MINUTE, m.group(6) != null ? Integer.parseInt(m.group(6)) + moff : 0); c.set(Calendar.SECOND, m.group(7) != null ? Integer.parseInt(m.group(7)) : 0); c.set(Calendar.MILLISECOND, m.group(8) != null ? Integer.parseInt(m.group(8)) : 0); return c.getTime(); } else { throw new IllegalArgumentException("Invalid Date Format"); } } /** * Create the serialized string form from a java.util.Date * * @param d A java.util.Date * @return The serialized string form of the date */ public static String format(Date date) { StringBuilder sb = new StringBuilder(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.setTime(date); sb.append(c.get(Calendar.YEAR)); sb.append('-'); int f = c.get(Calendar.MONTH); if (f < 9) sb.append('0'); sb.append(f + 1); sb.append('-'); f = c.get(Calendar.DATE); if (f < 10) sb.append('0'); sb.append(f); sb.append('T'); f = c.get(Calendar.HOUR_OF_DAY); if (f < 10) sb.append('0'); sb.append(f); sb.append(':'); f = c.get(Calendar.MINUTE); if (f < 10) sb.append('0'); sb.append(f); sb.append(':'); f = c.get(Calendar.SECOND); if (f < 10) sb.append('0'); sb.append(f); sb.append('.'); f = c.get(Calendar.MILLISECOND); if (f < 100) sb.append('0'); if (f < 10) sb.append('0'); sb.append(f); sb.append('Z'); return sb.toString(); } /** * Create a new Atom Date instance from the serialized string form * * @param value The serialized string form of the date * @return The created AtomDate */ public static AtomDate valueOf(String value) { return new AtomDate(value); } /** * Create a new Atom Date instance from a java.util.Date * * @param value a java.util.Date * @return The created AtomDate */ public static AtomDate valueOf(Date value) { return new AtomDate(value); } /** * Create a new Atom Date instance from a java.util.Calendar * * @param value A java.util.Calendar * @return The created AtomDate */ public static AtomDate valueOf(Calendar value) { return new AtomDate(value); } /** * Create a new Atom Date instance using the number of milliseconds since January 1, 1970, 00:00:00 GMT * * @param value The number of milliseconds since January 1, 1970, 00:00:00 GMT * @return The created AtomDate */ public static AtomDate valueOf(long value) { return new AtomDate(value); } }
781
apache/abdera/core/src/main/java/org/apache/abdera/model/Attribute.java
package org.apache.abdera.model; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; /** * An attribute. Returned by the Abdera XPath implementation when querying for Attribute nodes. */ public interface Attribute { /** * Get the QName of the attribute * * @return The attribute QName */ QName getQName(); /** * Return the text value of the attribute * * @return The attribute value */ String getText(); /** * Set the text value of the attribute. The value will be automatically escaped for proper serialization to XML * * @param text The attribute value */ Attribute setText(String text); /** * The Abdera Factory */ Factory getFactory(); }
5,075
apache/abdera/core/src/main/java/org/apache/abdera/model/Base.java
package org.apache.abdera.model; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import org.apache.abdera.factory.Factory; import org.apache.abdera.writer.WriterOptions; /** * The Base interface provides the basis for the Feed Object Model API and defines the operations common to both the * Element and Document interfaces. Classes implementing Base MUST NOT be assumed to be thread safe. Developers wishing * to allow multiple threads to perform concurrent modifications to a Base MUST provide their own synchronization. */ public interface Base extends Cloneable { /** * Get the default WriterOptions for this object */ WriterOptions getDefaultWriterOptions(); /** * Serializes the model component out to the specified stream * * @param out The target output stream * @param options The WriterOptions to use */ void writeTo(OutputStream out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified java.io.Writer * * @param out The target output writer * @param options The WriterOptions to use */ void writeTo(Writer out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified stream using the given Abdera writer * * @param writer The Abdera writer to use * @param out The target output stream */ void writeTo(org.apache.abdera.writer.Writer writer, OutputStream out) throws IOException; /** * Serializes the model component out to the specified java.io.Writer using the given Abdera writer * * @param writer The Abdera writer to use * @param out The target output writer */ void writeTo(org.apache.abdera.writer.Writer writer, Writer out) throws IOException; /** * Serializes the model component out to the specified stream using the given Abdera writer * * @param writer The Abdera writer to use * @param out The target output stream */ void writeTo(String writer, OutputStream out) throws IOException; /** * Serializes the model component out to the specified java.io.Writer using the given Abdera writer * * @param writer The Abdera writer to use * @param out The target output writer */ void writeTo(String writer, Writer out) throws IOException; /** * Serializes the model component out to the specified stream using the given abdera writer * * @param writer The Abdera writer to use * @param out The target output stream * @param options The WriterOptions to use */ void writeTo(org.apache.abdera.writer.Writer writer, OutputStream out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified java.io.Writer using the given abdera writer * * @param writer The Abdera writer to use * @param out The target output writer * @param options The WriterOptions to use */ void writeTo(org.apache.abdera.writer.Writer writer, Writer out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified stream using the given abdera writer * * @param writer The name of the Abdera writer to use * @param out The target output stream * @param options The WriterOptions to use */ void writeTo(String writer, OutputStream out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified java.io.Writer using the given abdera writer * * @param writer The name of the Abdera writer to use * @param out The target output writer * @param options The WriterOptions to use */ void writeTo(String writer, Writer out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified stream * * @param out The java.io.OutputStream to use when serializing the Base. The charset encoding specified for the * document will be used */ void writeTo(OutputStream out) throws IOException; /** * Serializes the model component out to the specified writer * * @param writer The java.io.Writer to use when serializing the Base */ void writeTo(Writer writer) throws IOException; /** * Clone this Base */ Object clone(); /** * Get the Factory used to create this Base * * @return The Factory used to create this object */ Factory getFactory(); /** * Add an XML comment to this Base * * @param value The text value of the comment */ <T extends Base> T addComment(String value); /** * Ensure that the underlying streams are fully parsed. Calling complete on an Element does not necessarily mean * that the underlying stream is fully consumed, only that that particular element has been completely parsed. */ <T extends Base> T complete(); }
4,659
apache/abdera/core/src/main/java/org/apache/abdera/model/Categories.java
package org.apache.abdera.model; import java.util.List; import org.apache.abdera.i18n.iri.IRI; /** * The Atom Publishing Protocol introduces the notion of a "Category Document" and the app:categories element. These are * used to provide a listing of atom:category elements that may be used with the members of an Atom Publishing Protocol * collection. */ public interface Categories extends ExtensibleElement { /** * When contained within an app:collection element, the app:categories element can have an href attribute whose * value MUST point to an Atompub Categories Document. * * @return The href attribute value */ IRI getHref(); /** * Returns the value of the href attribute resolved against the in-scope Base URI * * @return The fully resolved href attribute value */ IRI getResolvedHref(); /** * Sets the value of the href attribute. * * @param href The location of an Atompub Categories Document */ Categories setHref(String href); /** * If an app:categories element is marked as fixed, then the set of atom:category elements is considered to be a * closed set. That is, Atom Publishing Protocol clients SHOULD only use the atom:category elements listed. The * default is false (fixed="no") * * @return True if the categories listing is fixed */ boolean isFixed(); /** * Sets whether or not this is a fixed listing of categories. If set to false, the fixed attribute will be removed * from the app:categories element. * * @param fixed True if the app:categories listing is fixed */ Categories setFixed(boolean fixed); /** * The app:categories element may specify a default scheme attribute for listed atom:category elements that do not * have their own scheme attribute. * * @return The scheme IRI */ IRI getScheme(); /** * Sets the default scheme for this listing of categories * * @param scheme The default scheme used for this listing of categories */ Categories setScheme(String scheme); /** * Lists the complete set of categories * * @return This app:categories listing of atom:category elements */ List<Category> getCategories(); /** * Lists the complete set of categories that use the specified scheme * * @param scheme The IRI of an atom:category scheme * @return A listing of atom:category elements that use the specified scheme */ List<Category> getCategories(String scheme); /** * Returns a copy of the complete set of categories with the scheme attribute set * * @return A listing of atom:category elements using the default scheme specified by the app:categories scheme * attribute */ List<Category> getCategoriesWithScheme(); /** * Returns a copy of the complete set of categories with the scheme attribute set as specified in 7.2.1. (child * categories that do not have a scheme attribute inherit the scheme attribute of the parent) * * @param scheme A scheme IRI * @return A listing of atom:category elements */ List<Category> getCategoriesWithScheme(String scheme); /** * Add an atom:category to the listing * * @param category The atom:category to add to the listing */ Categories addCategory(Category category); /** * Create and add an atom:category to the listing * * @param term The string term * @return The newly created atom:category */ Category addCategory(String term); /** * Create an add an atom:category to the listing * * @param scheme The scheme IRI for the newly created category * @param term The string term * @param label The human readable label for the category * @return The newly created atom:category */ Category addCategory(String scheme, String term, String label); /** * Returns true if this app:categories listing contains a category with the specified term * * @param term The term to look for * @return True if the term is found */ boolean contains(String term); /** * Returns true if this app:categories listing contains a category with the specified term and scheme * * @param term The term to look for * @param scheme The IRI scheme * @return True if the term and scheme are found */ boolean contains(String term, String scheme); /** * Returns true if the href attribute is set */ boolean isOutOfLine(); }
2,708
apache/abdera/core/src/main/java/org/apache/abdera/model/Category.java
package org.apache.abdera.model; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Provides categorization informaton for a feed or entry * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:category" element conveys information about a category * associated with an entry or feed. This specification assigns no * meaning to the content (if any) of this element. * * atomCategory = * element atom:category { * atomCommonAttributes, * attribute term { text }, * attribute scheme { atomUri }?, * attribute label { text }?, * undefinedContent * } * </pre> */ public interface Category extends ExtensibleElement { /** * RFC4287: The "term" attribute is a string that identifies the category to which the entry or feed belongs. * Category elements MUST have a "term" attribute. * * @return The string value of the term attribute */ String getTerm(); /** * RFC4287: The "term" attribute is a string that identifies the category to which the entry or feed belongs. * Category elements MUST have a "term" attribute. * * @param term The string value of the term attribute */ Category setTerm(String term); /** * RFC4287: The "scheme" attribute is an IRI that identifies a categorization scheme. Category elements MAY have a * "scheme" attribute. * * @return The IRI value of the scheme attribute */ IRI getScheme(); /** * RFC4287: The "scheme" attribute is an IRI that identifies a categorization scheme. Category elements MAY have a * "scheme" attribute. * * @param scheme The IRI of the scheme */ Category setScheme(String scheme); /** * RFC4287: The "label" attribute provides a human-readable label for display in end-user applications. The content * of the "label" attribute is Language-Sensitive. Entities such as "&amp;amp;" and "&amp;lt;" represent their * corresponding characters ("&amp;" and "&lt;", respectively), not markup. Category elements MAY have a "label" * attribute. * * @return The value of the human-readable label */ String getLabel(); /** * RFC4287: The "label" attribute provides a human-readable label for display in end-user applications. The content * of the "label" attribute is Language-Sensitive. Entities such as "&amp;amp;" and "&amp;lt;" represent their * corresponding characters ("&amp;" and "&lt;", respectively), not markup. Category elements MAY have a "label" * attribute. * * @param label The value of the human-readable label */ Category setLabel(String label); }
5,799
apache/abdera/core/src/main/java/org/apache/abdera/model/Collection.java
package org.apache.abdera.model; import java.util.List; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Represents an collection element in an Atom Publishing Protocol introspection document. * </p> * * <pre> * The "app:collection" describes an Atom Protocol collection. One * child element is defined here for app:collection: "app:member-type". * * appCollection = * element app:collection { * appCommonAttributes, * attribute href { text }, * ( atomTitle * &amp; appAccept * &amp; extensionElement* ) * } * </pre> */ public interface Collection extends ExtensibleElement { /** * The text value of the collections atom:title element * * @return The atom:title value */ String getTitle(); /** * Set the value of the collections atom:title element using type="text" * * @param title The value of the atom:title * @return The newly created title element */ Text setTitle(String title); /** * Set the value of the collections atom:title element using type="html". Special characters in the value will be * automatically escaped (e.g. & will become &amp; * * @param title The value of the atom:title * @return The newly created title element */ Text setTitleAsHtml(String title); /** * Set the value of the collections atom:title element using type="xhtml". The title text will be wrapped in a * xhtml:div and parsed to ensure that it is welformed XML. A ParseException (RuntimeException) could be thrown * * @param title The value of the atom:title * @return The newly created title element */ Text setTitleAsXHtml(String title); /** * Return the title element * * @return The title element */ Text getTitleElement(); /** * Return the value of the app:collection elements href attribute * * @return The href attribute IRI value * @throws IRISyntaxException if the value of the href attribute is malformed */ IRI getHref(); /** * Return the href attribute resolved against the in-scope Base URI * * @return The href attribute IRI value * @throws IRISyntaxException if the value of the href attribute is malformed */ IRI getResolvedHref(); /** * Set the value of the href attribute * * @param href The value of href attribute * @throws IRISyntaxException if the href attribute is malformed */ Collection setHref(String href); /** * Returns the listing of media-ranges allowed for this collection * * @return An array listing the media-ranges allowed for this collection */ String[] getAccept(); /** * Set the listing of media-ranges allowed for this collection. The special value "entry" is used to indicate Atom * Entry Documents. * * @param mediaRanges a listing of media-ranges * @throws MimeTypeParseException */ Collection setAccept(String... mediaRanges); /** * Returns true if the collection accepts the given media-type * * @param mediaType The media-type to check * @return True if the media-type is acceptable */ boolean accepts(String mediaType); /** * Returns true if the collection accepts Atom entry documents (equivalent to calling * accepts("application/atom+xml;type=entry");) */ boolean acceptsEntry(); /** * Returns true if the collection accepts nothing (i.e. there is an empty accept element) */ boolean acceptsNothing(); /** * Sets the appropriate accept element to indicate that entries are accepted (equivalent to calling * setAccept("application/atom+xml;type=entry");) */ Collection setAcceptsEntry(); /** * Sets the collection so that nothing is accepted (equivalent to calling setAccept(""); ) */ Collection setAcceptsNothing(); /** * Adds a new accept element to the collection */ Collection addAccepts(String mediaRange); /** * Adds new accept elements to the collection */ Collection addAccepts(String... mediaRanges); /** * Same as setAcceptsEntry except the existing accepts are not discarded */ Collection addAcceptsEntry(); /** * Returns true if the collection accepts the given media-type * * @param mediaType The media-type to check * @return True if the media-type is acceptable */ boolean accepts(MimeType mediaType); /** * Returns the app:categories element * * @return The app:categories element */ List<Categories> getCategories(); /** * Add an app:categories element * * @return The newly created app:categories element */ Categories addCategories(); /** * Add an app:categories element that links to an external Category Document * * @param href The IRI of the external Category Document * @return The newly created app:categories element */ Categories addCategories(String href); /** * Add the app:categories element to the collection * * @param categories The app:categories element */ Collection addCategories(Categories categories); /** * Add a listing of categories to the collection * * @param categories The listing of categories to add * @param fixed True if the listing of categories should be fixed * @param scheme The default IRI scheme for the categories listing * @return The newly created app:categories element */ Categories addCategories(List<Category> categories, boolean fixed, String scheme); }
833
apache/abdera/core/src/main/java/org/apache/abdera/model/Comment.java
package org.apache.abdera.model; import org.apache.abdera.factory.Factory; /** * A comment. Returned by the Abdera XPath implementation when querying for comment nodes (e.g. * xpath.selectNodes("//comment()"); ...). Most applications should never have much of a reason to use this interface. * It is provided primarily to avoid application from having to deal directly with the underlying parser implementation */ public interface Comment { /** * Delete the comment node */ void discard(); /** * The text of this comment node */ String getText(); /** * The text of this comment node */ Comment setText(String text); /** * The Abdera Factory */ Factory getFactory(); /** * The parent node */ <T extends Base> T getParentElement(); }
9,355
apache/abdera/core/src/main/java/org/apache/abdera/model/Content.java
package org.apache.abdera.model; import javax.activation.DataHandler; import javax.activation.MimeType; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Represents an atom:content element. * </p> * <p> * Atom has a very clearly defined and extremely flexible content model. The model allows for five basic types of * content: * </p> * <ul> * <li>Text, consisting of content that is to be interpreted as plain text with no markup. For instance, * <code>&lt;content type="text">&amp;lt;content&amp;gt;&lt;/content></code> is interpreted as literal characer "&lt;" * followed by the word "content", followed by the literal character "&gt;".</li> * <li>HTML, consisting of content that is to be interpreted as escaped HTML markup. For instance, * <code>&lt;content type="html">&amp;lt;b&amp;gt;content&amp;lt;/b&amp;gt;&lt;/content></code> is interpreted as the * word "content" surrounded by the HTML <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> tags.</li> * <li>XHTML, consisting of well-formed XHTML content wrapped in an XHTML div element. For instance, * <code>&lt;content type="xhtml">&lt;div xmlns="http://www.w3.org/1999/xhtml">&lt;b>Content&lt;/b>&lt;/div>&lt;/content></code> * .</li> * <li>XML, consisting of well-formed XML content. For instance, * <code>&lt;content type="application/xml">&lt;a xmlns="...">&lt;b>&lt;c/>&lt;/b>&lt;/a>&lt;/content></code>. The * content could, alternatively, be linked to via the src attribute, * <code>&lt;content type="application/xml" src="http://example.org/foo.xml"/></code>.</li> * <li>Media, consisting of content conforming to any MIME media type. * <ul> * <li>Text media types are encoded literally, e.g. * <code>&lt;content type="text/calendar">BEGIN:VCALENDAR...&lt;/content></code>.</li> * <li>Other media types are encoded as Base64 strings, e.g. * <code>&lt;content type="image/jpeg">{Base64}&lt;/content></code>.</li> * <li>Alternatively, media content may use the src attribute, * <code>&lt;content type="text/calendar" src="http://example.org/foo.cal"/></code>, * <code>&lt;content type="image/jpeg" src="http://example.org/foo.jpg" /></code></li> * </ul> * </li> * </ul> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:content" element either contains or links to the content of * the entry. The content of atom:content is Language-Sensitive. * * atomInlineTextContent = * element atom:content { * atomCommonAttributes, * attribute type { "text" | "html" }?, * (text)* * } * * atomInlineXHTMLContent = * element atom:content { * atomCommonAttributes, * attribute type { "xhtml" }, * xhtmlDiv * } * atomInlineOtherContent = * element atom:content { * atomCommonAttributes, * attribute type { atomMediaType }?, * (text|anyElement)* * } * * atomOutOfLineContent = * element atom:content { * atomCommonAttributes, * attribute type { atomMediaType }?, * attribute src { atomUri }, * empty * } * * atomContent = atomInlineTextContent * | atomInlineXHTMLContent * | atomInlineOtherContent * | atomOutOfLineContent * * </pre> */ public interface Content extends Element { /** * Used to identify the type of content */ public enum Type { /** Plain text **/ TEXT, /** Escaped HTML **/ HTML, /** Welformed XHTML **/ XHTML, /** Welformed XML **/ XML, /** Base64-encoded Binary **/ MEDIA; /** * Return an appropriate Type given the specified @type attribute value */ public static Type typeFromString(String val) { Type type = TEXT; if (val != null) { if (val.equalsIgnoreCase("text")) type = TEXT; else if (val.equalsIgnoreCase("html")) type = HTML; else if (val.equalsIgnoreCase("xhtml")) type = XHTML; else if (MimeTypeHelper.isXml(val)) type = XML; else { type = MimeTypeHelper.isMimeType(val) ? MEDIA : null; } } return type; } } /** * Returns the Content Type * * @return The Content Type */ Type getContentType(); /** * Set the Content Type * * @param type The Content Type */ Content setContentType(Type type); /** * Return the value element or null if type="text", type="html" or type is some non-XML media type * * @return The first child element of the atom:content element or null */ <T extends Element> T getValueElement(); /** * Set the value element of the content. If the value is a Div, the type attribute will be set to type="xhtml", * otherwise, the attribute will be set to type="application/xml" * * @param value The element to set */ <T extends Element> Content setValueElement(T value); /** * RFC4287: On the atom:content element, the value of the "type" attribute MAY be one of "text", "html", or "xhtml". * Failing that, it MUST conform to the syntax of a MIME media type, but MUST NOT be a composite type. If neither * the type attribute nor the src attribute is provided, Atom Processors MUST behave as though the type attribute * were present with a value of "text". * * @return null if type = text, html or xhtml, otherwise a media type */ MimeType getMimeType(); /** * RFC4287: On the atom:content element, the value of the "type" attribute MAY be one of "text", "html", or "xhtml". * Failing that, it MUST conform to the syntax of a MIME media type, but MUST NOT be a composite type. If neither * the type attribute nor the src attribute is provided, Atom Processors MUST behave as though the type attribute * were present with a value of "text". * * @param type The media type * @throws MimeTypeParseException if the media type is malformed */ Content setMimeType(String type); /** * <p> * RFC4287: atom:content MAY have a "src" attribute, whose value MUST be an IRI reference. If the "src" attribute is * present, atom:content MUST be empty. Atom Processors MAY use the IRI to retrieve the content and MAY choose to * ignore remote content or to present it in a different manner than local content. * </p> * <p> * If the "src" attribute is present, the "type" attribute SHOULD be provided and MUST be a MIME media type, rather * than "text", "html", or "xhtml". * </p> * * @return The IRI value of the src attribute or null if none * @throws IRISyntaxException if the src attribute value is malformed */ IRI getSrc(); /** * Returns the fully qualified URI form of the content src attribute. * * @return The IRI value of the src attribute resolved against the in-scope Base URI * @throws IRISyntaxException if the src attribute value is malformed */ IRI getResolvedSrc(); /** * <p> * RFC4287: atom:content MAY have a "src" attribute, whose value MUST be an IRI reference. If the "src" attribute is * present, atom:content MUST be empty. Atom Processors MAY use the IRI to retrieve the content and MAY choose to * ignore remote content or to present it in a different manner than local content. * </p> * <p> * If the "src" attribute is present, the "type" attribute SHOULD be provided and MUST be a MIME media type, rather * than "text", "html", or "xhtml". * </p> * * @param src The IRI to use as the src attribute value for the content * @throws IRISyntaxException if the src value is malformed */ Content setSrc(String src); /** * Attempts to Base64 decode the string value of the content element. * * @return A DataHandler or null * @throws UnsupportedOperationException if type = text, html, xhtml, or any application/*+xml, or text/* type */ DataHandler getDataHandler(); /** * Sets the string value of the content element by Base64 encoding the specifed byte array. * * @param dataHandler The DataHandler for the binary content requiring Base64 encoding * @throws UnsupportedOperationException if type = text, html, xhtml, or any application/*+xml, or text/* type */ Content setDataHandler(DataHandler dataHandler); /** * Returns the string value of this atom:content element * * @return The string value */ String getValue(); /** * Set the string value of the atom:content element * * @param value The string value */ Content setValue(String value); /** * Return the string value of the atom:content element with the enclosing div tag if type="xhtml" * * @return The div wrapped value */ String getWrappedValue(); /** * Set the string value of the atom:content with the enclosing div tag * * @param wrappedValue The string value with the wrapping div tag */ Content setWrappedValue(String wrappedValue); }
3,183
apache/abdera/core/src/main/java/org/apache/abdera/model/Control.java
package org.apache.abdera.model; /** * <p> * Represents an Atom Publishing Protocol <code>control</code> element. * </p> * <p> * The purpose of the control extension is to provide a means for content publishers to embed various * publishing-operation specific control parameters within the body of the entry. For instance, the client may wish to * mark the entry as a draft, or may wish to ask the publishing server to enable or disable specific extended features * for a given entry. * </p> * <p> * Per APP Draft-08: * </p> * * <pre> * pubControl = * element pub:control { * atomCommonAttributes, * pubDraft? * &amp; extensionElement * } * * pubDraft = * element pub:draft { "yes" | "no" } * * The "pub:control" element MAY appear as a child of an "atom:entry" * which is being created or updated via the Atom Publishing Protocol. * The "pub:control" element, if it does appear in an entry, MUST only * appear at most one time. The "pub:control" element is considered * foreign markup as defined in Section 6 of [RFC4287]. * * The "pub:control" element and its child elements MAY be included in * Atom Feed or Entry Documents. * * The "pub:control" element MAY contain exactly one "pub:draft" element * as defined here, and MAY contain zero or more extension elements as * outlined in Section 6 of [RFC4287]. Both clients and servers MUST * ignore foreign markup present in the pub:control element. * </pre> */ public interface Control extends ExtensibleElement { /** * <p> * Returns true if the entry should <i>not</i> be made publicly visible. * </p> * <p> * APP Draft-08: The number of "pub:draft" elements in "pub:control" MUST be zero or one. Its value MUST be one of * "yes" or "no". A value of "no" means that the entry MAY be made publicly visible. If the "pub:draft" element is * missing then the value MUST be understood to be "no". The pub:draft element MAY be ignored. * </p> * * @return True if this is a draft */ boolean isDraft(); /** * <p> * Set to "true" if the entry should <i>not</i> be made publicly visible. * </p> * <p> * APP Draft-08: The number of "pub:draft" elements in "pub:control" MUST be zero or one. Its value MUST be one of * "yes" or "no". A value of "no" means that the entry MAY be made publicly visible. If the "pub:draft" element is * missing then the value MUST be understood to be "no". The pub:draft element MAY be ignored. * </p> * * @param draft true if app:draft should be set to "yes" */ Control setDraft(boolean draft); /** * <p> * Removes the draft setting completely from the control element. * </p> * <p> * APP Draft-08: The number of "pub:draft" elements in "pub:control" MUST be zero or one. Its value MUST be one of * "yes" or "no". A value of "no" means that the entry MAY be made publicly visible. If the "pub:draft" element is * missing then the value MUST be understood to be "no". The pub:draft element MAY be ignored. * </p> */ Control unsetDraft(); }
2,062
apache/abdera/core/src/main/java/org/apache/abdera/model/DateTime.java
package org.apache.abdera.model; import java.util.Calendar; import java.util.Date; /** * <p> * An element conforming to the Atom Date Construct. The data type implementation for this element is provided by the * AtomDate class. * </p> */ public interface DateTime extends Element { /** * Returns the content value of the element as an AtomDate object * * @return The Atom Date value of this element */ AtomDate getValue(); /** * Returns the content value of the element as a java.util.Date object * * @return The java.util.Date value of this element */ Date getDate(); /** * Returns the content value of the element as a java.util.Calendar object * * @return The java.util.Calendar value of this element */ Calendar getCalendar(); /** * Returns the content value of the element as a long (equivalent to calling DateTimeElement().getDate().getTime() * * @return The number of milliseconds since January 1, 1970, 00:00:00 GMT */ long getTime(); /** * Returns the content value of the element as a string conforming to RFC-3339 * * @return The serialized string form of this element */ String getString(); /** * Sets the content value of the element * * @param dateTime the Atom Date value */ DateTime setValue(AtomDate dateTime); /** * Sets the content value of the element * * @param date The java.util.Date value */ DateTime setDate(Date date); /** * Sets the content value of the element * * @param date The java.util.Calendar value */ DateTime setCalendar(Calendar date); /** * Sets the content value of the element * * @param date the number of milliseconds since January 1, 1970, 00:00:00 GMT */ DateTime setTime(long date); /** * Sets the content value of the element * * @param date The serialized string value */ DateTime setString(String date); }
2,129
apache/abdera/core/src/main/java/org/apache/abdera/model/DateTimeWrapper.java
package org.apache.abdera.model; import java.util.Calendar; import java.util.Date; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; /** * An ElementWrapper implementation that can serve as the basis for Atom Date Construct based extensions. */ public abstract class DateTimeWrapper extends ElementWrapper implements DateTime { protected DateTimeWrapper(Element internal) { super(internal); } protected DateTimeWrapper(Factory factory, QName qname) { super(factory, qname); } public AtomDate getValue() { AtomDate value = null; String v = getText(); if (v != null) { value = AtomDate.valueOf(v); } return value; } public DateTime setValue(AtomDate dateTime) { if (dateTime != null) setText(dateTime.getValue()); else setText(""); return this; } public DateTime setDate(Date date) { if (date != null) setText(AtomDate.valueOf(date).getValue()); else setText(""); return this; } public DateTime setCalendar(Calendar date) { if (date != null) setText(AtomDate.valueOf(date).getValue()); else setText(""); return this; } public DateTime setTime(long date) { setText(AtomDate.valueOf(date).getValue()); return this; } public DateTime setString(String date) { if (date != null) setText(AtomDate.valueOf(date).getValue()); else setText(""); return this; } public Date getDate() { AtomDate ad = getValue(); return (ad != null) ? ad.getDate() : null; } public Calendar getCalendar() { AtomDate ad = getValue(); return (ad != null) ? ad.getCalendar() : null; } public long getTime() { AtomDate ad = getValue(); return (ad != null) ? ad.getTime() : null; } public String getString() { AtomDate ad = getValue(); return (ad != null) ? ad.getValue() : null; } }
1,389
apache/abdera/core/src/main/java/org/apache/abdera/model/Div.java
package org.apache.abdera.model; /** * <p> * Represents an XHTML div tag. * </p> */ public interface Div extends ExtensibleElement { /** * Returns the array of class attribute values on the div * * @return A listing of class attribute values */ String[] getXhtmlClass(); /** * Returns the value of the div element's id attribute * * @return The value of the id attribute */ String getId(); /** * Returns the value of the div element's title attribute * * @return The value of the title attribute */ String getTitle(); /** * Sets the value of the div element's id attribute * * @param id The value of the id attribute */ Div setId(String id); /** * Set the value of the div element's title attribute * * @param title The value of the title attribute */ Div setTitle(String title); /** * Sets the array of class attribute values on the div * * @param classes A listing of class attribute values */ Div setXhtmlClass(String[] classes); /** * Returns the value of the div element * * @return The value of the div element */ String getValue(); /** * Set the value of the div element * * @param value The text value */ void setValue(String value); }
4,459
apache/abdera/core/src/main/java/org/apache/abdera/model/Document.java
package org.apache.abdera.model; import java.io.Serializable; import java.util.Date; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.util.EntityTag; import org.apache.abdera.util.XmlUtil.XMLVersion; /** * <p> * The top level artifact of the Feed Object Model. The Parser component processes data from an InputStream and returns * a Document instance. The type of Document returned depends on the XML format being parsed. The Feed Object Model * supports four basic types of documents: FeedDocument, EntryDocument, ServiceDocument (Atom Publishing Protocol * Introspection Documents) and XmlDocument (any arbitrary XML). * </p> */ public interface Document<T extends Element> extends Base, Serializable { /** * Returns the root element of the document (equivalent to DOM's getDocumentElement) * * @return The root element of the document */ T getRoot(); /** * Sets the root element of the document * * @param root Set the root element of the document */ Document<T> setRoot(T root); /** * Returns the Base URI of the document. All relative URI's contained in the document will be resolved according to * this base. * * @return The Base IRI */ IRI getBaseUri(); /** * Sets the Base URI of the document. All relative URI's contained in the document will be resolved according to * this base. * * @param base The Base URI * @throws IRISyntaxException if the IRI is malformed */ Document<T> setBaseUri(String base); /** * Returns the content type of this document * * @return The content type of this document */ MimeType getContentType(); /** * Sets the content type for this document * * @param contentType The content type of document * @throws MimeTypeParseException if the content type is malformed */ Document<T> setContentType(String contentType); /** * Returns the last modified date for this document * * @return The last-modified date */ Date getLastModified(); /** * Sets the last modified date for this document * * @param lastModified the last-modified date */ Document<T> setLastModified(Date lastModified); /** * Gets the charset used for this document * * @return The character encoding used for this document */ String getCharset(); /** * Sets the charset used for this document * * @param charset The character encoding to use */ Document<T> setCharset(String charset); /** * Add a processing instruction to the document * * @param target The processing instruction target * @param value The processing instruction value */ Document<T> addProcessingInstruction(String target, String value); /** * Get the values for the given processing instruction */ String[] getProcessingInstruction(String target); /** * Add a xml-stylesheet processing instruction to the document * * @param href The href of the stylesheet * @param media The media target for this stylesheet or null if none */ Document<T> addStylesheet(String href, String media); /** * Return the entity tag for this document */ EntityTag getEntityTag(); /** * Set the entity tag for this document */ Document<T> setEntityTag(EntityTag tag); /** * Set the entity tag for this document */ Document<T> setEntityTag(String tag); /** * Get the language */ String getLanguage(); /** * Returns the value of the xml:lang attribute as a Lang object */ Lang getLanguageTag(); /** * set the base language */ Document<T> setLanguage(String lang); /** * Get the slug for this document */ String getSlug(); /** * Set the slug for this document */ Document<T> setSlug(String slug); /** * Return true if insignificant whitespace must be preserved */ boolean getMustPreserveWhitespace(); /** * Set to true to preserve insignificant whitespace */ Document<T> setMustPreserveWhitespace(boolean preserve); /** * Get the XMLVersion used by this document */ XMLVersion getXmlVersion(); }
6,722
apache/abdera/core/src/main/java/org/apache/abdera/model/Element.java
package org.apache.abdera.model; import java.util.List; import java.util.Locale; import java.util.Map; import javax.activation.DataHandler; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; import org.apache.abdera.i18n.rfc4646.Lang; /** * Root interface for all elements in the Feed Object Model */ public interface Element extends Base, Iterable<Element> { /** * Return this Element's parent element or document * * @return The parent */ <T extends Base> T getParentElement(); /** * @deprecated This method will cause corruption of the object model because the parent of an * element cannot be set without adding that element as a child. */ <T extends Element> T setParentElement(Element parent); /** * Get the element preceding this one * * @return The preceding sibling */ <T extends Element> T getPreviousSibling(); /** * Get the element following this one * * @return The following sibling */ <T extends Element> T getNextSibling(); /** * Get the first child element * * @return The first child */ <T extends Element> T getFirstChild(); /** * Get the first previous sibling with the specified QName * * @param qname The XML QName of the sibling to find * @return The matching element */ <T extends Element> T getPreviousSibling(QName qname); /** * Get the first following sibling with the specified QName * * @param qname The XML QName of the sibling to find * @return The matching element */ <T extends Element> T getNextSibling(QName qname); /** * Get the first child element with the given QName * * @param qname The XML QName of the sibling to find * @return The matching element */ <T extends Element> T getFirstChild(QName qname); /** * Return the XML QName of this element * * @return The QName of the element */ QName getQName(); /** * Returns the value of this elements <code>xml:lang</code> attribute or null if <code>xml:lang</code> is undefined. * * @return The xml:lang value */ String getLanguage(); /** * Returns the value of the xml:lang attribute as a Lang object */ Lang getLanguageTag(); /** * Returns a Locale object created from the <code>xml:lang</code> attribute * * @return A Locale appropriate for the Language (xml:lang) */ Locale getLocale(); /** * Sets the value of this elements <code>xml:lang</code> attribute. * * @param language the value of the xml:lang element */ <T extends Element> T setLanguage(String language); /** * Returns the value of this element's <code>xml:base</code> attribute or null if <code>xml:base</code> is * undefined. * * @return The Base URI * @throws IRISyntaxException if the Base URI is malformed */ IRI getBaseUri(); /** * Returns the current in-scope, fully qualified Base URI for this element. * * @throws IRISyntaxException if the Base URI is malformed */ IRI getResolvedBaseUri(); /** * Sets the value of this element's <code>xml:base</code> attribute. * * @param base The IRI base value */ <T extends Element> T setBaseUri(IRI base); /** * Sets the value of this element's <code>xml:base</code> attribute. * * @param base The Base IRI * @throws IRISyntaxException if the base URI is malformed */ <T extends Element> T setBaseUri(String base); /** * Returns the document to which this element belongs * * @return The Document to which this element belongs */ <T extends Element> Document<T> getDocument(); /** * Returns the value of the named attribute * * @param name The name of the attribute * @return The value of the attribute */ String getAttributeValue(String name); /** * Returns the value of the named attribute * * @param qname The XML QName of the attribute * @return The value of the attribute */ String getAttributeValue(QName qname); /** * Returns a listing of all attributes on this element * * @return The listing of attributes for this element */ List<QName> getAttributes(); /** * Returns a listing of extension attributes on this element (extension attributes are attributes whose namespace * URI is different than the elements) * * @return The listing non-Atom attributes */ List<QName> getExtensionAttributes(); /** * Remove the named Attribute * * @param qname The XML QName of the attribute to remove */ <T extends Element> T removeAttribute(QName qname); /** * Remove the named attribute * * @param name The name of the attribute to remove */ <T extends Element> T removeAttribute(String name); /** * Sets the value of the named attribute * * @param name The name of the attribute * @param value The value of the attribute */ <T extends Element> T setAttributeValue(String name, String value); /** * Sets the value of the named attribute * * @param qname The XML QName of the attribute * @param value The value of the attribute */ <T extends Element> T setAttributeValue(QName qname, String value); /** * Removes this element from its current document */ void discard(); /** * Returns the Text value of this element * * @return The text value */ String getText(); /** * Set the Text value of this element * * @param text The text value */ void setText(String text); /** * Set the Text value of this element using the data handler */ <T extends Element> T setText(DataHandler dataHandler); /** * Declare a namespace */ <T extends Element> T declareNS(String uri, String prefix); /** * Return a map listing the xml namespaces declared for this element */ Map<String, String> getNamespaces(); /** * Return a listing of this elements child elements */ <T extends Element> List<T> getElements(); /** * Return true if insignificant whitespace must be preserved */ boolean getMustPreserveWhitespace(); /** * Set to true to preserve insignificant whitespace */ <T extends Element> T setMustPreserveWhitespace(boolean preserve); }
7,719
apache/abdera/core/src/main/java/org/apache/abdera/model/ElementWrapper.java
package org.apache.abdera.model; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import javax.activation.DataHandler; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.writer.WriterOptions; /** * Base implementation used for static extensions. */ @SuppressWarnings("unchecked") public abstract class ElementWrapper implements Element { private Element internal; protected ElementWrapper(Element internal) { this.internal = internal; } protected ElementWrapper(Factory factory, QName qname) { Element el = factory.newElement(qname); internal = (el instanceof ElementWrapper) ? ((ElementWrapper)el).getInternal() : el; } public <T extends Base> T addComment(String value) { internal.addComment(value); return (T)this; } public Object clone() { try { ElementWrapper wrapper = (ElementWrapper)super.clone(); wrapper.internal = (Element)internal.clone(); return wrapper; } catch (CloneNotSupportedException e) { // won't happen return null; } } public <T extends Element> T declareNS(String uri, String prefix) { internal.declareNS(uri, prefix); return (T)this; } public void discard() { internal.discard(); } public List<QName> getAttributes() { return internal.getAttributes(); } public String getAttributeValue(QName qname) { return internal.getAttributeValue(qname); } public String getAttributeValue(String name) { return internal.getAttributeValue(name); } public IRI getBaseUri() { return internal.getBaseUri(); } public <T extends Element> Document<T> getDocument() { return internal.getDocument(); } public List<QName> getExtensionAttributes() { return internal.getExtensionAttributes(); } public Factory getFactory() { return internal.getFactory(); } public <T extends Element> T getFirstChild() { return (T)internal.getFirstChild(); } public <T extends Element> T getFirstChild(QName qname) { return (T)internal.getFirstChild(qname); } public String getLanguage() { return internal.getLanguage(); } public Lang getLanguageTag() { return internal.getLanguageTag(); } public Locale getLocale() { return internal.getLocale(); } public <T extends Element> T getNextSibling() { return (T)internal.getNextSibling(); } public <T extends Element> T getNextSibling(QName qname) { return (T)internal.getNextSibling(qname); } public <T extends Base> T getParentElement() { return (T)internal.getParentElement(); } public <T extends Element> T getPreviousSibling() { return (T)internal.getPreviousSibling(); } public <T extends Element> T getPreviousSibling(QName qname) { return (T)internal.getPreviousSibling(qname); } public QName getQName() { return internal.getQName(); } public IRI getResolvedBaseUri() { return internal.getResolvedBaseUri(); } public String getText() { return internal.getText(); } public <T extends Element> T removeAttribute(QName qname) { internal.removeAttribute(qname); return (T)this; } public <T extends Element> T removeAttribute(String name) { internal.removeAttribute(name); return (T)this; } public <T extends Element> T setAttributeValue(QName qname, String value) { internal.setAttributeValue(qname, value); return (T)this; } public <T extends Element> T setAttributeValue(String name, String value) { internal.setAttributeValue(name, value); return (T)this; } public <T extends Element> T setBaseUri(IRI base) { internal.setBaseUri(base); return (T)this; } public <T extends Element> T setBaseUri(String base) { internal.setBaseUri(base); return (T)this; } public <T extends Element> T setLanguage(String language) { internal.setLanguage(language); return (T)this; } @SuppressWarnings("deprecation") public <T extends Element> T setParentElement(Element parent) { internal.setParentElement(parent); return (T)this; } public void setText(String text) { internal.setText(text); } public <T extends Element> T setText(DataHandler handler) { internal.setText(handler); return (T)this; } public void writeTo(OutputStream out) throws IOException { internal.writeTo(out); } public void writeTo(Writer writer) throws IOException { internal.writeTo(writer); } public boolean equals(Object other) { if (other instanceof ElementWrapper) other = ((ElementWrapper)other).getInternal(); return internal.equals(other); } public String toString() { return internal.toString(); } public int hashCode() { return internal.hashCode(); } public Element getInternal() { return internal; } public <T extends Element> List<T> getElements() { return internal.getElements(); } public Map<String, String> getNamespaces() { return internal.getNamespaces(); } public boolean getMustPreserveWhitespace() { return internal.getMustPreserveWhitespace(); } public <T extends Element> T setMustPreserveWhitespace(boolean preserve) { internal.setMustPreserveWhitespace(preserve); return (T)this; } public void writeTo(OutputStream out, WriterOptions options) throws IOException { internal.writeTo(out, options); } public void writeTo(org.apache.abdera.writer.Writer writer, OutputStream out, WriterOptions options) throws IOException { internal.writeTo(writer, out, options); } public void writeTo(org.apache.abdera.writer.Writer writer, OutputStream out) throws IOException { internal.writeTo(writer, out); } public void writeTo(org.apache.abdera.writer.Writer writer, Writer out, WriterOptions options) throws IOException { internal.writeTo(writer, out, options); } public void writeTo(org.apache.abdera.writer.Writer writer, Writer out) throws IOException { internal.writeTo(writer, out); } public void writeTo(String writer, OutputStream out, WriterOptions options) throws IOException { internal.writeTo(writer, out, options); } public void writeTo(String writer, OutputStream out) throws IOException { internal.writeTo(writer, out); } public void writeTo(String writer, Writer out, WriterOptions options) throws IOException { internal.writeTo(writer, out, options); } public void writeTo(String writer, Writer out) throws IOException { internal.writeTo(writer, out); } public void writeTo(Writer out, WriterOptions options) throws IOException { internal.writeTo(out, options); } public WriterOptions getDefaultWriterOptions() { return internal.getDefaultWriterOptions(); } public <T extends Base> T complete() { internal.complete(); return (T)this; } public Iterator<Element> iterator() { return internal.iterator(); } }
30,882
apache/abdera/core/src/main/java/org/apache/abdera/model/Entry.java
package org.apache.abdera.model; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import javax.activation.DataHandler; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Represents an Atom Entry element. * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:entry" element represents an individual entry, acting as a * container for metadata and data associated with the entry. This * element can appear as a child of the atom:feed element, or it can * appear as the document (i.e., top-level) element of a stand-alone * Atom Entry Document. * * atomEntry = * element atom:entry { * atomCommonAttributes, * (atomAuthor* * &amp; atomCategory* * &amp; atomContent? * &amp; atomContributor* * &amp; atomId * &amp; atomLink* * &amp; atomPublished? * &amp; atomRights? * &amp; atomSource? * &amp; atomSummary? * &amp; atomTitle * &amp; atomUpdated * &amp; extensionElement*) * } * * This specification assigns no significance to the order of appearance * of the child elements of atom:entry. * * The following child elements are defined by this specification (note * that it requires the presence of some of these elements): * * o atom:entry elements MUST contain one or more atom:author elements, * unless the atom:entry contains an atom:source element that * contains an atom:author element or, in an Atom Feed Document, the * atom:feed element contains an atom:author element itself. * o atom:entry elements MAY contain any number of atom:category * elements. * o atom:entry elements MUST NOT contain more than one atom:content * element. * o atom:entry elements MAY contain any number of atom:contributor * elements. * o atom:entry elements MUST contain exactly one atom:id element. * o atom:entry elements that contain no child atom:content element * MUST contain at least one atom:link element with a rel attribute * value of "alternate". * o atom:entry elements MUST NOT contain more than one atom:link * element with a rel attribute value of "alternate" that has the * same combination of type and hreflang attribute values. * o atom:entry elements MAY contain additional atom:link elements * beyond those described above. * o atom:entry elements MUST NOT contain more than one atom:published * element. * o atom:entry elements MUST NOT contain more than one atom:rights * element. * o atom:entry elements MUST NOT contain more than one atom:source * element. * o atom:entry elements MUST contain an atom:summary element in either * of the following cases: * * the atom:entry contains an atom:content that has a "src" * attribute (and is thus empty). * * the atom:entry contains content that is encoded in Base64; * i.e., the "type" attribute of atom:content is a MIME media type * [MIMEREG], but is not an XML media type [RFC3023], does not * begin with "text/", and does not end with "/xml" or "+xml". * o atom:entry elements MUST NOT contain more than one atom:summary * element. * o atom:entry elements MUST contain exactly one atom:title element. * o atom:entry elements MUST contain exactly one atom:updated element. * </pre> */ public interface Entry extends ExtensibleElement { /** * Returns the first author listed for the entry * * @return The atom:author */ Person getAuthor(); /** * Returns the complete set of authors listed for the entry * * @return The listing of atom:author elements */ List<Person> getAuthors(); /** * Adds an individual author to the entry * * @param person The person to add */ Entry addAuthor(Person person); /** * Adds an author * * @param name The name of the author * @return The newly created atom:author element */ Person addAuthor(String name); /** * Adds an author * * @param name The name of the author * @param email The author's email address * @param uri A URI belonging to the author * @return The newly created atom:author element * @throws IRISyntaxException if the URI is malformed */ Person addAuthor(String name, String email, String uri); /** * Lists the complete set of categories listed for the entry * * @return The listing of atom:category elements */ List<Category> getCategories(); /** * Lists the complete set of categories using the specified scheme A listing of atom:category elements using the * specified scheme * * @throws IRISyntaxException if the scheme is malformed */ List<Category> getCategories(String scheme); /** * Adds an individual category to the entry * * @param category The atom:category element to add */ Entry addCategory(Category category); /** * Adds a category to the entry * * @param term The category term to add * @return The newly created atom:category */ Category addCategory(String term); /** * Adds a category to the entry * * @param scheme The category scheme * @param term The category term * @param label The human readable label * @return The newly create atom:category * @throws IRISyntaxException if the scheme is malformed */ Category addCategory(String scheme, String term, String label); /** * Returns the content for this entry * * @return The atom:content element */ Content getContentElement(); /** * Sets the content for this entry * * @param content The atom:content element */ Entry setContentElement(Content content); /** * Sets the content for this entry as @type="text" * * @param value The text value of the content * @return The newly created atom:content */ Content setContent(String value); /** * Sets the content for this entry as @type="html" * * @param value The text value of the content. Special characters will be escaped (e.g. &amp; will become &amp;amp;) * @return The newly created atom:content */ Content setContentAsHtml(String value); /** * Sets the content for this entry as @type="xhtml" * * @param value The text value of the content. The text will be parsed as XHTML * @return The newly created atom:content */ Content setContentAsXhtml(String value); /** * Sets the content for this entry * * @param value The text value of the content * @param type The Content Type of the text * @return The newly created atom:content */ Content setContent(String value, Content.Type type); /** * Sets the content for this entry * * @param value The content element value. If the value is a Div, the the type attribute will be set to * type="xhtml", otherwise type="application/xml" * @return The newly create atom:content */ Content setContent(Element value); /** * Sets the content for this entry * * @param element The element value * @param mediaType The media type of the element * @throws MimeTypeParseException if the mediaType is malformed */ Content setContent(Element element, String mediaType); /** * Sets the content for this entry * * @param dataHandler The Data Handler containing the binary content needing Base64 encoding. * @throws MimeTypeParseException if the media Type specified by the dataHandler is malformed */ Content setContent(DataHandler dataHandler); /** * Sets the content for this entry * * @param dataHandler The Data Handler containing the binary content needing Base64 encoding. * @param mediaType The mediatype of the binary content * @return The created content element * @throws MimeTypeParseException if the media type specified is malformed */ Content setContent(DataHandler dataHandler, String mediatype); /** * Sets the content for this entry * * @param inputStream An inputstream providing binary content * @return The created content element */ Content setContent(InputStream inputStream); /** * Sets the content for this entry * * @param inputStream An inputstream providing binary content * @param mediaType The mediatype of the binary content * @return The created content element * @throws MimeTypeParseException if the media type specified is malformed */ Content setContent(InputStream inputStream, String mediatype); /** * Sets the content for this entry * * @param value the string value of the content * @param mediatype the media type for the content * @return The newly created atom:content * @throws MimeTypeParseException if the media type is malformed */ Content setContent(String value, String mediatype); /** * Sets the content for this entry as out of line. * * @param uri URI of the content (value of the "src" attribute). * @param mediatype Type of the content. * @return The new content element. * @throws MimeTypeParseException if the mime type is invalid. * @throws IRISyntaxException if the URI is invalid. */ Content setContent(IRI uri, String mediatype); /** * Returns the text of the content element * * @return text content */ String getContent(); /** * Returns an input stream from the content element value. This is particularly useful when dealing with Base64 * binary content. * * @throws IOException */ InputStream getContentStream() throws IOException; /** * Returns the content/@src attribute, if any * * @return The src IRI * @throws IRISyntaxException if the src attribute is invalid */ IRI getContentSrc(); /** * Returns the content type * * @return The content type */ Content.Type getContentType(); /** * Returns the media type of the content type or null if type equals 'text', 'html' or 'xhtml' * * @return The content media type */ MimeType getContentMimeType(); /** * Lists the complete set of contributors for this entry * * @return The listing of atom:contributor elements */ List<Person> getContributors(); /** * Adds an individual contributor to this entry * * @param person The atom:contributor element */ Entry addContributor(Person person); /** * Adds a contributor * * @param name The contributor name * @return The newly created atom:contributor */ Person addContributor(String name); /** * Adds an author * * @param name The contributor name * @param email The contributor's email address * @param uri The contributor's URI * @return The newly created atom:contributor * @throws IRISyntaxException if the uri is malformed */ Person addContributor(String name, String email, String uri); /** * Returns the universally unique identifier for this entry * * @return The atom:id element */ IRIElement getIdElement(); /** * Sets the universally unique identifier for this entry * * @param id The atom:id element */ Entry setIdElement(IRIElement id); /** * Returns the universally unique identifier for this entry * * @throws IRISyntaxException if the atom:id value is malformed */ IRI getId(); /** * Sets the universally unique identifier for this entry * * @param id The atom:id value * @return The newly created atom:id element * @throws IRISyntaxException if the atom:id value is malformed */ IRIElement setId(String id); /** * Creates a new randomized atom:id for the entry */ IRIElement newId(); /** * Sets the universally unique identifier for this entry * * @param id The atom:id value * @param normalize true if the atom:id value should be normalized as called for by RFC4287 * @return The newly created atom:id element * @throws IRISyntaxException if the atom:id value is malformed */ IRIElement setId(String id, boolean normalize); /** * Lists the complete set of links for this entry * * @return The listing of atom:link elements */ List<Link> getLinks(); /** * Lists the complete set of links using the specified rel attribute value * * @param rel The rel attribute value to look for * @return The listing of atom:link element's with the rel attribute */ List<Link> getLinks(String rel); /** * Lists the complete set of links using the specified rel attributes values * * @param rels A listing of link relations * @return A listof atom:link elements */ List<Link> getLinks(String... rel); /** * Adds an individual link to the entry * * @param link the atom:link to add */ Entry addLink(Link link); /** * Add a link to the entry * * @param href The IRI of the link * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href); /** * Add a link to the entry * * @param href The IRI of the link * @param rel The link rel attribute * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href, String rel); /** * Add a link to the entry * * @param href The IRI of the link * @param rel The link rel attribute * @param type The media type of the link * @param hreflang The language of the target * @param length The length of the resource * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href, String rel, String type, String title, String hreflang, long length); /** * RFC4287: The "atom:published" element is a Date construct indicating an instant in time associated with an event * early in the life cycle of the entry... Typically, atom:published will be associated with the initial creation or * first availability of the resource. * * @return The atom:published element */ DateTime getPublishedElement(); /** * RFC4287: The "atom:published" element is a Date construct indicating an instant in time associated with an event * early in the life cycle of the entry... Typically, atom:published will be associated with the initial creation or * first availability of the resource. * * @param dateTime the atom:published element */ Entry setPublishedElement(DateTime dateTime); /** * Return the value of the atom:published element * * @return a java.util.Date for the atom:published value */ Date getPublished(); /** * Set the value of the atom:published element * * @param value The java.util.Date * @return The newly created atom:published element */ DateTime setPublished(Date value); /** * Set the value of the atom:published element using the serialized string value * * @param value The serialized date * @return The newly created atom:published element */ DateTime setPublished(String value); /** * <p> * The rights element is typically used to convey a human readable copyright (e.g. "&lt;atom:rights>Copyright (c), * 2006&lt;/atom:rights>). * </p> * <p> * RFC4287: The "atom:rights" element is a Text construct that conveys information about rights held in and over an * entry or feed. * </p> * * @return The atom:rights element */ Text getRightsElement(); /** * <p> * The rights element is typically used to convey a human readable copyright (e.g. "&lt;atom:rights>Copyright (c), * 2006&lt;/atom:rights>). * </p> * <p> * RFC4287: The "atom:rights" element is a Text construct that conveys information about rights held in and over an * entry or feed. * </p> * * @param text The atom:rights element */ Entry setRightsElement(Text text); /** * Sets the value of the rights as @type="text" * * @param value The text value of the atom:rights element * @return The newly created atom:rights element */ Text setRights(String value); /** * Sets the value of the rights as @type="html". Special characters like & will be automatically escaped * * @param value The text value of the atom:rights element. * @return The newly created atom:rights element */ Text setRightsAsHtml(String value); /** * Sets the value of the rights as @type="xhtml" * * @param value The text value of the atom:rights element * @return The newly created atom:rights element */ Text setRightsAsXhtml(String value); /** * Sets the value of the rights * * @param value The text value of the atom:rights element * @param type The text type * @return The newly create atom:rights element */ Text setRights(String value, Text.Type type); /** * Sets the value of the right as @type="xhtml" * * @param value The XHTML div for the atom:rights element * @return The newly created atom:rights element */ Text setRights(Div value); /** * Return the String value of the atom:rights element * * @return The text value of the atom:rights element */ String getRights(); /** * Return the @type of the atom:rights element * * @return The Text.Type of the atom:rights element */ Text.Type getRightsType(); /** * <p> * Returns the source element for this entry. * </p> * <p> * RFC4287: If an atom:entry is copied from one feed into another feed, then the source atom:feed's metadata (all * child elements of atom:feed other than the atom:entry elements) MAY be preserved within the copied entry by * adding an atom:source child element, if it is not already present in the entry, and including some or all of the * source feed's Metadata elements as the atom:source element's children. Such metadata SHOULD be preserved if the * source atom:feed contains any of the child elements atom:author, atom:contributor, atom:rights, or atom:category * and those child elements are not present in the source atom:entry. * </p> * * @return The atom:source element */ Source getSource(); /** * <p> * Returns the source element for this entry. * </p> * <p> * RFC4287: If an atom:entry is copied from one feed into another feed, then the source atom:feed's metadata (all * child elements of atom:feed other than the atom:entry elements) MAY be preserved within the copied entry by * adding an atom:source child element, if it is not already present in the entry, and including some or all of the * source feed's Metadata elements as the atom:source element's children. Such metadata SHOULD be preserved if the * source atom:feed contains any of the child elements atom:author, atom:contributor, atom:rights, or atom:category * and those child elements are not present in the source atom:entry. * </p> * * @param source The atom:source element */ Entry setSource(Source source); /** * RFC4287: The "atom:summary" element is a Text construct that conveys a short summary, abstract, or excerpt of an * entry... It is not advisable for the atom:summary element to duplicate atom:title or atom:content because Atom * Processors might assume there is a useful summary when there is none. * * @return The atom:summary element */ Text getSummaryElement(); /** * RFC4287: The "atom:summary" element is a Text construct that conveys a short summary, abstract, or excerpt of an * entry... It is not advisable for the atom:summary element to duplicate atom:title or atom:content because Atom * Processors might assume there is a useful summary when there is none. * * @param text The atom:summary element */ Entry setSummaryElement(Text text); /** * Sets the value of the summary as @type="text" * * @param value The text value of the atom:summary element * @return the newly created atom:summary element */ Text setSummary(String value); /** * Sets the value of the summary as @type="html" * * @param value The text value of the atom:summary element * @return the newly created atom:summary element */ Text setSummaryAsHtml(String value); /** * Sets the value of the summary as @type="xhtml" * * @param value The text value of the atom:summary element * @return the newly created atom:summary element */ Text setSummaryAsXhtml(String value); /** * Sets the value of the summary * * @param value The text value of the atom:summary element * @param type The Text.Type of the atom:summary element * @return The newly created atom:summary element */ Text setSummary(String value, Text.Type type); /** * Sets the value of the summary as @type="xhtml" * * @param value The XHTML div * @return the newly created atom:summary element */ Text setSummary(Div value); /** * Returns the text string value of this summary * * @return the text value of the atom:summary */ String getSummary(); /** * Returns the summary type * * @return the Text.Type of the atom:summary */ Text.Type getSummaryType(); /** * RFC4287: The "atom:title" element is a Text construct that conveys a human-readable title for an entry or feed. * * @return the atom:title element */ Text getTitleElement(); /** * RFC4287: The "atom:title" element is a Text construct that conveys a human-readable title for an entry or feed. * * @param title the atom:title element */ Entry setTitleElement(Text title); /** * Sets the value of the title as @type="text" * * @param value The title value * @return The newly created atom:title element */ Text setTitle(String value); /** * Sets the value of the title as @type="html" * * @param value The title value * @return The newly created atom:title element */ Text setTitleAsHtml(String value); /** * Sets the value of the title as @type="xhtml" * * @param value The title value * @return The newly created atom:title element */ Text setTitleAsXhtml(String value); /** * Sets the value of the title * * @param value The title value * @param type The Text.Type of the title * @return the newly created atom:title element */ Text setTitle(String value, Text.Type type); /** * Sets the value of the title as @type="xhtml" * * @param value The XHTML div * @return the newly created atom:title element */ Text setTitle(Div value); /** * Returns the text string value of the title element * * @return text value of the atom:title */ String getTitle(); /** * Returns the @type of this entries title * * @return the Text.Type of the atom:title */ Text.Type getTitleType(); /** * RFC4287: The "atom:updated" element is a Date construct indicating the most recent instant in time when an entry * or feed was modified in a way the publisher considers significant. Therefore, not all modifications necessarily * result in a changed atom:updated value. * * @return the atom:updated element */ DateTime getUpdatedElement(); /** * RFC4287: The "atom:updated" element is a Date construct indicating the most recent instant in time when an entry * or feed was modified in a way the publisher considers significant. Therefore, not all modifications necessarily * result in a changed atom:updated value. * * @param updated the atom:updated element. */ Entry setUpdatedElement(DateTime updated); /** * Return atom:updated * * @return A java.util.Date value */ Date getUpdated(); /** * Set the atom:updated value * * @param value The new value * @return The newly created atom:updated element */ DateTime setUpdated(Date value); /** * Set the atom:updated value * * @param value The new value * @return The newly created atom:updated element */ DateTime setUpdated(String value); /** * APP Introduces a new app:edited element whose value changes every time the entry is updated * * @return the app:edited element */ DateTime getEditedElement(); /** * Set the app:edited element * * @param modified The app:edited element */ void setEditedElement(DateTime modified); /** * Return the value of app:edited * * @return app:edited */ Date getEdited(); /** * Set the value of app:edited * * @param value The java.util.Date value * @return The newly created app:edited element */ DateTime setEdited(Date value); /** * Set the value of app:edited * * @param value the serialized string value for app:edited * @return The newly created app:edited element */ DateTime setEdited(String value); /** * Returns this entries Atom Publishing Protocol control element. A new control element will be created if one * currently does not exist * * @return The app:control element */ Control getControl(boolean create); /** * Returns this entries Atom Publishing Protocol control element * * @return The app:control element */ Control getControl(); /** * Sets this entries Atom Publishing Protocol control element * * @param control The app:contorl element */ Entry setControl(Control control); /** * Sets whether or not this entry is a draft * * @param draft true if this entry should be marked as a draft */ Entry setDraft(boolean draft); /** * Returns true if this entry is a draft * * @return True if this entry is a date */ boolean isDraft(); /** * Returns the first link with the specified rel attribute value * * @param rel The link rel * @return a Link with the specified rel attribute */ Link getLink(String rel); /** * Returns this entries first alternate link * * @return the Alternate link */ Link getAlternateLink(); /** * Returns the first alternate link matching the specified type and hreflang * * @throws MimeTypeParseException * @param type The link media type * @param hreflang The link target language * @return The matching atom:link * @throws MimeTypeParseException if the type is malformed */ Link getAlternateLink(String type, String hreflang); /** * Returns this entries first enclosure link * * @return the Enclosure link */ Link getEnclosureLink(); /** * Returns this entries first edit link * * @return the Edit Link */ Link getEditLink(); /** * Returns this entries first edit-media link (if any) * * @return the Edit Media Link */ Link getEditMediaLink(); /** * Returns the first edit-media link matching the specified type and hreflang * * @param type a media type * @param hreflang a target language * @return A matching atom:link element * @throws MimeTypeParseException */ Link getEditMediaLink(String type, String hreflang); /** * Returns this entries first self link * * @return the Self Link */ Link getSelfLink(); /** * Return a link href resolved against the in-scope Base URI * * @param rel The rel attribute value * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getLinkResolvedHref(String rel); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getAlternateLinkResolvedHref(); /** * Return a link href resolved against the in-scope Base URI * * @param type A target type * @param hreflang A target language * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getAlternateLinkResolvedHref(String type, String hreflang); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getEnclosureLinkResolvedHref(); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getEditLinkResolvedHref(); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getEditMediaLinkResolvedHref(); /** * Return a link href resolved against the in-scope Base URI * * @param type A target type * @param hreflang A target language * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed * @throws MimeTypeParseException if the type is malformed */ IRI getEditMediaLinkResolvedHref(String type, String hreflang); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getSelfLinkResolvedHref(); Control addControl(); }
3,727
apache/abdera/core/src/main/java/org/apache/abdera/model/ExtensibleElement.java
package org.apache.abdera.model; import java.util.List; import javax.xml.namespace.QName; /** * An abstract element that can be extended with namespaced child elements */ public interface ExtensibleElement extends Element { /** * Returns the complete set of extension elements * * @return a listing of extensions */ List<Element> getExtensions(); /** * Returns the complete set of extension elements using the specified XML Namespace URI * * @param uri A namespace URI * @return A listing of extensions using the specified XML namespace */ List<Element> getExtensions(String uri); /** * Returns the complete set of extension elements using the specified XML qualified name * * @param qname An XML QName * @return A listing of extensions with the specified QName */ <T extends Element> List<T> getExtensions(QName qname); /** * Returns the first extension element with the XML qualified name * * @param qname An XML QName * @return An extension with the specified qname */ <T extends Element> T getExtension(QName qname); /** * Adds an individual extension element * * @param extension An extension element to add */ <T extends ExtensibleElement> T addExtension(Element extension); /** * Adds an individual extension element before the specified element */ <T extends ExtensibleElement> T addExtension(Element extension, Element before); /** * Adds an individual extension element * * @param qname An extension element to create * @return The newly created extension element */ <T extends Element> T addExtension(QName qname); /** * Adds an individual extension element * * @param qname An extension element to create * @return The newly created extension element */ <T extends Element> T addExtension(QName qname, QName before); /** * Adds an individual extension element * * @param namespace An XML namespace * @param localPart A localname * @param prefix A XML namespace prefix * @return The newly creatd extension element */ <T extends Element> T addExtension(String namespace, String localPart, String prefix); /** * Adds a simple extension (text content only) * * @param qname An XML QName * @param value The simple text value of the element * @return The newly created extension element */ Element addSimpleExtension(QName qname, String value); /** * Adds a simple extension (text content only) * * @param namespace An XML namespace * @param localPart A local name * @param prefix A namespace prefix * @param value The simple text value * @return The newly created extension element */ Element addSimpleExtension(String namespace, String localPart, String prefix, String value); /** * Gets the value of a simple extension * * @param qname An XML QName * @return The string value of the extension */ String getSimpleExtension(QName qname); /** * Gets the value of a simple extension * * @param namespace An XML namespace * @param localPart A localname * @param prefix A namespace prefix * @return The string value of the extension */ String getSimpleExtension(String namespace, String localPart, String prefix); /** * Find an extension by Class rather than QName * * @param _class The implementation class of the extension * @return The extension element */ <T extends Element> T getExtension(Class<T> _class); }
3,063
apache/abdera/core/src/main/java/org/apache/abdera/model/ExtensibleElementWrapper.java
package org.apache.abdera.model; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; /** * ElementWrapper implementation that implements the ExtensibleElement interface. This should be used to create static * extension elements that support extensions */ @SuppressWarnings("unchecked") public abstract class ExtensibleElementWrapper extends ElementWrapper implements ExtensibleElement { protected ExtensibleElementWrapper(Element internal) { super(internal); } public ExtensibleElementWrapper(Factory factory, QName qname) { super(factory, qname); } protected ExtensibleElement getExtInternal() { return (ExtensibleElement)getInternal(); } public <T extends ExtensibleElement> T addExtension(Element extension) { getExtInternal().addExtension(extension); return (T)this; } public <T extends Element> T addExtension(QName qname) { return (T)getExtInternal().addExtension(qname); } public <T extends Element> T addExtension(String namespace, String localPart, String prefix) { return (T)getExtInternal().addExtension(namespace, localPart, prefix); } public Element addSimpleExtension(QName qname, String value) { return getExtInternal().addSimpleExtension(qname, value); } public Element addSimpleExtension(String namespace, String localPart, String prefix, String value) { return getExtInternal().addSimpleExtension(namespace, localPart, prefix, value); } public <T extends Element> T getExtension(QName qname) { return (T)getExtInternal().getExtension(qname); } public <T extends Element> T getExtension(Class<T> _class) { return (T)getExtInternal().getExtension(_class); } public List<Element> getExtensions() { return getExtInternal().getExtensions(); } public List<Element> getExtensions(String uri) { return getExtInternal().getExtensions(uri); } public <T extends Element> List<T> getExtensions(QName qname) { return getExtInternal().getExtensions(qname); } public String getSimpleExtension(QName qname) { return getExtInternal().getSimpleExtension(qname); } public String getSimpleExtension(String namespace, String localPart, String prefix) { return getExtInternal().getSimpleExtension(namespace, localPart, prefix); } public boolean getMustPreserveWhitespace() { return getExtInternal().getMustPreserveWhitespace(); } public <T extends Element> T setMustPreserveWhitespace(boolean preserve) { getExtInternal().setMustPreserveWhitespace(preserve); return (T)this; } public <T extends ExtensibleElement> T addExtension(Element extension, Element before) { getExtInternal().addExtension(extension, before); return (T)this; } public <T extends Element> T addExtension(QName qname, QName before) { return (T)getExtInternal().addExtension(qname, before); } }
5,059
apache/abdera/core/src/main/java/org/apache/abdera/model/Feed.java
package org.apache.abdera.model; import java.util.Comparator; import java.util.List; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * Represents an Atom Feed Element * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:feed" element is the document (i.e., top-level) element of * an Atom Feed Document, acting as a container for metadata and data * associated with the feed. Its element children consist of metadata * elements followed by zero or more atom:entry child elements. * * atomFeed = * element atom:feed { * atomCommonAttributes, * (atomAuthor* * &amp; atomCategory* * &amp; atomContributor* * &amp; atomGenerator? * &amp; atomIcon? * &amp; atomId * &amp; atomLink* * &amp; atomLogo? * &amp; atomRights? * &amp; atomSubtitle? * &amp; atomTitle * &amp; atomUpdated * &amp; extensionElement*), * atomEntry* * } * * This specification assigns no significance to the order of atom:entry * elements within the feed. * * The following child elements are defined by this specification (note * that the presence of some of these elements is required): * * o atom:feed elements MUST contain one or more atom:author elements, * unless all of the atom:feed element's child atom:entry elements * contain at least one atom:author element. * o atom:feed elements MAY contain any number of atom:category * elements. * o atom:feed elements MAY contain any number of atom:contributor * elements. * o atom:feed elements MUST NOT contain more than one atom:generator * element. * o atom:feed elements MUST NOT contain more than one atom:icon * element. * o atom:feed elements MUST NOT contain more than one atom:logo * element. * o atom:feed elements MUST contain exactly one atom:id element. * o atom:feed elements SHOULD contain one atom:link element with a rel * attribute value of "self". This is the preferred URI for * retrieving Atom Feed Documents representing this Atom feed. * o atom:feed elements MUST NOT contain more than one atom:link * element with a rel attribute value of "alternate" that has the * same combination of type and hreflang attribute values. * o atom:feed elements MAY contain additional atom:link elements * beyond those described above. * o atom:feed elements MUST NOT contain more than one atom:rights * element. * o atom:feed elements MUST NOT contain more than one atom:subtitle * element. * o atom:feed elements MUST contain exactly one atom:title element. * o atom:feed elements MUST contain exactly one atom:updated element. * * If multiple atom:entry elements with the same atom:id value appear in * an Atom Feed Document, they represent the same entry. Their * atom:updated timestamps SHOULD be different. If an Atom Feed * Document contains multiple entries with the same atom:id, Atom * Processors MAY choose to display all of them or some subset of them. * One typical behavior would be to display only the entry with the * latest atom:updated timestamp. * </pre> */ public interface Feed extends Source { /** * Returns the complete set of entries contained in this feed * * @return A listing of atom:entry elements */ List<Entry> getEntries(); /** * Adds a new Entry to the <i>end</i> of the Feeds collection of entries * * @param entry Add an entry */ Feed addEntry(Entry entry); /** * Adds a new Entry to the <i>end</i> of the Feeds collection of entries * * @return A newly created atom:entry */ Entry addEntry(); /** * Adds a new Entry to the <i>start</i> of the Feeds collection of entries * * @param entry An atom:entry to insert */ Feed insertEntry(Entry entry); /** * Adds a new Entry to the <i>start</i> of the Feeds collection of entries * * @return A newly created atom:entry */ Entry insertEntry(); /** * Creates a Source element from this Feed * * @return Returns a copy of this atom:feed as a atom:source element */ Source getAsSource(); /** * Sorts entries by the atom:updated property * * @param new_first If true, entries with newer atom:updated values will come first */ Feed sortEntriesByUpdated(boolean new_first); /** * Sorts entries by the app:edited property. if app:edited is null, use app:updated */ Feed sortEntriesByEdited(boolean new_first); /** * Sorts entries using the given comparator * * @param comparator Sort the entries using the comparator */ Feed sortEntries(Comparator<Entry> comparator); /** * Retrieves the first entry in the feed with the given atom:id value * * @param id The id to retrieve * @return The matching atom:entry * @throws IRISyntaxException if the id is malformed */ Entry getEntry(String id); }
2,589
apache/abdera/core/src/main/java/org/apache/abdera/model/Generator.java
package org.apache.abdera.model; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * Identifies the software implementation that produced the Atom feed. * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:generator" element's content identifies the agent used to * generate a feed, for debugging and other purposes. * The content of this element, when present, MUST be a string that is a * human-readable name for the generating agent. Entities such as * "&amp;amp;" and "&amp;lt;" represent their corresponding characters * ("&amp;" and "&lt;" respectively), not markup. * * The atom:generator element MAY have a "uri" attribute whose value * MUST be an IRI reference [RFC3987]. When dereferenced, the resulting * URI (mapped from an IRI, if necessary) SHOULD produce a * representation that is relevant to that agent. * * The atom:generator element MAY have a "version" attribute that * indicates the version of the generating agent. * </pre> */ public interface Generator extends Element { /** * The atom:generator element MAY have a "uri" attribute whose value MUST be an IRI reference [RFC3987]. When * dereferenced, the resulting URI (mapped from an IRI, if necessary) SHOULD produce a representation that is * relevant to that agent. * * @throws IRISyntaxException if the uri is malformed */ IRI getUri(); /** * Returns the fully qualified form of the generator element's uri attribute (resolved against the in-scope Base * URI) * * @return the resolved uri value * @throws IRISyntaxException if the uri is malformed */ IRI getResolvedUri(); /** * The atom:generator element MAY have a "uri" attribute whose value MUST be an IRI reference [RFC3987]. When * dereferenced, the resulting URI (mapped from an IRI, if necessary) SHOULD produce a representation that is * relevant to that agent. * * @param uri The URI attribute value * @throws IRISyntaxException if the uri is malformed */ Generator setUri(String uri); /** * The atom:generator element MAY have a "version" attribute that indicates the version of the generating agent. * * @return The version attribute value */ String getVersion(); /** * The atom:generator element MAY have a "version" attribute that indicates the version of the generating agent. * * @param version The version attribute */ Generator setVersion(String version); }
1,172
apache/abdera/core/src/main/java/org/apache/abdera/model/IRIElement.java
package org.apache.abdera.model; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * The IRI interface provides a common base for a set of feed and entry elements whose content value must be a valid * IRI/URI reference. These include the elements atom:icon, atom:logo, and atom:id. * </p> */ public interface IRIElement extends Element { /** * Returns the value of the element as a java.net.URI * * @return The IRI value of this element */ IRI getValue(); /** * Sets the value of the element * * @param iri The iri value * @throws IRISyntaxException if the value is malformed */ IRIElement setValue(String iri); /** * Set the value of this element using the normalization as specified in RFC4287 * * @param iri A non-normalized IRI * @throws IRISyntaxException if the iri is malformed */ IRIElement setNormalizedValue(String iri); /** * Returns the value of the element resolved against the current in-scope Base URI * * @return The resolved IRI value */ IRI getResolvedValue(); }
9,902
apache/abdera/core/src/main/java/org/apache/abdera/model/Link.java
package org.apache.abdera.model; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Represents an Atom Link element. * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:link" element defines a reference from an entry or feed to * a Web resource. This specification assigns no meaning to the content * (if any) of this element. * * atomLink = * element atom:link { * atomCommonAttributes, * attribute href { atomUri }, * attribute rel { atomNCName | atomUri }?, * attribute type { atomMediaType }?, * attribute hreflang { atomLanguageTag }?, * attribute title { text }?, * attribute length { text }?, * undefinedContent * } * </pre> */ public interface Link extends ExtensibleElement { public static final String REL_ALTERNATE = "alternate"; public static final String REL_CURRENT = "current"; public static final String REL_ENCLOSURE = "enclosure"; public static final String REL_FIRST = "first"; public static final String REL_LAST = "last"; public static final String REL_NEXT = "next"; public static final String REL_PAYMENT = "payment"; public static final String REL_PREVIOUS = "previous"; public static final String REL_RELATED = "related"; public static final String REL_SELF = "self"; public static final String REL_VIA = "via"; public static final String REL_REPLIES = "replies"; public static final String REL_LICENSE = "license"; public static final String REL_EDIT = "edit"; public static final String REL_EDIT_MEDIA = "edit-media"; public static final String REL_SERVICE = "service"; public static final String IANA_BASE = "http://www.iana.org/assignments/relation/"; public static final String REL_ALTERNATE_IANA = IANA_BASE + REL_ALTERNATE; public static final String REL_CURRENT_IANA = IANA_BASE + REL_CURRENT; public static final String REL_ENCLOSURE_IANA = IANA_BASE + REL_ENCLOSURE; public static final String REL_FIRST_IANA = IANA_BASE + REL_FIRST; public static final String REL_LAST_IANA = IANA_BASE + REL_LAST; public static final String REL_NEXT_IANA = IANA_BASE + REL_NEXT; public static final String REL_PAYMENT_IANA = IANA_BASE + REL_PAYMENT; public static final String REL_PREVIOUS_IANA = IANA_BASE + REL_PREVIOUS; public static final String REL_RELATED_IANA = IANA_BASE + REL_RELATED; public static final String REL_SELF_IANA = IANA_BASE + REL_SELF; public static final String REL_VIA_IANA = IANA_BASE + REL_VIA; public static final String REL_REPLIES_IANA = IANA_BASE + REL_REPLIES; public static final String REL_LICENSE_IANA = IANA_BASE + REL_LICENSE; public static final String REL_EDIT_IANA = IANA_BASE + REL_EDIT; public static final String REL_EDIT_MEDIA_IANA = IANA_BASE + REL_EDIT_MEDIA; public static final String REL_SERVICE_IANA = IANA_BASE + REL_SERVICE; /** * RFC4287: The "href" attribute contains the link's IRI. atom:link elements MUST have an href attribute, whose * value MUST be a IRI reference [RFC3987]. * * @return The href IRI value * @throws IRISyntaxException if the href is malformed */ IRI getHref(); /** * Returns the value of the link's href attribute resolved against the in-scope Base IRI * * @return The href IRI value * @throws IRISyntaxException if the href is malformed */ IRI getResolvedHref(); /** * RFC4287: The "href" attribute contains the link's IRI. atom:link elements MUST have an href attribute, whose * value MUST be a IRI reference [RFC3987]. * * @param href The href IRI * @throws IRISyntaxException if the href is malformed */ Link setHref(String href); /** * <p> * RFC4287: atom:link elements MAY have a "rel" attribute that indicates the link relation type. If the "rel" * attribute is not present, the link element MUST be interpreted as if the link relation type is "alternate"... The * value of "rel" MUST be a string that is non-empty and matches either the "isegment-nz-nc" or the "IRI" production * in [RFC3987]. Note that use of a relative reference other than a simple name is not allowed. If a name is given, * implementations MUST consider the link relation type equivalent to the same name registered within the IANA * Registry of Link Relations (Section 7), and thus to the IRI that would be obtained by appending the value of the * rel attribute to the string "http://www.iana.org/assignments/relation/". The value of "rel" describes the meaning * of the link, but does not impose any behavioral requirements on Atom Processors. * </p> * * @return The rel attribute value */ String getRel(); /** * <p> * RFC4287: atom:link elements MAY have a "rel" attribute that indicates the link relation type. If the "rel" * attribute is not present, the link element MUST be interpreted as if the link relation type is "alternate"... The * value of "rel" MUST be a string that is non-empty and matches either the "isegment-nz-nc" or the "IRI" production * in [RFC3987]. Note that use of a relative reference other than a simple name is not allowed. If a name is given, * implementations MUST consider the link relation type equivalent to the same name registered within the IANA * Registry of Link Relations (Section 7), and thus to the IRI that would be obtained by appending the value of the * rel attribute to the string "http://www.iana.org/assignments/relation/". The value of "rel" describes the meaning * of the link, but does not impose any behavioral requirements on Atom Processors. * </p> * * @param rel The rel attribute value */ Link setRel(String rel); /** * RFC4287: On the link element, the "type" attribute's value is an advisory media type: it is a hint about the type * of the representation that is expected to be returned when the value of the href attribute is dereferenced. Note * that the type attribute does not override the actual media type returned with the representation. Link elements * MAY have a type attribute, whose value MUST conform to the syntax of a MIME media type [MIMEREG]. * * @return The value of the type attribute * @throws MimeTypeParseException if the type is malformed */ MimeType getMimeType(); /** * RFC4287: On the link element, the "type" attribute's value is an advisory media type: it is a hint about the type * of the representation that is expected to be returned when the value of the href attribute is dereferenced. Note * that the type attribute does not override the actual media type returned with the representation. Link elements * MAY have a type attribute, whose value MUST conform to the syntax of a MIME media type [MIMEREG]. * * @param type The link type * @throws MimeTypeParseException if the type is malformed */ Link setMimeType(String type); /** * RFC4287: The "hreflang" attribute's content describes the language of the resource pointed to by the href * attribute. When used together with the rel="alternate", it implies a translated version of the entry. Link * elements MAY have an hreflang attribute, whose value MUST be a language tag [RFC3066]. * * @return The hreflang value */ String getHrefLang(); /** * RFC4287: The "hreflang" attribute's content describes the language of the resource pointed to by the href * attribute. When used together with the rel="alternate", it implies a translated version of the entry. Link * elements MAY have an hreflang attribute, whose value MUST be a language tag [RFC3066]. * * @param lang The hreflang value */ Link setHrefLang(String lang); /** * RFC4287: The "title" attribute conveys human-readable information about the link. The content of the "title" * attribute is Language-Sensitive. Entities such as "&amp;amp;" and "&amp;lt;" represent their corresponding * characters ("&amp;" and "&lt;", respectively), not markup. Link elements MAY have a title attribute. * * @return The title attribute */ String getTitle(); /** * RFC4287: The "title" attribute conveys human-readable information about the link. The content of the "title" * attribute is Language-Sensitive. Entities such as "&amp;amp;" and "&amp;lt;" represent their corresponding * characters ("&amp;" and "&lt;", respectively), not markup. Link elements MAY have a title attribute. * * @param title The title attribute */ Link setTitle(String title); /** * RFC4287: The "length" attribute indicates an advisory length of the linked content in octets; it is a hint about * the content length of the representation returned when the URI in the href attribute is mapped to a IRI and * dereferenced. Note that the length attribute does not override the actual content length of the representation as * reported by the underlying protocol. Link elements MAY have a length attribute. * * @return The length attribute value */ long getLength(); /** * RFC4287: The "length" attribute indicates an advisory length of the linked content in octets; it is a hint about * the content length of the representation returned when the IRI in the href attribute is mapped to a URI and * dereferenced. Note that the length attribute does not override the actual content length of the representation as * reported by the underlying protocol. Link elements MAY have a length attribute. * * @param length The length attribute value */ Link setLength(long length); }
4,964
apache/abdera/core/src/main/java/org/apache/abdera/model/Person.java
package org.apache.abdera.model; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * An Atom Person Construct * </p> * <p> * Per RFC4287: * </p> * * <pre> * A Person construct is an element that describes a person, * corporation, or similar entity (hereafter, 'person'). * * atomPersonConstruct = * atomCommonAttributes, * (element atom:name { text } * &amp; element atom:uri { atomUri }? * &amp; element atom:email { atomEmailAddress }? * &amp; extensionElement*) * * </pre> */ public interface Person extends ExtensibleElement, Element { /** * The "atom:name" element's content conveys a human-readable name for the person. The content of atom:name is * Language-Sensitive. Person constructs MUST contain exactly one "atom:name" element. * * @return The atom:name element */ Element getNameElement(); /** * The "atom:name" element's content conveys a human-readable name for the person. The content of atom:name is * Language-Sensitive. Person constructs MUST contain exactly one "atom:name" element. * * @param element The atom:name element */ Person setNameElement(Element element); /** * The "atom:name" element's content conveys a human-readable name for the person. The content of atom:name is * Language-Sensitive. Person constructs MUST contain exactly one "atom:name" element. * * @param name The person name * @return The newly created atom:name element */ Element setName(String name); /** * The "atom:name" element's content conveys a human-readable name for the person. The content of atom:name is * Language-Sensitive. Person constructs MUST contain exactly one "atom:name" element. * * @return The name value */ String getName(); /** * The "atom:email" element's content conveys an e-mail address associated with the person. Person constructs MAY * contain an atom:email element, but MUST NOT contain more than one. Its content MUST conform to the "addr-spec" * production in [RFC2822]. * * @return the atom:email element */ Element getEmailElement(); /** * The "atom:email" element's content conveys an e-mail address associated with the person. Person constructs MAY * contain an atom:email element, but MUST NOT contain more than one. Its content MUST conform to the "addr-spec" * production in [RFC2822]. * * @param element The atom:email element */ Person setEmailElement(Element element); /** * The "atom:email" element's content conveys an e-mail address associated with the person. Person constructs MAY * contain an atom:email element, but MUST NOT contain more than one. Its content MUST conform to the "addr-spec" * production in [RFC2822]. * * @param email The person email * @return the newly created atom:email element */ Element setEmail(String email); /** * The "atom:email" element's content conveys an e-mail address associated with the person. Person constructs MAY * contain an atom:email element, but MUST NOT contain more than one. Its content MUST conform to the "addr-spec" * production in [RFC2822]. * * @return the person's emali */ String getEmail(); /** * The "atom:uri" element's content conveys an IRI associated with the person. Person constructs MAY contain an * atom:uri element, but MUST NOT contain more than one. The content of atom:uri in a Person construct MUST be an * IRI reference [RFC3987]. * * @return the atom:uri element */ IRIElement getUriElement(); /** * The "atom:uri" element's content conveys an IRI associated with the person. Person constructs MAY contain an * atom:uri element, but MUST NOT contain more than one. The content of atom:uri in a Person construct MUST be an * IRI reference [RFC3987]. * * @param uri The atom:uri element */ Person setUriElement(IRIElement uri); /** * The "atom:uri" element's content conveys an IRI associated with the person. Person constructs MAY contain an * atom:uri element, but MUST NOT contain more than one. The content of atom:uri in a Person construct MUST be an * IRI reference [RFC3987]. * * @param uri The atom:uri value * @throws IRISyntaxException if the uri is malformed */ IRIElement setUri(String uri); /** * The "atom:uri" element's content conveys an IRI associated with the person. Person constructs MAY contain an * atom:uri element, but MUST NOT contain more than one. The content of atom:uri in a Person construct MUST be an * IRI reference [RFC3987]. * * @return The atom:uri value * @throws IRISyntaxException if the uri is invalid */ IRI getUri(); }
3,499
apache/abdera/core/src/main/java/org/apache/abdera/model/PersonWrapper.java
package org.apache.abdera.model; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.util.Constants; /** * ElementWrapper implementation that implements the Person interface. Used to create static extensions based on the * Atom Person Construct */ public abstract class PersonWrapper extends ExtensibleElementWrapper implements Person, Constants { protected PersonWrapper(Element internal) { super(internal); } public PersonWrapper(Factory factory, QName qname) { super(factory, qname); } public String getEmail() { Element email = getEmailElement(); return (email != null) ? email.getText() : null; } public Element getEmailElement() { return getInternal().getFirstChild(EMAIL); } public String getName() { Element name = getNameElement(); return (name != null) ? name.getText() : null; } public Element getNameElement() { return getInternal().getFirstChild(NAME); } public IRI getUri() { IRIElement iri = getUriElement(); return (iri != null) ? iri.getResolvedValue() : null; } public IRIElement getUriElement() { return getInternal().getFirstChild(URI); } public Element setEmail(String email) { ExtensibleElement internal = getExtInternal(); Element el = getEmailElement(); if (email != null) { if (el == null) el = internal.getFactory().newEmail(internal); el.setText(email); return el; } else { if (el != null) el.discard(); return null; } } public Person setEmailElement(Element element) { ExtensibleElement internal = getExtInternal(); Element el = getEmailElement(); if (el != null) el.discard(); if (element != null) internal.addExtension(element); return this; } public Element setName(String name) { ExtensibleElement internal = getExtInternal(); Element el = getNameElement(); if (name != null) { if (el == null) el = internal.getFactory().newName(internal); el.setText(name); return el; } else { if (el != null) el.discard(); return null; } } public Person setNameElement(Element element) { ExtensibleElement internal = getExtInternal(); Element el = getNameElement(); if (el != null) el.discard(); if (element != null) internal.addExtension(element); return this; } public IRIElement setUri(String uri) { ExtensibleElement internal = getExtInternal(); IRIElement el = getUriElement(); if (uri != null) { if (el == null) el = internal.getFactory().newUri(internal); el.setText(uri.toString()); return el; } else { if (el != null) el.discard(); return null; } } public Person setUriElement(IRIElement element) { ExtensibleElement internal = getExtInternal(); Element el = getUriElement(); if (el != null) el.discard(); if (element != null) internal.addExtension(element); return this; } }
961
apache/abdera/core/src/main/java/org/apache/abdera/model/ProcessingInstruction.java
package org.apache.abdera.model; import org.apache.abdera.factory.Factory; /** * A processing instruction. Returned by the Abdera XPath implementation when querying for PI nodes (e.g. * xpath.selectNodes("//processing-instruction()"); ...). There should be very little reason for applications to use * this. It is provided to keep applications from having to deal with the underlying parser implementation */ public interface ProcessingInstruction { /** * Delete this PI */ void discard(); /** * The Abdera Factory */ Factory getFactory(); /** * The parent node */ <T extends Base> T getParentElement(); /** * The PI target */ String getTarget(); /** * The PI target */ void setTarget(String target); /** * The PI text */ String getText(); /** * The PI text */ <T extends ProcessingInstruction> T setText(String text); }
2,777
apache/abdera/core/src/main/java/org/apache/abdera/model/Service.java
package org.apache.abdera.model; import java.util.List; import javax.activation.MimeType; /** * <p> * Represents the root of an Atom Publishing Protocol Introspection Document. * </p> * <p> * Per APP Draft-08: * </p> * * <pre> * The root of an introspection document is the "app:service" element. * * The "app:service" element is the container for introspection * information associated with one or more workspaces. An app:service * element MUST contain one or more app:workspace elements. * * appService = * element app:service { * appCommonAttributes, * ( appWorkspace+ * &amp; extensionElement* ) * } * </pre> */ public interface Service extends ExtensibleElement { /** * Return the complete set of workspaces * * @return A listing of app:workspaces elements */ List<Workspace> getWorkspaces(); /** * Return the named workspace * * @param title The workspace title * @return A matching app:workspace */ Workspace getWorkspace(String title); /** * Add an individual workspace * * @param workspace a app:workspace element */ Service addWorkspace(Workspace workspace); /** * Add an individual workspace * * @param title The workspace title * @return The newly created app:workspace */ Workspace addWorkspace(String title); /** * Returns the named collection * * @param workspace The workspace title * @param collection The collection title * @return A matching app:collection element */ Collection getCollection(String workspace, String collection); /** * Returns a collection that accepts the specified media types * * @param a listing of media types the collection must accept * @return A matching app:collection element */ Collection getCollectionThatAccepts(MimeType... type); /** * Returns a collection that accepts the specified media types * * @param a listing of media types the collection must accept * @return A matching app:collection element */ Collection getCollectionThatAccepts(String... type); /** * Returns collections that accept the specified media types * * @param a listing of media types the collection must accept * @return A listing matching app:collection elements */ List<Collection> getCollectionsThatAccept(MimeType... type); /** * Returns collections that accept the specified media types * * @param a listing of media types the collection must accept * @return A listing of matching app:collection elements */ List<Collection> getCollectionsThatAccept(String... type); }
21,556
apache/abdera/core/src/main/java/org/apache/abdera/model/Source.java
package org.apache.abdera.model; import java.util.Date; import java.util.List; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Per RFC4287: * </p> * * <pre> * If an atom:entry is copied from one feed into another feed, then the * source atom:feed's metadata (all child elements of atom:feed other * than the atom:entry elements) MAY be preserved within the copied * entry by adding an atom:source child element, if it is not already * present in the entry, and including some or all of the source feed's * Metadata elements as the atom:source element's children. Such * metadata SHOULD be preserved if the source atom:feed contains any of * the child elements atom:author, atom:contributor, atom:rights, or * atom:category and those child elements are not present in the source * atom:entry. * * atomSource = * element atom:source { * atomCommonAttributes, * (atomAuthor* * &amp; atomCategory* * &amp; atomContributor* * &amp; atomGenerator? * &amp; atomIcon? * &amp; atomId? * &amp; atomLink* * &amp; atomLogo? * &amp; atomRights? * &amp; atomSubtitle? * &amp; atomTitle? * &amp; atomUpdated? * &amp; extensionElement*) * } * * The atom:source element is designed to allow the aggregation of * entries from different feeds while retaining information about an * entry's source feed. For this reason, Atom Processors that are * performing such aggregation SHOULD include at least the required * feed-level Metadata elements (atom:id, atom:title, and atom:updated) * in the atom:source element. * </pre> */ public interface Source extends ExtensibleElement { /** * Returns the first author listed for the entry * * @return This feed's author */ Person getAuthor(); /** * Returns the complete set of authors listed for the entry * * @return This feeds list of authors */ List<Person> getAuthors(); /** * Adds an individual author to the entry * * @param person an atom:author element */ <T extends Source> T addAuthor(Person person); /** * Adds an author * * @param name The author name * @return The newly created atom:author element */ Person addAuthor(String name); /** * Adds an author * * @param name The author name * @param email The author email * @param iri The author iri * @return The newly created atom:author element * @throws IRISyntaxException if the iri is malformed */ Person addAuthor(String name, String email, String iri); /** * Lists the complete set of categories listed for the entry * * @return A listing of app:category elements */ List<Category> getCategories(); /** * Lists the complete set of categories using the specified scheme * * @param scheme A Scheme IRI * @return The listing of app:category elements * @throws IRISyntaxException if the scheme is malformed */ List<Category> getCategories(String scheme); /** * Adds an individual category to the entry * * @param category A atom:category element */ <T extends Source> T addCategory(Category category); /** * Adds a category to the feed * * @param term A category term * @return The newly created atom:category element */ Category addCategory(String term); /** * Adds a category to the feed * * @param scheme A category scheme * @param term A category term * @param label The human readable label * @return the newly created atom:category element * @throws IRISyntaxException if the scheme is malformed */ Category addCategory(String scheme, String term, String label); /** * Lists the complete set of contributors for this entry * * @return A listing of atom:contributor elements */ List<Person> getContributors(); /** * Adds an individual contributor to this entry * * @param person a atom:contributor element */ <T extends Source> T addContributor(Person person); /** * Adds a contributor * * @param name The name of a contributor * @return The newly created atom:contributor element */ Person addContributor(String name); /** * Adds a contributor * * @param name The contributor name * @param email The contributor email * @param iri The contributor uri * @return The atom:contributor element * @throws IRISyntaxException if the iri is malformed */ Person addContributor(String name, String email, String iri); /** * RFC4287: The "atom:generator" element's content identifies the agent used to generate a feed, for debugging and * other purposes. * * @return The atom:generator */ Generator getGenerator(); /** * RFC4287: The "atom:generator" element's content identifies the agent used to generate a feed, for debugging and * other purposes. * * @param generator A atom:generator element */ <T extends Source> T setGenerator(Generator generator); /** * RFC4287: The "atom:generator" element's content identifies the agent used to generate a feed, for debugging and * other purposes. * * @param iri The iri attribute * @param version The version attribute * @param value The value attribute * @return A newly created atom:generator element * @throws IRISyntaxException if the iri is malformed */ Generator setGenerator(String iri, String version, String value); /** * RFC4287: The "atom:icon" element's content is an IRI reference [RFC3987] that identifies an image that provides * iconic visual identification for a feed... The image SHOULD have an aspect ratio of one (horizontal) to one * (vertical) and SHOULD be suitable for presentation at a small size. * * @return the atom:icon element */ IRIElement getIconElement(); /** * RFC4287: The "atom:icon" element's content is an IRI reference [RFC3987] that identifies an image that provides * iconic visual identification for a feed... The image SHOULD have an aspect ratio of one (horizontal) to one * (vertical) and SHOULD be suitable for presentation at a small size. * * @param iri The atom:icon element */ <T extends Source> T setIconElement(IRIElement iri); /** * RFC4287: The "atom:icon" element's content is an IRI reference [RFC3987] that identifies an image that provides * iconic visual identification for a feed... The image SHOULD have an aspect ratio of one (horizontal) to one * (vertical) and SHOULD be suitable for presentation at a small size. * * @param iri The atom:icon IRI value * @throws IRISyntaxException if the iri is malformed */ IRIElement setIcon(String iri); /** * RFC4287: The "atom:icon" element's content is an IRI reference [RFC3987] that identifies an image that provides * iconic visual identification for a feed... The image SHOULD have an aspect ratio of one (horizontal) to one * (vertical) and SHOULD be suitable for presentation at a small size. * * @return The atom:icon value * @throws IRISyntaxException if the atom:icon value is malformed */ IRI getIcon(); /** * RFC4287: The "atom:id" element conveys a permanent, universally unique identifier for an entry or feed. * * @return The atom:id element */ IRIElement getIdElement(); /** * RFC4287: The "atom:id" element conveys a permanent, universally unique identifier for an entry or feed. * * @param id A atom:id element */ <T extends Source> T setIdElement(IRIElement id); /** * Returns the universally unique identifier for this feed * * @return The atom:id value * @throws IRISyntaxException if the atom:id is malformed */ IRI getId(); /** * Sets the universally unique identifier for this feed * * @param id The atom:id value * @return The newly created atom:id element * @throws IRISyntaxException if the id is malformed */ IRIElement setId(String id); /** * Creates a new randomized atom:id for the entry */ IRIElement newId(); /** * Sets the universally unique identifier for this feed * * @param id The atom:id value * @param normalize True if the atom:id value should be normalized * @return The newly created atom:id element * @throws IRISyntaxException if the id is malformed */ IRIElement setId(String id, boolean normalize); /** * Lists the complete set of links for this entry * * @return returns a listing of atom:link elements */ List<Link> getLinks(); /** * Lists the complete set of links using the specified rel attribute value * * @param rel A link relation * @return A listing of atom:link elements */ List<Link> getLinks(String rel); /** * Lists the complete set of links using the specified rel attributes values * * @param rels A listing of link relations * @return A listof atom:link elements */ List<Link> getLinks(String... rel); /** * Adds an individual link to the entry * * @param link A atom:link element */ <T extends Source> T addLink(Link link); /** * Adds an individual link element * * @param href The href IRI of the link * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href); /** * Adds an individual link element * * @param href The href IRI of the link * @param rel The link rel attribute * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href, String rel); /** * Adds an individual link element * * @param href The href IRI of the link * @param rel The link rel attribute * @param type The link type attribute * @param hreflang The link hreflang attribute * @param length The length attribute * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href, String rel, String type, String title, String hreflang, long length); /** * RFC4287: The "atom:logo" element's content is an IRI reference [RFC3987] that identifies an image that provides * visual identification for a feed. The image SHOULD have an aspect ratio of 2 (horizontal) to 1 (vertical). * * @return the atom:logo element */ IRIElement getLogoElement(); /** * RFC4287: The "atom:logo" element's content is an IRI reference [RFC3987] that identifies an image that provides * visual identification for a feed. The image SHOULD have an aspect ratio of 2 (horizontal) to 1 (vertical). * * @param iri The atom:logo element */ <T extends Source> T setLogoElement(IRIElement iri); /** * RFC4287: The "atom:logo" element's content is an IRI reference [RFC3987] that identifies an image that provides * visual identification for a feed. The image SHOULD have an aspect ratio of 2 (horizontal) to 1 (vertical). * * @param iri The atom:logo value * @return The newly created atom:logo element * @throws IRISyntaxException if the iri is malformed */ IRIElement setLogo(String iri); /** * RFC4287: The "atom:logo" element's content is an IRI reference [RFC3987] that identifies an image that provides * visual identification for a feed. The image SHOULD have an aspect ratio of 2 (horizontal) to 1 (vertical). * * @return The atom:logo element value * @throws IRISyntaxException if the atom:logo value is malformed */ IRI getLogo(); /** * <p> * The rights element is typically used to convey a human readable copyright (e.g. "&lt;atom:rights>Copyright (c), * 2006&lt;/atom:rights>). * </p> * <p> * RFC4287: The "atom:rights" element is a Text construct that conveys information about rights held in and over an * entry or feed. * </p> * * @return The atom:rights element */ Text getRightsElement(); /** * <p> * The rights element is typically used to convey a human readable copyright (e.g. "&lt;atom:rights>Copyright (c), * 2006&lt;/atom:rights>). * </p> * <p> * RFC4287: The "atom:rights" element is a Text construct that conveys information about rights held in and over an * entry or feed. * </p> * * @param text The atom:rights element */ <T extends Source> T setRightsElement(Text text); /** * Sets the value of the rights as @type="text" * * @param value The atom:rights text value * @return The newly created atom:rights element */ Text setRights(String value); /** * Sets the value of the rights as @type="html" * * @param value The atom:rights text value * @return The newly created atom:rights element */ Text setRightsAsHtml(String value); /** * Sets the value of the rights as @type="xhtml" * * @param value The atom:rights text value * @return The newly created atom:rights element */ Text setRightsAsXhtml(String value); /** * Sets the value of the rights * * @param value The atom:rights text value * @param type The atom:rights text type * @return The newly created atom:rights element */ Text setRights(String value, Text.Type type); /** * Sets the value of the rights as @type="xhtml" * * @param value The XHTML div element * @return The newly created atom:rights element */ Text setRights(Div value); /** * Returns the text of atom:rights * * @return The value of the atom:rights element */ String getRights(); /** * Returns the type of atom:rights * * @return The Text.Type of the atom:rights element */ Text.Type getRightsType(); /** * RFC4287: The "atom:subtitle" element is a Text construct that conveys a human-readable description or subtitle * for a feed. * * @return The atom:subtitle element */ Text getSubtitleElement(); /** * RFC4287: The "atom:subtitle" element is a Text construct that conveys a human-readable description or subtitle * for a feed. * * @param text A atom:subtitle element */ <T extends Source> T setSubtitleElement(Text text); /** * Sets the value of the subtitle as @type="text" * * @param value the value of the atom:subtitle element * @return The atom:subtitle element */ Text setSubtitle(String value); /** * Sets the value of the subtitle as @type="html" * * @param value The value of the atom:subtitle element * @return The newly created atom:subtitle element */ Text setSubtitleAsHtml(String value); /** * Sets the value of the subtitle as @type="xhtml" * * @param value The value of the atom:subtitle element * @return The newly created atom:subtitle element */ Text setSubtitleAsXhtml(String value); /** * Sets the value of the subtitle * * @param value The value of the atom:subtitle element * @param type The atom:subtitle Text.Type * @return The newly created atom:subtitle element */ Text setSubtitle(String value, Text.Type type); /** * Sets the value of the subtitle as @type="xhtml" * * @param value The atom:subtitle element * @return The newly created atom:subtitle element */ Text setSubtitle(Div value); /** * Returns the text value of atom:subtitle * * @return The atom:subtitle text value */ String getSubtitle(); /** * Returns the atom:subtitle type * * @return The atom:subtitle Text.Type */ Text.Type getSubtitleType(); /** * RFC4287: The "atom:title" element is a Text construct that conveys a human-readable title for an entry or feed. * * @return The atom:title element */ Text getTitleElement(); /** * RFC4287: The "atom:title" element is a Text construct that conveys a human-readable title for an entry or feed. * * @param text The atom:title element */ <T extends Source> T setTitleElement(Text text); /** * Sets the value of the title as @type="text" * * @param value The atom:title value * @return The newly created atom:title element */ Text setTitle(String value); /** * Sets the value of the title as @type="html" * * @param value The atom:title value * @return The newly created atom:title element */ Text setTitleAsHtml(String value); /** * Sets the value of the title as @type="xhtml" * * @param value The atom:title value * @return The newly created atom:title element */ Text setTitleAsXhtml(String value); /** * Sets the value of the title * * @param value The atom:title value * @param type The atom:title Text.Type * @return The newly created atom:title element */ Text setTitle(String value, Text.Type type); /** * Sets the value of the title as @type="xhtml" * * @param value The XHTML div * @return The newly created atom:title element */ Text setTitle(Div value); /** * Returns the text of atom:title * * @return The text value of the atom:title element */ String getTitle(); /** * Returns the type of atom:title * * @return The atom:title Text.Type value */ Text.Type getTitleType(); /** * RFC4287: The "atom:updated" element is a Date construct indicating the most recent instant in time when an entry * or feed was modified in a way the publisher considers significant. Therefore, not all modifications necessarily * result in a changed atom:updated value. * * @return the atom:updated element */ DateTime getUpdatedElement(); /** * RFC4287: The "atom:updated" element is a Date construct indicating the most recent instant in time when an entry * or feed was modified in a way the publisher considers significant. Therefore, not all modifications necessarily * result in a changed atom:updated value. * * @param dateTime A atom:updated element */ <T extends Source> T setUpdatedElement(DateTime dateTime); /** * Return the atom:updated value * * @return The serialized string form value of atom:updated */ String getUpdatedString(); /** * Return the atom:updated value * * @return The atom:updated as a java.util.Date */ Date getUpdated(); /** * Set the atom:updated value * * @param value The java.util.Date * @return The newly created atom:updated element */ DateTime setUpdated(Date value); /** * Set the atom:updated value * * @param value The serialized string date * @return The newly created atom:updated element */ DateTime setUpdated(String value); /** * Returns the first link with the specified rel attribute value * * @param rel A link relation * @return The newly created atom:link element */ Link getLink(String rel); /** * Returns the first link using the rel attribute value "self" * * @return An atom:link */ Link getSelfLink(); /** * Returns this entries first alternate link * * @return An atom:link */ Link getAlternateLink(); /** * @param type A media type * @param hreflang A target language * @return A matching atom:link * @throws MimeTypeParseException if the type if malformed */ Link getAlternateLink(String type, String hreflang); /** * @param rel A link relation * @return An atom:link */ IRI getLinkResolvedHref(String rel); /** * @return An atom:link */ IRI getSelfLinkResolvedHref(); /** * @return An atom:link */ IRI getAlternateLinkResolvedHref(); /** * @param type A media type * @param hreflang A target language * @return A matching atom:link * @throws MimeTypeParseException if the type if malformed */ IRI getAlternateLinkResolvedHref(String type, String hreflang); /** * Return an app:collection element associatd with this atom:source. The Atom Publishing Protocol allows an * app:collection to be contained by atom:feed to specify the collection to which the feed is associated. * * @return An app:collection element */ Collection getCollection(); /** * Set the app:collection element * * @param collection An app:collection element */ <T extends Source> T setCollection(Collection collection); /** * Convert the Source element into an empty Feed element */ Feed getAsFeed(); }
3,345
apache/abdera/core/src/main/java/org/apache/abdera/model/Text.java
package org.apache.abdera.model; /** * <p> * Represents an Atom Text Contruct. * </p> * <p> * Atom allows three kinds of Text constructs: * </p> * <ul> * <li>Text, consisting of content that is to be interpreted as plain text with no markup. For instance, * <code>&lt;title type="text">&amp;lt;title&amp;gt;&lt;/title></code> is interpreted as literal characer "&lt;" * followed by the word "content", followed by the literal character "&gt;".</li> * <li>HTML, consisting of content that is to be interpreted as escaped HTML markup. For instance, * <code>&lt;title type="html">&amp;lt;b&amp;gt;title&amp;lt;/b&amp;gt;&lt;/title></code> is interpreted as the word * "content" surrounded by the HTML <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> tags.</li> * <li>XHTML, consisting of well-formed XHTML content wrapped in an XHTML div element. For instance, * <code>&lt;title type="xhtml">&lt;div xmlns="http://www.w3.org/1999/xhtml">&lt;b>Title&lt;/b>&lt;/div>&lt;/title></code> * .</li> * </ul> * <p> * Per RFC4287: * </p> * * <pre> * A Text construct contains human-readable text, usually in small * quantities. The content of Text constructs is Language-Sensitive. * * atomPlainTextConstruct = * atomCommonAttributes, * attribute type { "text" | "html" }?, * text * * atomXHTMLTextConstruct = * atomCommonAttributes, * attribute type { "xhtml" }, * xhtmlDiv * * atomTextConstruct = atomPlainTextConstruct | atomXHTMLTextConstruct * </pre> */ public interface Text extends Element { /** * Text Constructs can be either Text, HTML or XHTML */ public static enum Type { /** Plain Text **/ TEXT, /** Escaped HTML **/ HTML, /** Welformed XHTML **/ XHTML; /** * Return the text type */ public static Type typeFromString(String val) { Type type = TEXT; if (val != null) { if (val.equalsIgnoreCase("text")) type = TEXT; else if (val.equalsIgnoreCase("html")) type = HTML; else if (val.equalsIgnoreCase("xhtml")) type = XHTML; else type = null; } return type; } }; /** * Return the Text.Type * * @return The Text.Type */ Type getTextType(); /** * Set the Text.Type * * @param type The Text.Type */ Text setTextType(Type type); /** * Return the text value element * * @return A xhtml:div */ Div getValueElement(); /** * Set the text value element * * @param value The xhtml:div */ Text setValueElement(Div value); /** * Return the text value * * @return The text value */ String getValue(); /** * Set the text value * * @param value The text value */ Text setValue(String value); /** * Return the wrapped value * * @return The text value wrapped in a xhtml:div */ String getWrappedValue(); /** * Set the wrapped value * * @param wrappedValue The text value wrapped in a xhtml:div */ Text setWrappedValue(String wrappedValue); }
868
apache/abdera/core/src/main/java/org/apache/abdera/model/TextValue.java
package org.apache.abdera.model; import java.io.InputStream; import javax.activation.DataHandler; /** * A text value. Returned by the Abdera XPath implementation when querying for text nodes (e.g. * xpath.selectNodes("//text()"); ...). There should be very little reason why an application would use this. It is * provided to keep applications from having to deal directly with the underlying parser impl */ public interface TextValue { /** * A DataHandler for Base64 encoded binary data */ DataHandler getDataHandler(); /** * An InputStream used to read the text content */ InputStream getInputStream(); /** * Return the text value */ String getText(); /** * The parent element */ <T extends Base> T getParentElement(); /** * Delete this node */ void discard(); }
3,846
apache/abdera/core/src/main/java/org/apache/abdera/model/Workspace.java
package org.apache.abdera.model; import java.util.List; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * An Atom Publishing Protocol Introspection Document workspace element. * </p> * <p> * Per APP Draft-08 * </p> * * <pre> * The "app:workspace" element contains information elements about the * collections of resources available for editing. The app:workspace * element MUST contain one or more app:collection elements. * * appWorkspace = * element app:workspace { * appCommonAttributes, * ( atomTitle * &amp; appCollection* * &amp; extensionElement* ) * } * * </pre> */ public interface Workspace extends ExtensibleElement { /** * Return the workspace title * * @return The atom:title value */ String getTitle(); /** * Set the workspace title * * @param title The atom:title value * @return The newly created atom:title */ Text setTitle(String title); /** * Set the workspace title as escaped HTML * * @param title The atom:title value * @return The newly created atom:title */ Text setTitleAsHtml(String title); /** * Set the workspace title as XHTML * * @param title The atom:title value * @return the newly created atom:title */ Text setTitleAsXHtml(String title); /** * Return the atom:title * * @return The atom:title element */ Text getTitleElement(); /** * Returns the full set of collections in this workspace * * @return A listing of app:collection elements */ List<Collection> getCollections(); /** * Returns the named collection * * @param title A collection title * @return A matching app:collection */ Collection getCollection(String title); /** * Adds an individual collection to this workspace * * @param collection The collection to add */ Workspace addCollection(Collection collection); /** * Adds an individual collection to this workspace * * @param title The collection title * @param href The collection HREF * @return The newly created app:collection * @throws IRISyntaxException if the href is malformed */ Collection addCollection(String title, String href); /** * Adds a multipart collection to this workspace * * @param title The collection title * @param href The collection HREF * @return The newly created app:collection * @throws IRISyntaxException if the href is malformed */ public Collection addMultipartCollection(String title, String href); /** * Returns a collection that accepts the specified media types * * @param a listing of media types the collection must accept * @return A matching app:collection element */ Collection getCollectionThatAccepts(MimeType... type); /** * Returns a collection that accepts the specified media types * * @param a listing of media types the collection must accept * @return A matching app:collection element */ Collection getCollectionThatAccepts(String... type); /** * Returns collections that accept the specified media types * * @param a listing of media types the collection must accept * @return A listing matching app:collection elements */ List<Collection> getCollectionsThatAccept(MimeType... type); /** * Returns collections that accept the specified media types * * @param a listing of media types the collection must accept * @return A listing of matching app:collection elements */ List<Collection> getCollectionsThatAccept(String... type); }
1,173
apache/abdera/core/src/main/java/org/apache/abdera/parser/NamedParser.java
package org.apache.abdera.parser; import org.apache.abdera.util.NamedItem; /** * Abdera's abstract parsing model allows developers to implement parsers capable of translating non-Atom formats into * Abdera objects. For instance, a developer could create an RDF, RSS, JSON or hAtom microformat parser that * automatically converted to Atom. Alternative parsers are made available via the ParserFactory interface. * * <pre> * Parser parser = abdera.getParserFactory().getParser("json"); * Document&lt;Feed> doc = parser.parse(...); * * Parser parser = abdera.getParserFactory().getParser("hatom"); * Document&lt;Feed> doc = parser.parse(...); * </pre> */ public interface NamedParser extends Parser, NamedItem { /** * Returns a listing of media type of the format consumed by this parser * * @return An array of MIME Media Types */ String[] getInputFormats(); /** * Returns true if this parser is capable of consuming the specified media type * * @param mediatype The MIME media type to check * @return True if the media type is supported */ boolean parsesFormat(String mediatype); }
468
apache/abdera/core/src/main/java/org/apache/abdera/parser/ParseException.java
package org.apache.abdera.parser; public class ParseException extends RuntimeException { private static final long serialVersionUID = -2586758177341912116L; public ParseException() { super(); } public ParseException(String message) { super(message); } public ParseException(String message, Throwable cause) { super(message, cause); } public ParseException(Throwable cause) { super(cause); } }
8,211
apache/abdera/core/src/main/java/org/apache/abdera/parser/Parser.java
package org.apache.abdera.parser; import java.io.InputStream; import java.io.Reader; import java.nio.channels.ReadableByteChannel; import javax.xml.stream.XMLStreamReader; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; public interface Parser { /** * Parse the input stream using the default character set encoding (UTF-8) * * @param in The input stream to parse * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(InputStream in) throws ParseException; /** * Parse the input stream using the default character set encoding (UTF-8) * * @param reader The XMLStreamReader to use to parse * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(XMLStreamReader reader) throws ParseException; /** * Parse the input stream using the default character set encoding (UTF-8). The specified Base URI is used to * resolve relative references contained in the document * * @param in The input stream to parse * @param base The Base URI of the document * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(InputStream in, String base) throws ParseException; /** * Parse the input stream using the default character set encoding (UTF-8). The specified Base URI is used to * resolve relative references contained in the document * * @param in The input stream to parse * @param options The Parse options * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(InputStream in, ParserOptions options) throws ParseException; /** * Parse the input stream using using the specified Parse options. The parse options can be used to control various * aspects of the parsing process such as the character set encoding to use and whether certain elements should be * ignored. The specified Base URI is used to resolve relative references contained in the document. * * @param in The input stream to parse * @param base The Base URI of the document * @param options The Parse Options * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(InputStream in, String base, ParserOptions options) throws ParseException; /** * Parse the reader using the default Base URI and options * * @param in The Reader to parse * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(Reader in) throws ParseException; /** * Parse the reader using the specified Base URI * * @param in The Reader to parse * @param base The Base URI * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(Reader in, String base) throws ParseException; /** * Parse the reader using the specified Base URI * * @param in The Reader to parse * @param options The Parse Options * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(Reader in, ParserOptions options) throws ParseException; /** * Parse the reader using using the specified Parse options. The parse options can be used to control various * aspects of the parsing process such as the character set encoding to use and whether certain elements should be * ignored. The specified Base URI is used to resolve relative references contained in the document. * * @param in The reader to parse * @param base The Base URI of the document * @param options The Parse Options * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(Reader in, String base, ParserOptions options) throws ParseException; /** * Parse the channel using using the specified Parse options. The parse options can be used to control various * aspects of the parsing process such as the character set encoding to use and whether certain elements should be * ignored. The specified Base URI is used to resolve relative references contained in the document. * * @param in The ReadableByteChannel to parse * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(ReadableByteChannel buf) throws ParseException; /** * Parse the channel using using the specified Parse options. The parse options can be used to control various * aspects of the parsing process such as the character set encoding to use and whether certain elements should be * ignored. The specified Base URI is used to resolve relative references contained in the document. * * @param in The ReadableByteChannel to parse * @param base The Base URI of the document * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(ReadableByteChannel buf, String base) throws ParseException; /** * Parse the channel using using the specified Parse options. The parse options can be used to control various * aspects of the parsing process such as the character set encoding to use and whether certain elements should be * ignored. The specified Base URI is used to resolve relative references contained in the document. * * @param in The ReadableByteChannel to parse * @param base The Base URI of the document * @param options The Parse Options * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(ReadableByteChannel buf, String base, ParserOptions options) throws ParseException; /** * Parse the channel using using the specified Parse options. The parse options can be used to control various * aspects of the parsing process such as the character set encoding to use and whether certain elements should be * ignored. The specified Base URI is used to resolve relative references contained in the document. * * @param reader the XMLStreamReader parser to use to parse * @param base The Base URI of the document * @param options The Parse Options * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(XMLStreamReader reader, String base, ParserOptions options) throws ParseException; /** * Parse the channel using using the specified Parse options. The parse options can be used to control various * aspects of the parsing process such as the character set encoding to use and whether certain elements should be * ignored. The specified Base URI is used to resolve relative references contained in the document. * * @param in The ReadableByteChannel to parse * @param options The Parse Options * @return The parsed Abdera Document * @throws ParseException if the parse failed */ <T extends Element> Document<T> parse(ReadableByteChannel buf, ParserOptions options) throws ParseException; /** * Return the default parser options for this Parser. This method returns a copy of the default options. Changes to * this instance will not affect the defaults returned by subsequent requests. * * @return The default ParserOptions */ ParserOptions getDefaultParserOptions(); /** * Set the default parser options for this Parser. This method copies the specified options. * * @param options The Parser Options to use as the default */ Parser setDefaultParserOptions(ParserOptions options); }
622
apache/abdera/core/src/main/java/org/apache/abdera/parser/ParserFactory.java
package org.apache.abdera.parser; /** * The ParserFactory is used a acquire instances of alternative parsers registered with Abdera. * * @see org.apache.abdera.parser.NamedParser */ public interface ParserFactory { /** * Get the default parser. This is equivalent to calling Abdera.getParser() * * @return The default parser implementation */ <T extends Parser> T getParser(); /** * Get the named parser * * @param name The name of the parser instance to retrieve * @return The Named parser instance */ <T extends Parser> T getParser(String name); }
5,068
apache/abdera/core/src/main/java/org/apache/abdera/parser/ParserOptions.java
package org.apache.abdera.parser; import java.util.Map; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; import org.apache.abdera.filter.ParseFilter; import org.apache.abdera.i18n.text.io.CompressionUtil.CompressionCodec; /** * Parser options are used to modify the behavior of the parser. */ public interface ParserOptions extends Cloneable { Object clone() throws CloneNotSupportedException; /** * Returns the factory the parser should use */ Factory getFactory(); /** * Sets the factory the parser should use */ ParserOptions setFactory(Factory factory); /** * Returns the default character set to use for the parsed document */ String getCharset(); /** * Sets the character set to use for the parsed document */ ParserOptions setCharset(String charset); /** * Returns the Parse Filter. The parse filter is a set of XML QNames that the parse should watch out for. If the * filter is null, the parser will parse all elements in the document. I the filter is not null, the parser will * only pay attention to elements whose QName's appear in the filter list. */ ParseFilter getParseFilter(); /** * Sets the Parse Filter. The parse filter is a set of XML QNames that the parse should watch out for. If the filter * is null, the parser will parse all elements in the document. I the filter is not null, the parser will only pay * attention to elements whose QName's appear in the filter list. */ ParserOptions setParseFilter(ParseFilter parseFilter); /** * Returns true if the parser should attempt to automatically detect the character encoding from the stream */ boolean getAutodetectCharset(); /** * If true, the parser will attempt to automatically detect the character encoding from the stream by checking for * the byte order mark or checking the XML prolog. */ ParserOptions setAutodetectCharset(boolean detect); /** * If false, the parser will trim leading and trailing whitespace in element and attribute values unless there is an * in-scope xml:space="preserve". */ boolean getMustPreserveWhitespace(); /** * If false, the parser will trim leading and trailing whitespace in element and attribute values unless there is an * in-scope xml:space="preserve". */ ParserOptions setMustPreserveWhitespace(boolean preserve); /** * If true, the parser will attempt to silently filter out invalid XML characters appearing within the XML document. */ boolean getFilterRestrictedCharacters(); /** * If true, the parser will attempt to silently filter out invalid XML characters appearing within the XML document */ ParserOptions setFilterRestrictedCharacters(boolean filter); /** * If getFilterRestrictedCharacters is true, restricted characters will be replaced with the specified character */ char getFilterRestrictedCharacterReplacement(); /** * If getFilterRestrictedCharacters is true, restricted characters will be replaced with the specified character */ ParserOptions setFilterRestrictedCharacterReplacement(char replacement); /** * When parsing an InputStream that contains compressed data, use these codecs to decompress the stream. Only used * when parsing an InputStream. Ignored when parsing a Reader */ CompressionCodec[] getCompressionCodecs(); /** * When parsing an InputStream that contains compressed data, use these codecs to decompress the stream. Only used * when parsing an InputStream. Ignored when parsing a Reader */ ParserOptions setCompressionCodecs(CompressionCodec... codecs); /** * Register a named entity. This provides an escape clause for when feeds use entities that are not supported in XML * without a DTD decl. By default, all of the (X)HTML entities are preregistered */ ParserOptions registerEntity(String name, String value); /** * Resolves a value for a named entity. This provides an escape clause for when feeds use entities that are not * supported in XML without a DTD decl. By default, all of the (X)HTML entities are preregistered */ String resolveEntity(String name); /** * True if undeclared named entities should be resolved. */ ParserOptions setResolveEntities(boolean resolve); /** * True if undeclared named entities should be resolved. */ boolean getResolveEntities(); /** * True if QName-Alias mapping is enabled */ ParserOptions setQNameAliasMappingEnabled(boolean enabled); /** * True if QName-Alias mapping is enabled (default is false) */ boolean isQNameAliasMappingEnabled(); /** * Get the QName-Alias Mapping (default null) */ Map<QName, QName> getQNameAliasMap(); /** * Set the QName-Alias Mapping */ ParserOptions setQNameAliasMap(Map<QName, QName> map); }
901
apache/abdera/core/src/main/java/org/apache/abdera/protocol/EntityProvider.java
package org.apache.abdera.protocol; import java.util.Date; import org.apache.abdera.util.EntityTag; import org.apache.abdera.writer.StreamWriter; /** * An EntityProvider is used to serialize entities using the StreamWriter interface. The EntityProvider interface can be * implemented by applications to provide an efficient means of serializing non-FOM objects to Atom/XML. */ public interface EntityProvider { /** * Write to the specified StreamWriter */ void writeTo(StreamWriter sw); /** * True if the serialization is repeatable. */ boolean isRepeatable(); /** * Return the mime content type of the serialized entity */ String getContentType(); /** * Return the EntityTag of the entity, */ EntityTag getEntityTag(); /** * Return the Last-Modified date of the entity */ Date getLastModified(); }
396
apache/abdera/core/src/main/java/org/apache/abdera/protocol/ItemManager.java
package org.apache.abdera.protocol; /** * ItemManager is an internal utility class that provides a simple get/release interface. It is used primarily to * control access to pooled resources. */ public interface ItemManager<T> { /** * Get an item based on the specified request */ T get(Request request); /** * Release an item */ void release(T item); }
1,942
apache/abdera/core/src/main/java/org/apache/abdera/protocol/Message.java
package org.apache.abdera.protocol; import java.util.Date; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.protocol.util.ProtocolConstants; /** * A protocol message. This is used as the basis for both request and response objects in order to provide a consistent * interface. */ public interface Message extends ProtocolConstants { /** * Get the value of the specified header */ String getHeader(String name); /** * Get the decoded value of a RFC 2047 header */ String getDecodedHeader(String name); /** * Return multiple values for the specified header */ Object[] getHeaders(String name); /** * Return multiple decoded values for the specified header */ String[] getDecodedHeaders(String name); /** * Return a listing of header names */ String[] getHeaderNames(); /** * Return the value of the Cache-Control header */ String getCacheControl(); /** * Return the value of the Slug header */ String getSlug(); /** * Return the value of the Content-Type header */ MimeType getContentType(); /** * Return the value of the Content-Location header */ IRI getContentLocation(); /** * Return the value of the Content-Language header */ String getContentLanguage(); /** * Return the value of a Date header */ Date getDateHeader(String name); /** * Return the maximum-age as specified by the Cache-Control header */ long getMaxAge(); /** * Return true if the Cache-Control header contains no-cache */ boolean isNoCache(); /** * Return true if the Cache-Control header contains no-store */ boolean isNoStore(); /** * Return true if the Cache-Control header contains no-transform */ boolean isNoTransform(); }
1,466
apache/abdera/core/src/main/java/org/apache/abdera/protocol/Request.java
package org.apache.abdera.protocol; import java.util.Date; import org.apache.abdera.util.EntityTag; /** * A protocol request. This is used as a base for both server and client requests */ public interface Request extends Message { /** * Get the value of the Accept header */ String getAccept(); /** * Get the value of the Accept-Charset header */ String getAcceptCharset(); /** * Get the value of the Accept-Encoding header */ String getAcceptEncoding(); /** * Get the value of the Accept-Language header */ String getAcceptLanguage(); /** * Get the value of the Authorization header */ String getAuthorization(); /** * Get a listing of Etags from the If-Match header */ EntityTag[] getIfMatch(); /** * Get the value of the If-Modified-Since header */ Date getIfModifiedSince(); /** * Get a listing of ETags from the If-None-Match header */ EntityTag[] getIfNoneMatch(); /** * Get the value of the If-Unmodified-Since header */ Date getIfUnmodifiedSince(); /** * Get the max-stale value from the Cache-Control header */ long getMaxStale(); /** * Get the min-fresh value from the Cache-Control header */ long getMinFresh(); /** * True if the only-if-cached directive is set in the Cache-Control header */ boolean isOnlyIfCached(); }
283
apache/abdera/core/src/main/java/org/apache/abdera/protocol/Resolver.java
package org.apache.abdera.protocol; /** * The Resolver interface is a utility class used to resolve objects based on a request. It is used internally by Abdera * as the basis for Target and Subject resolvers. */ public interface Resolver<T> { T resolve(Request request); }
2,368
apache/abdera/core/src/main/java/org/apache/abdera/protocol/Response.java
package org.apache.abdera.protocol; import java.util.Date; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.util.EntityTag; /** * Base interface for an Atompub protocol response message */ public interface Response extends Message { /** * High level classifications of response types */ public static enum ResponseType { SUCCESS, REDIRECTION, CLIENT_ERROR, SERVER_ERROR, UNKNOWN; public static ResponseType select(int status) { if (status >= 200 && status < 300) return SUCCESS; if (status >= 300 && status < 400) return REDIRECTION; if (status >= 400 && status < 500) return CLIENT_ERROR; if (status >= 500 && status < 600) return SERVER_ERROR; return UNKNOWN; } } /** * Get the Entity Tag returned by the server */ EntityTag getEntityTag(); /** * Get the response type classification */ ResponseType getType(); /** * Get the specific response status code */ int getStatus(); /** * Get the response status text */ String getStatusText(); /** * Get the value of the Last-Modified response header */ Date getLastModified(); /** * Get the value of the Content-Length response header */ long getContentLength(); /** * Get the value of the Allow response header */ String getAllow(); /** * Get the value of the Location response header */ IRI getLocation(); /** * True if the Cache-Control header specifies the private directive */ boolean isPrivate(); /** * True if the Cache-Control header specified the public directive */ boolean isPublic(); /** * True if the Cache-Control header specifies the must-revalidate directive */ boolean isMustRevalidate(); /** * True if the Cache-Control header specifies the proxy-revalidate directive */ boolean isProxyRevalidate(); long getSMaxAge(); /** * Get the age of this response as specified by the server */ long getAge(); /** * Get the date/time this response expires */ Date getExpires(); String[] getNoCacheHeaders(); String[] getPrivateHeaders(); }
3,623
apache/abdera/core/src/main/java/org/apache/abdera/protocol/error/Error.java
package org.apache.abdera.protocol.error; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.ExtensibleElementWrapper; import org.apache.abdera.writer.StreamWriter; /** * Abdera protocol error element. The Abdera error document provides a simple structure for reporting errors back to * Abdera clients. */ public class Error extends ExtensibleElementWrapper { public static final String NS = "http://abdera.apache.org"; public static final QName ERROR = new QName(NS, "error"); public static final QName CODE = new QName(NS, "code"); public static final QName MESSAGE = new QName(NS, "message"); public Error(Element internal) { super(internal); } public Error(Factory factory, QName qname) { super(factory, qname); } /** * The code should typically match the HTTP status code; however, certain application scenarios may require the use * of a different code */ public int getCode() { String code = getSimpleExtension(CODE); return code != null ? Integer.parseInt(code) : -1; } /** * The code should typically match the HTTP status code; however, certain application scenarios may require the use * of a different code */ public Error setCode(int code) { if (code > -1) { Element element = getExtension(CODE); if (element != null) { element.setText(Integer.toString(code)); } else { addSimpleExtension(CODE, Integer.toString(code)); } } else { Element element = getExtension(CODE); if (element != null) element.discard(); } return this; } /** * Human-readable, language-sensitive description of the error */ public String getMessage() { return getSimpleExtension(MESSAGE); } /** * Human-readable, language-sensitive description of the error */ public Error setMessage(String message) { if (message != null) { Element element = getExtension(MESSAGE); if (element != null) { element.setText(message); } else { addSimpleExtension(MESSAGE, message); } } else { Element element = getExtension(MESSAGE); if (element != null) element.discard(); } return this; } /** * Will throw a ProtocolException that wraps this element. This is useful on the client side to surface error * responses */ public void throwException() { throw new ProtocolException(this); } /** * Create a new Error object */ public static Error create(Abdera abdera, int code, String message) { return create(abdera, code, message, null); } public static Error create(Abdera abdera, int code, String message, Throwable t) { Document<Error> doc = abdera.getFactory().newDocument(); Error error = abdera.getFactory().newElement(ERROR, doc); error.setCode(code).setMessage(message); return error; } public static void create(StreamWriter sw, int code, String message, Throwable t) { sw.startDocument().startElement(ERROR).startElement(CODE).writeElementText(code).endElement() .startElement(MESSAGE).writeElementText(message).endElement().endElement().endDocument(); } }
285
apache/abdera/core/src/main/java/org/apache/abdera/protocol/error/ErrorExtensionFactory.java
package org.apache.abdera.protocol.error; import org.apache.abdera.util.AbstractExtensionFactory; public class ErrorExtensionFactory extends AbstractExtensionFactory { public ErrorExtensionFactory() { super(Error.NS); addImpl(Error.ERROR, Error.class); } }
1,793
apache/abdera/core/src/main/java/org/apache/abdera/protocol/error/ProtocolException.java
package org.apache.abdera.protocol.error; import org.apache.abdera.Abdera; public class ProtocolException extends RuntimeException { private static final long serialVersionUID = 1017447143200419489L; private final Error error; public ProtocolException(Error error) { super(error.getCode() + "::" + error.getMessage()); this.error = error; } public ProtocolException(Abdera abdera, int code, String message) { super(code + "::" + message); this.error = Error.create(abdera, code, message); } public Error getError() { return error; } @Override public int hashCode() { final int prime = 31; int result = 1; String message = error != null ? error.getMessage() : null; int code = error != null ? error.getCode() : 0; result = prime * result + ((message == null) ? 0 : message.hashCode()); result = prime * result + code; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ProtocolException other = (ProtocolException)obj; String message = error != null ? error.getMessage() : null; int code = error != null ? error.getCode() : 0; String omessage = other.error != null ? other.error.getMessage() : null; int ocode = other.error != null ? other.error.getCode() : 0; if (message == null) { if (omessage != null) return false; } else if (!message.equals(omessage)) return false; if (code != ocode) return false; return true; } }
442
apache/abdera/core/src/main/java/org/apache/abdera/protocol/util/AbstractEntityProvider.java
package org.apache.abdera.protocol.util; import java.util.Date; import org.apache.abdera.protocol.EntityProvider; import org.apache.abdera.util.EntityTag; public abstract class AbstractEntityProvider implements EntityProvider { public String getContentType() { return "application/xml"; } public EntityTag getEntityTag() { return null; } public Date getLastModified() { return null; } }
433
apache/abdera/core/src/main/java/org/apache/abdera/protocol/util/AbstractItemManager.java
package org.apache.abdera.protocol.util; import org.apache.abdera.protocol.ItemManager; import org.apache.abdera.protocol.Request; public abstract class AbstractItemManager<T> extends PoolManager<T> implements ItemManager<T> { public AbstractItemManager() { super(); } public AbstractItemManager(int max) { super(max); } public T get(Request request) { return getInstance(); } }
2,561
apache/abdera/core/src/main/java/org/apache/abdera/protocol/util/AbstractMessage.java
package org.apache.abdera.protocol.util; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.text.Rfc2047Helper; import org.apache.abdera.i18n.text.UrlEncoding; import org.apache.abdera.protocol.Message; /** * Root impl for Message interface impls. This is provided solely as a way of keeping the interface and impl's * consistent across the Request and Response objects. */ public abstract class AbstractMessage implements Message { protected int flags = 0; protected long max_age = -1; public String getCacheControl() { return getHeader("Cache-Control"); } public String getContentLanguage() { return getHeader("Content-Language"); } public IRI getContentLocation() { String value = getHeader("Content-Location"); return (value != null) ? new IRI(value) : null; } public MimeType getContentType() { try { String value = getHeader("Content-Type"); return (value != null) ? new MimeType(value) : null; } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } } public String getDecodedHeader(String header) { return UrlEncoding.decode(Rfc2047Helper.decode(getHeader(header))); } public String[] getDecodedHeaders(String header) { Object[] headers = getHeaders(header); for (int n = 0; n < headers.length; n++) { headers[n] = UrlEncoding.decode(Rfc2047Helper.decode(headers[n].toString())); } return (String[])headers; } public String getSlug() { return getDecodedHeader("Slug"); } protected boolean check(int flag) { return (flags & flag) == flag; } protected void toggle(boolean val, int flag) { if (val) flags |= flag; else flags &= ~flag; } public boolean isNoCache() { if (check(NOCACHE)) return true; Object[] pragma = getHeaders("Pragma"); if (pragma != null) { for (Object o : pragma) { String s = (String)o; if (s.equalsIgnoreCase("no-cache")) { return true; } } } return false; } public boolean isNoStore() { return check(NOSTORE); } public boolean isNoTransform() { return check(NOTRANSFORM); } public long getMaxAge() { return max_age; } }
2,189
apache/abdera/core/src/main/java/org/apache/abdera/protocol/util/AbstractRequest.java
package org.apache.abdera.protocol.util; import java.util.Date; import org.apache.abdera.protocol.Request; import org.apache.abdera.util.EntityTag; public abstract class AbstractRequest extends AbstractMessage implements Request { protected long max_stale = -1; protected long min_fresh = -1; public String getAccept() { return getHeader("Accept"); } public String getAcceptCharset() { return getHeader("Accept-Charset"); } public String getAcceptEncoding() { return getHeader("Accept-Encoding"); } public String getAcceptLanguage() { return getHeader("Accept-Language"); } public String getAuthorization() { return getHeader("Authorization"); } public EntityTag[] getIfMatch() { return EntityTag.parseTags(getHeader("If-Match")); } public Date getIfModifiedSince() { return getDateHeader("If-Modified-Since"); } public EntityTag[] getIfNoneMatch() { return EntityTag.parseTags(getHeader("If-None-Match")); } public Date getIfUnmodifiedSince() { return getDateHeader("If-Unmodified-Since"); } public long getMaxStale() { return max_stale; } public long getMinFresh() { return min_fresh; } public boolean isOnlyIfCached() { return check(ONLYIFCACHED); } public AbstractRequest setMaxAge(long max_age) { this.max_age = max_age; return this; } public AbstractRequest setMaxStale(long max_stale) { this.max_stale = max_stale; return this; } public AbstractRequest setMinFresh(long min_fresh) { this.min_fresh = min_fresh; return this; } public AbstractRequest setNoCache(boolean val) { toggle(val, NOCACHE); return this; } public AbstractRequest setNoStore(boolean val) { toggle(val, NOSTORE); return this; } public AbstractRequest setNoTransform(boolean val) { toggle(val, NOTRANSFORM); return this; } public AbstractRequest setOnlyIfCached(boolean val) { toggle(val, ONLYIFCACHED); return this; } }
3,322
apache/abdera/core/src/main/java/org/apache/abdera/protocol/util/AbstractResponse.java
package org.apache.abdera.protocol.util; import java.util.Date; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.protocol.Response; import org.apache.abdera.util.EntityTag; public abstract class AbstractResponse extends AbstractMessage implements Response { protected String[] nocache_headers = null; protected String[] private_headers = null; protected long smax_age = -1; public long getAge() { String value = getHeader("Age"); try { return (value != null) ? Long.parseLong(value) : -1; } catch (NumberFormatException e) { return -1; } } public String getAllow() { return getHeader("Allow"); } public long getContentLength() { String value = getHeader("Content-Length"); try { return (value != null) ? Long.parseLong(value) : -1; } catch (NumberFormatException e) { return -1; } } public EntityTag getEntityTag() { String etag = getHeader("ETag"); return (etag != null) ? EntityTag.parse(getHeader("ETag")) : null; } public Date getExpires() { return getDateHeader("Expires"); } public Date getLastModified() { return getDateHeader("Last-Modified"); } public IRI getLocation() { String l = getHeader("Location"); return l != null ? new IRI(l) : null; } public String[] getNoCacheHeaders() { return nocache_headers; } public String[] getPrivateHeaders() { return private_headers; } public long getSMaxAge() { return smax_age; } public ResponseType getType() { return ResponseType.select(getStatus()); } public boolean isMustRevalidate() { return check(REVALIDATE); } public boolean isPrivate() { return check(PRIVATE); } public boolean isProxyRevalidate() { return check(PROXYREVALIDATE); } public boolean isPublic() { return check(PUBLIC); } public AbstractResponse setMaxAge(long max_age) { this.max_age = max_age; return this; } public AbstractResponse setMustRevalidate(boolean val) { toggle(val, REVALIDATE); return this; } public AbstractResponse setProxyRevalidate(boolean val) { toggle(val, PROXYREVALIDATE); return this; } public AbstractResponse setNoCache(boolean val) { toggle(val, NOCACHE); return this; } public AbstractResponse setNoStore(boolean val) { toggle(val, NOSTORE); return this; } public AbstractResponse setNoTransform(boolean val) { toggle(val, NOTRANSFORM); return this; } public AbstractResponse setPublic(boolean val) { toggle(val, PUBLIC); return this; } public AbstractResponse setPrivate(boolean val) { if (val) flags |= PRIVATE; else if (isPrivate()) flags ^= PRIVATE; return this; } public AbstractResponse setPrivateHeaders(String... headers) { this.private_headers = headers; return this; } public AbstractResponse setNoCacheHeaders(String... headers) { this.nocache_headers = headers; return this; } }
6,747
apache/abdera/core/src/main/java/org/apache/abdera/protocol/util/CacheControlUtil.java
package org.apache.abdera.protocol.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.abdera.i18n.text.io.CompressionUtil; /** * Provides parsing and properly handling of the HTTP Cache-Control header. */ public class CacheControlUtil { private static enum Idempotent { GET, HEAD, OPTIONS } /** * Idempotent methods are handled differently in caches than other methods */ public static boolean isIdempotent(String method) { try { Idempotent.valueOf(method.toUpperCase()); return true; } catch (Exception e) { return false; } } private static long value(String val) { return (val != null) ? Long.parseLong(val) : -1; } private static void append(StringBuilder buf, String value) { if (buf.length() > 0) buf.append(", "); buf.append(value); } /** * Construct the Cache-Control header from info in the request object */ public static String buildCacheControl(AbstractRequest request) { StringBuilder buf = new StringBuilder(); if (request.isNoCache()) append(buf, "no-cache"); if (request.isNoStore()) append(buf, "no-store"); if (request.isNoTransform()) append(buf, "no-transform"); if (request.isOnlyIfCached()) append(buf, "only-if-cached"); if (request.getMaxAge() != -1) append(buf, "max-age=" + request.getMaxAge()); if (request.getMaxStale() != -1) append(buf, "max-stale=" + request.getMaxStale()); if (request.getMinFresh() != -1) append(buf, "min-fresh=" + request.getMinFresh()); return buf.toString(); } /** * Parse the Cache-Control header */ public static void parseCacheControl(String cc, AbstractRequest request) { if (cc == null || cc.length() == 0) return; CacheControlParser parser = new CacheControlParser(cc); request.setNoCache(false); request.setNoStore(false); request.setNoTransform(false); request.setOnlyIfCached(false); request.setMaxAge(-1); request.setMaxStale(-1); request.setMinFresh(-1); for (Directive directive : parser) { switch (directive) { case NOCACHE: request.setNoCache(true); break; case NOSTORE: request.setNoStore(true); break; case NOTRANSFORM: request.setNoTransform(true); break; case ONLYIFCACHED: request.setOnlyIfCached(true); break; case MAXAGE: request.setMaxAge(value(parser.getValue(directive))); break; case MAXSTALE: request.setMaxStale(value(parser.getValue(directive))); break; case MINFRESH: request.setMinFresh(value(parser.getValue(directive))); break; } } } /** * Parse the Cache-Control header */ public static void parseCacheControl(String cc, AbstractResponse response) { if (cc == null) return; CacheControlParser parser = new CacheControlParser(cc); response.setNoCache(false); response.setNoStore(false); response.setNoTransform(false); response.setMustRevalidate(false); response.setPrivate(false); response.setPublic(false); response.setMaxAge(-1); for (Directive directive : parser) { switch (directive) { case NOCACHE: response.setNoCache(true); response.setNoCacheHeaders(parser.getValues(directive)); break; case NOSTORE: response.setNoStore(true); break; case NOTRANSFORM: response.setNoTransform(true); break; case MUSTREVALIDATE: response.setMustRevalidate(true); break; case PUBLIC: response.setPublic(true); break; case PRIVATE: response.setPrivate(true); response.setPrivateHeaders(parser.getValues(directive)); break; case MAXAGE: response.setMaxAge(value(parser.getValue(directive))); break; } } } /** * Cache Control Directives */ public enum Directive { MAXAGE, MAXSTALE, MINFRESH, NOCACHE, NOSTORE, NOTRANSFORM, ONLYIFCACHED, MUSTREVALIDATE, PRIVATE, PROXYREVALIDATE, PUBLIC, SMAXAGE, UNKNOWN; public static Directive select(String d) { try { d = d.toUpperCase().replaceAll("-", ""); return Directive.valueOf(d); } catch (Exception e) { } return UNKNOWN; } } /** * Parser for the Cache-Control header */ public static class CacheControlParser implements Iterable<Directive> { private static final String REGEX = "\\s*([\\w\\-]+)\\s*(=)?\\s*(\\d+|\\\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)+\\\")?\\s*"; private static final Pattern pattern = Pattern.compile(REGEX); private HashMap<Directive, String> values = new HashMap<Directive, String>(); public CacheControlParser(String value) { Matcher matcher = pattern.matcher(value); while (matcher.find()) { String d = matcher.group(1); Directive directive = Directive.select(d); if (directive != Directive.UNKNOWN) { values.put(directive, matcher.group(3)); } } } public Map<Directive, String> getValues() { return values; } public String getValue(Directive directive) { return values.get(directive); } public Iterator<Directive> iterator() { return values.keySet().iterator(); } public String[] getValues(Directive directive) { String value = getValue(directive); if (value != null) { return CompressionUtil.splitAndTrim(value, ",", true); } return null; } } }
1,506
apache/abdera/core/src/main/java/org/apache/abdera/protocol/util/PoolManager.java
package org.apache.abdera.protocol.util; import java.util.Stack; import org.apache.abdera.protocol.ItemManager; /** * Implements a simple pool manager. By default, an upper limit to the pool is set at 25 entries. New items can always * be created, but if more than 25 entries are released back to the pool, the extras are discarded. Items added to the * stack should never maintain any kind of state as it is entirely possible that different threads will be grabbing * items from the pool */ public abstract class PoolManager<T> implements ItemManager<T> { private static final int DEFAULT_SIZE = 25; private final Stack<T> pool; protected PoolManager() { this(DEFAULT_SIZE); } protected PoolManager(int max) { this.pool = initStack(max); } private Stack<T> initStack(final int max) { return new Stack<T>() { private static final long serialVersionUID = -6647024253014661104L; @Override public T push(T item) { T obj = super.push(item); if (this.size() > max) this.removeElementAt(0); return obj; } }; } protected synchronized T getInstance() { return (!pool.empty()) ? pool.pop() : internalNewInstance(); } public synchronized void release(T t) { if (t == null || pool.contains(t)) return; pool.push(t); } protected abstract T internalNewInstance(); }